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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Caeden117/ChroMapper | 11,561 | Assets/__Scripts/MapEditor/Grid/Collections/NoteGridContainer.cs | using System.Collections.Generic;
using Beatmap.Appearances;
using Beatmap.Base;
using Beatmap.Containers;
using Beatmap.Enums;
using UnityEngine;
using UnityEngine.Serialization;
public class NoteGridContainer : BeatmapObjectContainerCollection<BaseNote>
{
[SerializeField] private GameObject notePrefab;
[SerializeField] private GameObject bombPrefab;
[FormerlySerializedAs("noteAppearanceSO")] [SerializeField] private NoteAppearanceSO noteAppearanceSo;
[SerializeField] private TracksManager tracksManager;
[SerializeField] private CountersPlusController countersPlus;
private readonly List<ObjectContainer> objectsAtSameTime = new();
public static bool ShowArcVisualizer { get; private set; }
public override ObjectType ContainerType => ObjectType.Note;
internal override void SubscribeToCallbacks()
{
SpawnCallbackController.NotePassedThreshold += SpawnCallback;
SpawnCallbackController.RecursiveNoteCheckFinished += RecursiveCheckFinished;
DespawnCallbackController.NotePassedThreshold += DespawnCallback;
AudioTimeSyncController.PlayToggle += OnPlayToggle;
UIMode.PreviewModeSwitched += OnUIPreviewModeSwitch;
Settings.NotifyBySettingName(nameof(Settings.NoteColorMultiplier), AppearanceChanged);
Settings.NotifyBySettingName(nameof(Settings.ArrowColorMultiplier), AppearanceChanged);
Settings.NotifyBySettingName(nameof(Settings.ArrowColorWhiteBlend), AppearanceChanged);
Settings.NotifyBySettingName(nameof(Settings.AccurateNoteSize), AppearanceChanged);
}
internal override void UnsubscribeToCallbacks()
{
SpawnCallbackController.NotePassedThreshold -= SpawnCallback;
SpawnCallbackController.RecursiveNoteCheckFinished -= RecursiveCheckFinished;
DespawnCallbackController.NotePassedThreshold -= DespawnCallback;
AudioTimeSyncController.PlayToggle -= OnPlayToggle;
UIMode.PreviewModeSwitched -= OnUIPreviewModeSwitch;
Settings.ClearSettingNotifications(nameof(Settings.NoteColorMultiplier));
Settings.ClearSettingNotifications(nameof(Settings.ArrowColorMultiplier));
Settings.ClearSettingNotifications(nameof(Settings.ArrowColorWhiteBlend));
Settings.ClearSettingNotifications(nameof(Settings.AccurateNoteSize));
}
private void OnPlayToggle(bool isPlaying)
{
if (!isPlaying) RefreshPool();
}
private void OnUIPreviewModeSwitch() => RefreshPool(true);
private void AppearanceChanged(object _) => RefreshPool(true);
//We don't need to check index as that's already done further up the chain
private void SpawnCallback(bool initial, int index, BaseObject objectData)
{
if (!LoadedContainers.ContainsKey(objectData)) CreateContainerFromPool(objectData);
}
//We don't need to check index as that's already done further up the chain
private void DespawnCallback(bool initial, int index, BaseObject objectData)
{
if (LoadedContainers.ContainsKey(objectData))
{
if (!LoadedContainers[objectData].Animator.AnimatedLife)
RecycleContainer(objectData);
else
LoadedContainers[objectData].Animator.ShouldRecycle = true;
}
}
private void RecursiveCheckFinished(bool natural, int lastPassedIndex) => RefreshPool();
public void UpdateColor(Color red, Color blue) => noteAppearanceSo.UpdateColor(red, blue);
public override ObjectContainer CreateContainer()
{
ObjectContainer con = NoteContainer.SpawnBeatmapNote(null, ref notePrefab);
con.Animator.Atsc = AudioTimeSyncController;
con.Animator.TracksManager = tracksManager;
return con;
}
protected override void UpdateContainerData(ObjectContainer con, BaseObject obj)
{
var note = con as NoteContainer;
var noteData = obj as BaseNote;
noteAppearanceSo.SetNoteAppearance(note);
note.Setup();
note.DirectionTargetEuler = NoteContainer.Directionalize(noteData);
if (!note.Animator.AnimatedTrack)
{
var track = tracksManager.GetTrackAtTime(obj.SongBpmTime);
track.AttachContainer(con);
}
}
protected override void OnObjectSpawned(BaseObject _, bool __ = false) =>
countersPlus.UpdateStatistic(CountersPlusStatistic.Notes);
protected override void OnObjectDelete(BaseObject _, bool __ = false) =>
countersPlus.UpdateStatistic(CountersPlusStatistic.Notes);
// Here we check to see if any special angled notes are required.
protected override void OnContainerSpawn(ObjectContainer container, BaseObject obj) =>
RefreshSpecialAngles(obj, true, AudioTimeSyncController.IsPlaying);
protected override void OnContainerDespawn(ObjectContainer container, BaseObject obj) =>
RefreshSpecialAngles(obj, false, AudioTimeSyncController.IsPlaying);
public void RefreshSpecialAngles(BaseObject obj, bool objectWasSpawned, bool isNatural)
{
// Do not bother refreshing if objects are despawning naturally (while playing back the song)
if (!objectWasSpawned && isNatural) return;
// Do not do special angles for bombs and fakes
var note = obj as BaseNote;
if (note.Type == (int)NoteType.Bomb || note.CustomFake) return;
// Grab all objects with the same type, and time (within epsilon)
PopulateObjectsAtSameTime(note);
// Early return if we don't have exactly 2 notes to snap
if (objectsAtSameTime.Count != 2)
{
ClearSpecialAnglesFromObjectsAtSameTime();
return;
}
// Due to the potential for "obj" not having a container, we cannot reuse it as "a".
var a = objectsAtSameTime[0].ObjectData as BaseNote;
var b = objectsAtSameTime[^1].ObjectData as BaseNote;
// Grab the containers we will be flipping
var containerA = objectsAtSameTime[0] as NoteContainer;
var containerB = objectsAtSameTime[^1] as NoteContainer;
// Clear angles if directions are not the same (and both are not dot notes) or is precision placed
var hasNEcoordinates = a.CustomCoordinate != null || b.CustomCoordinate != null;
var hasMEprecision = a.CutDirection >= 1000 || a.CutDirection <= -1000 ||
b.CutDirection >= 1000 || b.CutDirection <= -1000;
if (a.CutDirection != b.CutDirection && a.CutDirection != (int)NoteCutDirection.Any &&
b.CutDirection != (int)NoteCutDirection.Any && !hasMEprecision && !hasNEcoordinates)
{
var directionA = NoteContainer.Directionalize(a);
var directionB = NoteContainer.Directionalize(b);
containerA.DirectionTarget.localEulerAngles = containerA.DirectionTargetEuler = directionA;
containerB.DirectionTarget.localEulerAngles = containerB.DirectionTargetEuler = directionB;
return;
}
// Swap references if our first note is a dot note
if (a.CutDirection == (int)NoteCutDirection.Any)
{
(a, b) = (b, a);
(containerA, containerB) = (containerB, containerA);
}
// Note jump animation broke when we used container local position. Use position from note data instead
var posA = a.GetPosition();
var posB = b.GetPosition();
var cutVector = a.CutDirection == (int)NoteCutDirection.Any ? Vector2.up : Direction(a);
var line = posA - posB;
var angle = SignedAngleToLine(cutVector, line);
// if both notes are dots, line them up with each other by adding the signed angle.
if (a.CutDirection == (int)NoteCutDirection.Any &&
b.CutDirection == (int)NoteCutDirection.Any)
{
containerA.DirectionTargetEuler = Vector3.forward * angle;
containerB.DirectionTargetEuler = Vector3.forward * angle;
}
// We restrict angles below 40 otherwise display their normal direction
else if (Mathf.Abs(angle) <= 40)
{
var originalA = NoteContainer.Directionalize(a) + new Vector3(0, 0, -a.AngleOffset);
var originalB = NoteContainer.Directionalize(b) + new Vector3(0, 0, -b.AngleOffset);
containerA.DirectionTargetEuler = originalA + (Vector3.forward * angle);
if (b.CutDirection == (int)NoteCutDirection.Any && !a.IsMainDirection)
containerB.DirectionTargetEuler = originalB + (Vector3.forward * (angle + 45));
else
containerB.DirectionTargetEuler = originalB + (Vector3.forward * angle);
}
// These notes do not snap so lets reset their angle
else
{
var directionA = NoteContainer.Directionalize(a);
var directionB = NoteContainer.Directionalize(b);
containerA.DirectionTargetEuler = directionA;
containerB.DirectionTargetEuler = directionB;
}
// Immediately update direction target
containerA.DirectionTarget.localEulerAngles = containerA.DirectionTargetEuler;
containerB.DirectionTarget.localEulerAngles = containerB.DirectionTargetEuler;
}
public void ClearSpecialAngles(BaseObject obj)
{
var note = obj as BaseNote;
PopulateObjectsAtSameTime(note);
ClearSpecialAnglesFromObjectsAtSameTime();
}
// Grab all objects with the same type, and time (within epsilon)
private void PopulateObjectsAtSameTime(BaseNote note)
{
objectsAtSameTime.Clear();
foreach (var x in LoadedContainers)
{
if (note.CustomFake
|| !(x.Key.JsonTime - Epsilon <= note.JsonTime && x.Key.JsonTime + Epsilon >= note.JsonTime
&& (x.Key as BaseNote).Type == note.Type))
{
continue;
}
objectsAtSameTime.Add(x.Value);
}
}
private void ClearSpecialAnglesFromObjectsAtSameTime()
{
foreach (var toReset in objectsAtSameTime)
{
var direction = NoteContainer.Directionalize(toReset.ObjectData as BaseNote);
(toReset as NoteContainer).DirectionTarget.localEulerAngles = direction;
(toReset as NoteContainer).DirectionTargetEuler = direction;
}
}
// Grab a Vector2 plane based on the cut direction
public static Vector2 Direction(BaseNote obj)
{
return obj.CutDirection switch
{
(int)NoteCutDirection.Up => new Vector2(0f, 1f),
(int)NoteCutDirection.Down => new Vector2(0f, -1f),
(int)NoteCutDirection.Left => new Vector2(-1f, 0f),
(int)NoteCutDirection.Right => new Vector2(1f, 0f),
(int)NoteCutDirection.UpLeft => new Vector2(-0.7071f, 0.7071f),
(int)NoteCutDirection.UpRight => new Vector2(0.7071f, 0.7071f),
(int)NoteCutDirection.DownLeft => new Vector2(-0.7071f, -0.7071f),
(int)NoteCutDirection.DownRight => new Vector2(0.7071f, -0.7071f),
_ => new Vector2(0f, 0f),
};
}
// Totally not ripped from Beat Saber (jaroslav beck plz dont hurt me)
private float SignedAngleToLine(Vector2 vec, Vector2 line)
{
var positive = Vector2.SignedAngle(vec, line);
var negative = Vector2.SignedAngle(vec, -line);
if (Mathf.Abs(positive) >= Mathf.Abs(negative)) return negative;
return positive;
}
}
| 0 | 0.967903 | 1 | 0.967903 | game-dev | MEDIA | 0.602732 | game-dev | 0.98397 | 1 | 0.98397 |
OpenSAGE/OpenSAGE | 2,489 | src/OpenSage.Game/Logic/Object/Collide/AODCrushCollide.cs | using OpenSage.Data.Ini;
namespace OpenSage.Logic.Object;
public sealed class AODCrushCollideModuleData : CollideModuleData
{
internal static AODCrushCollideModuleData Parse(IniParser parser) => parser.ParseBlock(FieldParseTable);
private static readonly IniParseTable<AODCrushCollideModuleData> FieldParseTable = new IniParseTable<AODCrushCollideModuleData>
{
{ "SmallFXList", (parser, x) => x.SmallFXList = parser.ParseAssetReference() },
{ "MediumFXList", (parser, x) => x.MediumFXList = parser.ParseAssetReference() },
{ "LargeFXList", (parser, x) => x.LargeFXList = parser.ParseAssetReference() },
{ "MediumObjectCreationList", (parser, x) => x.MediumObjectCreationList = parser.ParseAssetReference() },
{ "Damage", (parser, x) => x.Damage = parser.ParseFloat() },
{ "DamageType", (parser, x) => x.DamageType = parser.ParseEnum<DamageType>() },
{ "DeathType", (parser, x) => x.DeathType = parser.ParseEnum<DeathType>() },
{ "SpecialObject", (parser, x) => x.SpecialObject = ObjectFilter.Parse(parser) },
{ "SpecialDamage", (parser, x) => x.SpecialDamage = parser.ParseFloat() },
{ "SpecialDamageType", (parser, x) => x.SpecialDamageType = parser.ParseEnum<DamageType>() },
{ "SpecialDeathType", (parser, x) => x.SpecialDeathType = parser.ParseEnum<DeathType>() },
{ "SelfDamage", (parser, x) => x.SelfDamage = parser.ParseFloat() },
{ "SelfDamageType", (parser, x) => x.SelfDamageType = parser.ParseEnum<DamageType>() },
{ "SelfDeathType", (parser, x) => x.SelfDeathType = parser.ParseEnum<DeathType>() }
};
public string SmallFXList { get; private set; }
public string MediumFXList { get; private set; }
public string LargeFXList { get; private set; }
public string MediumObjectCreationList { get; private set; }
public float Damage { get; private set; }
public DamageType DamageType { get; private set; }
public DeathType DeathType { get; private set; }
public ObjectFilter SpecialObject { get; private set; }
public float SpecialDamage { get; private set; }
public DamageType SpecialDamageType { get; private set; }
public DeathType SpecialDeathType { get; private set; }
public float SelfDamage { get; private set; }
public DamageType SelfDamageType { get; private set; }
public DeathType SelfDeathType { get; private set; }
}
| 0 | 0.843662 | 1 | 0.843662 | game-dev | MEDIA | 0.511146 | game-dev | 0.958827 | 1 | 0.958827 |
kichikuou/xsystem35-sdl2 | 3,040 | modules/tDemo/tDemo.c | /*
* Copyright (C) 1997-1998 Masaki Chikama (Wren) <chikama@kasumi.ipl.mech.nagoya-u.ac.jp>
* 1998- <masaki-c@is.aist-nara.ac.jp>
* 2024 kichikuou <KichikuouChrome@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include "config.h"
#include <stdio.h>
#include "portab.h"
#include "system.h"
#include "xsystem35.h"
#include "modules.h"
#include "nact.h"
#include "alk.h"
#include "input.h"
#include "bgm.h"
#include "gfx.h"
#include "cg.h"
#include "jpeg.h"
#define TDEMO_MUSIC_NO 1
#define FPS 30
static void Init() {
int p1 = getCaliValue();
int p2 = getCaliValue();
int p3 = getCaliValue();
int *var = getCaliVariable();
*var = 1;
TRACE("tDemo.Init %d,%d,%d,%p:", p1, p2, p3, var);
}
static void SetKeyCancelFlag() {
int cancelflag = getCaliValue();
TRACE_UNIMPLEMENTED("tDemo.SetKeyCancelFlag %d:", cancelflag);
}
static void SetLoopFlag() {
/* Loop Flag */
int loopflag = getCaliValue(); /* 0 なら無限繰り返し */
TRACE_UNIMPLEMENTED("tDemo.SetLoopFlag %d:", loopflag);
}
static void Run() {
alk_t *alk = alk_new("tDEMO.alk");
if (!alk) {
WARNING("Cannot open tDEMO.alk");
return;
}
while (sys_getInputInfo()); // wait for key up
musbgm_play(TDEMO_MUSIC_NO, 0, 100, 0);
uint32_t start = sys_get_ticks();
while (!nact->is_quit) {
int i = (sys_get_ticks() - start) / (1000 / FPS);
if (i >= alk->datanum)
break;
cgdata *cg = jpeg_extract(alk->entries[i].data, alk->entries[i].size);
if (cg) {
SDL_Surface *sf = SDL_CreateRGBSurfaceWithFormatFrom(cg->pic, cg->width, cg->height, 24, cg->width * 3, SDL_PIXELFORMAT_RGB24);
SDL_BlitSurface(sf, NULL, main_surface, NULL);
ags_updateFull();
SDL_FreeSurface(sf);
cgdata_free(cg);
} else {
WARNING("Cannot decode CG %d", i);
}
int wait_ms = (i + 1) * (1000 / FPS) - (sys_get_ticks() - start);
if (wait_ms > 0) {
if (sys_keywait(wait_ms, KEYWAIT_CANCELABLE))
break;
} else {
gfx_updateScreen();
if (sys_getInputInfo())
break;
}
}
musbgm_stop(TDEMO_MUSIC_NO, 0);
alk_free(alk);
TRACE("tDemo.Run:");
}
static const ModuleFunc functions[] = {
{"Init", Init},
{"Run", Run},
{"SetKeyCancelFlag", SetKeyCancelFlag},
{"SetLoopFlag", SetLoopFlag},
};
const Module module_tDemo = {"tDemo", functions, sizeof(functions) / sizeof(ModuleFunc)};
| 0 | 0.687986 | 1 | 0.687986 | game-dev | MEDIA | 0.778199 | game-dev | 0.658092 | 1 | 0.658092 |
526077247/GenshinGamePlay | 4,707 | Packages/com.unity.timeline/Editor/Animation/BindingTreeViewDataSourceGUI.cs | using System.Linq;
using UnityEditor.IMGUI.Controls;
using UnityEngine;
using UnityEngine.Playables;
using UnityEngine.Timeline;
namespace UnityEditor.Timeline
{
class BindingTreeViewGUI : TreeViewGUI
{
const float k_RowRightOffset = 10;
const float k_CurveColorIndicatorIconSize = 11;
const float k_ColorIndicatorTopMargin = 3;
static readonly Color s_KeyColorForNonCurves = new Color(0.7f, 0.7f, 0.7f, 0.5f);
static readonly Color s_ChildrenCurveLabelColor = new Color(1.0f, 1.0f, 1.0f, 0.7f);
static readonly Color s_PhantomPropertyLabelColor = new Color(0.0f, 0.8f, 0.8f, 1f);
static readonly Texture2D s_DefaultScriptTexture = EditorGUIUtility.LoadIcon("cs Script Icon");
static readonly Texture2D s_TrackDefault = EditorGUIUtility.LoadIcon("UnityEngine/ScriptableObject Icon");
public float parentWidth { get; set; }
public BindingTreeViewGUI(TreeViewController treeView)
: base(treeView, true)
{
k_IconWidth = 13.0f;
iconOverlayGUI += OnItemIconOverlay;
}
public override void OnRowGUI(Rect rowRect, TreeViewItem node, int row, bool selected, bool focused)
{
Color originalColor = GUI.color;
bool leafNode = node.parent != null && node.parent.id != BindingTreeViewDataSource.RootID && node.parent.id != BindingTreeViewDataSource.GroupID;
GUI.color = Color.white;
if (leafNode)
{
CurveTreeViewNode curveNode = node as CurveTreeViewNode;
if (curveNode != null && curveNode.bindings.Any() && curveNode.bindings.First().isPhantom)
GUI.color = s_PhantomPropertyLabelColor;
else
GUI.color = s_ChildrenCurveLabelColor;
}
base.OnRowGUI(rowRect, node, row, selected, focused);
GUI.color = originalColor;
DoCurveColorIndicator(rowRect, node as CurveTreeViewNode);
}
protected override bool IsRenaming(int id)
{
return false;
}
public override bool BeginRename(TreeViewItem item, float delay)
{
return false;
}
static void DoCurveColorIndicator(Rect rect, CurveTreeViewNode node)
{
if (node == null)
return;
if (Event.current.type != EventType.Repaint)
return;
Color originalColor = GUI.color;
if (node.bindings.Length == 1 && !node.bindings[0].isPPtrCurve)
GUI.color = CurveUtility.GetPropertyColor(node.bindings[0].propertyName);
else
GUI.color = s_KeyColorForNonCurves;
Texture icon = CurveUtility.GetIconCurve();
rect = new Rect(rect.xMax - k_RowRightOffset - (k_CurveColorIndicatorIconSize / 2) - 5,
rect.yMin + k_ColorIndicatorTopMargin + (rect.height - EditorGUIUtility.singleLineHeight) / 2,
k_CurveColorIndicatorIconSize,
k_CurveColorIndicatorIconSize);
GUI.DrawTexture(rect, icon, ScaleMode.ScaleToFit, true, 1);
GUI.color = originalColor;
}
protected override Texture GetIconForItem(TreeViewItem item)
{
var node = item as CurveTreeViewNode;
if (node == null)
return null;
var type = node.iconType;
if (type == null)
return null;
// track type icon
if (typeof(TrackAsset).IsAssignableFrom(type))
{
var icon = TrackResourceCache.GetTrackIconForType(type);
return icon == s_TrackDefault ? s_DefaultScriptTexture : icon;
}
// custom clip icons always use the script texture
if (typeof(PlayableAsset).IsAssignableFrom(type))
return s_DefaultScriptTexture;
// this will return null for MonoBehaviours without a custom icon.
// use the scripting icon instead
return AssetPreview.GetMiniTypeThumbnail(type) ?? s_DefaultScriptTexture;
}
static void OnItemIconOverlay(TreeViewItem item, Rect rect)
{
var curveNodeItem = item as CurveTreeViewNode;
if (curveNodeItem != null && curveNodeItem.iconOverlay != null)
GUI.Label(rect, curveNodeItem.iconOverlay);
}
public override Vector2 GetTotalSize()
{
var originalSize = base.GetTotalSize();
originalSize.x = Mathf.Max(parentWidth, originalSize.x);
return originalSize;
}
}
}
| 0 | 0.929083 | 1 | 0.929083 | game-dev | MEDIA | 0.37678 | game-dev | 0.97569 | 1 | 0.97569 |
rednblackgames/HyperLap2D | 1,174 | src/main/java/games/rednblack/editor/controller/commands/resource/DeleteTalosVFX.java | package games.rednblack.editor.controller.commands.resource;
import games.rednblack.editor.renderer.data.SceneVO;
import games.rednblack.editor.utils.AssetIOManager;
import games.rednblack.editor.utils.AssetsUtils;
import games.rednblack.editor.view.stage.Sandbox;
public class DeleteTalosVFX extends DeleteResourceCommand {
private static final String CLASS_NAME = "games.rednblack.editor.controller.commands.resource.DeleteTalosVFX";
public static final String DONE = CLASS_NAME + "DONE";
@Override
protected String confirmDialogTitle() {
return "Delete Talos VFX";
}
@Override
public void doAction() {
String particleName = notification.getBody();
if (AssetIOManager.getInstance().deleteAsset(AssetsUtils.TYPE_TALOS_VFX, sandbox.getRootEntity(), particleName)) {
projectManager.loadProjectData(projectManager.getCurrentProjectPath());
sendNotification(DONE, particleName);
SceneVO vo = sandbox.sceneVoFromItems();
projectManager.saveCurrentProject(vo);
Sandbox.getInstance().loadCurrentProject();
} else {
cancel();
}
}
}
| 0 | 0.942205 | 1 | 0.942205 | game-dev | MEDIA | 0.960969 | game-dev | 0.926643 | 1 | 0.926643 |
bozimmerman/CoffeeMud | 8,450 | com/planet_ink/coffee_mud/Races/GreatCat.java | package com.planet_ink.coffee_mud.Races;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2001-2025 Bo Zimmerman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class GreatCat extends StdRace
{
@Override
public String ID()
{
return "GreatCat";
}
private final static String localizedStaticName = CMLib.lang().L("Great Cat");
@Override
public String name()
{
return localizedStaticName;
}
@Override
public int shortestMale()
{
return 18;
}
@Override
public int shortestFemale()
{
return 18;
}
@Override
public int heightVariance()
{
return 10;
}
@Override
public int lightestWeight()
{
return 100;
}
@Override
public int weightVariance()
{
return 60;
}
@Override
public long forbiddenWornBits()
{
return ~(Wearable.WORN_HEAD | Wearable.WORN_FEET | Wearable.WORN_NECK | Wearable.WORN_EARS | Wearable.WORN_EYES);
}
private final static String localizedStaticRacialCat = CMLib.lang().L("Feline");
@Override
public String racialCategory()
{
return localizedStaticRacialCat;
}
private final String[] racialAbilityNames = { "BigCatSpeak", "Skill_Climb" };
private final int[] racialAbilityLevels = { 1, 1 };
private final int[] racialAbilityProficiencies = { 100, 100 };
private final boolean[] racialAbilityQuals = { false, false };
private final String[] racialAbilityParms = { "", "" };
@Override
protected String[] racialAbilityNames()
{
return racialAbilityNames;
}
@Override
protected int[] racialAbilityLevels()
{
return racialAbilityLevels;
}
@Override
protected int[] racialAbilityProficiencies()
{
return racialAbilityProficiencies;
}
@Override
protected boolean[] racialAbilityQuals()
{
return racialAbilityQuals;
}
@Override
public String[] racialAbilityParms()
{
return racialAbilityParms;
}
private final String[] racialEffectNames = { "Carnivorous" };
private final int[] racialEffectLevels = { 1 };
private final String[] racialEffectParms = { "" };
@Override
protected String[] racialEffectNames()
{
return racialEffectNames;
}
@Override
protected int[] racialEffectLevels()
{
return racialEffectLevels;
}
@Override
protected String[] racialEffectParms()
{
return racialEffectParms;
}
// an ey ea he ne ar ha to le fo no gi mo wa ta wi
private static final int[] parts={0 ,2 ,2 ,1 ,1 ,0 ,0 ,1 ,4 ,4 ,1 ,0 ,1 ,1 ,1 ,0 };
@Override
public int[] bodyMask()
{
return parts;
}
private final int[] agingChart = { 0, 1, 2, 4, 7, 15, 20, 21, 22 };
@Override
public int[] getAgingChart()
{
return agingChart;
}
private static Vector<RawMaterial> resources = new Vector<RawMaterial>();
@Override
public int availabilityCode()
{
return Area.THEME_ALLTHEMES | Area.THEME_SKILLONLYMASK;
}
@Override
public void affectCharStats(final MOB affectedMOB, final CharStats affectableStats)
{
super.affectCharStats(affectedMOB, affectableStats);
affectableStats.setRacialStat(CharStats.STAT_STRENGTH,16);
affectableStats.setRacialStat(CharStats.STAT_DEXTERITY,16);
affectableStats.setRacialStat(CharStats.STAT_INTELLIGENCE,1);
}
@Override
public void unaffectCharStats(final MOB affectedMOB, final CharStats affectableStats)
{
super.unaffectCharStats(affectedMOB, affectableStats);
affectableStats.setStat(CharStats.STAT_STRENGTH,affectedMOB.baseCharStats().getStat(CharStats.STAT_STRENGTH));
affectableStats.setStat(CharStats.STAT_MAX_STRENGTH_ADJ,affectedMOB.baseCharStats().getStat(CharStats.STAT_MAX_STRENGTH_ADJ));
affectableStats.setStat(CharStats.STAT_DEXTERITY,affectedMOB.baseCharStats().getStat(CharStats.STAT_DEXTERITY));
affectableStats.setStat(CharStats.STAT_MAX_DEXTERITY_ADJ,affectedMOB.baseCharStats().getStat(CharStats.STAT_MAX_DEXTERITY_ADJ));
affectableStats.setStat(CharStats.STAT_INTELLIGENCE,affectedMOB.baseCharStats().getStat(CharStats.STAT_INTELLIGENCE));
affectableStats.setStat(CharStats.STAT_MAX_INTELLIGENCE_ADJ,affectedMOB.baseCharStats().getStat(CharStats.STAT_MAX_INTELLIGENCE_ADJ));
}
@Override
public String arriveStr()
{
return "struts in";
}
@Override
public String leaveStr()
{
return "struts";
}
@Override
public void affectPhyStats(final Physical affected, final PhyStats affectableStats)
{
super.affectPhyStats(affected,affectableStats);
affectableStats.setSensesMask(affectableStats.sensesMask()|PhyStats.CAN_SEE_DARK);
}
@Override
public String makeMobName(final char gender, final int age)
{
switch(age)
{
case Race.AGE_INFANT:
case Race.AGE_TODDLER:
return "baby "+name().toLowerCase()+" kitten";
case Race.AGE_CHILD:
return "young "+name().toLowerCase()+" kitten";
default :
return super.makeMobName(gender, age);
}
}
@Override
public Weapon[] getNaturalWeapons()
{
if(this.naturalWeaponChoices.length==0)
{
final Weapon naturalWeapon=CMClass.getWeapon("GenWeapon");
naturalWeapon.setName(L("huge sharp claws"));
naturalWeapon.setMaterial(RawMaterial.RESOURCE_BONE);
naturalWeapon.setUsesRemaining(1000);
naturalWeapon.setWeaponDamageType(Weapon.TYPE_PIERCING);
this.naturalWeaponChoices = new Weapon[] { naturalWeapon };
}
return super.getNaturalWeapons();
}
@Override
public String healthText(final MOB viewer, final MOB mob)
{
final double pct=(CMath.div(mob.curState().getHitPoints(),mob.maxState().getHitPoints()));
if(pct<.10)
return L("^r@x1^r is down to one life!^N",mob.name(viewer));
else
if(pct<.20)
return L("^r@x1^r is covered in blood and matted hair.^N",mob.name(viewer));
else
if(pct<.30)
return L("^r@x1^r is bleeding badly from lots of wounds.^N",mob.name(viewer));
else
if(pct<.40)
return L("^y@x1^y has large patches of bloody matted hair.^N",mob.name(viewer));
else
if(pct<.50)
return L("^y@x1^y has some bloody matted hair.^N",mob.name(viewer));
else
if(pct<.60)
return L("^p@x1^p has a lot of cuts and gashes.^N",mob.name(viewer));
else
if(pct<.70)
return L("^p@x1^p has a few cut patches.^N",mob.name(viewer));
else
if(pct<.80)
return L("^g@x1^g has a cut patch of fur.^N",mob.name(viewer));
else
if(pct<.90)
return L("^g@x1^g has some disheveled hair.^N",mob.name(viewer));
else
if(pct<.99)
return L("^g@x1^g has some misplaced hairs.^N",mob.name(viewer));
else
return L("^c@x1^c is in perfect health.^N",mob.name(viewer));
}
@Override
public List<RawMaterial> myResources()
{
synchronized(resources)
{
if(resources.size()==0)
{
resources.addElement(makeResource
(L("some @x1 claws",name().toLowerCase()),RawMaterial.RESOURCE_BONE));
for(int i=0;i<4;i++)
{
resources.addElement(makeResource
(L("a strip of @x1 hide",name().toLowerCase()),RawMaterial.RESOURCE_HIDE));
}
resources.addElement(makeResource
(L("a pound of @x1 meat",name().toLowerCase()),RawMaterial.RESOURCE_MEAT));
resources.addElement(makeResource
(L("some @x1 blood",name().toLowerCase()),RawMaterial.RESOURCE_BLOOD));
resources.addElement(makeResource
(L("a pile of @x1 bones",name().toLowerCase()),RawMaterial.RESOURCE_BONE));
}
}
return resources;
}
}
| 0 | 0.936137 | 1 | 0.936137 | game-dev | MEDIA | 0.937418 | game-dev | 0.939801 | 1 | 0.939801 |
arcemu/arcemu | 8,188 | src/world/PacketHandlers/ArenaTeamHandler.cpp | /*
* ArcEmu MMORPG Server
* Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/>
* Copyright (C) 2008-2012 <http://www.ArcEmu.org/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "StdAfx.h"
void WorldSession::HandleArenaTeamRosterOpcode(WorldPacket & recv_data)
{
uint32 teamId;
ArenaTeam* team;
recv_data >> teamId;
team = objmgr.GetArenaTeamById(teamId);
if(team)
{
//slot = TeamCountToId[team->m_type];
WorldPacket data(1000);
team->Roster(data);
SendPacket(&data);
}
}
void WorldSession::HandleArenaTeamQueryOpcode(WorldPacket & recv_data)
{
ArenaTeam* team;
uint32 team_id;
recv_data >> team_id;
team = objmgr.GetArenaTeamById(team_id);
if(team != NULL)
{
WorldPacket data(1000);
team->Query(data);
SendPacket(&data);
team->Stat(data);
SendPacket(&data);
}
}
void WorldSession::HandleArenaTeamAddMemberOpcode(WorldPacket & recv_data)
{
CHECK_INWORLD_RETURN
WorldPacket data(SMSG_ARENA_TEAM_INVITE, 40);
string player_name;
uint32 teamId;
recv_data >> teamId >> player_name;
ArenaTeam* pTeam = objmgr.GetArenaTeamById(teamId);
if(!pTeam)
return;
if(!pTeam->HasMember(GetPlayer()->GetLowGUID()))
{
GetPlayer()->SoftDisconnect();
return;
}
Player* plr = objmgr.GetPlayer(player_name.c_str(), false);
if(plr == NULL)
{
SystemMessage("Player `%s` is non-existent or not online.", player_name.c_str());
return;
}
if(pTeam->m_leader != _player->GetLowGUID())
{
SystemMessage("You are not the captain of this arena team.");
return;
}
if(plr->getLevel() < PLAYER_ARENA_MIN_LEVEL)
{
SystemMessage("Player must be level %u to join an arena team.", PLAYER_ARENA_MIN_LEVEL);
return;
}
if(plr->m_arenaTeams[pTeam->m_type] != NULL)
{
SystemMessage("That player is already in an arena team of this type.");
return;
}
if(plr->m_arenateaminviteguid != 0)
{
SystemMessage("That player is already invited to an arena team");
return;
}
if(plr->GetTeam() != _player->GetTeam() && !HasGMPermissions())
{
SystemMessage("That player is a member of a different faction.");
return;
}
plr->m_arenateaminviteguid = _player->m_arenaTeams[pTeam->m_type]->m_id;
data << _player->GetName();
data << _player->m_arenaTeams[pTeam->m_type]->m_name;
plr->GetSession()->SendPacket(&data);
}
void WorldSession::HandleArenaTeamRemoveMemberOpcode(WorldPacket & recv_data)
{
CHECK_INWORLD_RETURN
ArenaTeam* team;
uint8 slot;
uint32 teamId;
string name;
PlayerInfo* inf;
recv_data >> teamId >> name;
team = objmgr.GetArenaTeamById(teamId);
if(!team)
{
GetPlayer()->SoftDisconnect();
return;
}
slot = static_cast<uint8>(team->m_type);
if((team = _player->m_arenaTeams[slot]) == NULL)
{
SystemMessage("You are not in an arena team of this type.");
return;
}
if(team->m_leader != _player->GetLowGUID())
{
SystemMessage("You are not the leader of this team.");
return;
}
if((inf = objmgr.GetPlayerInfoByName(name.c_str())) == NULL)
{
SystemMessage("That player cannot be found.");
return;
}
if(!team->HasMember(inf->guid))
{
SystemMessage("That player is not in your arena team.");
return;
}
if(team->RemoveMember(inf))
{
char buffer[1024];
WorldPacket* data;
snprintf(buffer, 1024, "%s was removed from the arena team '%s'.", inf->name, team->m_name.c_str());
data = sChatHandler.FillSystemMessageData(buffer);
team->SendPacket(data);
delete data;
SystemMessage("Removed %s from the arena team '%s'.", inf->name, team->m_name.c_str());
}
}
void WorldSession::HandleArenaTeamInviteAcceptOpcode(WorldPacket & recv_data)
{
CHECK_INWORLD_RETURN
ArenaTeam* team;
if(_player->m_arenateaminviteguid == 0)
{
SystemMessage("You have not been invited into another arena team.");
return;
}
team = objmgr.GetArenaTeamById(_player->m_arenateaminviteguid);
_player->m_arenateaminviteguid = 0;
if(team == 0)
{
SystemMessage("That arena team no longer exists.");
return;
}
if(team->m_memberCount >= team->m_slots)
{
SystemMessage("That team is now full.");
return;
}
if(_player->m_arenaTeams[team->m_type] != NULL) /* shouldn't happen */
{
SystemMessage("You have already been in an arena team of that size.");
return;
}
if(team->AddMember(_player->m_playerInfo))
{
char buffer[1024];
WorldPacket* data;
snprintf(buffer, 1024, "%s joined the arena team, '%s'.", _player->GetName(), team->m_name.c_str());
data = sChatHandler.FillSystemMessageData(buffer);
team->SendPacket(data);
delete data;
}
else
{
SendNotification("Internal error.");
}
}
void WorldSession::HandleArenaTeamInviteDenyOpcode(WorldPacket & recv_data)
{
CHECK_INWORLD_RETURN
ArenaTeam* team;
if(_player->m_arenateaminviteguid == 0)
{
SystemMessage("You were not invited.");
return;
}
team = objmgr.GetArenaTeamById(_player->m_arenateaminviteguid);
_player->m_arenateaminviteguid = 0;
if(team == NULL)
return;
Player* plr = objmgr.GetPlayer(team->m_leader);
if(plr != NULL)
plr->GetSession()->SystemMessage("%s denied your arena team invitation for %s.", _player->GetName(), team->m_name.c_str());
}
void WorldSession::HandleArenaTeamLeaveOpcode(WorldPacket & recv_data)
{
CHECK_INWORLD_RETURN
ArenaTeam* team;
uint32 teamId;
recv_data >> teamId;
team = objmgr.GetArenaTeamById(teamId);
if(!team)
{
GetPlayer()->SoftDisconnect();
return;
}
if((team = _player->m_arenaTeams[team->m_type]) == NULL)
{
SystemMessage("You are not in an arena team of this type.");
return;
}
if(team->m_leader == _player->GetLowGUID() && team->m_memberCount == 1)
{
team->Destroy();
return;
}
if(team->m_leader == _player->GetLowGUID())
{
SystemMessage("You cannot leave the team yet, promote someone else to captain first.");
return;
}
if(team->RemoveMember(_player->m_playerInfo))
{
char buffer[1024];
WorldPacket* data;
snprintf(buffer, 1024, "%s left the arena team, '%s'.", _player->GetName(), team->m_name.c_str());
data = sChatHandler.FillSystemMessageData(buffer);
team->SendPacket(data);
delete data;
SystemMessage("You have left the arena team, '%s'.", team->m_name.c_str());
}
}
void WorldSession::HandleArenaTeamDisbandOpcode(WorldPacket & recv_data)
{
CHECK_INWORLD_RETURN
ArenaTeam* team;
uint32 teamId;
recv_data >> teamId;
team = objmgr.GetArenaTeamById(teamId);
if(!team)
{
GetPlayer()->SoftDisconnect();
return;
}
if((team = _player->m_arenaTeams[team->m_type]) == NULL)
{
SystemMessage("You are not in an arena team of this type.");
return;
}
if(team->m_leader != _player->GetLowGUID())
{
SystemMessage("You aren't the captain of this team.");
return;
}
team->Destroy();
}
void WorldSession::HandleArenaTeamPromoteOpcode(WorldPacket & recv_data)
{
CHECK_INWORLD_RETURN
uint32 teamId;
uint8 slot;
string name;
ArenaTeam* team;
PlayerInfo* inf;
recv_data >> teamId >> name;
team = objmgr.GetArenaTeamById(teamId);
if(!team)
{
GetPlayer()->SoftDisconnect();
return;
}
slot = static_cast<uint8>(team->m_type);
if(slot >= NUM_ARENA_TEAM_TYPES)
return;
if((team = _player->m_arenaTeams[slot]) == NULL)
{
SystemMessage("You are not in an arena team of this type.");
return;
}
if(team->m_leader != _player->GetLowGUID())
{
SystemMessage("You aren't the captain of this team.");
return;
}
if((inf = objmgr.GetPlayerInfoByName(name.c_str())) == NULL)
{
SystemMessage("That player cannot be found.");
return;
}
if(!team->HasMember(inf->guid))
{
SystemMessage("That player is not a member of your arena team.");
return;
}
team->SetLeader(inf);
}
| 0 | 0.958083 | 1 | 0.958083 | game-dev | MEDIA | 0.878552 | game-dev | 0.985871 | 1 | 0.985871 |
cherishsir/ubuntu230os | 8,683 | 14dayucgui/os/kernel/ucgui/GUI/Widget/EDITDec.c | /*
*********************************************************************************************************
* uC/GUI
* Universal graphic software for embedded applications
*
* (c) Copyright 2002, Micrium Inc., Weston, FL
* (c) Copyright 2002, SEGGER Microcontroller Systeme GmbH
*
* C/GUI is protected by international copyright laws. Knowledge of the
* source code may not be used to write a similar product. This file may
* only be used in accordance with a license and should not be redistributed
* in any way. We appreciate your understanding and fairness.
*
----------------------------------------------------------------------
File : EditDec
Purpose : Edit decimal values
---------------------------END-OF-HEADER------------------------------
*/
#include <string.h>
#include "EDIT.h"
#include "GUIDebug.h"
#include "GUI_Protected.h"
#include "EDIT_Private.h"
#if GUI_WINSUPPORT
/*********************************************************************
*
* Defaults for config switches
*
**********************************************************************
*/
#ifndef EDIT_DEC_DIGITONLY
#define EDIT_DEC_DIGITONLY 0
#endif
/*********************************************************************
*
* static Helpers
*
**********************************************************************
*/
/*********************************************************************
*
* _DecChar2Int
*/
static int _DecChar2Int(int Char) {
if ((Char >= '0') && (Char <= '9'))
return Char - '0';
return -1;
}
/*********************************************************************
*
* _UpdateBuffer
*/
static void _UpdateBuffer(EDIT_Handle hObj) {
char * s;
EDIT_Obj * pObj;
pObj = EDIT_H2P(hObj); /* The GUI needs not to be locked here. This function is called only from EDIT_AddKey which has already locked the GUI */
s = (char*) GUI_ALLOC_h2p(pObj->hpText);
if (pObj->Flags == GUI_EDIT_SIGNED) {
I32 Result = GUI_AddSign(pObj->CurrentValue, &s);
GUI_AddDecShift(Result, pObj->MaxLen - 1, pObj->NumDecs, &s);
} else {
GUI_AddDecShift(pObj->CurrentValue, pObj->MaxLen, pObj->NumDecs, &s);
}
}
/*********************************************************************
*
* _EditDec
*/
static void _EditDec(int Digit, EDIT_Obj* pObj, EDIT_Handle hObj) {
I32 Result = 0;
int i, Pos = 0;
char * s = (char*) GUI_ALLOC_h2p(pObj->hpText);
for (i = 0; i < pObj->MaxLen; i++) {
int Index = pObj->MaxLen - i - 1;
if (Index == pObj->CursorPos) {
Result += GUI_Pow10[Pos++] * Digit;
} else {
char c = *(s + Index);
int Value = _DecChar2Int(c);
if (Value >= 0) {
Result += GUI_Pow10[Pos++] * Value;
}
if (c == '-') {
Result *= -1;
}
}
}
EDIT_SetValue(hObj, Result);
}
/*********************************************************************
*
* EDIT_DEC_DIGITONLY
*/
#if EDIT_DEC_DIGITONLY
static int GetCurrentDigit(EDIT_Obj* pObj) {
return _DecChar2Int(EDIT__GetCurrentChar(pObj));
}
#endif
/*********************************************************************
*
* _MakePositive
*/
static void _MakePositive(EDIT_Obj* pObj, EDIT_Handle hObj) {
if ((I32)pObj->CurrentValue < 0) {
EDIT_SetValue(hObj, (I32)pObj->CurrentValue * -1);
}
}
/*********************************************************************
*
* _MakeNegative
*/
static void _MakeNegative(EDIT_Obj* pObj, EDIT_Handle hObj) {
if ((I32)pObj->CurrentValue > 0) {
EDIT_SetValue(hObj, (I32)pObj->CurrentValue * -1);
}
}
/*********************************************************************
*
* _SwapSign
*/
static void _SwapSign(EDIT_Obj* pObj, EDIT_Handle hObj) {
if ((I32)pObj->CurrentValue > 0)
_MakeNegative(pObj, hObj);
else
_MakePositive(pObj, hObj);
}
/*********************************************************************
*
* _IncrementCursor
*/
static void _IncrementCursor(EDIT_Obj* pObj) {
EDIT__SetCursorPos(pObj, pObj->CursorPos + 1);
if (EDIT__GetCurrentChar(pObj) == '.') {
if (pObj->CursorPos < (pObj->MaxLen - 1)) {
EDIT__SetCursorPos(pObj, pObj->CursorPos + 1);
} else {
EDIT__SetCursorPos(pObj, pObj->CursorPos - 1);
}
}
}
/*********************************************************************
*
* _AddPosition
*/
#if !EDIT_DEC_DIGITONLY
static void _AddPosition(EDIT_Obj* pObj, EDIT_Handle hObj, int Sign) {
int Pos;
I32 v;
v = Sign;
Pos = pObj->MaxLen - pObj->CursorPos-1;
if (pObj->NumDecs && (Pos > pObj->NumDecs)) {
Pos--;
}
while (Pos--) {
v *= 10;
}
EDIT_SetValue(hObj, (I32)pObj->CurrentValue + v);
}
#endif
/*********************************************************************
*
* Handle input
*
**********************************************************************
*/
/*********************************************************************
*
* _AddKeyDec
*/
static void _AddKeyDec(EDIT_Handle hObj, int Key) {
char c;
EDIT_Obj * pObj;
pObj = EDIT_H2P(hObj); /* The GUI needs not to be locked here. This function is called only from EDIT_AddKey which has already locked the GUI */
if (pObj) {
switch (Key) {
case '+':
if (pObj->CursorPos == 0) {
_MakePositive(pObj, hObj);
_IncrementCursor(pObj);
}
break;
case '-':
if (pObj->CursorPos == 0) {
_MakeNegative(pObj, hObj);
_IncrementCursor(pObj);
}
break;
#if EDIT_DEC_DIGITONLY
case GUI_KEY_UP:
c = EDIT__GetCurrentChar(pObj);
if ((c == '-') || (c == '+')) {
_SwapSign(pObj, hObj);
} else {
int Digit = GetCurrentDigit(pObj) + 1;
if (Digit > 9)
Digit = 0;
_EditDec(Digit, pObj, hObj);
}
break;
case GUI_KEY_DOWN:
c = EDIT__GetCurrentChar(pObj);
if ((c == '-') || (c == '+')) {
_SwapSign(pObj, hObj);
} else {
int Digit = GetCurrentDigit(pObj) - 1;
if (Digit < 0)
Digit = 9;
_EditDec(Digit, pObj, hObj);
}
break;
#else
case GUI_KEY_UP:
c = EDIT__GetCurrentChar(pObj);
if ((c == '-') || (c == '+')) {
_SwapSign(pObj, hObj);
} else {
_AddPosition(pObj, hObj, 1);
}
break;
case GUI_KEY_DOWN:
c = EDIT__GetCurrentChar(pObj);
if ((c == '-') || (c == '+')) {
_SwapSign(pObj, hObj);
} else {
_AddPosition(pObj, hObj, -1);
}
break;
#endif
case GUI_KEY_RIGHT:
_IncrementCursor(pObj);
break;
case GUI_KEY_LEFT:
EDIT__SetCursorPos(pObj, pObj->CursorPos - 1);
if (EDIT__GetCurrentChar(pObj) == '.') {
if (pObj->CursorPos > 0) {
EDIT__SetCursorPos(pObj, pObj->CursorPos - 1);
} else {
EDIT__SetCursorPos(pObj, pObj->CursorPos + 1);
}
}
break;
default:
{
char c = EDIT__GetCurrentChar(pObj);
if ((c != '-') && (c != '+')) {
int Digit = _DecChar2Int(Key);
if (Digit >= 0) {
_EditDec(Digit, pObj, hObj);
_IncrementCursor(pObj);
}
}
}
break;
}
}
_UpdateBuffer(hObj);
}
/*********************************************************************
*
* Exported routines
*
**********************************************************************
*/
/*********************************************************************
*
* EDIT_SetDecMode
*/
void EDIT_SetDecMode(EDIT_Handle hEdit, I32 Value, I32 Min, I32 Max, int Shift, U8 Flags) {
EDIT_Obj* pObj;
WM_LOCK();
if (hEdit) {
pObj = EDIT_H2P(hEdit);
pObj->pfAddKeyEx = _AddKeyDec;
pObj->pfUpdateBuffer= _UpdateBuffer;
pObj->CurrentValue = Value;
pObj->CursorPos = 0;
pObj->Min = Min;
pObj->Max = Max;
pObj->NumDecs = Shift;
pObj->Flags = Flags;
pObj->EditMode = GUI_EDIT_MODE_OVERWRITE;
_UpdateBuffer(hEdit);
if (EDIT__GetCurrentChar(pObj) == '.') {
EDIT__SetCursorPos(pObj, pObj->CursorPos + 1);
}
WM_Invalidate(hEdit);
}
WM_UNLOCK();
}
#else /* avoid empty object files */
void EditDec_C(void);
void EditDec_C(void){}
#endif /* GUI_WINSUPPORT */
| 0 | 0.801081 | 1 | 0.801081 | game-dev | MEDIA | 0.265007 | game-dev | 0.814253 | 1 | 0.814253 |
KhronosGroup/WebGL | 2,451 | conformance-suites/1.0.2/conformance/ogles/GL/functions/bvec4_empty_empty_bvec4_empty_vert.vert |
/*
** Copyright (c) 2012 The Khronos Group Inc.
**
** Permission is hereby granted, free of charge, to any person obtaining a
** copy of this software and/or associated documentation files (the
** "Materials"), to deal in the Materials without restriction, including
** without limitation the rights to use, copy, modify, merge, publish,
** distribute, sublicense, and/or sell copies of the Materials, and to
** permit persons to whom the Materials are 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 Materials.
**
** THE MATERIALS ARE 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
** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
*/
attribute vec4 gtf_Vertex;
uniform mat4 gtf_ModelViewProjectionMatrix;
varying vec4 color;
// Function declaration.
bvec4 function(bvec4 par);
bool is_all(const in bvec4 par, const in bool value);
void set_all(out bvec4 par, const in bool value);
void main (void)
{
bvec4 par = bvec4(true, true, true, true);
bvec4 ret = bvec4(false, false, false, false);
float gray = 0.0;
ret = function(par);
// The parameter should remain unchanged by the function and the function should return true.
if(is_all(par, true) && is_all(ret, true))
{
gray = 1.0;
}
color = vec4(gray, gray, gray, 1.0);
gl_Position = gtf_ModelViewProjectionMatrix * gtf_Vertex;
}
// Function definition.
bvec4 function(bvec4 par)
{
// Return the value of the parameter.
if(is_all(par, true))
{
// Test parameter qualifier (default is "in").
set_all(par, false);
return bvec4(true, true, true, true);
}
else
return bvec4(false, false, false, false);
}
bool is_all(const in bvec4 par, const in bool value)
{
bool ret = true;
if(par[0] != value)
ret = false;
if(par[1] != value)
ret = false;
if(par[2] != value)
ret = false;
if(par[3] != value)
ret = false;
return ret;
}
void set_all(out bvec4 par, const in bool value)
{
par[0] = value;
par[1] = value;
par[2] = value;
par[3] = value;
}
| 0 | 0.777593 | 1 | 0.777593 | game-dev | MEDIA | 0.539179 | game-dev | 0.654408 | 1 | 0.654408 |
MineralStudios/Mineral-Bot | 5,052 | bot-base-client/src/main/mc-client/net/minecraft/client/renderer/entity/RenderHorse.java | package net.minecraft.client.renderer.entity;
import com.google.common.collect.Maps;
import java.util.Map;
import net.minecraft.client.Minecraft;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.renderer.texture.LayeredTexture;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.passive.EntityHorse;
import net.minecraft.util.ResourceLocation;
import gg.mineral.bot.lwjgl.opengl.GL11;
public class RenderHorse extends RenderLiving {
private static final Map field_110852_a = Maps.newHashMap();
private static final ResourceLocation whiteHorseTextures = new ResourceLocation(
"textures/entity/horse/horse_white.png");
private static final ResourceLocation muleTextures = new ResourceLocation("textures/entity/horse/mule.png");
private static final ResourceLocation donkeyTextures = new ResourceLocation("textures/entity/horse/donkey.png");
private static final ResourceLocation zombieHorseTextures = new ResourceLocation(
"textures/entity/horse/horse_zombie.png");
private static final ResourceLocation skeletonHorseTextures = new ResourceLocation(
"textures/entity/horse/horse_skeleton.png");
public RenderHorse(Minecraft mc, ModelBase p_i1256_1_, float p_i1256_2_) {
super(mc, p_i1256_1_, p_i1256_2_);
}
/**
* Allows the render to do any OpenGL state modifications necessary before the
* model is rendered. Args:
* entityLiving, partialTickTime
*/
protected void preRenderCallback(EntityHorse p_77041_1_, float p_77041_2_) {
float var3 = 1.0F;
int var4 = p_77041_1_.getHorseType();
if (var4 == 1) {
var3 *= 0.87F;
} else if (var4 == 2) {
var3 *= 0.92F;
}
GL11.glScalef(var3, var3, var3);
super.preRenderCallback(p_77041_1_, p_77041_2_);
}
/**
* Renders the model in RenderLiving
*/
protected void renderModel(EntityHorse p_77036_1_, float p_77036_2_, float p_77036_3_, float p_77036_4_,
float p_77036_5_, float p_77036_6_, float p_77036_7_) {
if (p_77036_1_.isInvisible()) {
this.mainModel.setRotationAngles(p_77036_2_, p_77036_3_, p_77036_4_, p_77036_5_, p_77036_6_, p_77036_7_,
p_77036_1_);
} else {
this.bindEntityTexture(p_77036_1_);
this.mainModel.render(p_77036_1_, p_77036_2_, p_77036_3_, p_77036_4_, p_77036_5_, p_77036_6_, p_77036_7_);
}
}
/**
* Returns the location of an entity's texture. Doesn't seem to be called unless
* you call Render.bindEntityTexture.
*/
protected ResourceLocation getEntityTexture(EntityHorse p_110775_1_) {
if (!p_110775_1_.func_110239_cn()) {
switch (p_110775_1_.getHorseType()) {
case 0:
default:
return whiteHorseTextures;
case 1:
return donkeyTextures;
case 2:
return muleTextures;
case 3:
return zombieHorseTextures;
case 4:
return skeletonHorseTextures;
}
} else {
return this.func_110848_b(p_110775_1_);
}
}
private ResourceLocation func_110848_b(EntityHorse p_110848_1_) {
String var2 = p_110848_1_.getHorseTexture();
ResourceLocation var3 = (ResourceLocation) field_110852_a.get(var2);
if (var3 == null) {
var3 = new ResourceLocation(var2);
TextureManager textureManager = this.mc.getTextureManager();
if (textureManager != null)
textureManager.loadTexture(var3,
new LayeredTexture(this.mc, p_110848_1_.getVariantTexturePaths()));
field_110852_a.put(var2, var3);
}
return var3;
}
/**
* Allows the render to do any OpenGL state modifications necessary before the
* model is rendered. Args:
* entityLiving, partialTickTime
*/
protected void preRenderCallback(EntityLivingBase p_77041_1_, float p_77041_2_) {
this.preRenderCallback((EntityHorse) p_77041_1_, p_77041_2_);
}
/**
* Renders the model in RenderLiving
*/
protected void renderModel(EntityLivingBase p_77036_1_, float p_77036_2_, float p_77036_3_, float p_77036_4_,
float p_77036_5_, float p_77036_6_, float p_77036_7_) {
this.renderModel((EntityHorse) p_77036_1_, p_77036_2_, p_77036_3_, p_77036_4_, p_77036_5_, p_77036_6_,
p_77036_7_);
}
/**
* Returns the location of an entity's texture. Doesn't seem to be called unless
* you call Render.bindEntityTexture.
*/
protected ResourceLocation getEntityTexture(Entity p_110775_1_) {
return this.getEntityTexture((EntityHorse) p_110775_1_);
}
}
| 0 | 0.697872 | 1 | 0.697872 | game-dev | MEDIA | 0.685345 | game-dev,graphics-rendering | 0.737974 | 1 | 0.737974 |
ChoGGi/SurvivingMars_Mods | 1,213 | Mods ChoGGi/Consistent Build Menu/Code/Script.lua | -- See LICENSE for terms
local CmpLower = CmpLower
local _InternalTranslate = _InternalTranslate
--
-- Copied from ChoGGi_Funcs.Common.SortBuildMenuItems()
local SortBuildMenuItems = rawget(_G, "ChoGGi_Funcs") and ChoGGi_Funcs.Common.SortBuildMenuItems
or function()
local templates = Presets.BuildingTemplate
for i = 1, #templates do
local items = templates[i]
table.sort(items, function(a, b)
return CmpLower(_InternalTranslate(a.display_name), _InternalTranslate(b.display_name))
end)
for j = 1, #items do
items[j].build_pos = j
end
end
end
local mod_EnableMod
local function StartupCode()
if not mod_EnableMod then
return
end
SortBuildMenuItems()
end
-- Update mod options
local function ModOptions(id)
-- id is from ApplyModOptions
if id and id ~= CurrentModId then
return
end
mod_EnableMod = CurrentModOptions:GetProperty("EnableMod")
-- Make sure we're in-game
if not GameMaps then
return
end
StartupCode()
end
-- Load default/saved settings
OnMsg.ModsReloaded = ModOptions
-- Fired when Mod Options>Apply button is clicked
OnMsg.ApplyModOptions = ModOptions
-- New games
OnMsg.CityStart = StartupCode
-- Saved ones
OnMsg.LoadGame = StartupCode
| 0 | 0.679517 | 1 | 0.679517 | game-dev | MEDIA | 0.678982 | game-dev | 0.764256 | 1 | 0.764256 |
risingPhil/PokeMe64 | 2,778 | src/widget/MenuItemWidget.cpp | #include "widget/MenuItemWidget.h"
#include "core/RDPQGraphics.h"
MenuItemWidget::MenuItemWidget()
: data_()
, style_({0})
, focused_(false)
, visible_(true)
, aButtonPressed_(false)
{
}
MenuItemWidget::~MenuItemWidget()
{
}
const MenuItemData& MenuItemWidget::getData() const
{
return data_;
}
void MenuItemWidget::setData(const MenuItemData& data)
{
data_ = data;
}
void MenuItemWidget::setStyle(const MenuItemStyle& style)
{
style_ = style;
}
bool MenuItemWidget::isFocused() const
{
return focused_;
}
void MenuItemWidget::setFocused(bool focused)
{
focused_ = focused;
}
bool MenuItemWidget::isVisible() const
{
return visible_;
}
void MenuItemWidget::setVisible(bool visible)
{
visible_ = visible;
}
Rectangle MenuItemWidget::getBounds() const
{
return Rectangle{.x = 0, .y = 0, .width = style_.size.width, .height = style_.size.height};
}
void MenuItemWidget::setBounds(const Rectangle& bounds)
{
// Not relevant: the actual bounds are passed from the VerticalList widget
}
Dimensions MenuItemWidget::getSize() const
{
return style_.size;
}
bool MenuItemWidget::handleUserInput(const joypad_inputs_t& userInput)
{
// only handle button release, otherwise you'll be in trouble on scene transitions:
// the user can't release the button fast enough, so the same press would get handled twice.
if(userInput.btn.a)
{
aButtonPressed_ = true;
return true;
}
else if(aButtonPressed_)
{
aButtonPressed_ = false;
return execute();
}
return false;
}
void MenuItemWidget::render(RDPQGraphics& gfx, const Rectangle& parentBounds)
{
if(!visible_)
{
return;
}
Rectangle myBounds = {.x = parentBounds.x, .y = parentBounds.y, .width = style_.size.width, .height = style_.size.height};
if(style_.background.sprite)
{
gfx.drawSprite(myBounds, style_.background.sprite, style_.background.spriteSettings);
}
if(style_.icon.sprite)
{
const Rectangle iconSpriteBounds = addOffset(style_.icon.spriteBounds, myBounds);
gfx.drawSprite(iconSpriteBounds, style_.icon.sprite, style_.icon.spriteSettings);
}
myBounds.x += style_.leftMargin;
myBounds.y += style_.topMargin;
// account for leftMargin and topMargin twice (we also apply it for the rightmargin and bottom)
myBounds.width -= style_.leftMargin - style_.leftMargin;
myBounds.height -= style_.topMargin - style_.topMargin;
gfx.drawText(myBounds, data_.title, (focused_) ? style_.titleFocused : style_.titleNotFocused);
}
bool MenuItemWidget::execute()
{
if(data_.onConfirmAction)
{
data_.onConfirmAction(data_.context, data_.itemParam);
return true;
}
return false;
} | 0 | 0.969472 | 1 | 0.969472 | game-dev | MEDIA | 0.769867 | game-dev,desktop-app | 0.963894 | 1 | 0.963894 |
IceLanguage/Pokemon_Unity3D_Entitas | 10,843 | Assets/Unity Pacakage/AssetBundles-Browser-master/Editor/AssetBundleManageTab.cs | using UnityEditor;
using UnityEditor.IMGUI.Controls;
using UnityEngine;
using System.Collections.Generic;
namespace AssetBundleBrowser
{
[System.Serializable]
internal class AssetBundleManageTab
{
[SerializeField]
TreeViewState m_BundleTreeState;
[SerializeField]
TreeViewState m_AssetListState;
[SerializeField]
MultiColumnHeaderState m_AssetListMCHState;
[SerializeField]
TreeViewState m_BundleDetailState;
Rect m_Position;
AssetBundleTree m_BundleTree;
AssetListTree m_AssetList;
MessageList m_MessageList;
BundleDetailList m_DetailsList;
bool m_ResizingHorizontalSplitter = false;
bool m_ResizingVerticalSplitterRight = false;
bool m_ResizingVerticalSplitterLeft = false;
Rect m_HorizontalSplitterRect, m_VerticalSplitterRectRight, m_VerticalSplitterRectLeft;
[SerializeField]
float m_HorizontalSplitterPercent;
[SerializeField]
float m_VerticalSplitterPercentRight;
[SerializeField]
float m_VerticalSplitterPercentLeft;
const float k_SplitterWidth = 3f;
private static float s_UpdateDelay = 0f;
SearchField m_searchField;
EditorWindow m_Parent = null;
internal AssetBundleManageTab()
{
m_HorizontalSplitterPercent = 0.4f;
m_VerticalSplitterPercentRight = 0.7f;
m_VerticalSplitterPercentLeft = 0.85f;
}
internal void OnEnable(Rect pos, EditorWindow parent)
{
m_Parent = parent;
m_Position = pos;
m_HorizontalSplitterRect = new Rect(
(int)(m_Position.x + m_Position.width * m_HorizontalSplitterPercent),
m_Position.y,
k_SplitterWidth,
m_Position.height);
m_VerticalSplitterRectRight = new Rect(
m_HorizontalSplitterRect.x,
(int)(m_Position.y + m_HorizontalSplitterRect.height * m_VerticalSplitterPercentRight),
(m_Position.width - m_HorizontalSplitterRect.width) - k_SplitterWidth,
k_SplitterWidth);
m_VerticalSplitterRectLeft = new Rect(
m_Position.x,
(int)(m_Position.y + m_HorizontalSplitterRect.height * m_VerticalSplitterPercentLeft),
(m_HorizontalSplitterRect.width) - k_SplitterWidth,
k_SplitterWidth);
m_searchField = new SearchField();
}
internal void Update()
{
var t = Time.realtimeSinceStartup;
if (t - s_UpdateDelay > 0.1f ||
s_UpdateDelay > t) //something went strangely wrong if this second check is true.
{
s_UpdateDelay = t - 0.001f;
if(AssetBundleModel.Model.Update())
{
m_Parent.Repaint();
}
if (m_DetailsList != null)
m_DetailsList.Update();
if (m_AssetList != null)
m_AssetList.Update();
}
}
internal void ForceReloadData()
{
UpdateSelectedBundles(new List<AssetBundleModel.BundleInfo>());
SetSelectedItems(new List<AssetBundleModel.AssetInfo>());
AssetBundleModel.Model.ForceReloadData(m_BundleTree);
m_Parent.Repaint();
}
internal void OnGUI(Rect pos)
{
m_Position = pos;
if(m_BundleTree == null)
{
if (m_AssetListState == null)
m_AssetListState = new TreeViewState();
var headerState = AssetListTree.CreateDefaultMultiColumnHeaderState();// multiColumnTreeViewRect.width);
if (MultiColumnHeaderState.CanOverwriteSerializedFields(m_AssetListMCHState, headerState))
MultiColumnHeaderState.OverwriteSerializedFields(m_AssetListMCHState, headerState);
m_AssetListMCHState = headerState;
m_AssetList = new AssetListTree(m_AssetListState, m_AssetListMCHState, this);
m_AssetList.Reload();
m_MessageList = new MessageList();
if (m_BundleDetailState == null)
m_BundleDetailState = new TreeViewState();
m_DetailsList = new BundleDetailList(m_BundleDetailState);
m_DetailsList.Reload();
if (m_BundleTreeState == null)
m_BundleTreeState = new TreeViewState();
m_BundleTree = new AssetBundleTree(m_BundleTreeState, this);
m_BundleTree.Refresh();
m_Parent.Repaint();
}
HandleHorizontalResize();
HandleVerticalResize();
if (AssetBundleModel.Model.BundleListIsEmpty())
{
m_BundleTree.OnGUI(m_Position);
var style = new GUIStyle(GUI.skin.label);
style.alignment = TextAnchor.MiddleCenter;
style.wordWrap = true;
GUI.Label(
new Rect(m_Position.x + 1f, m_Position.y + 1f, m_Position.width - 2f, m_Position.height - 2f),
new GUIContent(AssetBundleModel.Model.GetEmptyMessage()),
style);
}
else
{
//Left half
var bundleTreeRect = new Rect(
m_Position.x,
m_Position.y,
m_HorizontalSplitterRect.x,
m_VerticalSplitterRectLeft.y - m_Position.y);
m_BundleTree.OnGUI(bundleTreeRect);
m_DetailsList.OnGUI(new Rect(
bundleTreeRect.x,
bundleTreeRect.y + bundleTreeRect.height + k_SplitterWidth,
bundleTreeRect.width,
m_Position.height - bundleTreeRect.height - k_SplitterWidth*2));
//Right half.
float panelLeft = m_HorizontalSplitterRect.x + k_SplitterWidth;
float panelWidth = m_VerticalSplitterRectRight.width - k_SplitterWidth * 2;
float searchHeight = 20f;
float panelTop = m_Position.y + searchHeight;
float panelHeight = m_VerticalSplitterRectRight.y - panelTop;
OnGUISearchBar(new Rect(panelLeft, m_Position.y, panelWidth, searchHeight));
m_AssetList.OnGUI(new Rect(
panelLeft,
panelTop,
panelWidth,
panelHeight));
m_MessageList.OnGUI(new Rect(
panelLeft,
panelTop + panelHeight + k_SplitterWidth,
panelWidth,
(m_Position.height - panelHeight) - k_SplitterWidth * 2));
if (m_ResizingHorizontalSplitter || m_ResizingVerticalSplitterRight || m_ResizingVerticalSplitterLeft)
m_Parent.Repaint();
}
}
void OnGUISearchBar(Rect rect)
{
m_BundleTree.searchString = m_searchField.OnGUI(rect, m_BundleTree.searchString);
m_AssetList.searchString = m_BundleTree.searchString;
}
public bool hasSearch
{
get { return m_BundleTree.hasSearch; }
}
private void HandleHorizontalResize()
{
m_HorizontalSplitterRect.x = (int)(m_Position.width * m_HorizontalSplitterPercent);
m_HorizontalSplitterRect.height = m_Position.height;
EditorGUIUtility.AddCursorRect(m_HorizontalSplitterRect, MouseCursor.ResizeHorizontal);
if (Event.current.type == EventType.MouseDown && m_HorizontalSplitterRect.Contains(Event.current.mousePosition))
m_ResizingHorizontalSplitter = true;
if (m_ResizingHorizontalSplitter)
{
m_HorizontalSplitterPercent = Mathf.Clamp(Event.current.mousePosition.x / m_Position.width, 0.1f, 0.9f);
m_HorizontalSplitterRect.x = (int)(m_Position.width * m_HorizontalSplitterPercent);
}
if (Event.current.type == EventType.MouseUp)
m_ResizingHorizontalSplitter = false;
}
private void HandleVerticalResize()
{
m_VerticalSplitterRectRight.x = m_HorizontalSplitterRect.x;
m_VerticalSplitterRectRight.y = (int)(m_HorizontalSplitterRect.height * m_VerticalSplitterPercentRight);
m_VerticalSplitterRectRight.width = m_Position.width - m_HorizontalSplitterRect.x;
m_VerticalSplitterRectLeft.y = (int)(m_HorizontalSplitterRect.height * m_VerticalSplitterPercentLeft);
m_VerticalSplitterRectLeft.width = m_VerticalSplitterRectRight.width;
EditorGUIUtility.AddCursorRect(m_VerticalSplitterRectRight, MouseCursor.ResizeVertical);
if (Event.current.type == EventType.MouseDown && m_VerticalSplitterRectRight.Contains(Event.current.mousePosition))
m_ResizingVerticalSplitterRight = true;
EditorGUIUtility.AddCursorRect(m_VerticalSplitterRectLeft, MouseCursor.ResizeVertical);
if (Event.current.type == EventType.MouseDown && m_VerticalSplitterRectLeft.Contains(Event.current.mousePosition))
m_ResizingVerticalSplitterLeft = true;
if (m_ResizingVerticalSplitterRight)
{
m_VerticalSplitterPercentRight = Mathf.Clamp(Event.current.mousePosition.y / m_HorizontalSplitterRect.height, 0.2f, 0.98f);
m_VerticalSplitterRectRight.y = (int)(m_HorizontalSplitterRect.height * m_VerticalSplitterPercentRight);
}
else if (m_ResizingVerticalSplitterLeft)
{
m_VerticalSplitterPercentLeft = Mathf.Clamp(Event.current.mousePosition.y / m_HorizontalSplitterRect.height, 0.25f, 0.98f);
m_VerticalSplitterRectLeft.y = (int)(m_HorizontalSplitterRect.height * m_VerticalSplitterPercentLeft);
}
if (Event.current.type == EventType.MouseUp)
{
m_ResizingVerticalSplitterRight = false;
m_ResizingVerticalSplitterLeft = false;
}
}
internal void UpdateSelectedBundles(IEnumerable<AssetBundleModel.BundleInfo> bundles)
{
AssetBundleModel.Model.AddBundlesToUpdate(bundles);
m_AssetList.SetSelectedBundles(bundles);
m_DetailsList.SetItems(bundles);
m_MessageList.SetItems(null);
}
internal void SetSelectedItems(IEnumerable<AssetBundleModel.AssetInfo> items)
{
m_MessageList.SetItems(items);
}
}
} | 0 | 0.939334 | 1 | 0.939334 | game-dev | MEDIA | 0.694905 | game-dev | 0.982641 | 1 | 0.982641 |
frauzufall/ofxGuiExtended | 3,079 | src/controls/ofxGuiSlider.h | #pragma once
#include "../ofxGuiElement.h"
#include "ofParameter.h"
class ofxGuiSliderType{
public:
enum Type{
/// \brief Default. Shows slider as a vertical or horizontal bar.
STRAIGHT,
/// \brief Displays circular slider.
CIRCULAR
};
};
template<typename DataType>
class ofxGuiSlider : public ofxGuiElement, public ofxGuiSliderType{
public:
ofxGuiSlider();
ofxGuiSlider(const ofJson & config);
ofxGuiSlider(ofParameter<DataType>& _val, const ofJson & config = ofJson());
ofxGuiSlider(const std::string& sliderName, DataType _val, DataType _min, DataType _max, const ofJson & config = ofJson());
~ofxGuiSlider();
void setMin(DataType min);
DataType getMin();
void setMax(DataType max);
DataType getMax();
void setType(const std::string &type);
void setType(const Type &type);
Type getType();
virtual float getMinWidth() override;
virtual float getMinHeight() override;
void setPrecision(int precision);
void setUpdateOnReleaseOnly(bool bUpdateOnReleaseOnly);
virtual bool mousePressed(ofMouseEventArgs & args) override;
virtual bool mouseDragged(ofMouseEventArgs & args) override;
virtual bool mouseReleased(ofMouseEventArgs & args) override;
virtual bool mouseScrolled(ofMouseEventArgs & args) override;
template<class ListenerClass, typename ListenerMethod>
void addListener(ListenerClass * listener, ListenerMethod method){
value.addListener(listener,method);
}
template<class ListenerClass, typename ListenerMethod>
void removeListener(ListenerClass * listener, ListenerMethod method){
value.removeListener(listener,method);
}
double operator=(DataType v);
operator const DataType & ();
ofAbstractParameter & getParameter() override;
static std::string getClassType();
protected:
void setup();
virtual std::vector<std::string> getClassTypes() override;
virtual void _setConfig(const ofJson & config) override;
virtual void render() override;
virtual void resized(DOM::ResizeEventArgs&);
ofParameter<DataType> value;
ofParameter<ofxGuiSliderType::Type> type;
virtual bool setValue(float mx, float my, bool bCheck) override;
virtual bool setValue(float mx, float my, bool bCheck, ofParameter<DataType>* referenceValue);
virtual void setValue(DataType value);
virtual void generateDraw() override;
virtual void generateText();
virtual void _generateText(std::string valStr);
virtual void generateShapes(ofParameter<DataType>* valueReference);
virtual void setSliderBarValue(DataType value);
void valueChanged(DataType & value);
void handleMousePressed(float x, float y, ofParameter<DataType>* referenceValue);
virtual std::string getText();
ofPath bar;
ofVboMesh textMesh;
ofParameter<bool> updateOnReleaseOnly;
ofParameter<bool> showValue;
ofParameter<unsigned int> precision;
/// \brief The Slider orientation.
bool horizontal;
bool hasFocus;
//circular type
void arcStrip(ofPath & path, ofPoint center, float outer_radius, float inner_radius, float percent);
float _mouseOffset;
};
typedef ofxGuiSlider<float> ofxGuiFloatSlider;
typedef ofxGuiSlider<int> ofxGuiIntSlider;
| 0 | 0.907203 | 1 | 0.907203 | game-dev | MEDIA | 0.550318 | game-dev | 0.782147 | 1 | 0.782147 |
rlf/uSkyBlock | 3,101 | uSkyBlock-Core/src/main/java/us/talabrek/ultimateskyblock/command/admin/JobsCommand.java | package us.talabrek.ultimateskyblock.command.admin;
import dk.lockfuglsang.minecraft.command.AbstractCommand;
import dk.lockfuglsang.minecraft.command.CompositeCommand;
import org.bukkit.command.CommandSender;
import us.talabrek.ultimateskyblock.async.JobManager;
import us.talabrek.ultimateskyblock.uSkyBlock;
import dk.lockfuglsang.minecraft.util.TimeUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import static dk.lockfuglsang.minecraft.po.I18nUtil.marktr;
import static dk.lockfuglsang.minecraft.po.I18nUtil.tr;
/**
* Command for reporting and controlling async jobs.
*/
public class JobsCommand extends CompositeCommand {
private final uSkyBlock plugin;
public JobsCommand(uSkyBlock plugin) {
super("jobs|j", "usb.admin.jobs", marktr("controls async jobs"));
this.plugin = plugin;
/*
add(new AbstractCommand("list|l", "usb.admin.jobs.list", "list all jobs") {
@Override
public boolean execute(CommandSender sender, String alias, Map<String, Object> data, String... args) {
return false;
}
});
*/
add(new AbstractCommand("stats|s", "usb.admin.jobs.stats", "show statistics") {
@Override
public boolean execute(CommandSender sender, String alias, Map<String, Object> data, String... args) {
StringBuilder sb = new StringBuilder();
sb.append(tr("\u00a79Job Statistics") + "\n");
sb.append(tr("\u00a77----------------") + "\n");
Map<String, JobManager.Stats> stats = JobManager.getStats();
List<String> jobs = new ArrayList<>(stats.keySet());
Collections.sort(jobs);
sb.append(String.format("\u00a77%-6s %-8s %-8s %-8s %-8s %-8s %-20s\n",
tr("#"), tr("ms/job"), tr("ms/tick"), tr("ticks"), tr("act"), tr("time"), tr("name")));
for (String jobName : jobs) {
JobManager.Stats stat = stats.get(jobName);
sb.append(String.format("\u00a77%6d %8s %8s %8d \u00a7c%8d \u00a77%8s \u00a79%-20s \n", stat.getJobs(),
TimeUtil.millisAsShort(Math.round(stat.getAvgMsActivePerJob())),
TimeUtil.millisAsShort(Math.round(stat.getAvgMsActivePerTick())),
stat.getTicks(),
stat.getRunningJobs(),
TimeUtil.millisAsShort(Math.round(stat.getAvgMsElapsedPerJob())),
tr(jobName)
));
}
sender.sendMessage(sb.toString().split("\n"));
return true;
}
});
/*
add(new AbstractCommand("report|r", "usb.admin.jobs.report", "dump report to file") {
@Override
public boolean execute(CommandSender sender, String alias, Map<String, Object> data, String... args) {
return false;
}
});
*/
}
}
| 0 | 0.716655 | 1 | 0.716655 | game-dev | MEDIA | 0.617574 | game-dev | 0.847586 | 1 | 0.847586 |
michalzalobny/creative-bay | 9,744 | src/containers/projects/FirstPerson/classes/utils/FirstPersonCamera.ts | import * as THREE from 'three';
import RAPIER from '@dimforge/rapier3d';
import { clamp } from 'three/src/math/MathUtils';
import { UpdateInfo } from 'utils/sharedTypes';
import { clampRange } from 'utils/functions/clamp';
import { isTouchDevice } from 'utils/functions/isTouchDevice';
import { Gun3D } from '../Components/Gun3D';
import { FirstPersonControls, Keys } from './FirstPersonControls';
interface Props {
camera: THREE.Camera;
}
const KEYS = {
w: 'KeyW',
s: 'KeyS',
a: 'KeyA',
d: 'KeyD',
arrowUp: 'ArrowUp',
arrowDown: 'ArrowDown',
arrowLeft: 'ArrowLeft',
arrowRight: 'ArrowRight',
};
export class FirstPersonCamera {
static cameraEase = 0.25;
_camera;
_rotation = new THREE.Quaternion();
_translation = new THREE.Vector3(0, 0, 0); //Starting position
_phi = 0;
_theta = 0;
_phiSpeed = 5 * 0.5;
_thetaSpeed = 5 * 0.5;
_moveSpeed = 0.2;
_stepSpeed = 1.9;
_stepHeight = 1.1;
_headBobActive = false;
_headBobTimer = 0;
_firstPersonControls;
_forwardVelocity = 0;
_strafeVelocity = 0;
_mouseSpeed = 0.76;
_domElement: HTMLElement;
_playerBody: RAPIER.RigidBody | null = null;
_gun3D: Gun3D | null = null;
_playerCollider: RAPIER.Collider | null = null;
_world: RAPIER.World | null = null;
_characterController: RAPIER.KinematicCharacterController | null = null;
_mouse = {
x: 0,
y: 0,
};
_infoDomEl: HTMLElement | null;
_boardDomEl: HTMLElement | null;
constructor(props: Props) {
this._camera = props.camera;
this._domElement = document.body;
this._firstPersonControls = new FirstPersonControls({
camera: this._camera,
domElement: this._domElement,
});
this._addEvents();
this._infoDomEl = document.querySelector('[data-first-peron="esc"]');
this._boardDomEl = document.querySelector('[data-first-peron="board"]');
}
setWorld(world: RAPIER.World) {
this._world = world;
this._useCharacterControls();
}
_useCharacterControls() {
if (!this._world) return;
this._characterController = this._world.createCharacterController(0.1);
this._characterController.enableAutostep(0.7, 0.3, true);
this._characterController.enableSnapToGround(0.7);
this._characterController.setMaxSlopeClimbAngle(Math.PI * 0.5);
}
//Updates camera and gun position
_updateCamera() {
this._camera.quaternion.copy(this._rotation);
this._gun3D?.quaternion.copy(this._rotation);
//Stick camera to the position of player
if (this._playerBody) {
const pos = this._playerBody.translation();
this._camera.position.set(pos.x, pos.y + 1.85 * 0.5, pos.z); //1.85 *0.5 is halth of the height of character
this._gun3D?.position.set(pos.x, pos.y + 1.85 * 0.5, pos.z);
}
// this._camera.position.y += Math.sin(this._headBobTimer) * this._stepHeight;
if (this._gun3D) {
this._gun3D.position.y += Math.sin(this._headBobTimer) * this._stepHeight * 0.02;
}
//test
// this._camera.position.set(-12 * 0, 8, -12 * 0);
// this._camera.lookAt(new THREE.Vector3(0, 0, 0));
}
_handleMouseMove = (e: THREE.Event) => {
const xh = e.dx * 0.0005 * this._mouseSpeed;
const yh = e.dy * 0.0005 * this._mouseSpeed;
//Used for sway
this._mouse.x = e.dx * 1;
this._mouse.y = e.dy * 1;
this._phi = this._phi + -xh * this._phiSpeed;
this._theta = clamp(
this._theta + -yh * this._thetaSpeed,
-Math.PI * 0.51, //0.51 to fix approximation issue
Math.PI * 0.51
);
};
_updateRotation() {
const qx = new THREE.Quaternion();
qx.setFromAxisAngle(new THREE.Vector3(0, 1, 0), this._phi);
const qz = new THREE.Quaternion();
qz.setFromAxisAngle(new THREE.Vector3(1, 0, 0), this._theta);
const q = new THREE.Quaternion();
q.multiply(qx);
q.multiply(qz);
this._rotation.copy(q);
}
_updateHeadBob(updateInfo: UpdateInfo) {
if (this._headBobActive) {
const wavelength = Math.PI;
const nextStep = 1 + Math.floor((this._headBobTimer + 0.000001) / wavelength);
const nextStepTime = nextStep * wavelength;
this._headBobTimer = Math.min(
this._headBobTimer + 0.15 * updateInfo.slowDownFactor * this._stepSpeed,
nextStepTime
);
if (this._headBobTimer == nextStepTime) {
this._headBobActive = false;
}
}
}
_handleKeyChange = (e: THREE.Event) => {
const keys = e.keys as Keys;
this._forwardVelocity =
(keys[KEYS.w] || keys[KEYS.arrowUp] ? 1 * this._moveSpeed : 0) +
(keys[KEYS.s] || keys[KEYS.arrowDown] ? -1 * this._moveSpeed : 0);
this._strafeVelocity =
(keys[KEYS.a] || keys[KEYS.arrowLeft] ? 1 * this._moveSpeed : 0) +
(keys[KEYS.d] || keys[KEYS.arrowRight] ? -1 * this._moveSpeed : 0);
};
_updateTranslation(updateInfo: UpdateInfo) {
const qx = new THREE.Quaternion();
qx.setFromAxisAngle(new THREE.Vector3(0, 1, 0), this._phi);
const forward = new THREE.Vector3(0, 0, -1);
forward.applyQuaternion(qx);
const left = new THREE.Vector3(-1, 0, 0);
left.applyQuaternion(qx);
forward.multiplyScalar(this._forwardVelocity * updateInfo.slowDownFactor);
left.multiplyScalar(this._strafeVelocity * updateInfo.slowDownFactor);
this._translation = forward.add(left);
if (this._forwardVelocity != 0 || this._strafeVelocity != 0) {
this._headBobActive = true;
}
}
setPlayerBody(body: RAPIER.RigidBody) {
this._playerBody = body;
}
setGun3D(obj: Gun3D) {
this._gun3D = obj;
}
setPlayerCollider(collider: RAPIER.Collider) {
this._playerCollider = collider;
}
update(updateInfo: UpdateInfo) {
this._updateGunSway(updateInfo);
this._updateRotation();
this._updateTranslation(updateInfo);
this._updateHeadBob(updateInfo);
this._updateCamera();
this._updateCharacter();
}
//https://www.youtube.com/watch?v=45ssV6CEgoU
_updateGunSway(updateInfo: UpdateInfo) {
if (!this._gun3D) return;
//Move sway
const inputX = -this._mouse.x;
const inputY = this._mouse.y;
const movementX = clampRange(
inputX * Gun3D.swayAmount,
-Gun3D.maxSwayAmount,
Gun3D.maxSwayAmount
);
const movementY = clampRange(
inputY * Gun3D.swayAmount,
-Gun3D.maxSwayAmount,
Gun3D.maxSwayAmount
);
const finalPosition = new THREE.Vector3(movementX, movementY, 0);
const localPosition = this._gun3D.getGunGroupPosition();
const gunPosition = localPosition.lerp(
finalPosition.add(Gun3D.startPosition),
Gun3D.smoothAmount * updateInfo.slowDownFactor
);
this._gun3D.setGunGroupPosition(gunPosition);
//Rotation
const tiltY = clampRange(
inputX * Gun3D.swayRotationAmount,
-Gun3D.maxSwayRotationAmount,
Gun3D.maxSwayRotationAmount
);
const tiltX = clampRange(
inputY * Gun3D.swayRotationAmount,
-Gun3D.maxSwayRotationAmount,
Gun3D.maxSwayRotationAmount
);
const finalRotation = new THREE.Quaternion();
finalRotation.setFromEuler(
new THREE.Euler(
this._gun3D.swayRotation.rotationX ? -tiltX : 0,
this._gun3D.swayRotation.rotationY ? tiltY : 0,
this._gun3D.swayRotation.rotationZ ? tiltY : 0
)
);
const localRotation = this._gun3D.getGunGroupRotation();
const gunRotation = localRotation.slerp(
finalRotation.multiply(Gun3D.startRotation),
Gun3D.smoothRotationAmount * updateInfo.slowDownFactor
);
this._gun3D.setGunGroupRotation(gunRotation);
this._mouse.x = 0;
this._mouse.y = 0;
}
_updateCharacter() {
if (!this._characterController || !this._playerCollider || !this._playerBody) return;
const speed = 0.1; //Docs value for Y
const movementDirection = {
x: this._translation.x, //Left
y: -speed, //Up
z: this._translation.z, //Forward
};
this._characterController.computeColliderMovement(this._playerCollider, movementDirection);
const movement = this._characterController.computedMovement();
const newPos = this._playerBody.translation();
newPos.x += movement.x;
newPos.y += movement.y;
newPos.z += movement.z;
this._playerBody.setNextKinematicTranslation(newPos);
}
_handleClick = () => {
if (isTouchDevice()) return;
this._requestLock();
};
_requestLock() {
if (this._domElement.ownerDocument.pointerLockElement === this._domElement) return;
this._domElement.requestPointerLock();
}
_handleLock = () => {
if (!this._infoDomEl || !this._boardDomEl) return;
this._infoDomEl.style.opacity = '1';
this._boardDomEl.style.opacity = '0';
};
_handleUnLock = () => {
if (!this._infoDomEl || !this._boardDomEl) return;
this._infoDomEl.style.opacity = '0';
this._boardDomEl.style.opacity = '0.8';
};
_addEvents() {
this._firstPersonControls.addEventListener('mousemove', this._handleMouseMove);
this._firstPersonControls.addEventListener('keychange', this._handleKeyChange);
this._firstPersonControls.addEventListener('lock', this._handleLock);
this._firstPersonControls.addEventListener('unlock', this._handleUnLock);
this._domElement.addEventListener('click', this._handleClick);
}
_removeEvents() {
this._firstPersonControls.removeEventListener('mousemove', this._handleMouseMove);
this._firstPersonControls.removeEventListener('keychange', this._handleKeyChange);
this._firstPersonControls.removeEventListener('lock', this._handleLock);
this._firstPersonControls.removeEventListener('unlock', this._handleUnLock);
this._domElement.removeEventListener('click', this._handleClick);
}
destroy() {
this._removeEvents();
this._firstPersonControls.destroy();
}
}
| 0 | 0.926993 | 1 | 0.926993 | game-dev | MEDIA | 0.890661 | game-dev | 0.985516 | 1 | 0.985516 |
PolarisSS13/Polaris | 3,333 | code/game/objects/structures/tank_dispenser.dm | #define TANK_DISPENSER_CAPACITY 10
/obj/structure/dispenser
name = "tank storage unit"
desc = "A simple yet bulky storage device for gas tanks. Has room for up to ten oxygen tanks, and ten phoron tanks."
icon = 'icons/obj/objects.dmi'
icon_state = "dispenser"
density = 1
anchored = 1.0
w_class = ITEMSIZE_HUGE
var/oxygentanks = TANK_DISPENSER_CAPACITY
var/phorontanks = TANK_DISPENSER_CAPACITY
/obj/structure/dispenser/oxygen
phorontanks = 0
/obj/structure/dispenser/phoron
oxygentanks = 0
/obj/structure/dispenser/Initialize()
. = ..()
for(var/i in 1 to oxygentanks)
new /obj/item/tank/oxygen(src)
for(var/i in 1 to phorontanks)
new /obj/item/tank/phoron(src)
update_icon()
/obj/structure/dispenser/update_icon()
cut_overlays()
switch(oxygentanks)
if(1 to 3) add_overlay("oxygen-[oxygentanks]")
if(4 to INFINITY) add_overlay("oxygen-4")
switch(phorontanks)
if(1 to 4) add_overlay("phoron-[phorontanks]")
if(5 to INFINITY) add_overlay("phoron-5")
/obj/structure/dispenser/attack_ai(mob/user)
// This looks silly, but robots also call attack_ai, and they're allowed physical state stuff.
if(user.Adjacent(src))
return attack_hand(user)
..()
/obj/structure/dispenser/attack_hand(mob/user)
tgui_interact(user)
/obj/structure/dispenser/tgui_state(mob/user)
return GLOB.tgui_physical_state
/obj/structure/dispenser/tgui_interact(mob/user, datum/tgui/ui)
ui = SStgui.try_update_ui(user, src, ui)
if(!ui)
ui = new(user, src, "TankDispenser", name)
ui.open()
/obj/structure/dispenser/tgui_data(mob/user)
var/list/data = list()
data["oxygen"] = oxygentanks
data["plasma"] = phorontanks
return data
/obj/structure/dispenser/attackby(obj/item/I, mob/user)
var/full
if(istype(I, /obj/item/tank/oxygen) || istype(I, /obj/item/tank/air) || istype(I, /obj/item/tank/anesthetic))
if(oxygentanks < TANK_DISPENSER_CAPACITY)
oxygentanks++
else
full = TRUE
else if(istype(I, /obj/item/tank/phoron))
if(phorontanks < TANK_DISPENSER_CAPACITY)
phorontanks++
else
full = TRUE
else if(I.is_wrench())
if(anchored)
to_chat(user, "<span class='notice'>You lean down and unwrench [src].</span>")
anchored = 0
else
to_chat(user, "<span class='notice'>You wrench [src] into place.</span>")
anchored = 1
return
else if(user.a_intent != I_HURT)
to_chat(user, "<span class='notice'>[I] does not fit into [src].</span>")
return
else
return ..()
if(full)
to_chat(user, "<span class='notice'>[src] can't hold any more of [I].</span>")
return
if(!user.unEquip(I, target = src))
return
to_chat(user, "<span class='notice'>You put [I] in [src].</span>")
update_icon()
/obj/structure/dispenser/tgui_act(action, params)
if(..())
return
switch(action)
if("plasma")
var/obj/item/tank/phoron/tank = locate() in src
if(tank && Adjacent(usr))
usr.put_in_hands(tank)
phorontanks--
. = TRUE
playsound(src, 'sound/items/drop/gascan.ogg', 100, 1, 1)
if("oxygen")
var/obj/item/tank/tank = null
for(var/obj/item/tank/T in src)
if(istype(T, /obj/item/tank/oxygen) || istype(T, /obj/item/tank/air) || istype(T, /obj/item/tank/anesthetic))
tank = T
break
if(tank && Adjacent(usr))
usr.put_in_hands(tank)
oxygentanks--
. = TRUE
playsound(src, 'sound/items/drop/gascan.ogg', 100, 1, 1)
update_icon() | 0 | 0.922686 | 1 | 0.922686 | game-dev | MEDIA | 0.931714 | game-dev | 0.818974 | 1 | 0.818974 |
oot-pc-port/oot-pc-port | 9,623 | asm/non_matchings/overlays/actors/ovl_En_In/func_80A79C78.s | glabel func_80A79C78
/* 00CC8 80A79C78 27BDFFA8 */ addiu $sp, $sp, 0xFFA8 ## $sp = FFFFFFA8
/* 00CCC 80A79C7C 3C0F80A8 */ lui $t7, %hi(D_80A7B990) ## $t7 = 80A80000
/* 00CD0 80A79C80 AFBF0024 */ sw $ra, 0x0024($sp)
/* 00CD4 80A79C84 AFB20020 */ sw $s2, 0x0020($sp)
/* 00CD8 80A79C88 AFB1001C */ sw $s1, 0x001C($sp)
/* 00CDC 80A79C8C AFB00018 */ sw $s0, 0x0018($sp)
/* 00CE0 80A79C90 25EFB990 */ addiu $t7, $t7, %lo(D_80A7B990) ## $t7 = 80A7B990
/* 00CE4 80A79C94 8DF90000 */ lw $t9, 0x0000($t7) ## 80A7B990
/* 00CE8 80A79C98 8CB11C44 */ lw $s1, 0x1C44($a1) ## 00001C44
/* 00CEC 80A79C9C 27AE0034 */ addiu $t6, $sp, 0x0034 ## $t6 = FFFFFFDC
/* 00CF0 80A79CA0 ADD90000 */ sw $t9, 0x0000($t6) ## FFFFFFDC
/* 00CF4 80A79CA4 95F90004 */ lhu $t9, 0x0004($t7) ## 80A7B994
/* 00CF8 80A79CA8 00808025 */ or $s0, $a0, $zero ## $s0 = 00000000
/* 00CFC 80A79CAC 00A09025 */ or $s2, $a1, $zero ## $s2 = 00000000
/* 00D00 80A79CB0 00A02025 */ or $a0, $a1, $zero ## $a0 = 00000000
/* 00D04 80A79CB4 0C03008C */ jal func_800C0230
/* 00D08 80A79CB8 A5D90004 */ sh $t9, 0x0004($t6) ## FFFFFFE0
/* 00D0C 80A79CBC A60201F0 */ sh $v0, 0x01F0($s0) ## 000001F0
/* 00D10 80A79CC0 02402025 */ or $a0, $s2, $zero ## $a0 = 00000000
/* 00D14 80A79CC4 00002825 */ or $a1, $zero, $zero ## $a1 = 00000000
/* 00D18 80A79CC8 0C0300C5 */ jal func_800C0314
/* 00D1C 80A79CCC 24060001 */ addiu $a2, $zero, 0x0001 ## $a2 = 00000001
/* 00D20 80A79CD0 02402025 */ or $a0, $s2, $zero ## $a0 = 00000000
/* 00D24 80A79CD4 860501F0 */ lh $a1, 0x01F0($s0) ## 000001F0
/* 00D28 80A79CD8 0C0300C5 */ jal func_800C0314
/* 00D2C 80A79CDC 24060007 */ addiu $a2, $zero, 0x0007 ## $a2 = 00000007
/* 00D30 80A79CE0 C6040024 */ lwc1 $f4, 0x0024($s0) ## 00000024
/* 00D34 80A79CE4 3C014270 */ lui $at, 0x4270 ## $at = 42700000
/* 00D38 80A79CE8 44814000 */ mtc1 $at, $f8 ## $f8 = 60.00
/* 00D3C 80A79CEC E7A40048 */ swc1 $f4, 0x0048($sp)
/* 00D40 80A79CF0 C6060028 */ lwc1 $f6, 0x0028($s0) ## 00000028
/* 00D44 80A79CF4 3C0141B0 */ lui $at, 0x41B0 ## $at = 41B00000
/* 00D48 80A79CF8 C7B20048 */ lwc1 $f18, 0x0048($sp)
/* 00D4C 80A79CFC 46083280 */ add.s $f10, $f6, $f8
/* 00D50 80A79D00 44813000 */ mtc1 $at, $f6 ## $f6 = 22.00
/* 00D54 80A79D04 3C014220 */ lui $at, 0x4220 ## $at = 42200000
/* 00D58 80A79D08 02402025 */ or $a0, $s2, $zero ## $a0 = 00000000
/* 00D5C 80A79D0C E7AA004C */ swc1 $f10, 0x004C($sp)
/* 00D60 80A79D10 C610002C */ lwc1 $f16, 0x002C($s0) ## 0000002C
/* 00D64 80A79D14 C7A4004C */ lwc1 $f4, 0x004C($sp)
/* 00D68 80A79D18 E7B2003C */ swc1 $f18, 0x003C($sp)
/* 00D6C 80A79D1C E7B00050 */ swc1 $f16, 0x0050($sp)
/* 00D70 80A79D20 C7AA0050 */ lwc1 $f10, 0x0050($sp)
/* 00D74 80A79D24 44818000 */ mtc1 $at, $f16 ## $f16 = 40.00
/* 00D78 80A79D28 46062201 */ sub.s $f8, $f4, $f6
/* 00D7C 80A79D2C 27A60048 */ addiu $a2, $sp, 0x0048 ## $a2 = FFFFFFF0
/* 00D80 80A79D30 27A7003C */ addiu $a3, $sp, 0x003C ## $a3 = FFFFFFE4
/* 00D84 80A79D34 46105480 */ add.s $f18, $f10, $f16
/* 00D88 80A79D38 E7A80040 */ swc1 $f8, 0x0040($sp)
/* 00D8C 80A79D3C E7B20044 */ swc1 $f18, 0x0044($sp)
/* 00D90 80A79D40 0C030136 */ jal func_800C04D8
/* 00D94 80A79D44 860501F0 */ lh $a1, 0x01F0($s0) ## 000001F0
/* 00D98 80A79D48 26040024 */ addiu $a0, $s0, 0x0024 ## $a0 = 00000024
/* 00D9C 80A79D4C AFA4002C */ sw $a0, 0x002C($sp)
/* 00DA0 80A79D50 0C01E01A */ jal Math_Vec3f_Yaw
/* 00DA4 80A79D54 27A5003C */ addiu $a1, $sp, 0x003C ## $a1 = FFFFFFE4
/* 00DA8 80A79D58 27A30034 */ addiu $v1, $sp, 0x0034 ## $v1 = FFFFFFDC
/* 00DAC 80A79D5C A60200B6 */ sh $v0, 0x00B6($s0) ## 000000B6
/* 00DB0 80A79D60 8C690000 */ lw $t1, 0x0000($v1) ## FFFFFFDC
/* 00DB4 80A79D64 02402025 */ or $a0, $s2, $zero ## $a0 = 00000000
/* 00DB8 80A79D68 24052025 */ addiu $a1, $zero, 0x2025 ## $a1 = 00002025
/* 00DBC 80A79D6C AA090310 */ swl $t1, 0x0310($s0) ## 00000310
/* 00DC0 80A79D70 BA090313 */ swr $t1, 0x0313($s0) ## 00000313
/* 00DC4 80A79D74 94690004 */ lhu $t1, 0x0004($v1) ## FFFFFFE0
/* 00DC8 80A79D78 00003025 */ or $a2, $zero, $zero ## $a2 = 00000000
/* 00DCC 80A79D7C A6090314 */ sh $t1, 0x0314($s0) ## 00000314
/* 00DD0 80A79D80 8C6B0000 */ lw $t3, 0x0000($v1) ## FFFFFFDC
/* 00DD4 80A79D84 AA0B0316 */ swl $t3, 0x0316($s0) ## 00000316
/* 00DD8 80A79D88 BA0B0319 */ swr $t3, 0x0319($s0) ## 00000319
/* 00DDC 80A79D8C 946B0004 */ lhu $t3, 0x0004($v1) ## FFFFFFE0
/* 00DE0 80A79D90 0C042DA0 */ jal func_8010B680
/* 00DE4 80A79D94 A60B031A */ sh $t3, 0x031A($s0) ## 0000031A
/* 00DE8 80A79D98 240C0001 */ addiu $t4, $zero, 0x0001 ## $t4 = 00000001
/* 00DEC 80A79D9C A60C0308 */ sh $t4, 0x0308($s0) ## 00000308
/* 00DF0 80A79DA0 8FAD002C */ lw $t5, 0x002C($sp)
/* 00DF4 80A79DA4 26320024 */ addiu $s2, $s1, 0x0024 ## $s2 = 00000024
/* 00DF8 80A79DA8 8DAF0000 */ lw $t7, 0x0000($t5) ## 00000000
/* 00DFC 80A79DAC AE4F0000 */ sw $t7, 0x0000($s2) ## 00000024
/* 00E00 80A79DB0 8DAE0004 */ lw $t6, 0x0004($t5) ## 00000004
/* 00E04 80A79DB4 AE4E0004 */ sw $t6, 0x0004($s2) ## 00000028
/* 00E08 80A79DB8 8DAF0008 */ lw $t7, 0x0008($t5) ## 00000008
/* 00E0C 80A79DBC AE4F0008 */ sw $t7, 0x0008($s2) ## 0000002C
/* 00E10 80A79DC0 0C01DE1C */ jal Math_Sins
## sins?
/* 00E14 80A79DC4 860400B6 */ lh $a0, 0x00B6($s0) ## 000000B6
/* 00E18 80A79DC8 3C0142C8 */ lui $at, 0x42C8 ## $at = 42C80000
/* 00E1C 80A79DCC 44813000 */ mtc1 $at, $f6 ## $f6 = 100.00
/* 00E20 80A79DD0 C6240024 */ lwc1 $f4, 0x0024($s1) ## 00000024
/* 00E24 80A79DD4 46003202 */ mul.s $f8, $f6, $f0
/* 00E28 80A79DD8 46082280 */ add.s $f10, $f4, $f8
/* 00E2C 80A79DDC E62A0024 */ swc1 $f10, 0x0024($s1) ## 00000024
/* 00E30 80A79DE0 0C01DE0D */ jal Math_Coss
## coss?
/* 00E34 80A79DE4 860400B6 */ lh $a0, 0x00B6($s0) ## 000000B6
/* 00E38 80A79DE8 3C0142C8 */ lui $at, 0x42C8 ## $at = 42C80000
/* 00E3C 80A79DEC 44819000 */ mtc1 $at, $f18 ## $f18 = 100.00
/* 00E40 80A79DF0 C630002C */ lwc1 $f16, 0x002C($s1) ## 0000002C
/* 00E44 80A79DF4 8E220440 */ lw $v0, 0x0440($s1) ## 00000440
/* 00E48 80A79DF8 46009182 */ mul.s $f6, $f18, $f0
/* 00E4C 80A79DFC 240A000A */ addiu $t2, $zero, 0x000A ## $t2 = 0000000A
/* 00E50 80A79E00 46068100 */ add.s $f4, $f16, $f6
/* 00E54 80A79E04 1040000A */ beq $v0, $zero, .L80A79E30
/* 00E58 80A79E08 E624002C */ swc1 $f4, 0x002C($s1) ## 0000002C
/* 00E5C 80A79E0C 8E590000 */ lw $t9, 0x0000($s2) ## 00000024
/* 00E60 80A79E10 2408000A */ addiu $t0, $zero, 0x000A ## $t0 = 0000000A
/* 00E64 80A79E14 AC590024 */ sw $t9, 0x0024($v0) ## 00000024
/* 00E68 80A79E18 8E580004 */ lw $t8, 0x0004($s2) ## 00000028
/* 00E6C 80A79E1C AC580028 */ sw $t8, 0x0028($v0) ## 00000028
/* 00E70 80A79E20 8E590008 */ lw $t9, 0x0008($s2) ## 0000002C
/* 00E74 80A79E24 AC59002C */ sw $t9, 0x002C($v0) ## 0000002C
/* 00E78 80A79E28 8E290440 */ lw $t1, 0x0440($s1) ## 00000440
/* 00E7C 80A79E2C A5280110 */ sh $t0, 0x0110($t1) ## 00000110
.L80A79E30:
/* 00E80 80A79E30 A62A0110 */ sh $t2, 0x0110($s1) ## 00000110
/* 00E84 80A79E34 8E0B0004 */ lw $t3, 0x0004($s0) ## 00000004
/* 00E88 80A79E38 2401FFFE */ addiu $at, $zero, 0xFFFE ## $at = FFFFFFFE
/* 00E8C 80A79E3C 24040020 */ addiu $a0, $zero, 0x0020 ## $a0 = 00000020
/* 00E90 80A79E40 01616024 */ and $t4, $t3, $at
/* 00E94 80A79E44 0C02CE10 */ jal func_800B3840 ## letterbox_target_addr
/* 00E98 80A79E48 AE0C0004 */ sw $t4, 0x0004($s0) ## 00000004
/* 00E9C 80A79E4C 0C020978 */ jal Interface_ChangeAlpha
/* 00EA0 80A79E50 24040002 */ addiu $a0, $zero, 0x0002 ## $a0 = 00000002
/* 00EA4 80A79E54 8FBF0024 */ lw $ra, 0x0024($sp)
/* 00EA8 80A79E58 8FB00018 */ lw $s0, 0x0018($sp)
/* 00EAC 80A79E5C 8FB1001C */ lw $s1, 0x001C($sp)
/* 00EB0 80A79E60 8FB20020 */ lw $s2, 0x0020($sp)
/* 00EB4 80A79E64 03E00008 */ jr $ra
/* 00EB8 80A79E68 27BD0058 */ addiu $sp, $sp, 0x0058 ## $sp = 00000000
| 0 | 0.74194 | 1 | 0.74194 | game-dev | MEDIA | 0.916832 | game-dev | 0.698646 | 1 | 0.698646 |
ItsGraphax/reddit-bonanza | 1,056 | src/tags/reddit.lua | local reddit_orange = {1.0, 0.337, 0, 1}
SMODS.Tag {
key = 'reddit',
atlas = 'reddit_tags',
pos = {x = 0, y = 0},
min_ante = 2,
loc_vars = function(self, info_queue)
info_queue[#info_queue+1] = G.P_CENTERS.p_reddit_bonanza_pack_mega1
end,
apply = function(self, tag, context)
if context.type == 'new_blind_choice' then
local lock = tag.ID
G.CONTROLLER.locks[lock] = true
tag:yep('+', reddit_orange, function()
local booster = SMODS.create_card { key = 'p_reddit_bonanza_pack_mega1', area = G.play }
booster.T.x = G.play.T.x + G.play.T.w / 2 - G.CARD_W * 1.27 / 2
booster.T.y = G.play.T.y + G.play.T.h / 2 - G.CARD_H * 1.27 / 2
booster.T.w = G.CARD_W * 1.27
booster.T.h = G.CARD_H * 1.27
booster.cost = 0
booster.from_tag = true
G.FUNCS.use_card({ config = { ref_table = booster } })
booster:start_materialize()
G.CONTROLLER.locks[lock] = nil
return true
end)
tag.triggered = true
return true
end
end
} | 0 | 0.983447 | 1 | 0.983447 | game-dev | MEDIA | 0.897295 | game-dev | 0.986358 | 1 | 0.986358 |
beyond-aion/aion-server | 1,547 | game-server/src/com/aionemu/gameserver/network/aion/clientpackets/CM_GROUP_LOOT.java | package com.aionemu.gameserver.network.aion.clientpackets;
import java.util.Set;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.network.aion.AionClientPacket;
import com.aionemu.gameserver.network.aion.AionConnection.State;
import com.aionemu.gameserver.services.drop.DropDistributionService;
/**
* @author Rhys2002
*/
public class CM_GROUP_LOOT extends AionClientPacket {
@SuppressWarnings("unused")
private int groupId;
private int index;
@SuppressWarnings("unused")
private int unk1;
private int itemId;
@SuppressWarnings("unused")
private int unk2;
@SuppressWarnings("unused")
private int unk3;
private int npcObjId;
private int distributionMode;
private int roll;
private long bid;
@SuppressWarnings("unused")
private int unk4;
@SuppressWarnings("unused")
private int unk5;
public CM_GROUP_LOOT(int opcode, Set<State> validStates) {
super(opcode, validStates);
}
@Override
protected void readImpl() {
groupId = readD();
index = readD();
unk1 = readD();
itemId = readD();
unk2 = readUC();
unk3 = readUC(); // 3.0
unk4 = readUC(); // 3.5
npcObjId = readD();
distributionMode = readUC();// 2: Roll 3: Bid
roll = readD();// 0: Never Rolled 1: Rolled
bid = readQ();// 0: No Bid else bid amount
}
@Override
protected void runImpl() {
Player player = getConnection().getActivePlayer();
if (player == null)
return;
DropDistributionService.getInstance().handleRollOrBid(player, distributionMode, roll, bid, itemId, npcObjId, index);
}
}
| 0 | 0.870575 | 1 | 0.870575 | game-dev | MEDIA | 0.698776 | game-dev | 0.774597 | 1 | 0.774597 |
CleanroomMC/Cleanroom | 5,087 | src/main/java/net/minecraftforge/client/model/MultiModelState.java | /*
* Minecraft Forge
* Copyright (c) 2016-2020.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.client.model;
import net.minecraftforge.common.model.IModelPart;
import net.minecraftforge.common.model.IModelState;
import net.minecraftforge.common.model.TRSRTransformation;
import org.apache.commons.lang3.tuple.Pair;
import com.google.common.base.Objects;
import java.util.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
public final class MultiModelState implements IModelState
{
private final ImmutableMap<MultiModelPart, ? extends IModelState> states;
public <M extends IModel, S extends IModelState> MultiModelState(ImmutableList<Pair<M, S>> states)
{
ImmutableMap.Builder<MultiModelPart, S> builder = ImmutableMap.builder();
for(int i = 0; i < states.size(); i++)
{
Pair<M, S> pair = states.get(i);
builder.put(new MultiModelPart(pair.getLeft(), i), pair.getRight());
}
this.states = builder.build();
}
public static IModelState getPartState(IModelState state, IModel model, int index)
{
if(state.apply(Optional.of(new MultiModelPart(model, index))).isPresent())
{
return new PartState(state, model, index);
}
return state;
}
@Override
public Optional<TRSRTransformation> apply(Optional<? extends IModelPart> part)
{
if(part.isPresent())
{
if(part.get() instanceof MultiModelPart)
{
MultiModelPart key = (MultiModelPart)part.get();
if(states.containsKey(key))
{
return Optional.of(states.get(key).apply(Optional.empty()).orElse(TRSRTransformation.identity()));
}
}
else if(part.get() instanceof PartPart)
{
PartPart partPart = (PartPart)part.get();
MultiModelPart key = new MultiModelPart(partPart.model, partPart.index);
if(states.containsKey(key))
{
return states.get(key).apply(partPart.part);
}
}
}
return Optional.empty();
}
private static class PartState implements IModelState
{
private final IModelState state;
private final IModel model;
private final int index;
public PartState(IModelState state, IModel model, int index)
{
this.state = state;
this.model = model;
this.index = index;
}
@Override
public Optional<TRSRTransformation> apply(Optional<? extends IModelPart> part)
{
Optional<TRSRTransformation> normal = state.apply(part);
Optional<TRSRTransformation> multi = state.apply(Optional.of(new PartPart(model, index, part)));
if(normal.isPresent() && multi.isPresent())
{
return Optional.of(normal.get().compose(multi.get()));
}
if (normal.isPresent()) {
return normal;
}
return multi;
}
}
private static class MultiModelPart implements IModelPart
{
private final IModel model;
private final int index;
public MultiModelPart(IModel model, int index)
{
this.model = model;
this.index = index;
}
@Override
public int hashCode()
{
return Objects.hashCode(model, index);
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MultiModelPart other = (MultiModelPart)obj;
return Objects.equal(this.model, other.model) && this.index == other.index;
}
}
private static class PartPart implements IModelPart
{
private final IModel model;
private final int index;
private final Optional<? extends IModelPart> part;
public PartPart(IModel model, int index, Optional<? extends IModelPart> part)
{
this.model = model;
this.index = index;
this.part = part;
}
}
}
| 0 | 0.881824 | 1 | 0.881824 | game-dev | MEDIA | 0.374965 | game-dev | 0.878803 | 1 | 0.878803 |
DoqueDB/doquedb | 14,024 | una/1.0/test/src/nlpconcept.cpp | // -*-Mode: C++; tab-width: 4;-*-
// vi:set ts=4 sw=4:
//
// 形態素解析+正規化機能テストプログラム(NlpAnalyzer)
//
// Copyright (c) 2003, 2022, 2023 Ricoh Company, Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include <stdio.h>
#include <iostream>
#include <iomanip>
#include "ModOstrStream.h"
#include "ModUnicodeString.h"
#include "ModNLP.h"
#include "ModTime.h"
#include "ModTimeSpan.h"
#include "ModLanguageSet.h"
#if 0
#include "Keyword.h"
#endif
using namespace std;
using namespace UNA;
const ModSize MAX_DAT_LEN = 655360;
const ModSize MAX_LANGUAGE_NUM = 9;
const ModUnicodeString NLP_PATH("../unadic/");
const ModUnicodeChar SEPARATOR = 0x0a; // \n
const ModUnicodeChar EXP_SEP = 0x2c; // ,
static ModTimeSpan TOTAL_TIME;
void print_time()
{
cout << "Total Time: "
<< TOTAL_TIME.getDays() << " "
<< TOTAL_TIME.getHours() << " "
<< TOTAL_TIME.getMinutes() << " "
<< TOTAL_TIME.getSeconds() << "."
<< setw(3) << setfill('0')
<< TOTAL_TIME.getMilliSeconds()
<< endl;
return;
}
ModBoolean
get_target(FILE*& file, ModUnicodeString* target,
ModKanjiCode::KanjiCodeType code, ModBoolean do_line)
{
char buf[MAX_DAT_LEN];
memset( buf, 0, MAX_DAT_LEN );
*target = ModUnicodeString("");
while (fgets(buf, MAX_DAT_LEN, file))
{
if (do_line == ModTrue)
{
*target = ModUnicodeString( buf, code );
ModUnicodeChar* r = target->rsearch('\n');
if (r != 0)
{
// 末尾の改行を削除
target->truncate(r);
}
return ModTrue;
}
else
{
if ( target->getLength() == 0 )
{
*target = ModUnicodeString( buf, code );
}
else if (buf[0]=='\n')
//else if (buf[0]==0x0D || buf[0]==0x0A)
{
ModUnicodeChar* r = target->rsearch('\n');
if(r!=0)
{
// 末尾の改行を削除
target->truncate(r);
}
return ModTrue;
}
else
{
ModUnicodeString line( buf, code );
*target += line;
}
}
memset( buf, 0, MAX_DAT_LEN );
}
if ( target->getLength() != 0 )
{
if ( target->at(target->getLength()-1) == 0x0A )
{
ModUnicodeChar* r = target->rsearch('\n');
if(r!=0)
{
// 末尾の改行を削除
target->truncate(r);
}
}
return ModTrue;
}
return ModFalse;
}
void print_help() {
cerr << "Usage: "
<< "[-h] "
<< "[-r DIR] "
<< "[-i FILE] "
<< "[-o FILE] "
<< "[-l] "
<< "[-w maxWordLength] "
<< "[-p] "
<< "[-x] "
<< "[-d] "
<< "[-t] "
<< "[-s1 CHAR] "
<< "[-S1 HEX] "
<< "[-s2 CHAR] "
<< "[-S2 HEX] "
<< "[-m MODE] "
<< "[-U] "
<< "[-X] " << endl
<< "\t-h : このメッセージを表示" << endl
<< "\t-r DIR : 辞書ディレクトリ(デフォルトは../unadic)" << endl
<< "\t-m MODE : 下位構造展開(MODE=1,2)/ステミング実施(MODE=1,3)" << endl
<< "\t-U MODE : mode of intializing resource ( MODE = 0,1,2,3 )" << endl
<< "\t-w WDLEN : 最大単語長" << endl
<< "\t-i FILE : 入力ファイル(デフォルトは標準入力)" << endl
<< "\t-o FILE : 出力ファイル(デフォルトは標準出力)" << endl
<< "\t-L : 言語指定 en/ja+en/es のように複数指定可能" << endl
<< "\t-c CODE : 入出力文字コード(デフォルトはutf8)" << endl
<< "\t euc" << endl
<< "\t utf8" << endl
<< "\t shiftJis" << endl
<< "\t-l : 1行ずつ処理(デフォルトは空行で区切る)" << endl
<< "\t-p : 原文を表示" << endl
<< "\t-P KEY VAL: パラメータ(キー文字 値文字)をセット" << endl
<< "\t-d : 詳細情報を表示(区切りはデフォルト)" << endl
<< "\t-s1 CHAR : 形態素区切り(デフォルトは改行)" << endl
<< "\t-S1 HEX : 形態素区切り(デフォルトは0x0a)" << endl
<< "\t-s2 CHAR : 展開表記区切り(デフォルトはコンマ)" << endl
<< "\t-S2 HEX : 展開表記区切り(デフォルトは0x2c)" << endl
<< "\t-t : 関数実行時間を測定" << endl
<< "\t-X : エラーテスト(ModException以外でFAILEDを出力)" << endl
<< "\t-v : ベクター型結果取得 " << endl
<< "\t-npc : 名詞句コスト取得型関数による名詞句抽出 " << endl;
return;
}
int main(int ac, char** av)
{
ModOs::Process::setEncodingType(ModKanjiCode::literalCode);
ModMemoryPool::setTotalLimit(256*1024);
ModTime t0;
ModTime t1;
FILE* fin = stdin;
FILE* fout = stdout;
ModUnicodeString nlp_path(NLP_PATH);
ModLanguageSet nlp_lang[MAX_LANGUAGE_NUM];
nlp_lang[0] = ModUnicodeString("ja+en");
ModSize nlp_lang_num=1;
int normMode(1);
ModUnicodeChar sep(SEPARATOR);
ModUnicodeChar exp_sep(EXP_SEP);
ModBoolean do_line(ModFalse);
ModBoolean print_input(ModFalse);
ModBoolean print_detail(ModFalse);
ModBoolean get_time(ModFalse);
ModBoolean get_vector(ModFalse);
ModBoolean rv;
ModSize maxWordLength=0;
ModBoolean npCostMode(ModFalse);
ModBoolean test_error(ModFalse);
ModMap<ModUnicodeString, ModUnicodeString, ModLess<ModUnicodeString> > params;
ModKanjiCode::KanjiCodeType io_code = ModKanjiCode::utf8;
for (int i = 1; i < ac; i++) {
if (strncmp(av[i], "-h", 2) == 0) {
print_help();
return 0;
}
if (strncmp(av[i], "-r", 2) == 0) { // データディレクトリ
nlp_path = av[++i];
nlp_path += "/";
} else if (strncmp(av[i], "-m", 2) == 0) { // モード指定
normMode = atoi(av[++i]);
} else if (strncmp(av[i], "-w", 2) == 0) { // モード指定
maxWordLength = atoi(av[++i]);
} else if (strncmp(av[i], "-i", 2) == 0) { // 入力ファイル
fin = fopen(av[++i], "rb");
} else if (strncmp(av[i], "-o", 2) == 0) { // 出力ファイル
fout = fopen(av[++i], "wb");
} else if (strncmp(av[i], "-L", 2) == 0) { // 言語
i++;
int st=0;
nlp_lang_num=0;
for ( int ed=0;;++ed){ // 複数言語指定の解析
if ( av[i][ed]=='/' ||av[i][ed]==0){
nlp_lang[nlp_lang_num]=ModUnicodeString((av[i]+st),(ed-st));
nlp_lang_num++;
if ( nlp_lang_num>=MAX_LANGUAGE_NUM){
break;
}
st = ed+1;
if ( av[i][ed]==0)
break;
}
}
} else if (strncmp(av[i], "-c", 2) == 0) { // 入出力文字コード
if (strcmp(av[++i], "euc") == 0) {
io_code = ModKanjiCode::euc;
} else if (strcmp(av[i], "shiftJis") == 0) {
io_code = ModKanjiCode::shiftJis;
} else if (strcmp(av[i], "utf8") == 0) { // デフォルト
;
} else {
cerr << "ERROR: unexpected char code" << endl;
exit(1);
}
} else if (strncmp(av[i], "-l", 2) == 0) {
do_line = ModTrue;
} else if (strncmp(av[i], "-p", 2) == 0) {
print_input = ModTrue;
} else if (strncmp(av[i], "-P", 2) == 0) { // string param
params.insert(av[i+1], av[i+2]);
i+=2;
} else if (strncmp(av[i], "-d", 2) == 0) {
print_detail = ModTrue;
sep = SEPARATOR;
exp_sep = EXP_SEP;
} else if (strncmp(av[i], "-s1", 3) == 0) {
if (print_detail == ModFalse) {
sep = ModUnicodeChar(av[++i][0]);
}
} else if (strncmp(av[i], "-S1", 3) == 0) {
if (print_detail == ModFalse) {
sep = ModUnicodeChar(strtol(av[++i], 0, 16));
}
} else if (strncmp(av[i], "-s2", 3) == 0) {
if (print_detail == ModFalse) {
exp_sep = ModUnicodeChar(av[++i][0]);
}
} else if (strncmp(av[i], "-S2", 3) == 0) {
if (print_detail == ModFalse) {
exp_sep = ModUnicodeChar(strtol(av[++i], 0, 16));
}
} else if (strncmp(av[i], "-t", 2) == 0) {
get_time = ModTrue;
} else if (strncmp(av[i], "-X", 2) == 0) {
test_error = ModTrue;
} else if (strncmp(av[i], "-npc", 4) == 0) {
npCostMode = ModTrue;
} else if (strncmp(av[i], "-v", 2) == 0) {
get_vector = ModTrue;
} else {
cerr << "ERROR: unexpected parameter " << av[i] << endl;
exit(1);
}
}
if (!fin) {
cerr << "ERROR: input file not opened." << endl;
exit(1);
}
if (!fout) {
cerr << "ERROR: output file not opened." << endl;
exit(1);
}
ModUnicodeString cstrMaxWordLength;
ModUnicodeString cstrStemming;
ModUnicodeString cstrCompoundDiv;
ModUnicodeString cstrCarriageRet;
try {
ModMemoryPool::initialize(ModSizeMax >> 10);
ModSize currentLang = 0;
ModLanguageSet language = nlp_lang[currentLang];
ModNlpResource* rr = new ModNlpResource();
rr->load(nlp_path,ModFalse);
UNA::ModNlpAnalyzer* nlp = new UNA::ModNlpAnalyzer();
nlp->setResource(rr);
char czMaxWordLength[10];
sprintf(czMaxWordLength,"%d",maxWordLength);
cstrMaxWordLength = ModUnicodeString(czMaxWordLength);
params.insert("maxwordlen",cstrMaxWordLength);
switch (normMode)
{
case 0: // ModNlpNormOnly
cstrStemming = "false";
cstrCompoundDiv = "false";
cstrCarriageRet = "false";
break;
case 1: // ModNlpNormStemDiv;
cstrStemming = "true";
cstrCompoundDiv = "true";
cstrCarriageRet = "false";
break;
case 2: // ModNlpNormDiv;
cstrStemming = "false";
cstrCompoundDiv = "true";
cstrCarriageRet = "false";
break;
case 3: // ModNlpNormStem;
cstrStemming = "true";
cstrCompoundDiv = "false";
cstrCarriageRet = "false";
break;
case 4: // ModNlpNormRet;
cstrStemming = "false";
cstrCompoundDiv = "false";
cstrCarriageRet = "true";
break;
case 5: // ModNlpNormRetStemDiv;
cstrStemming = "true";
cstrCompoundDiv = "true";
cstrCarriageRet = "true";
break;
case 6: // ModNlpNormRetDiv;
cstrStemming = "false";
cstrCompoundDiv = "true";
cstrCarriageRet = "true";
break;
case 7: // ModNlpNormRetStem;
cstrStemming = "true";
cstrCompoundDiv = "false";
cstrCarriageRet = "true";
break;
}
params.insert("stem", cstrStemming);
params.insert("compound", cstrCompoundDiv);
params.insert("carriage", cstrCarriageRet);
ModUnicodeString target;
TOTAL_TIME = 0;
while (get_target(fin, &target, io_code, do_line)) {
// 入力中のU+FFF0, U+FFF1をそれぞれサロゲートペア前半, 後半の断片で置き換える
target.replace(0xfff0, 0xd800);
target.replace(0xfff1, 0xdc00);
nlp->prepare(params);
nlp->set(target, nlp_lang[currentLang]);
currentLang = (currentLang+1)%nlp_lang_num;
if (print_input == ModTrue) {
fputs(target.getString(io_code), fout);
fputc(0x0a, fout);
}
int num(0);
while (1)
{
ModUnicodeString original;
ModUnicodeString normalized;
ModVector<ModUnicodeString> normVector;
normVector.clear();
ModVector<ModUnicodeString> orgVector;
orgVector.clear();
ModVector<int> posVector;
posVector.clear();
double npCost;
t0 = ModTime::getCurrentTime();
if(npCostMode == ModTrue)
{
if( get_vector == ModTrue )
{
rv = nlp->getConcept( normalized,
original,
npCost,
normVector,
orgVector,
posVector);
}
else
{
rv = nlp->getConcept( normalized,
original,
npCost);
}
}
else
{
rv = nlp->getConcept( original,
normVector,
orgVector,
posVector);
}
t1 = ModTime::getCurrentTime();
TOTAL_TIME = TOTAL_TIME + (t1-t0);
if ( rv != ModTrue){
break;
}
++ num;
if ( get_vector == ModTrue )
{
ModSize i = 0;
ModSize len = orgVector.getSize();
for( i = 0; i < len; i++ )
//オリジナル---中日: "私は男ッス" 以外: "I AM A MAN "
{
fprintf(fout,"%s",orgVector[i].getString(io_code));
if( nlp_lang[currentLang] != ModLanguageSet("ja")
&& nlp_lang[currentLang].round() != ModLanguageSet("zh") )
{
fprintf(fout," ");
}
}
fprintf(fout," : ");
if (normVector.getSize()==0)
//normがないのでオリジナルで代用
//(getNormMessageから呼ばれるMorph.cppのgetNormがこうなっている)
{
for( i = 0; i < orgVector.getSize(); i++ )
//オリジナル---中日: "私/は/男/ッス/" 以外: "I/AM/A/MAN/"
{
fprintf(fout,"%s/",orgVector[i].getString(io_code));
}
}
else
{
for( i = 0; i < normVector.getSize(); i++ )
//正規化---中日: "私/は/男/ツス/" 以外: "i/am/a/man/"
{
fprintf(fout,"%s/",normVector[i].getString(io_code));
}
}
// 名詞句コストの出力
if(npCostMode == ModTrue)
{
fprintf(fout,", %f",npCost);
}
fprintf(fout,"\n");
}
else
{
if (sep != '\n' || num > 1) {
if(npCostMode == ModFalse)
{
fputc(sep, fout);
}
}
if (print_detail == ModTrue) {
fprintf(fout, "%d", num);
fputc(0x20, fout);
}
fputs(original.getString(io_code), fout);
// 名詞句コストの出力
if(npCostMode == ModTrue)
{
fprintf(fout,":");
fputs(normalized.getString(io_code), fout);
fprintf(fout,", %f",npCost);
}
fprintf(fout,"\n");
if(npCostMode == ModFalse)
{
int iVecSize = orgVector.getSize();//popFrontするので最初に取得
for( int i = 0; i < iVecSize; i++ )
{
ModUnicodeString norm;
ModUnicodeString org;
int pos;
norm = normVector.getFront();
normVector.popFront();
org = orgVector.getFront();
orgVector.popFront();
pos = posVector.getFront();
posVector.popFront();
fprintf(fout,"(%d) ", i+1);
fputs(norm.getString(io_code), fout);
fputc(':', fout);
fputs(org.getString(io_code), fout);
fprintf(fout," %d\n", pos);
}
}
}
}
if (get_vector != ModTrue || num != 0)
{
fputc(sep, fout);
fputc(0x0a, fout);
if (do_line == ModFalse && sep != '\n')
{
fputc(0x0a, fout);
}
}
target.clear();
}
nlp->releaseResource();
delete nlp,nlp=0;
rr->unload();
delete rr,rr=0;
if (fin) fclose(fin);
if (fout) fclose(fout);
} catch (ModException& e) {
ModErrorMessage << "ModException!: " << e << ModEndl;
cout << "ModException!: "
<< e.getErrorModule() << " "
<< e.getErrorNumber() << " "
<< e.getErrorLevel() << "."
<< endl;
exit(1);
} catch (...) {
ModErrorMessage << "Unexpected exception!" << ModEndl;
if (test_error == ModTrue) {
cout << "FAILED" << endl;
}
exit(1);
}
if (test_error == ModTrue) {
cout << "FAILED" << endl;
}
if ( get_time == ModTrue){
print_time();
}
return 0;
}
| 0 | 0.868601 | 1 | 0.868601 | game-dev | MEDIA | 0.50986 | game-dev | 0.950463 | 1 | 0.950463 |
RobertSkalko/Age-of-Exile | 4,428 | src/main/java/com/robertx22/age_of_exile/player_skills/crafting_inv/ProfCraftContainer.java | package com.robertx22.age_of_exile.player_skills.crafting_inv;
import com.robertx22.age_of_exile.mmorpg.registers.common.SlashContainers;
import com.robertx22.age_of_exile.player_skills.ingredient.ProfCraftingRecipe;
import com.robertx22.age_of_exile.player_skills.ingredient.items.CraftToolItem;
import com.robertx22.age_of_exile.saveclasses.player_skills.PlayerSkillEnum;
import com.robertx22.age_of_exile.uncommon.datasaving.StackSaving;
import com.robertx22.age_of_exile.vanilla_mc.blocks.BaseTileContainer;
import com.robertx22.library_of_exile.main.Packets;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.CraftingInventory;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Inventory;
import net.minecraft.inventory.container.Slot;
import net.minecraft.item.ItemStack;
import net.minecraft.network.PacketBuffer;
public class ProfCraftContainer extends BaseTileContainer {
CraftingInventory craftInv; // craft inv allows to tell container when its changed
Inventory resultInv;
PlayerEntity player;
PlayerSkillEnum skill;
public ProfCraftContainer(int syncid, PlayerInventory playerinv, PacketBuffer buf) {
this(playerinv.player.getItemInHand(playerinv.player.swingingArm), syncid, playerinv);
}
public ProfCraftContainer(ItemStack tool, int id, PlayerInventory invPlayer) {
super(6, SlashContainers.PROF_CRAFTING.get(), id, invPlayer);
try {
if (tool.getItem() instanceof CraftToolItem) {
CraftToolItem t = (CraftToolItem) tool.getItem();
skill = t.skill;
}
if (skill == null) {
this.removed(invPlayer.player);
return;
}
this.player = invPlayer.player;
this.craftInv = new CraftingInventory(this, 3, 2);
this.resultInv = new Inventory(1);
int num = 0;
for (int x = 0; x < 3; ++x) {
for (int y = 0; y < 2; ++y) {
int xpos = 113 + x * 18;
int ypos = 11 + (y) * 18;
this.addSlot(new IngredientSlot(skill, craftInv, num, xpos, ypos));
num++;
}
}
addSlot(new ProfCraftResultSlot(player, craftInv, resultInv, 0, 133, 75));
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void slotsChanged(IInventory inv) {
if (!player.level.isClientSide) {
ProfCraftResult result = ProfCraftingRecipe.canCraft(player, craftInv, resultInv, skill);
if (result.reason != null) {
Packets.sendToClient(player, new FailReasonPacket(result.reason.locName()));
}
if (result.canCraft) {
ItemStack resultstack = ProfCraftingRecipe.craftResult(craftInv, resultInv, skill);
this.resultInv.setItem(0, resultstack);
} else {
this.resultInv.setItem(0, ItemStack.EMPTY);
}
}
super.slotsChanged(inv);
}
@Override
public ItemStack quickMoveStack(PlayerEntity playerIn, int index) {
return ItemStack.EMPTY;
}
@Override
public void removed(PlayerEntity p) {
super.removed(p);
this.clearContainer(p, p.level, craftInv);
this.resultInv.setItem(0, ItemStack.EMPTY);
}
@Override
public boolean stillValid(PlayerEntity player) {
return true;
}
private class IngredientSlot extends Slot {
PlayerSkillEnum skill;
public IngredientSlot(PlayerSkillEnum skill, CraftingInventory inventory, int index, int x, int y) {
super(inventory, index, x, y);
this.skill = skill;
}
@Override
public boolean mayPickup(PlayerEntity player) {
return true;
}
@Override
public boolean mayPlace(ItemStack stack) {
if (skill.isGearCraftingProf()) {
if (skill.gearMatchesProfession(stack.getItem())) {
return true;
}
}
return StackSaving.INGREDIENTS.has(stack) && StackSaving.INGREDIENTS.loadFrom(stack)
.getIngredient()
.isAllowedInProfession(skill.id);
}
}
} | 0 | 0.918251 | 1 | 0.918251 | game-dev | MEDIA | 0.996592 | game-dev | 0.966008 | 1 | 0.966008 |
vlad250906/Create-UfoPort | 4,368 | modules/create/src/main/java/com/simibubi/create/infrastructure/data/CreateDatagen.java | package com.simibubi.create.infrastructure.data;
import java.util.Map.Entry;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.simibubi.create.AllSoundEvents;
import com.simibubi.create.Create;
import com.simibubi.create.compat.archEx.ArchExCompat;
import com.simibubi.create.foundation.advancement.AllAdvancements;
import com.simibubi.create.foundation.data.DamageTypeTagGen;
import com.simibubi.create.foundation.data.TagLangGen;
import com.simibubi.create.foundation.data.recipe.MechanicalCraftingRecipeGen;
import com.simibubi.create.foundation.data.recipe.ProcessingRecipeGen;
import com.simibubi.create.foundation.data.recipe.SequencedAssemblyRecipeGen;
import com.simibubi.create.foundation.data.recipe.StandardRecipeGen;
import com.simibubi.create.foundation.ponder.PonderLocalization;
import com.simibubi.create.foundation.utility.FilesHelper;
import com.simibubi.create.infrastructure.ponder.AllPonderTags;
import com.simibubi.create.infrastructure.ponder.GeneralText;
import com.simibubi.create.infrastructure.ponder.PonderIndex;
import com.simibubi.create.infrastructure.ponder.SharedText;
import com.tterrag.registrate.providers.ProviderType;
import io.github.fabricators_of_create.porting_lib_ufo.data.ExistingFileHelper;
import net.fabricmc.fabric.api.datagen.v1.FabricDataOutput;
import net.minecraft.core.HolderLookup;
import net.fabricmc.fabric.api.datagen.v1.DataGeneratorEntrypoint;
import net.fabricmc.fabric.api.datagen.v1.FabricDataGenerator;
import net.minecraft.core.RegistrySetBuilder;
import net.minecraft.data.PackOutput;
public class CreateDatagen implements DataGeneratorEntrypoint {
@Override
public void onInitializeDataGenerator(FabricDataGenerator generator) {
ExistingFileHelper helper = ExistingFileHelper.withResourcesFromArg();
FabricDataGenerator.Pack pack = generator.createPack();
Create.REGISTRATE.setupDatagen(pack, helper);
gatherData(pack, helper);
}
public static void gatherData(FabricDataGenerator.Pack pack, ExistingFileHelper existingFileHelper) {
addExtraRegistrateData();
// fabric: tag lang
TagLangGen.datagen();
// fabric: archex compat
ArchExCompat.init(pack);
// fabric: pretty much redone, make sure all providers make it through merges
pack.addProvider(AllSoundEvents::provider);
pack.addProvider(GeneratedEntriesProvider::new);
pack.addProvider(CreateRecipeSerializerTagsProvider::new);
pack.addProvider(DamageTypeTagGen::new);
pack.addProvider(AllAdvancements::new);
pack.addProvider(StandardRecipeGen::new);
pack.addProvider(MechanicalCraftingRecipeGen::new);
pack.addProvider(SequencedAssemblyRecipeGen::new);
pack.addProvider(ProcessingRecipeGen::registerAll);
}
@Override
public void buildRegistry(RegistrySetBuilder registryBuilder) {
GeneratedEntriesProvider.addBootstraps(registryBuilder);
}
private static void addExtraRegistrateData() {
CreateRegistrateTags.addGenerators();
Create.REGISTRATE.addDataGenerator(ProviderType.LANG, provider -> {
BiConsumer<String, String> langConsumer = provider::add;
provideDefaultLang("interface", langConsumer);
provideDefaultLang("tooltips", langConsumer);
AllAdvancements.provideLang(langConsumer);
AllSoundEvents.provideLang(langConsumer);
providePonderLang(langConsumer);
});
}
private static void provideDefaultLang(String fileName, BiConsumer<String, String> consumer) {
String path = "assets/create/lang/default/" + fileName + ".json";
JsonElement jsonElement = FilesHelper.loadJsonResource(path);
if (jsonElement == null) {
throw new IllegalStateException(String.format("Could not find default lang file: %s", path));
}
JsonObject jsonObject = jsonElement.getAsJsonObject();
for (Entry<String, JsonElement> entry : jsonObject.entrySet()) {
String key = entry.getKey();
String value = entry.getValue().getAsString();
consumer.accept(key, value);
}
}
private static void providePonderLang(BiConsumer<String, String> consumer) {
// Register these since FMLClientSetupEvent does not run during datagen
AllPonderTags.register();
PonderIndex.register();
SharedText.gatherText();
PonderLocalization.generateSceneLang();
GeneralText.provideLang(consumer);
PonderLocalization.provideLang(Create.ID, consumer);
}
}
| 0 | 0.944353 | 1 | 0.944353 | game-dev | MEDIA | 0.963744 | game-dev | 0.937614 | 1 | 0.937614 |
s0bvi/goldsvet-opensource | 44,713 | casino/app/Games/JumanjiNET/SlotSettings.php | <?php
namespace VanguardLTE\Games\JumanjiNET
{
class SlotSettings
{
public $playerId = null;
public $splitScreen = null;
public $reelStrip1 = null;
public $reelStrip2 = null;
public $reelStrip3 = null;
public $reelStrip4 = null;
public $reelStrip5 = null;
public $reelStrip6 = null;
public $reelStripBonus1 = null;
public $reelStripBonus2 = null;
public $reelStripBonus3 = null;
public $reelStripBonus4 = null;
public $reelStripBonus5 = null;
public $reelStripBonus6 = null;
public $slotId = '';
public $slotDBId = '';
public $Line = null;
public $scaleMode = null;
public $numFloat = null;
public $gameLine = null;
public $Bet = null;
public $isBonusStart = null;
public $Balance = null;
public $SymbolGame = null;
public $GambleType = null;
public $lastEvent = null;
public $Jackpots = [];
public $keyController = null;
public $slotViewState = null;
public $hideButtons = null;
public $slotReelsConfig = null;
public $slotFreeCount = null;
public $slotFreeMpl = null;
public $slotWildMpl = null;
public $slotExitUrl = null;
public $slotBonus = null;
public $slotBonusType = null;
public $slotScatterType = null;
public $slotGamble = null;
public $Paytable = [];
public $slotSounds = [];
public $jpgs = null;
private $Bank = null;
private $Percent = null;
private $WinLine = null;
private $WinGamble = null;
private $Bonus = null;
private $shop_id = null;
public $currency = null;
public $user = null;
public $game = null;
public $shop = null;
public $jpgPercentZero = false;
public $count_balance = null;
public function __construct($sid, $playerId)
{
$this->slotId = $sid;
$this->playerId = $playerId;
$user = \VanguardLTE\User::lockForUpdate()->find($this->playerId);
$this->user = $user;
$this->shop_id = $user->shop_id;
$gamebank = \VanguardLTE\GameBank::where(['shop_id' => $this->shop_id])->lockForUpdate()->get();
$game = \VanguardLTE\Game::where([
'name' => $this->slotId,
'shop_id' => $this->shop_id
])->lockForUpdate()->first();
$this->shop = \VanguardLTE\Shop::find($this->shop_id);
$this->game = $game;
$this->MaxWin = $this->shop->max_win;
$this->increaseRTP = 1;
$this->CurrentDenom = $this->game->denomination;
$this->scaleMode = 0;
$this->numFloat = 0;
$this->Paytable['SYM_0'] = [
0,
0,
0,
0,
0,
0
];
$this->Paytable['SYM_1'] = [
0,
0,
0,
0,
0,
0
];
$this->Paytable['SYM_2'] = [
0,
0,
0,
0,
0,
0
];
$this->Paytable['SYM_3'] = [
0,
0,
0,
6,
20,
140
];
$this->Paytable['SYM_4'] = [
0,
0,
0,
5,
15,
50
];
$this->Paytable['SYM_5'] = [
0,
0,
0,
4,
10,
30
];
$this->Paytable['SYM_6'] = [
0,
0,
0,
3,
8,
25
];
$this->Paytable['SYM_7'] = [
0,
0,
0,
2,
4,
10
];
$this->Paytable['SYM_8'] = [
0,
0,
0,
2,
4,
9
];
$this->Paytable['SYM_9'] = [
0,
0,
0,
2,
3,
8
];
$this->Paytable['SYM_10'] = [
0,
0,
0,
2,
3,
7
];
$reel = new GameReel();
foreach( [
'reelStrip1',
'reelStrip2',
'reelStrip3',
'reelStrip4',
'reelStrip5',
'reelStrip6'
] as $reelStrip )
{
if( count($reel->reelsStrip[$reelStrip]) )
{
$this->$reelStrip = $reel->reelsStrip[$reelStrip];
}
}
$this->keyController = [
'13' => 'uiButtonSpin,uiButtonSkip',
'49' => 'uiButtonInfo',
'50' => 'uiButtonCollect',
'51' => 'uiButtonExit2',
'52' => 'uiButtonLinesMinus',
'53' => 'uiButtonLinesPlus',
'54' => 'uiButtonBetMinus',
'55' => 'uiButtonBetPlus',
'56' => 'uiButtonGamble',
'57' => 'uiButtonRed',
'48' => 'uiButtonBlack',
'189' => 'uiButtonAuto',
'187' => 'uiButtonSpin'
];
$this->slotReelsConfig = [
[
425,
142,
3
],
[
669,
142,
3
],
[
913,
142,
3
],
[
1157,
142,
3
],
[
1401,
142,
3
]
];
$this->slotBonusType = 1;
$this->slotScatterType = 0;
$this->splitScreen = false;
$this->slotBonus = true;
$this->slotGamble = true;
$this->slotFastStop = 1;
$this->slotExitUrl = '/';
$this->slotWildMpl = 1;
$this->GambleType = 1;
$this->Denominations = \VanguardLTE\Game::$values['denomination'];
$this->CurrentDenom = $this->Denominations[0];
$this->CurrentDenomination = $this->Denominations[0];
$this->slotFreeCount = [
0,
0,
0,
0,
0,
0
];
$this->slotFreeMpl = 1;
$this->slotViewState = ($game->slotViewState == '' ? 'Normal' : $game->slotViewState);
$this->hideButtons = [];
$this->jpgs = \VanguardLTE\JPG::where('shop_id', $this->shop_id)->lockForUpdate()->get();
$this->slotJackPercent = [];
$this->slotJackpot = [];
for( $jp = 1; $jp <= 4; $jp++ )
{
$this->slotJackpot[] = $game->{'jp_' . $jp};
$this->slotJackPercent[] = $game->{'jp_' . $jp . '_percent'};
}
$this->Line = [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15
];
$this->gameLine = [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15
];
$this->Bet = explode(',', $game->bet);
$this->Balance = $user->balance;
$this->SymbolGame = [
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'10'
];
$this->Bank = $game->get_gamebank();
$this->Percent = $this->shop->percent;
$this->WinGamble = $game->rezerv;
$this->slotDBId = $game->id;
$this->slotCurrency = $user->shop->currency;
$this->count_balance = $user->count_balance;
if( $user->address > 0 && $user->count_balance == 0 )
{
$this->Percent = 0;
$this->jpgPercentZero = true;
}
else if( $user->count_balance == 0 )
{
$this->Percent = 100;
}
if( !isset($this->user->session) || strlen($this->user->session) <= 0 )
{
$this->user->session = serialize([]);
}
$this->gameData = unserialize($this->user->session);
if( count($this->gameData) > 0 )
{
foreach( $this->gameData as $key => $vl )
{
if( $vl['timelife'] <= time() )
{
unset($this->gameData[$key]);
}
}
}
if( !isset($this->game->advanced) || strlen($this->game->advanced) <= 0 )
{
$this->game->advanced = serialize([]);
}
$this->gameDataStatic = unserialize($this->game->advanced);
if( count($this->gameDataStatic) > 0 )
{
foreach( $this->gameDataStatic as $key => $vl )
{
if( $vl['timelife'] <= time() )
{
unset($this->gameDataStatic[$key]);
}
}
}
}
public function is_active()
{
if( $this->game && $this->shop && $this->user && (!$this->game->view || $this->shop->is_blocked || $this->user->is_blocked || $this->user->status == \VanguardLTE\Support\Enum\UserStatus::BANNED) )
{
\VanguardLTE\Session::where('user_id', $this->user->id)->delete();
$this->user->update(['remember_token' => null]);
return false;
}
if( !$this->game->view )
{
return false;
}
if( $this->shop->is_blocked )
{
return false;
}
if( $this->user->is_blocked )
{
return false;
}
if( $this->user->status == \VanguardLTE\Support\Enum\UserStatus::BANNED )
{
return false;
}
return true;
}
public function SetGameData($key, $value)
{
$timeLife = 86400;
$this->gameData[$key] = [
'timelife' => time() + $timeLife,
'payload' => $value
];
}
public function GetGameData($key)
{
if( isset($this->gameData[$key]) )
{
return $this->gameData[$key]['payload'];
}
else
{
return 0;
}
}
public function FormatFloat($num)
{
$str0 = explode('.', $num);
if( isset($str0[1]) )
{
if( strlen($str0[1]) > 4 )
{
return round($num * 100) / 100;
}
else if( strlen($str0[1]) > 2 )
{
return floor($num * 100) / 100;
}
else
{
return $num;
}
}
else
{
return $num;
}
}
public function SaveGameData()
{
$this->user->session = serialize($this->gameData);
$this->user->save();
}
public function CheckBonusWin()
{
$allRateCnt = 0;
$allRate = 0;
foreach( $this->Paytable as $vl )
{
foreach( $vl as $vl2 )
{
if( $vl2 > 0 )
{
$allRateCnt++;
$allRate += $vl2;
break;
}
}
}
return $allRate / $allRateCnt;
}
public function GetRandomPay()
{
$allRate = [];
foreach( $this->Paytable as $vl )
{
foreach( $vl as $vl2 )
{
if( $vl2 > 0 )
{
$allRate[] = $vl2;
}
}
}
shuffle($allRate);
if( $this->game->stat_in < ($this->game->stat_out + ($allRate[0] * $this->AllBet)) )
{
$allRate[0] = 0;
}
return $allRate[0];
}
public function HasGameDataStatic($key)
{
if( isset($this->gameDataStatic[$key]) )
{
return true;
}
else
{
return false;
}
}
public function SaveGameDataStatic()
{
$this->game->advanced = serialize($this->gameDataStatic);
$this->game->save();
$this->game->refresh();
}
public function SetGameDataStatic($key, $value)
{
$timeLife = 86400;
$this->gameDataStatic[$key] = [
'timelife' => time() + $timeLife,
'payload' => $value
];
}
public function GetGameDataStatic($key)
{
if( isset($this->gameDataStatic[$key]) )
{
return $this->gameDataStatic[$key]['payload'];
}
else
{
return 0;
}
}
public function HasGameData($key)
{
if( isset($this->gameData[$key]) )
{
return true;
}
else
{
return false;
}
}
public function GetHistory()
{
$history = \VanguardLTE\GameLog::whereRaw('game_id=? and user_id=? ORDER BY id DESC LIMIT 10', [
$this->slotDBId,
$this->playerId
])->get();
$this->lastEvent = 'NULL';
foreach( $history as $log )
{
$tmpLog = json_decode($log->str);
if( $tmpLog->responseEvent != 'gambleResult' && $tmpLog->responseEvent != 'jackpot' )
{
$this->lastEvent = $log->str;
break;
}
}
if( isset($tmpLog) )
{
return $tmpLog;
}
else
{
return 'NULL';
}
}
public function UpdateJackpots($bet)
{
$bet = $bet * $this->CurrentDenom;
$count_balance = $this->count_balance;
$jsum = [];
$payJack = 0;
for( $i = 0; $i < count($this->jpgs); $i++ )
{
if( $count_balance == 0 || $this->jpgPercentZero )
{
$jsum[$i] = $this->jpgs[$i]->balance;
}
else if( $count_balance < $bet )
{
$jsum[$i] = $count_balance / 100 * $this->jpgs[$i]->percent + $this->jpgs[$i]->balance;
}
else
{
$jsum[$i] = $bet / 100 * $this->jpgs[$i]->percent + $this->jpgs[$i]->balance;
}
if( $this->jpgs[$i]->get_pay_sum() < $jsum[$i] && $this->jpgs[$i]->get_pay_sum() > 0 )
{
if( $this->jpgs[$i]->user_id && $this->jpgs[$i]->user_id != $this->user->id )
{
}
else
{
$payJack = $this->jpgs[$i]->get_pay_sum() / $this->CurrentDenom;
$jsum[$i] = $jsum[$i] - $this->jpgs[$i]->get_pay_sum();
$this->SetBalance($this->jpgs[$i]->get_pay_sum() / $this->CurrentDenom);
if( $this->jpgs[$i]->get_pay_sum() > 0 )
{
\VanguardLTE\StatGame::create([
'user_id' => $this->playerId,
'balance' => $this->Balance * $this->CurrentDenom,
'bet' => 0,
'win' => $this->jpgs[$i]->get_pay_sum(),
'game' => $this->game->name . ' JPG ' . $this->jpgs[$i]->id,
'in_game' => 0,
'in_jpg' => 0,
'in_profit' => 0,
'shop_id' => $this->shop_id,
'date_time' => \Carbon\Carbon::now()
]);
}
}
}
$this->jpgs[$i]->balance = $jsum[$i];
$this->jpgs[$i]->save();
if( $this->jpgs[$i]->balance < $this->jpgs[$i]->get_min('start_balance') )
{
$summ = $this->jpgs[$i]->get_start_balance();
if( $summ > 0 )
{
$this->jpgs[$i]->add_jpg('add', $summ);
}
}
}
if( $payJack > 0 )
{
$payJack = sprintf('%01.2f', $payJack);
$this->Jackpots['jackPay'] = $payJack;
}
}
public function GetBank($slotState = '')
{
if( $this->isBonusStart || $slotState == 'bonus' || $slotState == 'freespin' || $slotState == 'respin' )
{
$slotState = 'bonus';
}
else
{
$slotState = '';
}
$game = $this->game;
$this->Bank = $game->get_gamebank($slotState);
return $this->Bank / $this->CurrentDenom;
}
public function GetPercent()
{
return $this->Percent;
}
public function GetCountBalanceUser()
{
return $this->user->count_balance;
}
public function InternalError($errcode)
{
$strLog = '';
$strLog .= "\n";
$strLog .= ('{"responseEvent":"error","responseType":"' . $errcode . '","serverResponse":"InternalError","request":' . json_encode($_REQUEST) . ',"requestRaw":' . file_get_contents('php://input') . '}');
$strLog .= "\n";
$strLog .= ' ############################################### ';
$strLog .= "\n";
$slg = '';
if( file_exists(storage_path('logs/') . $this->slotId . 'Internal.log') )
{
$slg = file_get_contents(storage_path('logs/') . $this->slotId . 'Internal.log');
}
file_put_contents(storage_path('logs/') . $this->slotId . 'Internal.log', $slg . $strLog);
exit( '' );
}
public function InternalErrorSilent($errcode)
{
$strLog = '';
$strLog .= "\n";
$strLog .= ('{"responseEvent":"error","responseType":"' . $errcode . '","serverResponse":"InternalError","request":' . json_encode($_REQUEST) . ',"requestRaw":' . file_get_contents('php://input') . '}');
$strLog .= "\n";
$strLog .= ' ############################################### ';
$strLog .= "\n";
$slg = '';
if( file_exists(storage_path('logs/') . $this->slotId . 'Internal.log') )
{
$slg = file_get_contents(storage_path('logs/') . $this->slotId . 'Internal.log');
}
file_put_contents(storage_path('logs/') . $this->slotId . 'Internal.log', $slg . $strLog);
}
public function SetBank($slotState = '', $sum, $slotEvent = '')
{
if( $this->isBonusStart || $slotState == 'bonus' || $slotState == 'freespin' || $slotState == 'respin' )
{
$slotState = 'bonus';
}
else
{
$slotState = '';
}
if( $this->GetBank($slotState) + $sum < 0 )
{
$this->InternalError('Bank_ ' . $sum . ' CurrentBank_ ' . $this->GetBank($slotState) . ' CurrentState_ ' . $slotState . ' Trigger_ ' . ($this->GetBank($slotState) + $sum));
}
$sum = $sum * $this->CurrentDenom;
$game = $this->game;
$bankBonusSum = 0;
if( $sum > 0 && $slotEvent == 'bet' )
{
$this->toGameBanks = 0;
$this->toSlotJackBanks = 0;
$this->toSysJackBanks = 0;
$this->betProfit = 0;
$prc = $this->GetPercent();
$prc_b = 10;
if( $prc <= $prc_b )
{
$prc_b = 0;
}
$count_balance = $this->count_balance;
$gameBet = $sum / $this->GetPercent() * 100;
if( $count_balance < $gameBet && $count_balance > 0 )
{
$firstBid = $count_balance;
$secondBid = $gameBet - $firstBid;
if( isset($this->betRemains0) )
{
$secondBid = $this->betRemains0;
}
$bankSum = $firstBid / 100 * $this->GetPercent();
$sum = $bankSum + $secondBid;
$bankBonusSum = $firstBid / 100 * $prc_b;
}
else if( $count_balance > 0 )
{
$bankBonusSum = $gameBet / 100 * $prc_b;
}
for( $i = 0; $i < count($this->jpgs); $i++ )
{
if( !$this->jpgPercentZero )
{
if( $count_balance < $gameBet && $count_balance > 0 )
{
$this->toSlotJackBanks += ($count_balance / 100 * $this->jpgs[$i]->percent);
}
else if( $count_balance > 0 )
{
$this->toSlotJackBanks += ($gameBet / 100 * $this->jpgs[$i]->percent);
}
}
}
$this->toGameBanks = $sum;
$this->betProfit = $gameBet - $this->toGameBanks - $this->toSlotJackBanks - $this->toSysJackBanks;
}
if( $sum > 0 )
{
$this->toGameBanks = $sum;
}
if( $bankBonusSum > 0 )
{
$sum -= $bankBonusSum;
$game->set_gamebank($bankBonusSum, 'inc', 'bonus');
}
if( $sum == 0 && $slotEvent == 'bet' && isset($this->betRemains) )
{
$sum = $this->betRemains;
}
$game->set_gamebank($sum, 'inc', $slotState);
$game->save();
return $game;
}
public function SetBalance($sum, $slotEvent = '')
{
if( $this->GetBalance() + $sum < 0 )
{
$this->InternalError('Balance_ ' . $sum);
}
$sum = $sum * $this->CurrentDenom;
if( $sum < 0 && $slotEvent == 'bet' )
{
$user = $this->user;
if( $user->count_balance == 0 )
{
$remains = [];
$this->betRemains = 0;
$sm = abs($sum);
if( $user->address < $sm && $user->address > 0 )
{
$remains[] = $sm - $user->address;
}
for( $i = 0; $i < count($remains); $i++ )
{
if( $this->betRemains < $remains[$i] )
{
$this->betRemains = $remains[$i];
}
}
}
if( $user->count_balance > 0 && $user->count_balance < abs($sum) )
{
$remains0 = [];
$sm = abs($sum);
$tmpSum = $sm - $user->count_balance;
$this->betRemains0 = $tmpSum;
if( $user->address > 0 )
{
$this->betRemains0 = 0;
if( $user->address < $tmpSum && $user->address > 0 )
{
$remains0[] = $tmpSum - $user->address;
}
for( $i = 0; $i < count($remains0); $i++ )
{
if( $this->betRemains0 < $remains0[$i] )
{
$this->betRemains0 = $remains0[$i];
}
}
}
}
$sum0 = abs($sum);
if( $user->count_balance == 0 )
{
$sm = abs($sum);
if( $user->address < $sm && $user->address > 0 )
{
$user->address = 0;
}
else if( $user->address > 0 )
{
$user->address -= $sm;
}
}
else if( $user->count_balance > 0 && $user->count_balance < $sum0 )
{
$sm = $sum0 - $user->count_balance;
if( $user->address < $sm && $user->address > 0 )
{
$user->address = 0;
}
else if( $user->address > 0 )
{
$user->address -= $sm;
}
}
$this->user->count_balance = $this->user->updateCountBalance($sum, $this->count_balance);
$this->user->count_balance = $this->FormatFloat($this->user->count_balance);
}
$this->user->increment('balance', $sum);
$this->user->balance = $this->FormatFloat($this->user->balance);
$this->user->save();
return $this->user;
}
public function GetBalance()
{
$user = $this->user;
$this->Balance = $user->balance / $this->CurrentDenom;
return $this->Balance;
}
public function SaveLogReport($spinSymbols, $bet, $lines, $win, $slotState)
{
$reportName = $this->slotId . ' ' . $slotState;
if( $slotState == 'freespin' )
{
$reportName = $this->slotId . ' FG';
}
else if( $slotState == 'bet' )
{
$reportName = $this->slotId . '';
}
else if( $slotState == 'slotGamble' )
{
$reportName = $this->slotId . ' DG';
}
$game = $this->game;
if( $slotState == 'bet' )
{
$this->user->update_level('bet', $bet * $this->CurrentDenom);
}
if( $slotState != 'freespin' )
{
$game->increment('stat_in', $bet * $this->CurrentDenom);
}
$game->increment('stat_out', $win * $this->CurrentDenom);
$game->tournament_stat($slotState, $this->user->id, $bet * $this->CurrentDenom, $win * $this->CurrentDenom);
$this->user->update(['last_bid' => \Carbon\Carbon::now()]);
if( !isset($this->betProfit) )
{
$this->betProfit = 0;
$this->toGameBanks = 0;
$this->toSlotJackBanks = 0;
$this->toSysJackBanks = 0;
}
if( !isset($this->toGameBanks) )
{
$this->toGameBanks = 0;
}
$this->game->increment('bids');
$this->game->refresh();
$gamebank = \VanguardLTE\GameBank::where(['shop_id' => $game->shop_id])->first();
if( $gamebank )
{
list($slotsBank, $bonusBank, $fishBank, $tableBank, $littleBank) = \VanguardLTE\Lib\Banker::get_all_banks($game->shop_id);
}
else
{
$slotsBank = $game->get_gamebank('', 'slots');
$bonusBank = $game->get_gamebank('bonus', 'bonus');
$fishBank = $game->get_gamebank('', 'fish');
$tableBank = $game->get_gamebank('', 'table_bank');
$littleBank = $game->get_gamebank('', 'little');
}
$totalBank = $slotsBank + $bonusBank + $fishBank + $tableBank + $littleBank;
\VanguardLTE\GameLog::create([
'game_id' => $this->slotDBId,
'user_id' => $this->playerId,
'ip' => $_SERVER['REMOTE_ADDR'],
'str' => $spinSymbols,
'shop_id' => $this->shop_id
]);
\VanguardLTE\StatGame::create([
'user_id' => $this->playerId,
'balance' => $this->Balance * $this->CurrentDenom,
'bet' => $bet * $this->CurrentDenom,
'win' => $win * $this->CurrentDenom,
'game' => $reportName,
'in_game' => $this->toGameBanks,
'in_jpg' => $this->toSlotJackBanks,
'in_profit' => $this->betProfit,
'denomination' => $this->CurrentDenom,
'shop_id' => $this->shop_id,
'slots_bank' => (double)$slotsBank,
'bonus_bank' => (double)$bonusBank,
'fish_bank' => (double)$fishBank,
'table_bank' => (double)$tableBank,
'little_bank' => (double)$littleBank,
'total_bank' => (double)$totalBank,
'date_time' => \Carbon\Carbon::now()
]);
}
public function GetSpinSettings($garantType = 'bet', $bet, $lines)
{
$curField = 10;
switch( $lines )
{
case 10:
$curField = 10;
break;
case 9:
case 8:
$curField = 9;
break;
case 7:
case 6:
$curField = 7;
break;
case 5:
case 4:
$curField = 5;
break;
case 3:
case 2:
$curField = 3;
break;
case 1:
$curField = 1;
break;
default:
$curField = 10;
break;
}
if( $garantType != 'bet' )
{
$pref = '_bonus';
}
else
{
$pref = '';
}
$this->AllBet = $bet * $lines;
$linesPercentConfigSpin = $this->game->get_lines_percent_config('spin');
$linesPercentConfigBonus = $this->game->get_lines_percent_config('bonus');
$currentPercent = $this->shop->percent;
$currentSpinWinChance = 0;
$currentBonusWinChance = 0;
$percentLevel = '';
foreach( $linesPercentConfigSpin['line' . $curField . $pref] as $k => $v )
{
$l = explode('_', $k);
$l0 = $l[0];
$l1 = $l[1];
if( $l0 <= $currentPercent && $currentPercent <= $l1 )
{
$percentLevel = $k;
break;
}
}
$currentSpinWinChance = $linesPercentConfigSpin['line' . $curField . $pref][$percentLevel];
$currentBonusWinChance = $linesPercentConfigBonus['line' . $curField . $pref][$percentLevel];
$RtpControlCount = 200;
if( !$this->HasGameDataStatic('SpinWinLimit') )
{
$this->SetGameDataStatic('SpinWinLimit', 0);
}
if( !$this->HasGameDataStatic('RtpControlCount') )
{
$this->SetGameDataStatic('RtpControlCount', $RtpControlCount);
}
if( $this->game->stat_in > 0 )
{
$rtpRange = $this->game->stat_out / $this->game->stat_in * 100;
}
else
{
$rtpRange = 0;
}
if( $this->GetGameDataStatic('RtpControlCount') == 0 )
{
if( $currentPercent + rand(1, 2) < $rtpRange && $this->GetGameDataStatic('SpinWinLimit') <= 0 )
{
$this->SetGameDataStatic('SpinWinLimit', rand(25, 50));
}
if( $pref == '' && $this->GetGameDataStatic('SpinWinLimit') > 0 )
{
$currentBonusWinChance = 5000;
$currentSpinWinChance = 20;
$this->MaxWin = rand(1, 5);
if( $rtpRange < ($currentPercent - 1) )
{
$this->SetGameDataStatic('SpinWinLimit', 0);
$this->SetGameDataStatic('RtpControlCount', $this->GetGameDataStatic('RtpControlCount') - 1);
}
}
}
else if( $this->GetGameDataStatic('RtpControlCount') < 0 )
{
if( $currentPercent + rand(1, 2) < $rtpRange && $this->GetGameDataStatic('SpinWinLimit') <= 0 )
{
$this->SetGameDataStatic('SpinWinLimit', rand(25, 50));
}
$this->SetGameDataStatic('RtpControlCount', $this->GetGameDataStatic('RtpControlCount') - 1);
if( $pref == '' && $this->GetGameDataStatic('SpinWinLimit') > 0 )
{
$currentBonusWinChance = 5000;
$currentSpinWinChance = 20;
$this->MaxWin = rand(1, 5);
if( $rtpRange < ($currentPercent - 1) )
{
$this->SetGameDataStatic('SpinWinLimit', 0);
}
}
if( $this->GetGameDataStatic('RtpControlCount') < (-1 * $RtpControlCount) && $currentPercent - 1 <= $rtpRange && $rtpRange <= ($currentPercent + 2) )
{
$this->SetGameDataStatic('RtpControlCount', $RtpControlCount);
}
}
else
{
$this->SetGameDataStatic('RtpControlCount', $this->GetGameDataStatic('RtpControlCount') - 1);
}
$bonusWin = rand(1, $currentBonusWinChance);
$spinWin = rand(1, $currentSpinWinChance);
$return = [
'none',
0
];
if( $bonusWin == 1 && $this->slotBonus )
{
$this->isBonusStart = true;
$garantType = 'bonus';
$winLimit = $this->GetBank($garantType);
$return = [
'bonus',
$winLimit
];
if( $this->game->stat_in < ($this->CheckBonusWin() * $bet + $this->game->stat_out) || $winLimit < ($this->CheckBonusWin() * $bet) )
{
$return = [
'none',
0
];
}
}
else if( $spinWin == 1 )
{
$winLimit = $this->GetBank($garantType);
$return = [
'win',
$winLimit
];
}
if( $garantType == 'bet' && $this->GetBalance() <= (2 / $this->CurrentDenom) )
{
$randomPush = rand(1, 10);
if( $randomPush == 1 )
{
$winLimit = $this->GetBank('');
$return = [
'win',
$winLimit
];
}
}
return $return;
}
public function getNewSpin($game, $spinWin = 0, $bonusWin = 0, $lines, $garantType = 'bet')
{
$curField = 10;
switch( $lines )
{
case 10:
$curField = 10;
break;
case 9:
case 8:
$curField = 9;
break;
case 7:
case 6:
$curField = 7;
break;
case 5:
case 4:
$curField = 5;
break;
case 3:
case 2:
$curField = 3;
break;
case 1:
$curField = 1;
break;
default:
$curField = 10;
break;
}
if( $garantType != 'bet' )
{
$pref = '_bonus';
}
else
{
$pref = '';
}
if( $spinWin )
{
$win = explode(',', $game->game_win->{'winline' . $pref . $curField});
}
if( $bonusWin )
{
$win = explode(',', $game->game_win->{'winbonus' . $pref . $curField});
}
$number = rand(0, count($win) - 1);
return $win[$number];
}
public function GetRandomScatterPos($rp)
{
$rpResult = [];
for( $i = 0; $i < count($rp); $i++ )
{
if( $rp[$i] == '0' )
{
if( isset($rp[$i + 1]) && isset($rp[$i - 1]) )
{
array_push($rpResult, $i);
}
if( isset($rp[$i - 1]) && isset($rp[$i - 2]) )
{
array_push($rpResult, $i - 1);
}
if( isset($rp[$i + 1]) && isset($rp[$i + 2]) )
{
array_push($rpResult, $i + 1);
}
}
}
shuffle($rpResult);
if( !isset($rpResult[0]) )
{
$rpResult[0] = rand(2, count($rp) - 3);
}
return $rpResult[0];
}
public function GetGambleSettings()
{
$spinWin = rand(1, $this->WinGamble);
return $spinWin;
}
public function GetReelStrips($winType, $slotEvent)
{
$game = $this->game;
if( $slotEvent == 'freespin' )
{
$reel = new GameReel();
$fArr = $reel->reelsStripBonus;
foreach( [
'reelStrip1',
'reelStrip2',
'reelStrip3',
'reelStrip4',
'reelStrip5',
'reelStrip6'
] as $reelStrip )
{
$curReel = array_shift($fArr);
if( count($curReel) )
{
$this->$reelStrip = $curReel;
}
}
}
if( $winType != 'bonus' )
{
$prs = [];
foreach( [
'reelStrip1',
'reelStrip2',
'reelStrip3',
'reelStrip4',
'reelStrip5',
'reelStrip6'
] as $index => $reelStrip )
{
if( is_array($this->$reelStrip) && count($this->$reelStrip) > 0 )
{
$prs[$index + 1] = mt_rand(0, count($this->$reelStrip) - 3);
}
}
}
else
{
$reelsId = [];
foreach( [
'reelStrip1',
'reelStrip2',
'reelStrip3',
'reelStrip4',
'reelStrip5',
'reelStrip6'
] as $index => $reelStrip )
{
if( is_array($this->$reelStrip) && count($this->$reelStrip) > 0 )
{
$prs[$index + 1] = $this->GetRandomScatterPos($this->$reelStrip);
$reelsId[] = $index + 1;
}
}
$scattersCnt = rand(3, count($reelsId));
shuffle($reelsId);
for( $i = 0; $i < count($reelsId); $i++ )
{
if( $i < $scattersCnt )
{
$prs[$reelsId[$i]] = $this->GetRandomScatterPos($this->{'reelStrip' . $reelsId[$i]});
}
else
{
$prs[$reelsId[$i]] = rand(0, count($this->{'reelStrip' . $reelsId[$i]}) - 3);
}
}
}
$reel = [
'rp' => []
];
foreach( $prs as $index => $value )
{
$key = $this->{'reelStrip' . $index};
$cnt = count($key);
$key[-1] = $key[$cnt - 1];
$key[-2] = $key[$cnt - 2];
$key[-3] = $key[$cnt - 3];
$key[$cnt] = $key[0];
$key[$cnt + 1] = $key[1];
$key[$cnt + 2] = $key[2];
if( $index == 1 || $index == 5 )
{
$reel['reel' . $index][0] = $key[$value - 1];
$reel['reel' . $index][1] = $key[$value];
$reel['reel' . $index][2] = $key[$value + 1];
$reel['reel' . $index][3] = '';
$reel['reel' . $index][4] = '';
$reel['reel' . $index][5] = '';
}
if( $index == 2 || $index == 4 )
{
$reel['reel' . $index][0] = $key[$value - 1];
$reel['reel' . $index][1] = $key[$value];
$reel['reel' . $index][2] = $key[$value + 1];
$reel['reel' . $index][3] = $key[$value + 2];
$reel['reel' . $index][4] = '';
$reel['reel' . $index][5] = '';
}
if( $index == 3 )
{
$reel['reel' . $index][0] = $key[$value - 1];
$reel['reel' . $index][1] = $key[$value];
$reel['reel' . $index][2] = $key[$value + 1];
$reel['reel' . $index][3] = $key[$value + 2];
$reel['reel' . $index][4] = $key[$value + 3];
$reel['reel' . $index][5] = '';
}
$reel['rp'][] = $value;
}
return $reel;
}
}
}
| 0 | 0.616184 | 1 | 0.616184 | game-dev | MEDIA | 0.564895 | game-dev,web-backend | 0.833372 | 1 | 0.833372 |
Pierre-Terdiman/WFC_Explorer | 4,331 | WFC/Src/Ice/APIs/Ice/IceCore/IceRandom.h | ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Contains code for random generators.
* \file IceRandom.h
* \author Pierre Terdiman
* \date August, 9, 2001
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Include Guard
#ifndef ICERANDOM_H
#define ICERANDOM_H
// Wrappers for system random functions
FUNCTION ICECORE_API void SRand(udword seed);
FUNCTION ICECORE_API udword Rand();
//! Returns a random floating-point value f such as 0.0f <= f <= 1.0f
inline_ float UnitRandomFloat() { return float(Rand()) * ONE_OVER_RAND_MAX; }
//! Returns a random number i so that 0 <= i < max_value
FUNCTION ICECORE_API udword GetRandomNumber(udword max_value=0xffffffff);
//! Returns a random bool (0 or 1)
FUNCTION ICECORE_API udword GetRandomBool();
//! Returns a pseudo random number i so that 0 <= i < max_value
//! Uses a better random number generator than "GetRandomNumber".
FUNCTION ICECORE_API udword GetPseudoRandomNumber(udword max_value=0xffffffff);
//! Returns a real random number i so that 0 <= i < max_value
//! The set of numbers returned by this function will always be different
//! each time you run your app.
FUNCTION ICECORE_API udword GetRealRandomNumber(udword max_value=0xffffffff);
// This one is not very good....
class ICECORE_API BasicRandom
{
public:
//! Constructor
inline_ BasicRandom(udword seed=0) : mRnd(seed) {}
//! Destructor
inline_ ~BasicRandom() {}
inline_ void SetSeed(udword seed) { mRnd = seed; }
inline_ udword GetCurrentValue() const { return mRnd; }
inline_ udword Randomize() { mRnd = mRnd * 2147001325 + 715136305; return mRnd; }
inline_ float RandomFloat() { return (float(Randomize() & 0xffff)/65535.0f) - 0.5f; }
private:
udword mRnd;
};
// Following is a set of better random generators.
// Base class for random number generators
class ICECORE_API RandomGenerator
{
protected:
RandomGenerator();
virtual ~RandomGenerator();
mutable sdword mSeed;
public:
void SetNewSeed();
inline_ sdword GetSeed() const { return mSeed; }
virtual void SetSeed(sdword s) = 0;
virtual udword RandI() const = 0; // 0..2^31
virtual float RandF() const // 0.0 .. 1.0 float generator
{
// default: multiply by 1/(2^31)
return float(RandI()) * float(1.0f/2147483647.0f);
}
sdword RandI(sdword i, sdword n) // i..n integer generator
{
ASSERT(i<=n);
return (sdword)(i + (RandI() % (n - i + 1)) );
}
float RandF(float i, float n) // i..n float generator
{
ASSERT(i<=n);
return (i + (n - i) * RandF());
}
};
// Linear Congruential Method, the "minimal standard generator"
// Fast, farly good random numbers (better than using rand)
// Park & Miller, 1988, Comm of the ACM, 31(10), pp. 1192-1201
class ICECORE_API RandomLCG : public RandomGenerator
{
public:
RandomLCG();
RandomLCG(sdword s);
virtual void SetSeed(sdword s);
virtual udword RandI() const;
protected:
static const sdword msQuotient;
static const sdword msRemainder;
};
//--------------------------------------
// Fast, very good random numbers
//
// Period = 2^249
//
// Kirkpatrick, S., and E. Stoll, 1981; A Very Fast Shift-Register
// Sequence Random Number Generator, Journal of Computational Physics,
// V. 40.
//
// Maier, W.L., 1991; A Fast Pseudo Random Number Generator,
// Dr. Dobb's Journal, May, pp. 152 - 157
class ICECORE_API RandomR250: public RandomGenerator
{
public:
RandomR250();
RandomR250(sdword s);
virtual void SetSeed(sdword s);
virtual udword RandI() const;
private:
mutable udword mBuffer[250];
mutable sdword mIndex;
};
#endif // ICERANDOM_H
| 0 | 0.751277 | 1 | 0.751277 | game-dev | MEDIA | 0.819341 | game-dev | 0.848298 | 1 | 0.848298 |
BuildCraft/BuildCraft | 1,069 | common/buildcraft/lib/misc/data/BoxIterable.java | /*
* Copyright (c) 2017 SpaceToad and the BuildCraft team
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/
*/
package buildcraft.lib.misc.data;
import net.minecraft.util.math.BlockPos;
import buildcraft.api.core.IBox;
public class BoxIterable implements Iterable<BlockPos> {
private final BlockPos min, max;
private final AxisOrder order;
private final boolean invert;
public BoxIterable(IBox box, AxisOrder order) {
this(box.max(), box.max(), order);
}
public BoxIterable(BlockPos min, BlockPos max, AxisOrder order) {
this(min, max, order, false);
}
public BoxIterable(BlockPos min, BlockPos max, AxisOrder order, boolean invert) {
this.min = min;
this.max = max;
this.order = order;
this.invert = invert;
}
@Override
public BoxIterator iterator() {
return new BoxIterator(min, max, order, invert);
}
}
| 0 | 0.801231 | 1 | 0.801231 | game-dev | MEDIA | 0.960014 | game-dev | 0.597223 | 1 | 0.597223 |
locklin/lush-code | 24,889 | lush1/tags/debian_version_1_0+cvs_2003_02_14/src/binary.c | /***********************************************************************
*
* LUSH Lisp Universal Shell
* Copyright (C) 2002 Leon Bottou, Yann Le Cun, AT&T Corp, NECI.
* Includes parts of TL3:
* Copyright (C) 1987-1999 Leon Bottou and Neuristique.
* Includes selected parts of SN3.2:
* Copyright (C) 1991-2001 AT&T Corp.
*
* 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, USA
*
***********************************************************************/
/***********************************************************************
* $Id: binary.c,v 1.12 2002-07-07 02:02:59 leonb Exp $
**********************************************************************/
#include "header.h"
#define BINARYSTART (0x9f)
enum binarytokens {
TOK_NULL,
TOK_REF,
TOK_DEF,
TOK_NIL,
TOK_CONS,
TOK_NUMBER,
TOK_STRING,
TOK_SYMBOL,
TOK_OBJECT,
TOK_CLASS,
TOK_MATRIX,
TOK_ARRAY,
TOK_DE,
TOK_DF,
TOK_DM,
TOK_CFUNC,
TOK_CCLASS,
TOK_COBJECT,
};
/*** GLOBAL VARIABLES ****/
int in_bwrite = 0;
static int opt_bwrite = 0;
static FILE *fin;
static FILE *fout;
/*** THE RELOCATION STRUCTURE **********/
static int relocm = 0;
static int relocn = 0;
static gptr *relocp = 0;
static char *relocf = 0;
#define R_EMPTY 0
#define R_REFD 1
#define R_DEFD 2
static void
check_reloc_size(int m)
{
char *f;
gptr *p;
if (relocm >= m)
return;
if (relocm == 0) {
m = 1 + (m | 0x3ff);
f = malloc(sizeof(char)*m);
p = malloc(sizeof(gptr)*m);
} else {
m = 1 + (m | 0x3ff);
f = realloc(relocf,sizeof(char)*m);
p = realloc(relocp,sizeof(gptr)*m);
}
if (f && p)
{
relocf = f;
relocp = p;
relocm = m;
}
else
{
if (f)
free(f);
if (p)
free(p);
relocf = 0;
relocp = 0;
relocm = 0;
error(NIL,"Internal error: memory allocation failure",NIL);
}
}
static void
clear_reloc(int n)
{
int i;
check_reloc_size(n);
for (i=0; i<n; i++) {
relocp[i] = 0;
relocf[i] = 0;
}
relocn = n;
}
static void
insert_reloc(void *p)
{
int i;
check_reloc_size(relocn+1);
i = relocn;
relocn += 1;
relocp[i] = 0;
relocf[i] = 0;
while (i>0 && p<=relocp[i-1]) {
relocp[i] = relocp[i-1];
relocf[i] = relocf[i-1];
i--;
}
if (relocp[i]==p)
error(NIL,"Internal error: relocation requested twice",NIL);
relocp[i] = p;
relocf[i] = R_EMPTY;
}
static int
search_reloc(void *p)
{
int lo = 0;
int hi = relocn - 1;
int k;
while (hi>=lo) {
k = (lo+hi)/2;
if (p>relocp[k])
lo = k+1;
else if (p<relocp[k])
hi = k-1;
else
return k;
}
error(NIL,"Internal error: relocation search failed",NIL);
}
static void
define_refd_reloc(int k, at *p)
{
gptr f;
at **h = relocp[k];
while (h) {
f = *h;
LOCK(p);
*h = p;
h = f;
}
}
static void
forbid_refd_reloc(void)
{
int i;
int flag = 0;
for (i=0; i<relocn; i++) {
if (relocf[i]!= R_DEFD)
flag = 1;
if (relocf[i]== R_REFD)
define_refd_reloc(i,NIL);
}
if (flag)
error(NIL,"Corrupted binary file (unresolved relocs)",NIL);
}
/*** SWEEP OVER THE ELEMENTS TO SAVE ***/
static int cond_set_flags(at *p);
static int cond_clear_flags(at *p);
static int local_write(at *p);
static int local_bread(at **pp, int opt);
/* This function recursively performs an action on
* all objects under p. If action returns a non 0
* result, recursion is stopped.
*/
static void
sweep(at *p, int code)
{
again:
switch (code)
{
case SRZ_SETFL:
if (cond_set_flags(p))
return;
break;
case SRZ_CLRFL:
if (cond_clear_flags(p))
return;
break;
case SRZ_WRITE:
if (local_write(p))
return;
break;
default:
error(NIL,"internal error (unknown serialization action)",NIL);
}
if (!p)
return;
else if (p->flags & C_CONS)
{
sweep(p->Car,code);
p = p->Cdr;
goto again;
}
else if (! (p->flags & C_EXTERN))
return;
else if (p->flags & X_OOSTRUCT)
{
struct oostruct *c = p->Object;
int i;
if (opt_bwrite)
sweep(p->Class->backptr, code);
else
sweep(p->Class->classname, code);
for(i=0;i<c->size;i++) {
sweep(c->slots[i].symb, code);
sweep(c->slots[i].val, code);
}
}
else if (p->Class == &class_class)
{
class *s = p->Object;
sweep(s->priminame, code);
if (s->atsuper && !s->classdoc)
{
sweep(s->atsuper, code);
sweep(s->keylist, code);
sweep(s->defaults, code);
}
sweep(s->methods, code);
}
else if (p->Class == &index_class && !opt_bwrite)
{
struct index *ind = p->Object;
if (ind->st->srg.type == ST_AT)
if (! (ind->flags & IDF_UNSIZED))
{
at** data;
struct idx id;
index_read_idx(ind, &id);
data = IDX_DATA_PTR(&id);
begin_idx_aloop1(&id, off) {
sweep(data[off], code);
} end_idx_aloop1(&id, off);
index_rls_idx(ind, &id);
}
}
else if (p->Class == &de_class ||
p->Class == &df_class ||
p->Class == &dm_class )
{
struct lfunction *c = p->Object;
sweep(c->formal_arg_list, code);
sweep(c->evaluable_list, code);
}
else if (p->Class == &dx_class ||
p->Class == &dy_class ||
p->Class == &dh_class )
{
struct cfunction *c = p->Object;
sweep(c->name, code);
}
else if ( p->Class->serialize )
{
sweep(p->Class->classname, code);
(*p->Class->serialize) (&p, code);
}
}
/*** MARKING, FLAGGING ***/
/* This functions computes all objects
* which must be relocated when saving object p
*/
static int
cond_set_flags(at *p)
{
if (p) {
if (p->flags&C_MARK) {
if (! (p->flags&C_MULTIPLE))
insert_reloc(p);
p->flags |= C_MULTIPLE;
return 1; /* stop recursion */
}
p->flags |= C_MARK;
return 0;
}
return 1;
}
static void
set_flags(at *p)
{
sweep(p, SRZ_SETFL);
}
/* This function clears all flags
* leaving Lush ready for another run
*/
static int
cond_clear_flags(at *p)
{
if (p && (p->flags&C_MARK)) {
p->flags &= ~(C_MULTIPLE|C_MARK);
return 0;
} else
return 1; /* stop recursion if already cleared */
}
static void
clear_flags(at *p)
{
sweep(p, SRZ_CLRFL);
}
/*** LOW LEVEL CHECK/READ/WRITE ***/
static void
check(FILE *f)
{
if (feof(f))
error(NIL,"End of file during bread",NIL);
if (ferror(f))
test_file_error(NULL);
}
/* read */
static int
read_card8(void)
{
unsigned char c[1];
if (fread(c, sizeof(char), 1, fin) != 1)
check(fin);
return c[0];
}
static int
read_card16(void)
{
unsigned char c[2];
if (fread(c, sizeof(char), 2, fin) != 3)
check(fin);
return (c[0]<<8)+c[1];
}
static int
read_card24(void)
{
unsigned char c[3];
if (fread(c, sizeof(char), 3, fin) != 3)
check(fin);
return (((c[0]<<8)+c[1])<<8)+c[2];
}
static int
read_card32(void)
{
unsigned char c[4];
if (fread(c, sizeof(char), 4, fin) != 4)
check(fin);
return (((((c[0]<<8)+c[1])<<8)+c[2])<<8)+c[3];
}
static void
read_buffer(void *s, int n)
{
if (fread(s, sizeof(char), (size_t)n, fin) != (size_t)n)
check(fin);
}
/* write */
static void
write_card8(int x)
{
char c[1];
in_bwrite += 1;
c[0] = x;
if (fwrite(&c, sizeof(char), 1, fout) != 1)
check(fout);
}
static void
write_card16(int x)
{
char c[2];
in_bwrite += 2;
c[0] = x>>8;
c[1] = x;
if (fwrite(&c, sizeof(char), 2, fout) != 3)
check(fout);
}
static void
write_card24(int x)
{
char c[3];
in_bwrite += 3;
c[0] = x>>16;
c[1] = x>>8;
c[2] = x;
if (fwrite(&c, sizeof(char), 3, fout) != 3)
check(fout);
}
static void
write_card32(int x)
{
char c[4];
in_bwrite += 4;
c[0] = x>>24;
c[1] = x>>16;
c[2] = x>>8;
c[3] = x;
if (fwrite(&c, sizeof(char), 4, fout) != 4)
check(fout);
}
static void
write_buffer(void *s, int n)
{
in_bwrite += n;
if (fwrite(s, sizeof(char), (size_t)n, fout) != (size_t)n)
check(fout);
}
/*** The swap stuff ***/
static int swapflag;
static void
set_swapflag(void)
{
union { int i; char c; } s;
s.i = 1;
swapflag = s.c;
}
static void
swap_buffer(void *bb, int n, int m)
{
int i,j;
char *b = bb;
char buffer[16];
for (i=0; i<n; i++) {
for (j=0; j<m; j++)
buffer[j] = b[m-j-1];
for (j=0; j<m; j++)
*b++ = buffer[j];
}
}
/*** The serialization stuff ***/
FILE *
serialization_file_descriptor(int code)
{
switch (code)
{
case SRZ_READ:
return fin;
case SRZ_WRITE:
return fout;
default:
return NULL;
}
}
void
serialize_char(char *data, int code)
{
switch (code)
{
case SRZ_READ:
*data = read_card8();
return;
case SRZ_WRITE:
write_card8(*data);
return;
}
}
void
serialize_short(short int *data, int code)
{
switch(code)
{
case SRZ_READ:
*data = read_card16();
return;
case SRZ_WRITE:
write_card16((int)*data);
return;
}
}
void
serialize_int(int *data, int code)
{
switch(code)
{
case SRZ_READ:
*data = read_card32();
return;
case SRZ_WRITE:
write_card32((int)*data);
return;
}
}
void
serialize_string(char **data, int code, int maxlen)
{
int l;
char *buffer;
switch (code)
{
case SRZ_READ:
if (read_card8() != 's')
error(NIL,"serialization error (string expected)",NIL);
l = read_card24();
if (maxlen == -1) {
/* automatic mallocation */
ifn ((buffer = malloc(l+1))) {
error(NIL,"out of memory", NIL);
}
} else {
/* user provided buffer */
buffer = *data;
if (l+1 >= maxlen)
error(NIL,"serialization error (string too large)",NIL);
}
read_buffer(buffer,l);
buffer[l] = 0;
*data = buffer;
return;
case SRZ_WRITE:
write_card8('s');
l = strlen(*data);
write_card24(l);
write_buffer(*data,l);
return;
}
}
void
serialize_chars(void **data, int code, int thelen)
{
int l;
char *buffer;
switch (code)
{
case SRZ_READ:
if (read_card8() != 's')
error(NIL,"serialization error (string expected)",NIL);
l = read_card32();
if (thelen == -1) {
/* automatic mallocation */
ifn ((buffer = malloc(l))) {
error(NIL,"out of memory", NIL);
}
} else {
/* user provided buffer */
buffer = *data;
if (l != thelen)
error(NIL,"serialization error (lengths mismatch)",NIL);
}
read_buffer(buffer,l);
*data = buffer;
return;
case SRZ_WRITE:
write_card8('s');
write_card32(thelen);
write_buffer(*data,thelen);
return;
}
}
void
serialize_flt(flt *data, int code)
{
flt x;
switch (code)
{
case SRZ_READ:
read_buffer(&x, sizeof(flt));
if (swapflag)
swap_buffer(&x,1,sizeof(flt));
*data = x;
return;
case SRZ_WRITE:
x = *data;
if (swapflag)
swap_buffer(&x,1,sizeof(flt));
write_buffer(&x, sizeof(flt));
return;
}
}
void
serialize_float(float *data, int code)
{
float x;
switch (code)
{
case SRZ_READ:
read_buffer(&x, sizeof(float));
if (swapflag)
swap_buffer(&x,1,sizeof(float));
*data = x;
return;
case SRZ_WRITE:
x = *data;
if (swapflag)
swap_buffer(&x,1,sizeof(float));
write_buffer(&x, sizeof(float));
return;
}
}
void
serialize_real(real *data, int code)
{
real x;
switch (code)
{
case SRZ_READ:
read_buffer(&x, sizeof(real));
if (swapflag)
swap_buffer(&x,1,sizeof(real));
*data = x;
return;
case SRZ_WRITE:
x = *data;
if (swapflag)
swap_buffer(&x,1,sizeof(real));
write_buffer(&x, sizeof(real));
return;
}
}
void
serialize_double(double *data, int code)
{
double x;
switch (code)
{
case SRZ_READ:
read_buffer(&x, sizeof(double));
if (swapflag)
swap_buffer(&x,1,sizeof(double));
*data = x;
return;
case SRZ_WRITE:
x = *data;
if (swapflag)
swap_buffer(&x,1,sizeof(double));
write_buffer(&x, sizeof(double));
return;
}
}
int
serialize_atstar(at **data, int code)
{
switch (code)
{
case SRZ_CLRFL:
case SRZ_SETFL:
sweep(*data, code);
return 0;
case SRZ_READ:
if (read_card8() != 'p')
error(NIL, "Serialization error (pointer expected)", NIL);
return local_bread(data, NIL);
case SRZ_WRITE:
write_card8('p');
sweep(*data, code);
return 0;
}
error(NIL,"binary internal: wrong serialization mode",NIL);
}
/*** BINARY WRITE ***/
/* This local writing routine
* is called from sweep
*/
static int
local_write(at *p)
{
if (p==0 || (p->flags & X_ZOMBIE))
{
write_card8(TOK_NIL);
return 1;
}
if (p->flags & C_MULTIPLE)
{
int k = search_reloc(p);
if (relocf[k]) {
write_card8(TOK_REF);
write_card24(k);
return 1;
} else {
write_card8(TOK_DEF);
write_card24(k);
relocf[k] = R_DEFD;
/* continue */
}
}
if (p->flags & C_CONS)
{
write_card8(TOK_CONS);
return 0;
}
if (p->flags & C_NUMBER)
{
double x = p->Number;
write_card8(TOK_NUMBER);
if (swapflag)
swap_buffer(&x,1,sizeof(real));
write_buffer( &x, sizeof(real) );
return 1;
}
if (! (p->flags & C_EXTERN))
{
error(NIL,"Internal error: What's this",p);
}
if (p->Class == &string_class)
{
char *s = SADD(p->Object);
int l = strlen(s);
write_card8(TOK_STRING);
write_card24(l);
write_buffer(s,l);
return 1;
}
if (p->Class == &symbol_class)
{
char *s = nameof(p);
int l = strlen(s);
write_card8(TOK_SYMBOL);
write_card24(l);
write_buffer(s,l);
return 1;
}
if (p->flags & X_OOSTRUCT)
{
struct oostruct *s = p->Object;
write_card8(TOK_OBJECT);
write_card24(s->size);
return 0;
}
if (p->Class == &class_class)
{
struct class *c = p->Object;
if (c->atsuper && !c->classdoc)
write_card8(TOK_CLASS);
else
write_card8(TOK_CCLASS);
return 0;
}
if (p->Class == &index_class && !opt_bwrite)
{
int i;
struct index *arr = p->Object;
if (arr->st->srg.type == ST_AT)
{
/* THIS IS AN ARRAY */
int ndim = arr->ndim;
if (arr->flags & STF_UNSIZED)
ndim = 0xFFFFFF;
write_card8(TOK_ARRAY);
write_card24(ndim);
for (i=0; i<ndim; i++)
write_card32(arr->dim[i]);
return 0;
}
else
{
/* THIS IS A MATRIX */
write_card8(TOK_MATRIX);
in_bwrite += save_matrix_len(p);
if (arr->st->srg.type == ST_GPTR)
error(NIL,"Cannot save a gptr matrix",p);
if (arr->st->srg.type == ST_GPTR)
error(NIL,"Cannot save a lisp array",p);
save_matrix(p, fout);
return 1;
}
}
if (p->Class == &de_class)
{
write_card8(TOK_DE);
return 0;
}
if (p->Class == &df_class)
{
write_card8(TOK_DF);
return 0;
}
if (p->Class == &dm_class)
{
write_card8(TOK_DM);
return 0;
}
if (p->Class == &dx_class ||
p->Class == &dy_class ||
p->Class == &dh_class )
{
write_card8(TOK_CFUNC);
return 0;
}
if (p->Class->serialize)
{
write_card8(TOK_COBJECT);
return 0;
}
error(NIL,"Cannot save this object",p);
}
/* Writes object p on file f.
* Returns the number of bytes
*/
int
bwrite(at *p, FILE *f, int opt)
{
int count;
if (in_bwrite!=0)
error(NIL,"Recursive binary read/write are forbidden",NIL);
opt_bwrite = opt;
fout = f;
in_bwrite = 0;
clear_reloc(0);
set_flags(p);
write_card8(BINARYSTART);
write_card24(relocn);
sweep(p, SRZ_WRITE);
clear_flags(p);
count = in_bwrite;
in_bwrite = 0;
return count;
}
DX(xbwrite)
{
int i;
int count = 0;
ALL_ARGS_EVAL;
for (i=1; i<=arg_number; i++)
count += bwrite( APOINTER(i), context->output_file, FALSE );
return NEW_NUMBER(count);
}
DX(xbwrite_exact)
{
int i;
int count = 0;
ALL_ARGS_EVAL;
for (i=1; i<=arg_number; i++)
count += bwrite( APOINTER(i), context->output_file, TRUE );
return NEW_NUMBER(count);
}
/*** BINARY READ ***/
/* Special routines for reading array and objects */
static void
local_bread_cobject(at **pp)
{
at *name, *cname, *cptr;
class *cl;
if (local_bread(&cname, NIL))
error(NIL,"Corrupted file (unresolved class)",NIL);
name = cname;
cptr = NIL;
if (CONSP(cname))
cptr = find_primitive(cname->Car, name = cname->Cdr);
if (! cptr)
cptr = find_primitive(NIL, name);
if (! EXTERNP(name, &symbol_class))
error(NIL,"Corrupted file (expecting class name)",NIL);
if (! EXTERNP(cptr,&class_class))
error(NIL,"Cannot find primitive class",name);
cl = cptr->Object;
if (! cl->serialize)
error(NIL,"Serialization error (undefined serialization)",name);
UNLOCK(cname);
*pp = 0;
(*cl->serialize)(pp,SRZ_READ);
UNLOCK(cptr);
}
static void
local_bread_object(at **pp, int opt)
{
int size,i,j;
at *name, *cname, *cptr;
struct oostruct *s;
size = read_card24();
if (local_bread(&cptr, NIL))
error(NIL,"Corrupted file (unresolved class)",NIL);
cname = cptr;
if (EXTERNP(cname,&symbol_class))
cptr = var_get(cname);
if (! EXTERNP(cptr, &class_class))
error(NIL,"Corrupted binary file (class expected)",cname);
if (cname == cptr) {
cname = ((struct class*)(cptr->Object))->classname;
LOCK(cname);
}
*pp = new_oostruct(cptr); /* create structure */
s = (*pp)->Object; /* access slots */
if (size > s->size)
error(NIL,"Class definition has less slots than expected",cname);
else if ( (size < s->size) && opt)
error(NIL,"Class definition has more slots than expected",cname);
for(i=j=0; i<size; i++,j++)
{
if (local_bread(&name, NIL))
error(NIL,"Corrupted file (accessing slot name)",cname);
ifn (EXTERNP(name,&symbol_class))
error(NIL,"Corrupted binary file (slot name expected)",cname);
while (j<s->size && name!=s->slots[j].symb)
j += 1;
if (j>= s->size)
error(NIL,"Incompatible class definition",cname);
UNLOCK(name);
UNLOCK(s->slots[j].val);
s->slots[j].val = NIL;
local_bread(&(s->slots[j].val), NIL);
}
UNLOCK(cname);
UNLOCK(cptr);
}
static void
local_bread_class(at **pp)
{
at *name, *super, *key, *def;
struct class *cl;
if (local_bread(&name, NIL) ||
local_bread(&super, NIL) ||
local_bread(&key, NIL) ||
local_bread(&def, NIL) )
error(NIL,"Corrupted file (unresolved critical class component!)",NIL);
*pp = new_ooclass(name,super,key,def);
cl = (*pp)->Object;
local_bread(&cl->methods, NIL);
cl->hashok = FALSE;
}
static void
local_bread_array(at **pp)
{
struct index *ind;
struct idx id;
int dim[MAXDIMS];
int i, size, ndim;
ndim = read_card24();
if (ndim == 0xFFFFFF)
{
/* THIS IS AN UNSIZED ARRAY */
at *atst = new_AT_storage();
*pp = new_index(atst);
UNLOCK(atst);
}
else if (ndim < MAXDIMS)
{
/* THIS IS A NORMAL ARRAY */
size = 1;
for (i=0; i<ndim; i++)
size *= ( dim[i] = read_card32() );
*pp = AT_matrix(ndim,dim);
ind = (*pp)->Object;
index_write_idx(ind, &id);
pp = IDX_DATA_PTR(&id);
for (i=0; i<size; i++)
local_bread(pp++, NIL);
index_rls_idx(ind,&id);
}
else
error(NIL,"corrupted binary file",NIL);
}
static void
local_bread_lfunction(at **pp, at *(*new) (at*, at*))
{
struct lfunction *f;
*pp = (*new)(NIL,NIL);
f = (*pp)->Object;
local_bread( & f->formal_arg_list, NIL );
local_bread( & f->evaluable_list, NIL );
}
static void
local_bread_primitive(at **pp)
{
at *p, *q;
if (local_bread(&q, NIL))
error(NIL,"Corrupted file (unresolved symbol!)",NIL);
if (CONSP(q)) {
p = find_primitive(q->Car, q->Cdr);
if (! p)
p = find_primitive(NIL, q->Cdr);
} else
p = find_primitive(NIL,q);
if (! p)
error(NIL,"Cannot find primitive", q);
UNLOCK(q);
*pp = p;
}
/* This is the basic reading routine */
static int
local_bread(at **pp, int opt)
{
int tok;
int ret = 1;
again:
tok = read_card8();
switch (tok)
{
case TOK_DEF:
{
int xdef;
xdef = read_card24();
if (local_bread(pp, opt))
error(NIL,"corrupted binary file (unresolved ref follows def)",NIL);
if (relocf[xdef] == R_DEFD)
error(NIL,"corrupted binary file (duplicate reloc definition)",NIL);
if (relocf[xdef] == R_REFD)
define_refd_reloc(xdef,*pp);
relocf[xdef] = R_DEFD;
relocp[xdef] = *pp;
return 0;
}
case TOK_REF:
{
int xdef;
xdef = read_card24();
if (xdef<0 || xdef>=relocn)
error(NIL,"corrupted binary file (illegal ref)",NIL);
if (relocf[xdef] == R_DEFD) {
*pp = relocp[xdef];
LOCK(*pp);
return 0;
} else {
*pp = relocp[xdef];
relocp[xdef] = pp;
relocf[xdef] = R_REFD;
return ret;
}
}
case TOK_NIL:
{
*pp = NIL;
return 0;
}
case TOK_CONS:
{
*pp = new_cons(NIL,NIL);
local_bread( & ((*pp)->Car), opt );
pp = & ((*pp)->Cdr);
ret = 0;
goto again;
}
case TOK_NUMBER:
{
*pp = new_number(0.0);
read_buffer( &(*pp)->Number, sizeof(real) );
if (swapflag)
swap_buffer( &(*pp)->Number, 1, sizeof(real) );
return 0;
}
case TOK_STRING:
{
int l = read_card24();
*pp = new_string_bylen(l);
read_buffer(SADD((*pp)->Object),l);
return 0;
}
case TOK_SYMBOL:
{
int l = read_card24();
read_buffer(string_buffer,l);
string_buffer[l] = 0;
*pp = named(string_buffer);
return 0;
}
case TOK_OBJECT:
{
local_bread_object(pp, opt);
return 0;
}
case TOK_CLASS:
{
local_bread_class(pp);
return 0;
}
case TOK_ARRAY:
{
local_bread_array(pp);
return 0;
}
case TOK_MATRIX:
{
*pp = load_matrix(fin);
return 0;
}
case TOK_DE:
{
local_bread_lfunction(pp,new_de);
return 0;
}
case TOK_DF:
{
local_bread_lfunction(pp,new_df);
return 0;
}
case TOK_DM:
{
local_bread_lfunction(pp,new_dm);
return 0;
}
case TOK_CFUNC:
{
local_bread_primitive(pp);
return 0;
}
case TOK_CCLASS:
{
class *cl;
local_bread_primitive(pp);
cl = (*pp)->Object;
local_bread(&cl->methods, opt);
cl->hashok = 0;
return 0;
}
case TOK_COBJECT:
{
local_bread_cobject(pp);
return 0;
}
default:
error(NIL,"corrupted binary file (illegal token in file)",NEW_NUMBER(tok));
}
}
at *
bread(FILE *f, int opt)
{
at *ans = NIL;
int tok;
if (in_bwrite!=0)
error(NIL,"Recursive binary read/write are forbidden",NIL);
fin = f;
in_bwrite = -1;
tok = read_card8();
if (tok != BINARYSTART)
error(NIL,"corrupted binary file (cannot find BINARYSTART)",NIL);
tok = read_card24();
if (tok<0 || tok>10000000)
error(NIL,"corrupted binary file (illegal reloc number)",NEW_NUMBER(tok));
clear_reloc(tok);
local_bread(&ans, opt);
forbid_refd_reloc();
in_bwrite = 0;
return ans;
}
DX(xbread)
{
ARG_NUMBER(0);
return bread(context->input_file, FALSE);
}
DX(xbread_exact)
{
ARG_NUMBER(0);
return bread(context->input_file, TRUE);
}
/*** INITIALISATION ***/
void
init_binary(void)
{
set_swapflag();
dx_define("bwrite",xbwrite);
dx_define("bwrite-exact",xbwrite_exact);
dx_define("bread",xbread);
dx_define("bread-exact",xbread_exact);
}
| 0 | 0.952826 | 1 | 0.952826 | game-dev | MEDIA | 0.258513 | game-dev | 0.992177 | 1 | 0.992177 |
Shinoow/AbyssalCraft | 2,405 | src/main/java/com/shinoow/abyssalcraft/api/block/SingletonInventoryUtil.java | /*******************************************************************************
* AbyssalCraft
* Copyright (c) 2012 - 2025 Shinoow.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v3
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-3.0.txt
*
* Contributors:
* Shinoow - implementation
******************************************************************************/
package com.shinoow.abyssalcraft.api.block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.SoundEvents;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
/**
* Utility class for common handling code used along with<br>
* {@link ISingletonInventory} implementations.
* @author shinoow
*
*/
public class SingletonInventoryUtil {
/**
* Call this in the block's onBlockActivated method to handle
* placing/removing something on/from the block
* @param world Current World
* @param pos Current position
* @param player Interacting Player
* @param heldItem Current held item
* @return True if successful, otherwise false
*/
public static boolean handleBlockActivation(World world, BlockPos pos, EntityPlayer player, ItemStack heldItem){
TileEntity tile = world.getTileEntity(pos);
if(tile != null && tile instanceof ISingletonInventory)
if(!((ISingletonInventory)tile).getItem().isEmpty()){
if(player.inventory.addItemStackToInventory(((ISingletonInventory)tile).getItem())){
((ISingletonInventory)tile).setItem(ItemStack.EMPTY);
world.playSound(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, SoundEvents.ENTITY_ITEM_PICKUP, SoundCategory.PLAYERS, 0.5F, world.rand.nextFloat() - world.rand.nextFloat() * 0.2F + 1, false);
return true;
}
} else if(!heldItem.isEmpty()){
ItemStack newItem = heldItem.copy();
newItem.setCount(1);
((ISingletonInventory)tile).setItem(newItem);
heldItem.shrink(1);
world.playSound(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, SoundEvents.ENTITY_ITEM_PICKUP, SoundCategory.PLAYERS, 0.5F, world.rand.nextFloat() - world.rand.nextFloat() * 0.2F + 1, false);
return true;
}
return false;
}
}
| 0 | 0.739575 | 1 | 0.739575 | game-dev | MEDIA | 0.999005 | game-dev | 0.616248 | 1 | 0.616248 |
The-Aether-Team/The-Aether-II | 2,423 | src/main/java/com/aetherteam/aetherii/entity/ai/brain/behavior/taegore/TaegoreFinishedDigging.java | package com.aetherteam.aetherii.entity.ai.brain.behavior.taegore;
import com.aetherteam.aetherii.entity.ai.brain.memory.AetherIIMemoryModuleTypes;
import com.aetherteam.aetherii.entity.passive.Taegore;
import net.minecraft.core.BlockPos;
import net.minecraft.core.GlobalPos;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.ai.behavior.Behavior;
import net.minecraft.world.entity.ai.memory.MemoryModuleType;
import net.minecraft.world.entity.ai.memory.MemoryStatus;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class TaegoreFinishedDigging extends Behavior<Taegore> {
public TaegoreFinishedDigging(int duration) {
super(Map.of(
MemoryModuleType.IS_PANICKING, MemoryStatus.VALUE_ABSENT,
MemoryModuleType.WALK_TARGET, MemoryStatus.VALUE_ABSENT,
AetherIIMemoryModuleTypes.TAEGORE_DIGGING.get(), MemoryStatus.VALUE_PRESENT,
AetherIIMemoryModuleTypes.TAEGORE_SEARCH_COOLDOWN.get(), MemoryStatus.VALUE_PRESENT
), duration, duration);
}
protected boolean checkExtraStartConditions(ServerLevel serverLevel, Taegore owner) {
return true;
}
protected boolean canStillUse(ServerLevel serverLevel, Taegore owner, long gameTime) {
return owner.getBrain().getMemory(AetherIIMemoryModuleTypes.TAEGORE_DIGGING.get()).isPresent();
}
@Override
protected void start(ServerLevel serverLevel, Taegore owner, long gameTime) {
serverLevel.broadcastEntityEvent(owner, (byte) Taegore.DIGGING_STOP_EVENT);
}
protected void stop(ServerLevel serverLevel, Taegore owner, long gameTime) {
boolean flag = this.timedOut(gameTime);
this.onDiggingComplete(owner, flag);
owner.getBrain().eraseMemory(AetherIIMemoryModuleTypes.TAEGORE_DIGGING.get());
}
public void onDiggingComplete(Taegore owner, boolean storeExploredPosition) {
if (storeExploredPosition) {
this.storeExploredPosition(owner, owner.getOnPos());
}
}
private void storeExploredPosition(Taegore owner, BlockPos pos) {
List<GlobalPos> list = owner.getExploredPositions().limit(20L).collect(Collectors.toList());
list.addFirst(GlobalPos.of(owner.level().dimension(), pos));
owner.getBrain().setMemory(AetherIIMemoryModuleTypes.TAEGORE_EXPLORED_POSITIONS.get(), list);
}
}
| 0 | 0.906978 | 1 | 0.906978 | game-dev | MEDIA | 0.98418 | game-dev | 0.88051 | 1 | 0.88051 |
Fluorohydride/ygopro-scripts | 2,087 | c31222701.lua | --揺れる眼差し
function c31222701.initial_effect(c)
--activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_DESTROY+CATEGORY_DAMAGE+CATEGORY_SEARCH)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(c31222701.target)
e1:SetOperation(c31222701.activate)
c:RegisterEffect(e1)
end
function c31222701.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetFieldGroupCount(tp,LOCATION_PZONE,LOCATION_PZONE)>0 end
local g=Duel.GetFieldGroup(tp,LOCATION_PZONE,LOCATION_PZONE)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0)
Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,500)
end
function c31222701.thfilter1(c)
return c:IsType(TYPE_PENDULUM) and c:IsAbleToHand()
end
function c31222701.thfilter2(c)
return c:IsCode(31222701) and c:IsAbleToHand()
end
function c31222701.activate(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetFieldGroup(tp,LOCATION_PZONE,LOCATION_PZONE)
local ct=Duel.Destroy(g,REASON_EFFECT)
if ct>=1 then
Duel.BreakEffect()
Duel.Damage(1-tp,500,REASON_EFFECT)
end
local hg1=Duel.GetMatchingGroup(c31222701.thfilter1,tp,LOCATION_DECK,0,nil)
if ct>=2 and hg1:GetCount()>0 and Duel.SelectYesNo(tp,aux.Stringid(31222701,0)) then
Duel.BreakEffect()
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local shg1=hg1:Select(tp,1,1,nil)
Duel.SendtoHand(shg1,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,shg1)
end
local rg=Duel.GetMatchingGroup(Card.IsAbleToRemove,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,aux.ExceptThisCard(e))
if ct>=3 and rg:GetCount()>0 and Duel.SelectYesNo(tp,aux.Stringid(31222701,1)) then
Duel.BreakEffect()
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local srg=rg:Select(tp,1,1,nil)
Duel.Remove(srg,POS_FACEUP,REASON_EFFECT)
end
local hg2=Duel.GetMatchingGroup(c31222701.thfilter2,tp,LOCATION_DECK,0,nil)
if ct==4 and hg2:GetCount()>0 and Duel.SelectYesNo(tp,aux.Stringid(31222701,2)) then
Duel.BreakEffect()
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local shg2=hg2:Select(tp,1,1,nil)
Duel.SendtoHand(shg2,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,shg2)
end
end
| 0 | 0.742259 | 1 | 0.742259 | game-dev | MEDIA | 0.959499 | game-dev | 0.887581 | 1 | 0.887581 |
ouya/ouya-sdk-examples | 15,288 | Marmalade/MarmaladeODK/source/android/ODK_platform.cpp | /*
* Copyright (C) 2012, 2013 OUYA, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* android-specific implementation of the ODK extension.
* Add any platform-specific functionality here.
*/
/*
* NOTE: This file was originally written by the extension builder, but will not
* be overwritten (unless --force is specified) and is intended to be modified.
*/
#include "ODK_internal.h"
#include "CallbackSingleton.h"
#include "CallbacksInitOuyaPlugin.h"
#include "CallbacksRequestGamerInfo.h"
#include "CallbacksRequestProducts.h"
#include "CallbacksRequestPurchase.h"
#include "CallbacksRequestReceipts.h"
#include "JSONArray.h"
#include "JSONObject.h"
#include "OuyaController.h"
#include "PluginOuya.h"
#include <map>
#include "s3eEdk.h"
#include "s3eEdk_android.h"
#include <jni.h>
#include "IwDebug.h"
#include <android/log.h>
#define LOG_TAG "ODK_platform.cpp"
using namespace org_json_JSONObject;
using namespace org_json_JSONArray;
using namespace tv_ouya_console_api_OuyaController;
static OuyaSDK::PluginOuya g_pluginOuya;
// use string to send char* to invoker
static std::string g_tempPluginString;
#define MAX_CONTROLLERS 4
//axis states
static std::vector< std::map<int, float> > g_axis;
//button states
static std::vector< std::map<int, bool> > g_button;
static std::vector< std::map<int, bool> > g_buttonDown;
static std::vector< std::map<int, bool> > g_buttonUp;
static std::vector< std::map<int, bool> > g_lastButtonDown;
static std::vector< std::map<int, bool> > g_lastButtonUp;
void dispatchGenericMotionEventNative(JNIEnv* env, jobject thiz,
jint deviceId,
jint axis,
jfloat val)
{
#if ENABLE_VERBOSE_LOGGING
__android_log_print(ANDROID_LOG_INFO, LOG_TAG, "dispatchGenericMotionEventNative: Device=%d axis=%d val=%f", deviceId, axis, val);
#endif
if (deviceId < 0 ||
deviceId >= MAX_CONTROLLERS)
{
deviceId = 0;
}
g_axis[deviceId][axis] = val;
}
void dispatchKeyEventNative(JNIEnv* env, jobject thiz,
jint deviceId,
jint keyCode,
jint action)
{
#if ENABLE_VERBOSE_LOGGING
__android_log_print(ANDROID_LOG_INFO, LOG_TAG, "dispatchKeyEventNative: Device=%d KeyCode=%d Action=%d", deviceId, keyCode, action);
#endif
if (deviceId < 0 ||
deviceId >= MAX_CONTROLLERS)
{
deviceId = 0;
}
bool buttonDown = action == 0;
if (g_button[deviceId][keyCode] != buttonDown)
{
g_button[deviceId][keyCode] = buttonDown;
if (buttonDown)
{
g_buttonDown[deviceId][keyCode] = true;
}
else
{
g_buttonUp[deviceId][keyCode] = true;
}
}
}
static JNINativeMethod method_table[] = {
{ "dispatchGenericMotionEventNative", "(IIF)V", (void *)dispatchGenericMotionEventNative }
};
static int method_table_size = sizeof(method_table) / sizeof(method_table[0]);
static JNINativeMethod method_table2[] = {
{ "dispatchKeyEventNative", "(III)V", (void *)dispatchKeyEventNative }
};
static int method_table_size2 = sizeof(method_table2) / sizeof(method_table2[0]);
s3eResult ODKInit_platform()
{
__android_log_print(ANDROID_LOG_INFO, LOG_TAG, "Marmalade Plugin Native Version: 0.0.1");
IwTrace(ODK, ("Marmalade Plugin Native Version: 0.0.1"));
// Get the environment from the pointer
JNIEnv* env = s3eEdkJNIGetEnv();
for (int index = 0; index < MAX_CONTROLLERS; ++index)
{
g_axis.push_back(std::map<int, float>());
g_button.push_back(std::map<int, bool>());
g_buttonDown.push_back(std::map<int, bool>());
g_buttonUp.push_back(std::map<int, bool>());
g_lastButtonDown.push_back(std::map<int, bool>());
g_lastButtonUp.push_back(std::map<int, bool>());
}
__android_log_print(ANDROID_LOG_INFO, LOG_TAG, "Find OuyaInputView...");
jclass clazz = env->FindClass("tv/ouya/sdk/marmalade/OuyaInputView");
if (clazz)
{
jint ret = env->RegisterNatives(clazz, method_table, method_table_size);
ret = env->RegisterNatives(clazz, method_table2, method_table_size2);
const char* strField = "sNativeInitialized";
jfieldID fieldNativeInitialized = env->GetStaticFieldID(clazz, strField, "Z");
env->SetStaticBooleanField(clazz, fieldNativeInitialized, true);
env->DeleteLocalRef(clazz);
__android_log_print(ANDROID_LOG_INFO, LOG_TAG, "Loaded Native Plugin: 003");
}
else
{
IwTrace(ODK, ("*********************Failed to find OuyaInputView"));
goto fail;
}
if (JSONArray::InitJNI(env) == JNI_ERR)
{
goto fail;
}
if (JSONObject::InitJNI(env) == JNI_ERR)
{
goto fail;
}
if (OuyaController::InitJNI(env) == JNI_ERR)
{
goto fail;
}
// cache class references
g_pluginOuya.CacheClasses(env);
// Add any platform-specific initialization code here
return S3E_RESULT_SUCCESS;
fail:
jthrowable exc = env->ExceptionOccurred();
if (exc)
{
env->ExceptionDescribe();
env->ExceptionClear();
IwTrace(ODK, ("One or more java methods could not be found"));
}
return S3E_RESULT_ERROR;
}
void ODKTerminate_platform()
{
// Add any platform-specific termination code here
}
// get axis value, cast float to int for the application bridge
int OuyaPlugin_getAxis(int deviceId, int axis)
{
if (deviceId < 0 ||
deviceId >= MAX_CONTROLLERS)
{
deviceId = 0;
}
std::map<int, float>::const_iterator search = g_axis[deviceId].find(axis);
float val = 0.0f;
if (search != g_axis[deviceId].end())
{
val = search->second;
}
//__android_log_print(ANDROID_LOG_INFO, LOG_TAG, "OuyaPlugin_getAxis: Device=%d axis=%d val=%f", deviceId, axis, val);
return *(reinterpret_cast<int*>(&val));
}
// check if a button is pressed
bool OuyaPlugin_isPressed(int deviceId, int keyCode)
{
if (deviceId < 0 ||
deviceId >= MAX_CONTROLLERS)
{
deviceId = 0;
}
std::map<int, bool>::const_iterator search = g_button[deviceId].find(keyCode);
bool val = false;
if (search != g_button[deviceId].end())
{
val = search->second;
}
//__android_log_print(ANDROID_LOG_INFO, LOG_TAG, "OuyaPlugin_isPressed: Device=%d KeyCode=%d Action=%d", deviceId, keyCode, val);
return val;
}
// check if a button was down
bool OuyaPlugin_isPressedDown(int deviceId, int keyCode)
{
if (deviceId < 0 ||
deviceId >= MAX_CONTROLLERS)
{
deviceId = 0;
}
std::map<int, bool>::const_iterator search = g_lastButtonDown[deviceId].find(keyCode);
if (search != g_lastButtonDown[deviceId].end())
{
return search->second;
}
return false;
}
// check if a button was up
bool OuyaPlugin_isPressedUp(int deviceId, int keyCode)
{
if (deviceId < 0 ||
deviceId >= MAX_CONTROLLERS)
{
deviceId = 0;
}
std::map<int, bool>::const_iterator search = g_lastButtonUp[deviceId].find(keyCode);
if (search != g_lastButtonUp[deviceId].end())
{
return search->second;
}
return false;
}
// clear the button state for detecting up and down
void OuyaPlugin_clearButtonStates()
{
for (int deviceId = 0; deviceId < MAX_CONTROLLERS; ++deviceId)
{
g_lastButtonDown[deviceId].clear();
g_lastButtonUp[deviceId].clear();
for (std::map<int, bool>::iterator it = g_buttonDown[deviceId].begin(); it != g_buttonDown[deviceId].end(); ++it)
{
int keyCode = it->first;
g_lastButtonDown[deviceId][keyCode] = g_buttonDown[deviceId][keyCode];
}
for (std::map<int, bool>::iterator it = g_buttonUp[deviceId].begin(); it != g_buttonUp[deviceId].end(); ++it)
{
int keyCode = it->first;
g_lastButtonUp[deviceId][keyCode] = g_buttonUp[deviceId][keyCode];
}
g_buttonDown[deviceId].clear();
g_buttonUp[deviceId].clear();
}
}
const char* OuyaPlugin_getDeviceName(int playerNum)
{
OuyaController* ouyaController = OuyaController::getControllerByPlayer(playerNum);
if (NULL != ouyaController)
{
g_tempPluginString = ouyaController->getDeviceName();
ouyaController->Dispose();
}
else
{
g_tempPluginString = "Unavailable";
}
return g_tempPluginString.c_str();
}
void OuyaPlugin_initOuyaPlugin(const char* jsonData, s3eCallback onSuccess, s3eCallback onFailure)
{
IwTrace(ODK, ("OuyaPlugin_initOuyaPlugin"));
OuyaSDK::CallbackSingleton::GetInstance()->m_callbacksInitOuyaPlugin->RegisterCallbacks(onSuccess, onFailure);
g_pluginOuya.AsyncInitOuyaPlugin(jsonData);
}
void OuyaPlugin_asyncOuyaRequestGamerInfo(s3eCallback onSuccess, s3eCallback onFailure, s3eCallback onCancel)
{
IwTrace(ODK, ("ODK_platform: OuyaPlugin_asyncOuyaRequestGamerInfo"));
OuyaSDK::CallbackSingleton::GetInstance()->m_callbacksRequestGamerInfo->RegisterCallbacks(onSuccess, onFailure, onCancel);
g_pluginOuya.AsyncOuyaRequestGamerInfo();
}
void OuyaPlugin_asyncOuyaRequestProducts(const char* productsJson, s3eCallback onSuccess, s3eCallback onFailure, s3eCallback onCancel)
{
IwTrace(ODK, ("ODK_platform: OuyaPlugin_asyncOuyaRequestProducts"));
std::string msg = "OuyaPlugin_asyncOuyaRequestProducts: productsJson=";
msg.append(productsJson);
IwTrace(ODK, (msg.c_str()));
//convert JSON to product id array
JSONArray jsonArray = JSONArray(productsJson);
std::vector<std::string> productIds;
for (int i = 0; i < jsonArray.length(); i++)
{
std::string productId = jsonArray.getString(i);
productIds.push_back(productId);
}
OuyaSDK::CallbackSingleton::GetInstance()->m_callbacksRequestProducts->RegisterCallbacks(onSuccess, onFailure, onCancel);
g_pluginOuya.AsyncOuyaRequestProducts(productIds);
}
void OuyaPlugin_asyncOuyaRequestPurchase(const char* purchasable, s3eCallback onSuccess, s3eCallback onFailure, s3eCallback onCancel)
{
IwTrace(ODK, ("ODK_platform: OuyaPlugin_asyncOuyaRequestPurchase"));
std::string msg = "OuyaPlugin_asyncOuyaRequestPurchase: purchasable=";
msg.append(purchasable);
IwTrace(ODK, (msg.c_str()));
OuyaSDK::CallbackSingleton::GetInstance()->m_callbacksRequestPurchase->RegisterCallbacks(onSuccess, onFailure, onCancel);
g_pluginOuya.AsyncOuyaRequestPurchase(purchasable);
}
void OuyaPlugin_asyncOuyaRequestReceipts(s3eCallback onSuccess, s3eCallback onFailure, s3eCallback onCancel)
{
IwTrace(ODK, ("ODK_platform: OuyaPlugin_asyncOuyaRequestReceipts"));
OuyaSDK::CallbackSingleton::GetInstance()->m_callbacksRequestReceipts->RegisterCallbacks(onSuccess, onFailure, onCancel);
g_pluginOuya.AsyncOuyaRequestReceipts();
}
static int g_refCountJSONObject = 0;
static std::map<int, JSONObject*> g_refJSONObject = std::map<int, JSONObject*>();
int OuyaPlugin_JSONObject_Construct()
{
JSONObject* jsonObject = new JSONObject();
g_refJSONObject[g_refCountJSONObject] = jsonObject;
int result = g_refCountJSONObject;
++g_refCountJSONObject;
return result;
}
void OuyaPlugin_JSONObject_Put(int jsonObject, const char* name, const char* value)
{
#if ENABLE_VERBOSE_LOGGING
__android_log_print(ANDROID_LOG_INFO, LOG_TAG, "OuyaPlugin_JSONObject_Put: jsonObject=%d", jsonObject);
#endif
std::map<int, JSONObject*>::const_iterator search = g_refJSONObject.find(jsonObject);
if (search != g_refJSONObject.end())
{
JSONObject* instance = search->second;
if (instance)
{
#if ENABLE_VERBOSE_LOGGING
__android_log_print(ANDROID_LOG_INFO, LOG_TAG, "OuyaPlugin_JSONObject_Put JSONObject reference is valid");
#endif
instance->put(name, value);
}
else
{
__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, "OuyaPlugin_JSONObject_Put JSONObject reference is invalid");
}
}
else
{
__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, "OuyaPlugin_JSONObject_Put failed to find JSONObject reference");
}
}
const char* OuyaPlugin_JSONObject_ToString(int jsonObject)
{
#if ENABLE_VERBOSE_LOGGING
__android_log_print(ANDROID_LOG_INFO, LOG_TAG, "OuyaPlugin_JSONObject_ToString: jsonObject=%d", jsonObject);
#endif
std::map<int, JSONObject*>::const_iterator search = g_refJSONObject.find(jsonObject);
if (search != g_refJSONObject.end())
{
JSONObject* instance = search->second;
if (instance)
{
#if ENABLE_VERBOSE_LOGGING
__android_log_print(ANDROID_LOG_INFO, LOG_TAG, "OuyaPlugin_JSONObject_ToString JSONObject reference is valid");
#endif
g_tempPluginString = instance->toString();
#if ENABLE_VERBOSE_LOGGING
__android_log_print(ANDROID_LOG_INFO, LOG_TAG, "OuyaPlugin_JSONObject_ToString jsonData=%s", g_tempPluginString.c_str());
#endif
return g_tempPluginString.c_str();
}
else
{
__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, "OuyaPlugin_JSONObject_ToString JSONObject reference is invalid");
}
}
else
{
__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, "OuyaPlugin_JSONObject_ToString failed to find JSONObject reference");
}
return "";
}
static int g_refCountJSONArray = 0;
static std::map<int, JSONArray*> g_refJSONArray = std::map<int, JSONArray*>();
int OuyaPlugin_JSONArray_Construct()
{
JSONArray* jsonArray = new JSONArray();
g_refJSONArray[g_refCountJSONArray] = jsonArray;
int result = g_refCountJSONArray;
++g_refCountJSONArray;
return result;
}
void OuyaPlugin_JSONArray_Put(int jsonArray, int index, int jsonObject)
{
std::map<int, JSONArray*>::const_iterator searchJSONArray = g_refJSONArray.find(jsonArray);
if (searchJSONArray == g_refJSONArray.end())
{
__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, "OuyaPlugin_JSONArray_Put JSONArray reference is invalid");
return;
}
std::map<int, JSONObject*>::const_iterator searchJSONObject = g_refJSONObject.find(jsonObject);
if (searchJSONObject == g_refJSONObject.end())
{
__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, "OuyaPlugin_JSONArray_Put JSONObject reference is invalid");
return;
}
JSONArray* instanceJSONArray = searchJSONArray->second;
if (!instanceJSONArray)
{
__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, "OuyaPlugin_JSONArray_Put JSONArray instance is invalid");
return;
}
JSONObject* instanceJSONObject = searchJSONObject->second;
if (!instanceJSONObject)
{
__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, "OuyaPlugin_JSONArray_Put JSONObject instance is invalid");
return;
}
instanceJSONArray->put(index, instanceJSONObject->GetInstance());
}
const char* OuyaPlugin_JSONArray_ToString(int jsonArray)
{
#if ENABLE_VERBOSE_LOGGING
__android_log_print(ANDROID_LOG_INFO, LOG_TAG, "OuyaPlugin_JSONArray_ToString: jsonArray=%d", jsonArray);
#endif
std::map<int, JSONArray*>::const_iterator search = g_refJSONArray.find(jsonArray);
if (search != g_refJSONArray.end())
{
JSONArray* instance = search->second;
if (instance)
{
#if ENABLE_VERBOSE_LOGGING
__android_log_print(ANDROID_LOG_INFO, LOG_TAG, "OuyaPlugin_JSONArray_ToString JSONArray reference is valid");
#endif
g_tempPluginString = instance->toString();
#if ENABLE_VERBOSE_LOGGING
__android_log_print(ANDROID_LOG_INFO, LOG_TAG, "OuyaPlugin_JSONArray_ToString jsonData=%s", g_tempPluginString.c_str());
#endif
return g_tempPluginString.c_str();
}
else
{
__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, "OuyaPlugin_JSONArray_ToString JSONArray reference is invalid");
}
}
else
{
__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, "OuyaPlugin_JSONArray_ToString failed to find JSONArray reference");
}
return "";
}
| 0 | 0.918516 | 1 | 0.918516 | game-dev | MEDIA | 0.489177 | game-dev | 0.877032 | 1 | 0.877032 |
DigitalRune/DigitalRune | 44,508 | Source/DigitalRune.Animation/AnimationInstance.cs | // DigitalRune Engine - Copyright (C) DigitalRune GmbH
// This file is subject to the terms and conditions defined in
// file 'LICENSE.TXT', which is part of this source code package.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using DigitalRune.Mathematics;
namespace DigitalRune.Animation
{
/// <summary>
/// Represents an instance of an animation timeline.
/// </summary>
/// <remarks>
/// <para>
/// Animation instances are used to play back animations. They maintain the runtime-state of an
/// animation.
/// </para>
/// <para>
/// Animation instances are automatically created and managed by the animation system when a new
/// animation is started using one of the <strong>StartAnimation</strong>-methods or when an
/// animation controller is created using one of the <strong>CreateController</strong>-methods
/// (see <see cref="IAnimationService"/>).
/// </para>
/// <para>
/// <strong>Animation Value:</strong> An animation usually produces a value as the output. The
/// base class <see cref="AnimationInstance"/> manages the timeline of the animation. The derived
/// class <see cref="AnimationInstance{T}"/> manages the animation value. The animation system
/// automatically applies the output values to the properties that are being animated (see
/// <see cref="IAnimatableProperty{T}"/>).
/// </para>
/// <para>
/// <strong>Animation State and Timing:</strong> The property <see cref="State"/> returns the
/// current state of the animation. The animation can be <see cref="AnimationState.Delayed"/>,
/// <see cref="AnimationState.Playing"/>, <see cref="AnimationState.Filling"/> or
/// <see cref="AnimationState.Stopped"/>. But the state does not indicate whether the animation
/// timing is active. The property <see cref="IsPaused"/> indicates whether the animation timing
/// is active or paused.
/// </para>
/// <para>
/// Active animations are managed by the <see cref="AnimationManager"/>. The animation system
/// automatically advances and updates the animations.
/// </para>
/// <para>
/// The current state of an animation is computed once per frame (in
/// <see cref="AnimationManager.Update"/>) and cached until the next frame. The animation instance
/// does not monitor the animation for changes. I.e. when the animation is modified the animation
/// instance needs to be notified by calling <see cref="Invalidate"/>. Otherwise, it can return an
/// invalid state in the current frame. For example, an animation instance plays a certain
/// <see cref="TimelineClip"/>. During playback the user changes the
/// <see cref="TimelineClip.Delay"/> of the animation. Now, when the user reads
/// <see cref="State"/> in the same frame the instance might return the wrong value. The user
/// needs to call <see cref="Invalidate"/> to get the correct, up-to-date value. (It is not
/// necessary to call <see cref="Invalidate"/> if the animations are updated using
/// <see cref="AnimationManager.Update"/>. <see cref="AnimationManager.Update"/>
/// automatically computes the new values.)
/// </para>
/// <para>
/// <strong>Animation Tree:</strong> Animation instances can have children. For example, when a
/// <see cref="TimelineGroup"/> is started it creates a root instance that has several children -
/// one animation instance per animation in the timeline group. A timeline group might contain
/// other timeline groups. The animation instances are organized in a tree structure.
/// </para>
/// <para>
/// Only the root instance of a tree can be controlled interactively (using an
/// <see cref="AnimationController"/>).
/// </para>
/// <para>
/// <strong>Speed Ratio:</strong> The playback speed of the animation tree can be controlled by
/// changing the property <see cref="Speed"/>. The speed ratio defines the rate at which time
/// progresses. The default value is 1. A value of, for example, 2 means that the animation runs
/// twice as fast. A value of 0.5 causes the animation to run in slow-motion at half speed.
/// </para>
/// <para>
/// Note that the only the speed ratio of the root instance in the animation tree can be
/// controlled. (Changing the speed ratio of other nodes in the animation tree has no effect.)
/// </para>
/// <para>
/// <strong>Animation Weights:</strong> Each animation instance has a weight (see
/// <see cref="Weight"/>) that defines the intensity of the animation. It is a factor that is
/// applied to the animation output. The animation weight is in particular relevant when multiple
/// animations should be combined. Each animation combines its output with the output of the
/// previous stage in the animation composition chain. (If the animation is the first animation of
/// a composition chain it combines its value with the base value of the property that is being
/// animated.)
/// </para>
/// <para>
/// The default value is 1, which means that 100% of the animation is returned overriding any
/// previous stage in an animation composition chain. A value of 0.75 means that result is
/// weighted combination of the previous stage (25%) and the output of the current animation
/// (75%). A value of 0 basically disables the output of the current stage.
/// </para>
/// <para>
/// Changing the animation weight of an instance affects the entire subtree: The current animation
/// instance and all children. The effective animation weight is the product of all weights from
/// the root instance to the current animation instance.
/// </para>
/// <para>
/// <strong>Secondary Animations:</strong> An animation instance itself is an
/// <see cref="IAnimatableObject"/>, which means that it has properties which can be animated.
/// The properties that can be animated are <see cref="Speed"/> and <see cref="Weight"/>.
/// Secondary animation can be used, for example, to fade-in an animation by letting the animation
/// weight go from 0 to 1 over time.
/// </para>
/// </remarks>
public class AnimationInstance : IAnimatableObject, IRecyclable
{
// Ideas for new methods:
// SkipToEnd() ... see SkipToFill() in WPF.
// Seek() ... see Seek() in WPF.
//--------------------------------------------------------------
#region Fields
//--------------------------------------------------------------
private static readonly ResourcePool<AnimationInstance> Pool = new ResourcePool<AnimationInstance>(
() => new AnimationInstance(), // Create
null, // Initialize
null); // Uninitialize
#endregion
//--------------------------------------------------------------
#region Properties & Events
//--------------------------------------------------------------
/// <summary>
/// Gets a value that indicates the version of the animation instance.
/// </summary>
/// <value>The version of the animation instance.</value>
/// <remarks>
/// This number is automatically incremented every time the animation instance is recycled.
/// </remarks>
internal int RunCount
{
get { return _runCount; }
}
private int _runCount;
/// <summary>
/// Gets the parent of this animation instance.
/// </summary>
/// <value>
/// The parent of this animation instance; <see langword="null"/>, if the current instance does
/// not have a parent.
/// </value>
public AnimationInstance Parent
{
get { return _parent; }
internal set { _parent = value; }
}
private AnimationInstance _parent;
/// <summary>
/// Gets the children of this animation instance.
/// </summary>
/// <value>The children of this animation instance.</value>
public AnimationInstanceCollection Children
{
get { return _children; }
}
private readonly AnimationInstanceCollection _children;
/// <summary>
/// Gets the animation timeline that is being played back.
/// </summary>
/// <value>The animation timeline that is being played back.</value>
public ITimeline Animation
{
get { return _animation; }
}
private ITimeline _animation;
/// <summary>
/// Gets or sets a value indicating whether this animation instance should be automatically
/// recycled when it is stopped and removed from the animation system.
/// </summary>
/// <value>
/// <see langword="true"/> if the animation instance is recycled automatically; otherwise,
/// <see langword="false"/>.
/// </value>
/// <remarks>
/// See <see cref="AnimationController"/> for more information.
/// </remarks>
public bool AutoRecycleEnabled
{
get { return _autoRecycleEnabled; }
set { _autoRecycleEnabled = value; }
}
private bool _autoRecycleEnabled;
/// <summary>
/// Gets a value indicating whether this animation instance is paused.
/// </summary>
/// <value>
/// <see langword="true"/> if this animation instance (or any of its ancestors in the animation
/// tree) is paused; otherwise, <see langword="false"/>.
/// </value>
public bool IsPaused
{
get
{
// Only the root instance can be paused.
return (Parent != null) ? Parent.IsPaused : _isPaused;
// Alternatively, if the animation tree can be paused at any level.
// (But this is currently not supported.)
//return _isPaused || (Parent != null) ? Parent.IsPaused : false;
}
}
private bool _isPaused;
/// <summary>
/// Gets a value indicating whether this animation instance is the root node in the animation
/// tree.
/// </summary>
/// <value>
/// <see langword="true"/> if animation instance is the root node in the animation tree;
/// otherwise, <see langword="false"/>.
/// </value>
internal bool IsRoot
{
get { return _parent == null; }
}
/// <summary>
/// Gets the current state of the animation.
/// </summary>
/// <value>The current state of the animation.</value>
public AnimationState State
{
get
{
UpdateState();
return _state;
}
}
private AnimationState _state;
private bool _isStateValid;
/// <summary>
/// Gets or sets the current animation time.
/// </summary>
/// <value>
/// The current animation time. (The animation time is <see langword="null"/> if the instance
/// has not been started.)
/// </value>
/// <exception cref="InvalidOperationException">
/// Cannot set animation time because this is not the root instance. The animation instance is
/// a node in the animation tree, but only the root node of the tree can be controlled directly.
/// </exception>
public TimeSpan? Time
{
get { return _time; }
set
{
if (!IsRoot)
{
throw new InvalidOperationException(
"Cannot set animation time because it is not the root instance. "
+ "The animation instance is a node in the animation tree, "
+ "but only the root node of the tree can be controlled directly.");
}
if (_time != value)
SetTime(value);
}
}
private TimeSpan? _time;
/// <summary>
/// Gets the <see cref="Speed"/> property as an <see cref="IAnimatableProperty{T}"/>.
/// </summary>
/// <value>
/// The <see cref="Speed"/> property as an <see cref="IAnimatableProperty{T}"/>.
/// </value>
internal IAnimatableProperty<float> SpeedProperty
{
get { return _speedProperty; }
}
private readonly ImmediateAnimatableProperty<float> _speedProperty;
/// <summary>
/// Gets or sets the rate at which time progresses.
/// </summary>
/// <value>The speed ratio. The default value is 1.</value>
/// <remarks>
/// <para>
/// The speed ratio defines the rate at which time progresses on the timeline. The default value
/// is 1. A value of, for example, 2 means that the animation runs twice as fast. A value of
/// 0.5 causes the animation to run in slow-motion with half speed.
/// </para>
/// <para>
/// Note that the only the speed ratio of the root instance in the animation tree can be
/// controlled. (Changing the speed ratio of other nodes in the animation tree has no effect.)
/// </para>
/// </remarks>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="value"/> is NaN or infinity.
/// </exception>
public float Speed
{
get { return _speedProperty.Value; }
set
{
if (!Numeric.IsFinite(value))
throw new ArgumentOutOfRangeException("value", "The speed ratio must be a finite value.");
_speedProperty.Value = value;
}
}
/// <summary>
/// Gets the <see cref="Weight"/> property as an <see cref="IAnimatableProperty{T}"/>.
/// </summary>
/// <value>
/// The <see cref="Weight"/> property as an <see cref="IAnimatableProperty{T}"/>.
/// </value>
internal IAnimatableProperty<float> WeightProperty
{
get { return _weightProperty; }
}
private readonly ImmediateAnimatableProperty<float> _weightProperty;
/// <summary>
/// Gets or sets the animation weight.
/// </summary>
/// <value>
/// The animation weight. The value lies in the range [0, 1]. The default value is 1.
/// </value>
/// <remarks>
/// <para>
/// The animation weight defines the intensity of the animation. It is a factor that is applied
/// to the animation output. The animation weight is in particular relevant when multiple
/// animations should be combined. Each animation combines its output with the output of the
/// previous stage in the animation composition chain. (If the animation is the first animation
/// of a composition chain it combines its value with the base value of the property that is
/// being animated.)
/// </para>
/// <para>
/// The default value is 1 which means that 100% of the animation is returned, overriding any
/// previous stage in a animation composition chain. A value of 0.75 means that result is
/// weighted combination of the previous stage (25%) and the output of the current animation
/// (75%). A value of 0 basically disables the output of the current animation.
/// </para>
/// <para>
/// Changing the animation weight of an instance affects the entire subtree: the current
/// animation instance and all children. The effective animation weight is the product of all
/// weights from the root node to the current animation instance.
/// </para>
/// </remarks>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="value"/> is negative or greater than 1.
/// </exception>
public float Weight
{
get { return _weightProperty.Value; }
set
{
// The following check is only applied when the value is set explicitly. The check
// is not applied when the animation value is set. (Note: The animation value can be
// can be outside of the range [0, 1]. Some easing functions produce values outside
// this range.)
if (value < 0.0f || value > 1.0f || Numeric.IsNaN(value))
throw new ArgumentOutOfRangeException("value", "The animation weight must be a value in the range [0, 1].");
_weightProperty.Value = value;
}
}
/// <summary>
/// Occurs when the animation has completed playing. Use with caution - see remarks.
/// </summary>
/// <remarks>
/// <para>
/// A root instance has completed playing when the root timeline has reached the end of its
/// duration (including any repeats). A child instance is considered to have finished playing
/// when the root instance has finished playing.
/// </para>
/// <para>
/// <strong>Important:</strong> The completion event does not trigger when animation is
/// explicitly stopped or removed before it has reached the end of its duration. (But the
/// completion event is triggered when the user sets the <see cref="Time"/> to a value past the
/// end of the duration.)
/// </para>
/// <para>
/// The completion event is not raised immediately when the state of the animation changes.
/// Instead, the <see cref="AnimationManager"/> records all animations that have finished
/// playing in <see cref="AnimationManager.Update"/> and explicitly raises the completion events
/// in <see cref="AnimationManager.ApplyAnimations"/>.
/// </para>
/// <para>
/// <strong>Use with Caution:</strong> The animation system uses weak references to ensure that
/// animations do not accidentally keep the animated objects and properties alive. Animations
/// are automatically removed if the animated objects are removed (i.e. garbage collected). But
/// the <see cref="Completed"/> event stores the event handlers using a strong reference. If an
/// event handler keeps the animation objects or properties alive, then the animation system
/// will not be able to automatically remove the animation and the referenced resources. To
/// ensure that all resources are properly freed, make sure that one of the following conditions
/// is true:
/// <list type="bullet">
/// <item>
/// <description>
/// The completion event handlers do not keep the target object or properties that are being
/// animated alive.
/// </description>
/// </item>
/// <item>
/// <description>
/// The completion event handlers are removed explicitly if they are no longer required.
/// </description>
/// </item>
/// <item>
/// <description>
/// The animation is stopped explicitly when it is no longer needed, e.g. by calling
/// <see cref="AnimationController.Stop()"/>).
/// </description>
/// </item>
/// <item>
/// <description>
/// The animation is stopped implicitly, e.g. by starting a new animation which replaces it.
/// </description>
/// </item>
/// <item>
/// <description>
/// The animation has a limited duration and stops automatically. (The
/// <see cref="ITimeline.FillBehavior"/> needs to be set to <see cref="FillBehavior.Stop"/>.)
/// </description>
/// </item>
/// </list>
/// </para>
/// </remarks>
public event EventHandler<EventArgs> Completed;
/// <summary>
/// Gets a value indicating whether the animation service needs to call
/// <see cref="RaiseCompletedEvent"/> when the animation completes.
/// </summary>
/// <value>
/// <see langword="true"/> if the animation service needs to call
/// <see cref="RaiseCompletedEvent"/>; otherwise, <see langword="false"/>.
/// </value>
internal bool RequiresCompletedEvent
{
get { return Completed != null; }
}
#endregion
//--------------------------------------------------------------
#region Creation & Cleanup
//--------------------------------------------------------------
/// <summary>
/// Initializes a new instance of the <see cref="AnimationInstance"/> class.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
protected AnimationInstance()
{
// Initialize RunCount with 1. (0 is invalid.)
_runCount = 1;
_state = AnimationState.Stopped;
_time = null;
_speedProperty = new ImmediateAnimatableProperty<float> { Value = 1.0f };
_weightProperty = new ImmediateAnimatableProperty<float> { Value = 1.0f };
// ReSharper disable DoNotCallOverridableMethodsInConstructor
_children = CreateChildCollection();
// ReSharper restore DoNotCallOverridableMethodsInConstructor
}
/// <summary>
/// Creates an instance of the <see cref="AnimationInstance"/> class. (This method reuses a
/// previously recycled instance or allocates a new instance if necessary.)
/// </summary>
/// <param name="animation">The animation timeline.</param>
/// <returns>
/// A new or reusable instance of the <see cref="AnimationInstance"/> class.
/// </returns>
/// <remarks>
/// <para>
/// This method tries to obtain a previously recycled instance from a resource pool if resource
/// pooling is enabled (see <see cref="ResourcePool.Enabled">ResourcePool.Enabled</see>). If no
/// object is available, a new instance is automatically allocated on the heap.
/// </para>
/// <para>
/// The owner of the object should call <see cref="Recycle"/> when the instance is no longer
/// needed.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException">
/// <paramref name="animation"/> is <see langword="null"/>.
/// </exception>
public static AnimationInstance Create(ITimeline animation)
{
var animationInstance = Pool.Obtain();
animationInstance.Initialize(animation);
return animationInstance;
}
/// <summary>
/// Recycles this animation instance (including all children).
/// </summary>
/// <remarks>
/// <para>
/// This method resets this instance (and all children) and returns it to a resource pool if
/// resource pooling is enabled (see <see cref="ResourcePool.Enabled">ResourcePool.Enabled</see>).
/// </para>
/// </remarks>
public virtual void Recycle()
{
// Recursively recycle animation tree.
foreach (var child in Children)
child.Recycle();
Reset();
if (RunCount < int.MaxValue)
Pool.Recycle(this);
}
/// <summary>
/// Initializes the animation instance.
/// </summary>
/// <param name="animation">The animation timeline.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="animation"/> is <see langword="null"/>.
/// </exception>
internal void Initialize(ITimeline animation)
{
Debug.Assert(_animation == null, "Animation instance has not been properly reset.");
Debug.Assert(_autoRecycleEnabled == false, "Animation instance has not been properly reset.");
Debug.Assert(_isPaused == false, "Animation instance has not been properly reset.");
Debug.Assert(_isStateValid == false, "Animation instance has not been properly reset.");
Debug.Assert(_parent == null, "Animation instance has not been properly reset.");
Debug.Assert(_state == AnimationState.Stopped, "Animation instance has not been properly reset.");
Debug.Assert(_time == null, "Animation instance has not been properly reset.");
Debug.Assert(_speedProperty.Value == 1.0f, "Animation instance has not been properly reset.");
Debug.Assert(_weightProperty.Value == 1.0f, "Animation instance has not been properly reset.");
Debug.Assert(_children.Count == 0, "Animation instance has not been properly reset.");
Debug.Assert(_runCount > 0, "Animation instance has invalid RunCount.");
Debug.Assert(Completed == null, "Animation instance has invalid Completed.");
if (animation == null)
throw new ArgumentNullException("animation");
_animation = animation;
}
/// <summary>
/// Resets this animation instance.
/// </summary>
internal void Reset()
{
Debug.Assert(SpeedProperty.IsAnimated == false, "The speed ratio is still animated. Make sure that all animations are stopped before recycling an animation instance!");
Debug.Assert(WeightProperty.IsAnimated == false, "The animation weight is still animated. Make sure that all animations are stopped before recycling an animation instance!");
Debug.Assert(State == AnimationState.Stopped, "Animation instance is still running.");
_animation = null;
_autoRecycleEnabled = false;
_isPaused = false;
_isStateValid = false;
_parent = null;
_state = AnimationState.Stopped;
_time = null;
_speedProperty.Value = 1.0f;
_weightProperty.Value = 1.0f;
_children.Clear();
Completed = null;
// The animation instance requires a new ID: Increment RunCount.
_runCount++;
}
#endregion
//--------------------------------------------------------------
#region Methods
//--------------------------------------------------------------
/// <summary>
/// Creates the child collection of this animation instance.
/// </summary>
/// <returns>The child collection to be used by this animation instance.</returns>
internal virtual AnimationInstanceCollection CreateChildCollection()
{
return new AnimationInstanceCollection(this);
}
/// <summary>
/// Gets the effective animation weight.
/// </summary>
/// <returns>The effective animation weight.</returns>
/// <remarks>
/// The effective animation weight is the product of all animation weights (from the root
/// instance in the animation tree to current animation instance).
/// </remarks>
internal float GetEffectiveWeight()
{
float weight = Weight;
var animationInstance = Parent;
while (animationInstance != null)
{
weight *= animationInstance.Weight;
animationInstance = animationInstance.Parent;
}
return weight;
}
/// <summary>
/// Advances the animation time by the given time.
/// </summary>
/// <param name="deltaTime">The elapsed time.</param>
/// <remarks>
/// Calling this method has no effect when the animation instance or any of its ancestors in the
/// animation tree is paused.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// Cannot advance animation because this is not the root instance. The animation instance is a
/// node in the animation tree, but only the root node of the tree can be controlled directly.
/// </exception>
internal void AdvanceTime(TimeSpan deltaTime)
{
if (!IsRoot)
{
throw new InvalidOperationException(
"Cannot advance animation because it is not the root instance. "
+ "The animation instance is a node in the animation tree, "
+ "but only the root node of the tree can be interactively controlled.");
}
if (_time == null)
_time = TimeSpan.Zero;
if (!IsPaused)
{
// Apply speed ratio.
deltaTime = new TimeSpan((long)(deltaTime.Ticks * Speed));
SetTime(_time + deltaTime);
}
}
/// <summary>
/// Sets the animation time of the current animation instance and updates all children.
/// </summary>
/// <param name="time">The time value to set.</param>
internal virtual void SetTime(TimeSpan? time)
{
_time = time;
int numberOfChildren = Children.Count;
if (numberOfChildren > 0)
{
if (time.HasValue)
{
// Convert time to local animation time.
time = Animation.GetAnimationTime(time.Value);
}
// Update children.
for (int i = 0; i < numberOfChildren; i++)
{
var child = Children[i];
child.SetTime(time);
}
}
// Invalidate this instance.
// (Note: Children are automatically invalidated when their animation time changes.)
InvalidateState();
}
/// <summary>
/// Invalidates the current state of the animation.
/// </summary>
/// <remarks>
/// <para>
/// This method needs to be called manually if the animation data (such as the begin time of an
/// animation) is changed and other objects want to read the animation state in the same frame.
/// If an animation instance has been invalidated, it will automatically recompute its state
/// when <see cref="State"/> is read.
/// </para>
/// <para>
/// In is not necessary to explicitly call this method if <see cref="AnimationManager.Update"/>
/// is called. In this case the state of the animation will be recomputed automatically.
/// </para>
/// </remarks>
public void Invalidate()
{
InvalidateState();
foreach (var animationInstance in Children)
animationInstance.Invalidate();
}
private void InvalidateState()
{
_isStateValid = false;
}
internal void UpdateState()
{
if (!_isStateValid)
{
_state = _time.HasValue ? Animation.GetState(_time.Value) : AnimationState.Stopped;
_isStateValid = true;
}
}
/// <summary>
/// Stops the animation from progressing.
/// </summary>
/// <remarks>
/// <para>
/// This method stops the animation timing. The animation no longer progresses when
/// <see cref="AdvanceTime"/> is called. The timing can be resumed by calling
/// <see cref="Resume"/>.
/// </para>
/// <para>
/// Pausing an animation instance implicitly pauses all child instances.
/// </para>
/// </remarks>
/// <exception cref="InvalidOperationException">
/// Cannot pause animation because this is not the root instance. The animation instance is a
/// node in the animation tree, but only the root node of the tree can be controlled directly.
/// </exception>
internal void Pause()
{
if (!IsRoot)
{
throw new InvalidOperationException(
"Cannot pause animation because it is not the root instance. "
+ "The animation instance is a node in the animation tree, "
+ "but only the root node of the tree can be interactively controlled.");
}
_isPaused = true;
}
/// <summary>
/// Resumes an animation that was previously stopped.
/// </summary>
/// <remarks>
/// <para>
/// This method resumes the animation timing from where it was stopped. The timing can be
/// stopped by calling <see cref="Pause"/>.
/// </para>
/// <para>
/// Resuming an animation instance implicitly resumes all child instances.
/// </para>
/// </remarks>
/// <exception cref="InvalidOperationException">
/// Cannot pause animation because this is not the root instance. The animation instance is a
/// node in the animation tree, but only the root node of the tree can be controlled directly.
/// </exception>
internal void Resume()
{
if (!IsRoot)
{
throw new InvalidOperationException(
"Cannot resume animation because it is not the root instance. "
+ "The animation instance is a node in the animation tree, "
+ "but only the root node of the tree can be interactively controlled.");
}
_isPaused = false;
}
/// <overloads>
/// <summary>
/// Determines whether the animation tree can be assigned to the given objects or properties.
/// </summary>
/// </overloads>
///
/// <summary>
/// Determines whether this animation tree can be assigned to the specified set of objects.
/// </summary>
/// <param name="objects">The set of animatable objects.</param>
/// <returns>
/// <see langword="true"/> if this animation instance (or one of its children) can be assigned
/// to <paramref name="objects"/>; otherwise, <see langword="false"/>.
/// </returns>
internal virtual bool IsAssignableTo(IEnumerable<IAnimatableObject> objects)
{
string objectName = Animation.TargetObject;
if (String.IsNullOrEmpty(objectName))
{
// No target object set. All objects are potential targets.
foreach (var child in Children)
if (child.IsAssignableTo(objects))
return true;
}
else
{
// Find target object.
IAnimatableObject targetObject = null;
foreach (var obj in objects)
{
if (obj.Name == objectName)
{
targetObject = obj;
break;
}
}
if (targetObject != null)
{
// Check whether any child can be assigned to the target object.
foreach (var child in Children)
if (child.IsAssignableTo(targetObject))
return true;
}
}
return false;
}
/// <summary>
/// Determines whether this animation tree can be assigned to the specified object.
/// </summary>
/// <param name="obj">The animatable object.</param>
/// <returns>
/// <see langword="true"/> if this animation instance (or one of its children) can be assigned
/// to <paramref name="obj"/>; otherwise, <see langword="false"/>.
/// </returns>
internal virtual bool IsAssignableTo(IAnimatableObject obj)
{
// Note: In this case we do not check whether Animation.TargetObject matches obj.Name.
// This method should only be called to explicitly assign the animation to the given object.
foreach (var child in Children)
if (child.IsAssignableTo(obj))
return true;
return false;
}
/// <summary>
/// Determines whether this animation tree can be assigned to the specified property.
/// </summary>
/// <param name="property">The animatable property.</param>
/// <returns>
/// <see langword="true"/> if this animation instance (or one of its children) can be assigned
/// to <paramref name="property"/>; otherwise, <see langword="false"/>.
/// </returns>
internal virtual bool IsAssignableTo(IAnimatableProperty property)
{
foreach (var child in Children)
if (child.IsAssignableTo(property))
return true;
return false;
}
/// <summary>
/// Determines whether this animation tree is assigned to the specified property.
/// </summary>
/// <param name="property">The animatable property.</param>
/// <returns>
/// <see langword="true"/> if this animation instance (or one of its children) is assigned to
/// <paramref name="property"/>; otherwise, <see langword="false"/>.
/// </returns>
internal virtual bool IsAssignedTo(IAnimatableProperty property)
{
foreach (var child in Children)
if (child.IsAssignedTo(property))
return true;
return false;
}
/// <overloads>
/// <summary>
/// Assigns this animation tree to objects or properties.
/// </summary>
/// </overloads>
///
/// <summary>
/// Assigns this animation tree to the specified set of objects.
/// </summary>
/// <param name="objects">The collection of animatable object.</param>
internal virtual void AssignTo(IEnumerable<IAnimatableObject> objects)
{
string objectName = Animation.TargetObject;
if (String.IsNullOrEmpty(objectName))
{
// No target object set. All objects are potential targets.
foreach (var child in Children)
child.AssignTo(objects);
}
else
{
// Find target object.
IAnimatableObject targetObject = null;
foreach (var obj in objects)
{
if (obj.Name == objectName)
{
targetObject = obj;
break;
}
}
if (targetObject != null)
{
// Assign children to the selected object.
foreach (var child in Children)
child.AssignTo(targetObject);
}
}
}
/// <summary>
/// Assigns this animation tree to the specified object.
/// </summary>
/// <param name="obj">The animatable object.</param>
internal virtual void AssignTo(IAnimatableObject obj)
{
// Note: In this case we do not check whether Animation.TargetObject matches obj.Name.
// This method should only be called to explicitly assign the animation to the given object.
foreach (var child in Children)
child.AssignTo(obj);
}
/// <summary>
/// Assigns this animation tree to the specified property.
/// </summary>
/// <param name="property">The animatable property.</param>
internal virtual void AssignTo(IAnimatableProperty property)
{
foreach (var child in Children)
child.AssignTo(property);
}
///// <summary>
///// Unassigns this animation trees. (Removes all references to the currently assigned
///// properties.)
///// </summary>
//internal virtual void Unassign()
//{
// foreach (var child in Children)
// child.Unassign();
//}
/// <summary>
/// Checks whether this animation tree is assigned to a certain animated property and returns
/// the animation instance.
/// </summary>
/// <param name="property">The animatable property.</param>
/// <returns>
/// The animation instance that is assigned to <paramref name="property"/>.
/// <see langword="null"/> if neither this instance nor its children are assigned to the
/// property. If multiple children are assigned to the property the last found child is
/// returned.
/// </returns>
internal virtual AnimationInstance GetAssignedInstance(IAnimatableProperty property)
{
for (int i = Children.Count - 1; i >= 0; i--)
{
var child = Children[i];
var assignedInstance = child.GetAssignedInstance(property);
if (assignedInstance != null)
return assignedInstance;
}
return null;
}
/// <summary>
/// Gets all assigned properties and stores them in the given list.
/// </summary>
/// <param name="properties">A list in which the target properties shall be stored.</param>
internal virtual void GetAssignedProperties(List<IAnimatableProperty> properties)
{
foreach (var child in Children)
child.GetAssignedProperties(properties);
}
/// <summary>
/// Determines whether this animation tree is currently applied to any properties.
/// </summary>
/// <param name="animationManager">The <see cref="AnimationManager"/>.</param>
/// <returns>
/// <see langword="true"/> if this animation tree is applied to any properties; otherwise,
/// <see langword="false"/>.
/// </returns>
internal virtual bool IsActive(AnimationManager animationManager)
{
foreach (var child in Children)
if (child.IsActive(animationManager))
return true;
return false;
}
/// <summary>
/// Applies this animation tree to the assigned properties.
/// </summary>
/// <param name="animationManager">The <see cref="AnimationManager"/>.</param>
/// <param name="handoffBehavior">
/// A value indicating how the new animations interact with existing ones.
/// </param>
/// <param name="previousInstance">
/// Optional: The animation instance after which this animation instance will be added in the
/// animation composition chain. If set to <see langword="null"/> this animation instance will
/// be appended at the end of the composition chain. This parameter is only relevant when
/// <paramref name="handoffBehavior"/> is <see cref="HandoffBehavior.Compose"/>.
/// </param>
internal virtual void AddToCompositionChains(AnimationManager animationManager, HandoffBehavior handoffBehavior, AnimationInstance previousInstance)
{
foreach (var child in Children)
child.AddToCompositionChains(animationManager, handoffBehavior, previousInstance);
}
/// <summary>
/// Removes this animation tree from the animated properties.
/// </summary>
/// <param name="animationManager">The <see cref="AnimationManager"/>.</param>
internal virtual void RemoveFromCompositionChains(AnimationManager animationManager)
{
foreach (var child in Children)
child.RemoveFromCompositionChains(animationManager);
}
/// <summary>
/// Stops all animations that affect the animation tree (such as animations that control the
/// speed ratios or animation weights).
/// </summary>
/// <param name="animationManager">The <see cref="AnimationManager"/>.</param>
internal void StopSecondaryAnimations(AnimationManager animationManager)
{
if (((IAnimatableProperty<float>)_speedProperty).IsAnimated)
{
animationManager.StopAnimation(_speedProperty);
animationManager.UpdateAndApplyAnimation(_speedProperty);
}
if (((IAnimatableProperty<float>)_weightProperty).IsAnimated)
{
animationManager.StopAnimation(_weightProperty);
animationManager.UpdateAndApplyAnimation(_weightProperty);
}
foreach (var child in Children)
child.StopSecondaryAnimations(animationManager);
}
/// <summary>
/// Immediately evaluates the given animation instance and applies the new animation values.
/// </summary>
/// <param name="animationManager">The <see cref="AnimationManager"/>.</param>
internal virtual void UpdateAndApply(AnimationManager animationManager)
{
foreach (var child in Children)
child.UpdateAndApply(animationManager);
}
internal void RaiseCompletedEvent()
{
foreach (var child in Children)
child.RaiseCompletedEvent();
OnCompleted(EventArgs.Empty);
}
/// <summary>
/// Raises the <see cref="Completed"/> event.
/// </summary>
/// <param name="eventArgs">
/// <see cref="EventArgs"/> object that provides the arguments for the event.
/// </param>
/// <remarks>
/// <strong>Notes to Inheritors:</strong> When overriding <see cref="OnCompleted"/> in a derived
/// class, be sure to call the base class's <see cref="OnCompleted"/> method so that registered
/// delegates receive the event.
/// </remarks>
protected virtual void OnCompleted(EventArgs eventArgs)
{
var handler = Completed;
if (handler != null)
handler(this, eventArgs);
}
#endregion
//--------------------------------------------------------------
#region IAnimatableObject
//--------------------------------------------------------------
/// <summary>
/// Not implemented.
/// </summary>
/// <value>
/// Not implemented. Always returns <see cref="String.Empty"/>.
/// </value>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
string INamedObject.Name
{
get { return string.Empty; }
}
/// <summary>
/// Gets the properties which are currently being animated.
/// </summary>
/// <returns>
/// The properties which are currently being animated.
/// </returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
IEnumerable<IAnimatableProperty> IAnimatableObject.GetAnimatedProperties()
{
if (((IAnimatableProperty<float>)_speedProperty).IsAnimated)
yield return _speedProperty;
if (((IAnimatableProperty<float>)_weightProperty).IsAnimated)
yield return _weightProperty;
}
/// <summary>
/// Gets the property with given name and type which can be animated.
/// </summary>
/// <typeparam name="T">The type of the property.</typeparam>
/// <param name="name">The name of the property.</param>
/// <returns>
/// The <see cref="IAnimatableProperty"/> that has the given name and type; otherwise,
/// <see langword="null"/> if the object does not have an property with this name or type.
/// </returns>
/// <remarks>
/// An animation instance has two animatable properties: <see cref="Speed"/> and
/// <see cref="Weight"/>.
/// </remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
IAnimatableProperty<T> IAnimatableObject.GetAnimatableProperty<T>(string name)
{
switch (name)
{
case "Speed":
return _speedProperty as IAnimatableProperty<T>;
case "Weight":
return _weightProperty as IAnimatableProperty<T>;
default:
return null;
}
}
#endregion
}
}
| 0 | 0.841327 | 1 | 0.841327 | game-dev | MEDIA | 0.649694 | game-dev | 0.512205 | 1 | 0.512205 |
oiuv/mud | 1,796 | inherit/weapon/hammer.c | // hammer.c
#include <ansi.h>
#include <weapon.h>
#ifdef AS_FEATURE
#include <dbase.h>
#else
inherit EQUIP;
#endif
int is_weapon() { return 1; }
varargs void init_hammer(int damage, int flag)
{
if( clonep(this_object()) ) return;
set("weapon_prop/damage", damage);
set("flag", flag );
set("skill_type", "hammer");
if( !query("actions") ) {
set("actions", (: call_other, WEAPON_D, "query_action" :) );
set("verbs", ({ "bash", "crush", "slam" }) );
}
}
string extra_long()
{
mapping need;
string str;
str = HIW "\n物品类型 : 兵器(锤)\n" NOR;
if (query("bindable"))
{
string type;
int t;
t = query("bindable");
if (t == 1) type = "装备绑定";
else if (t == 2) type = "拾取帮定";
else if (t == 3) type = "直接绑定";
str += sprintf(HIW "绑定类型 : %s\n" NOR, type);
}
str += sprintf(HIW "重 量 : %d\n" NOR, this_object()->query_weight());
str += sprintf(HIW "伤 害 力 : %d\n" NOR, query("weapon_prop/damage"));
// str += sprintf(HIW "杀 戮 : %d\n" NOR, query("combat/PKS"));
str += sprintf(HIW "镶嵌凹槽 : %d\n" NOR, (int)query("enchase/flute"));
if (mapp(need = query("need")) && sizeof(need))
foreach (string key in keys(need))
str += sprintf(HIW "装备要求 : %s %d\n" NOR,
to_chinese(key), need[key]);
/*
str += sprintf(HIW "使用方式 : 输入指令 wield %s 装备。\n", query("id"));
str += sprintf(HIW "使用方式 : 输入指令 unwield %s 卸下。\n", query("id"));
*/
str += sprintf(HIW "下线丢失 : %s\n" NOR,
this_object()->query_autoload() ? "否" : "是");
return str;
}
| 0 | 0.90286 | 1 | 0.90286 | game-dev | MEDIA | 0.848069 | game-dev | 0.916258 | 1 | 0.916258 |
Tslat/Advent-Of-Ascension | 2,158 | source/content/item/weapon/thrown/Chakram.java | package net.tslat.aoa3.content.item.weapon.thrown;
import net.minecraft.core.Direction;
import net.minecraft.core.Position;
import net.minecraft.network.chat.Component;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.effect.MobEffects;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.projectile.Projectile;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.level.Level;
import net.minecraft.world.phys.Vec3;
import net.tslat.aoa3.content.entity.projectile.gun.BaseBullet;
import net.tslat.aoa3.content.entity.projectile.thrown.ChakramEntity;
import net.tslat.aoa3.util.EntityUtil;
import net.tslat.aoa3.util.LocaleUtil;
import net.tslat.effectslib.api.util.EffectBuilder;
import org.jetbrains.annotations.Nullable;
import java.util.List;
public class Chakram extends BaseThrownWeapon {
public Chakram(Item.Properties properties) {
super(properties);
}
@Nullable
@Override
public SoundEvent getFiringSound() {
return SoundEvents.WITCH_THROW;
}
@Override
public BaseBullet createProjectileEntity(LivingEntity shooter, ItemStack gunStack, InteractionHand hand) {
return new ChakramEntity(shooter, this);
}
@Override
public Projectile asProjectile(Level level, Position position, ItemStack stack, Direction direction) {
return new ChakramEntity(level, position.x(), position.y(), position.z());
}
@Override
protected void doImpactEffect(Entity target, LivingEntity shooter, BaseBullet bullet, Vec3 impactPos, float bulletDmgMultiplier) {
EntityUtil.applyPotions(target, new EffectBuilder(MobEffects.POISON, 60).level(2));
}
@Override
public void appendHoverText(ItemStack stack, TooltipContext context, List<Component> tooltip, TooltipFlag flag) {
tooltip.add(LocaleUtil.getFormattedItemDescriptionText(LocaleUtil.Keys.POISONS_TARGETS, LocaleUtil.ItemDescriptionType.BENEFICIAL));
super.appendHoverText(stack, context, tooltip, flag);
}
}
| 0 | 0.74908 | 1 | 0.74908 | game-dev | MEDIA | 0.997473 | game-dev | 0.841326 | 1 | 0.841326 |
mastercomfig/tf2-patches-old | 5,191 | src/game/shared/obstacle_pushaway.h | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#ifndef OBSTACLE_PUSHAWAY_H
#define OBSTACLE_PUSHAWAY_H
#ifdef _WIN32
#pragma once
#endif
#include "props_shared.h"
#ifndef CLIENT_DLL
#include "func_breakablesurf.h"
#include "BasePropDoor.h"
#include "doors.h"
#endif // CLIENT_DLL
//--------------------------------------------------------------------------------------------------------------
bool IsPushAwayEntity( CBaseEntity *pEnt );
bool IsPushableEntity( CBaseEntity *pEnt );
//--------------------------------------------------------------------------------------------------------------
#ifndef CLIENT_DLL
bool IsBreakableEntity( CBaseEntity *pEnt );
#endif // !CLIENT_DLL
//--------------------------------------------------------------------------------------------------------------
class CPushAwayEnumerator : public IPartitionEnumerator
{
public:
// Forced constructor
CPushAwayEnumerator(CBaseEntity **ents, int nMaxEnts)
{
m_nAlreadyHit = 0;
m_AlreadyHit = ents;
m_nMaxHits = nMaxEnts;
}
// Actual work code
virtual IterationRetval_t EnumElement( IHandleEntity *pHandleEntity )
{
#ifdef CLIENT_DLL
CBaseEntity *pEnt = ClientEntityList().GetBaseEntityFromHandle( pHandleEntity->GetRefEHandle() );
#else
CBaseEntity *pEnt = gEntList.GetBaseEntity( pHandleEntity->GetRefEHandle() );
#endif // CLIENT_DLL
if ( IsPushAwayEntity( pEnt ) && m_nAlreadyHit < m_nMaxHits )
{
m_AlreadyHit[m_nAlreadyHit] = pEnt;
m_nAlreadyHit++;
}
return ITERATION_CONTINUE;
}
public:
CBaseEntity **m_AlreadyHit;
int m_nAlreadyHit;
int m_nMaxHits;
};
#ifndef CLIENT_DLL
//--------------------------------------------------------------------------------------------------------------
/**
* This class will collect breakable objects in a volume. Physics props that can be damaged, func_breakable*, etc
* are all collected by this class.
*/
class CBotBreakableEnumerator : public CPushAwayEnumerator
{
public:
CBotBreakableEnumerator(CBaseEntity **ents, int nMaxEnts) : CPushAwayEnumerator(ents, nMaxEnts)
{
}
virtual IterationRetval_t EnumElement( IHandleEntity *pHandleEntity )
{
CBaseEntity *pEnt = gEntList.GetBaseEntity( pHandleEntity->GetRefEHandle() );
if ( !IsBreakableEntity( pEnt ) )
return ITERATION_CONTINUE;
// ignore breakables parented to doors
if ( pEnt->GetParent() &&
( FClassnameIs( pEnt->GetParent(), "func_door*" ) ||
FClassnameIs( pEnt, "prop_door*" ) ) )
return ITERATION_CONTINUE;
if ( m_nAlreadyHit < m_nMaxHits )
{
m_AlreadyHit[m_nAlreadyHit] = pEnt;
m_nAlreadyHit++;
}
return ITERATION_CONTINUE;
}
};
//--------------------------------------------------------------------------------------------------------------
/**
* This class will collect door objects in a volume.
*/
class CBotDoorEnumerator : public CPushAwayEnumerator
{
public:
CBotDoorEnumerator(CBaseEntity **ents, int nMaxEnts) : CPushAwayEnumerator(ents, nMaxEnts)
{
}
virtual IterationRetval_t EnumElement( IHandleEntity *pHandleEntity )
{
CBaseEntity *pEnt = gEntList.GetBaseEntity( pHandleEntity->GetRefEHandle() );
if ( pEnt == NULL )
return ITERATION_CONTINUE;
if ( ( pEnt->ObjectCaps() & FCAP_IMPULSE_USE ) == 0 )
{
return ITERATION_CONTINUE;
}
if ( FClassnameIs( pEnt, "func_door*" ) )
{
CBaseDoor *door = dynamic_cast<CBaseDoor *>(pEnt);
if ( !door )
{
return ITERATION_CONTINUE;
}
if ( door->m_toggle_state == TS_GOING_UP || door->m_toggle_state == TS_GOING_DOWN )
{
return ITERATION_CONTINUE;
}
}
else if ( FClassnameIs( pEnt, "prop_door*" ) )
{
CBasePropDoor *door = dynamic_cast<CBasePropDoor *>(pEnt);
if ( !door )
{
return ITERATION_CONTINUE;
}
if ( door->IsDoorOpening() || door->IsDoorClosing() )
{
return ITERATION_CONTINUE;
}
}
else
{
return ITERATION_CONTINUE;
}
if ( m_nAlreadyHit < m_nMaxHits )
{
m_AlreadyHit[m_nAlreadyHit] = pEnt;
m_nAlreadyHit++;
}
return ITERATION_CONTINUE;
}
};
//--------------------------------------------------------------------------------------------------------------
/**
* Returns an entity that matches the filter that is along the line segment
*/
CBaseEntity * CheckForEntitiesAlongSegment( const Vector &start, const Vector &end, const Vector &mins, const Vector &maxs, CPushAwayEnumerator *enumerator );
#endif // CLIENT_DLL
//--------------------------------------------------------------------------------------------------------------
// Retrieves physics objects near pPushingEntity
void AvoidPushawayProps( CBaseCombatCharacter *pPlayer, CUserCmd *pCmd );
int GetPushawayEnts( CBaseCombatCharacter *pPushingEntity, CBaseEntity **ents, int nMaxEnts, float flPlayerExpand, int PartitionMask, CPushAwayEnumerator *enumerator = NULL );
//--------------------------------------------------------------------------------------------------------------
// Pushes physics objects away from the entity
void PerformObstaclePushaway( CBaseCombatCharacter *pPushingEntity );
#endif // OBSTACLE_PUSHAWAY_H
| 0 | 0.964486 | 1 | 0.964486 | game-dev | MEDIA | 0.566491 | game-dev | 0.836953 | 1 | 0.836953 |
ReinfyTeam/Zuri | 3,152 | src/checks/fly/FlyA.php | <?php
/*
*
* ____ _ __ _____
* | _ \ ___ (_) _ __ / _| _ _ |_ _| ___ __ _ _ __ ___
* | |_) | / _ \ | | | '_ \ | |_ | | | | | | / _ \ / _` | | '_ ` _ \
* | _ < | __/ | | | | | | | _| | |_| | | | | __/ | (_| | | | | | | |
* |_| \_\ \___| |_| |_| |_| |_| \__, | |_| \___| \__,_| |_| |_| |_|
* |___/
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Zuri attempts to enforce "vanilla Minecraft" mechanics, as well as preventing
* players from abusing weaknesses in Minecraft or its protocol, making your server
* more safe. Organized in different sections, various checks are performed to test
* players doing, covering a wide range including flying and speeding, fighting
* hacks, fast block breaking and nukers, inventory hacks, chat spam and other types
* of malicious behaviour.
*
* @author ReinfyTeam
* @link https://github.com/ReinfyTeam/
*
*
*/
declare(strict_types=1);
namespace ReinfyTeam\Zuri\checks\fly;
use pocketmine\network\mcpe\protocol\DataPacket;
use ReinfyTeam\Zuri\checks\Check;
use ReinfyTeam\Zuri\player\PlayerAPI;
use ReinfyTeam\Zuri\utils\BlockUtil;
use ReinfyTeam\Zuri\utils\discord\DiscordWebhookException;
use function microtime;
class FlyA extends Check {
public function getName() : string {
return "Fly";
}
public function getSubType() : string {
return "A";
}
/**
* @throws DiscordWebhookException
*/
public function check(DataPacket $packet, PlayerAPI $playerAPI) : void {
$player = $playerAPI->getPlayer();
if (
$playerAPI->getAttackTicks() < 40 ||
$playerAPI->getOnlineTime() <= 30 ||
$playerAPI->getJumpTicks() < 40 ||
$playerAPI->isInWeb() ||
$playerAPI->isOnGround() ||
$playerAPI->isOnAdhesion() ||
$player->getAllowFlight() ||
$player->hasNoClientPredictions() ||
!$player->isSurvival() ||
!$playerAPI->isCurrentChunkIsLoaded() ||
BlockUtil::isGroundSolid($player) ||
$playerAPI->isGliding() ||
$playerAPI->recentlyCancelledEvent() < 40
) {
$playerAPI->unsetExternalData("lastYNoGroundF");
$playerAPI->unsetExternalData("lastTimeF");
return;
}
$lastYNoGround = $playerAPI->getExternalData("lastYNoGroundF");
$lastTime = $playerAPI->getExternalData("lastTimeF");
if ($lastYNoGround !== null && $lastTime !== null) {
$diff = microtime(true) - $lastTime;
if ($diff > $this->getConstant("max-ground-diff")) {
if ((int) $player->getLocation()->getY() == $lastYNoGround) {
$this->failed($playerAPI);
}
$playerAPI->unsetExternalData("lastYNoGroundF");
$playerAPI->unsetExternalData("lastTimeF");
}
$this->debug($playerAPI, "diff=$diff, lastTime=$lastTime, lastYNoGround=$lastYNoGround");
} else {
$playerAPI->setExternalData("lastYNoGroundF", (int) $player->getLocation()->getY());
$playerAPI->setExternalData("lastTimeF", microtime(true));
}
}
} | 0 | 0.803349 | 1 | 0.803349 | game-dev | MEDIA | 0.622776 | game-dev | 0.581708 | 1 | 0.581708 |
FunkinCrew/Funkin | 2,139 | source/funkin/ui/debug/charting/commands/RemoveItemsCommand.hx | package funkin.ui.debug.charting.commands;
import funkin.data.song.SongData.SongNoteData;
import funkin.data.song.SongData.SongEventData;
import funkin.data.song.SongDataUtils;
/**
* Deletes the given notes and events from the current chart in the chart editor.
* Use only when BOTH notes and events are being deleted.
*/
@:nullSafety
@:access(funkin.ui.debug.charting.ChartEditorState)
class RemoveItemsCommand implements ChartEditorCommand
{
var notes:Array<SongNoteData>;
var events:Array<SongEventData>;
public function new(notes:Array<SongNoteData>, events:Array<SongEventData>)
{
this.notes = notes;
this.events = events;
}
public function execute(state:ChartEditorState):Void
{
if ((notes.length + events.length) == 0) return;
state.currentSongChartNoteData = SongDataUtils.subtractNotes(state.currentSongChartNoteData, notes);
state.currentSongChartEventData = SongDataUtils.subtractEvents(state.currentSongChartEventData, events);
state.currentNoteSelection = [];
state.currentEventSelection = [];
state.playSound(Paths.sound('chartingSounds/noteErase'));
state.saveDataDirty = true;
state.noteDisplayDirty = true;
state.notePreviewDirty = true;
state.sortChartData();
}
public function undo(state:ChartEditorState):Void
{
if ((notes.length + events.length) == 0) return;
for (note in notes)
{
state.currentSongChartNoteData.push(note);
}
for (event in events)
{
state.currentSongChartEventData.push(event);
}
state.currentNoteSelection = notes;
state.currentEventSelection = events;
state.playSound(Paths.sound('chartingSounds/undo'));
state.saveDataDirty = true;
state.noteDisplayDirty = true;
state.notePreviewDirty = true;
state.sortChartData();
}
public function shouldAddToHistory(state:ChartEditorState):Bool
{
// This command is undoable. Add to the history if we actually performed an action.
return (notes.length > 0 || events.length > 0);
}
public function toString():String
{
return 'Remove ${notes.length + events.length} Items';
}
}
| 0 | 0.905704 | 1 | 0.905704 | game-dev | MEDIA | 0.737584 | game-dev | 0.801704 | 1 | 0.801704 |
gerstrong/Commander-Genius | 2,437 | GsKit/widgets/GsMenuController.h | /*
* CMenuController.h
*
* Created on: 19.02.2012
* Author: gerstrong
*/
#include <base/GsEvent.h>
#include <base/Singleton.h>
#include <memory>
#include "GsBaseMenu.h"
#ifndef GSMENUCONTROLLER_H
#define GSMENUCONTROLLER_H
#define gMenuController CMenuController::get()
/**
* @brief drawMenuInGameButton Draws a sandwich that is visible while in gameplay
* @param buttonRect where and how large to draw that menu...
*/
void drawMenuInGameButton(const SDL_Rect &buttonRect);
/**
* @brief checkSandwichMenuClicked Return true if sandwich menu was clicked
*/
bool checkSandwichMenuClicked(GsRect<float> &rRect);
/**
* Events
*/
struct OpenMenuEvent : CEvent
{
OpenMenuEvent(CBaseMenu* menuDlgPtr) :
mMenuDialogPointer(menuDlgPtr) {}
std::shared_ptr<CBaseMenu> mMenuDialogPointer;
};
struct CloseMenuEvent : CEvent
{
/**
* @brief CloseMenuEvent
* @param replayMusic If menu are closed so it goes back to the title
* or gameplay whatever is open, trigger a ReplayMusic
* Event
*/
CloseMenuEvent(const bool replayMusic) :
mReplayMusic(replayMusic) {}
const bool mReplayMusic;
};
struct CloseAllMenusEvent : CEvent
{};
/**
* @brief Sent when all the menus are closed
*/
struct EventAllMenusClosed : CEvent
{};
/**
* Class Declaration
*/
class CMenuController : public GsSingleton<CMenuController>
{
public:
CMenuController() : mOpenedGamePlay(false),
mLocked(false),
mHidden(false) {}
void clearMenuStack();
void pumpEvent(const std::shared_ptr<CEvent> &evPtr);
void ponder(const float deltaT);
void render();
bool active()
{ return !mMenuStack.empty(); }
void lock(const bool value)
{ mLocked = value; }
bool isLocked()
{ return mLocked; }
void hide(const bool value)
{ mHidden = value; }
bool empty()
{ return mMenuStack.empty(); }
bool mOpenedGamePlay;
std::function<void(GsWeakSurface&)> mBackroundDrawFcn;
std::function<void(GsWeakSurface&, const GsRect<int>)> mDrawTwirlFcn;
std::function<void()> mExecAfterClose;
bool mEnableTwirl = false;
void updateGraphics();
private:
void popBackMenu();
std::list< std::shared_ptr<CBaseMenu> > mMenuStack;
bool mLocked;
bool mHidden;
};
#endif /* GSMENUCONTROLLER_H */
| 0 | 0.93197 | 1 | 0.93197 | game-dev | MEDIA | 0.678199 | game-dev | 0.668962 | 1 | 0.668962 |
Daivuk/PureDOOM | 8,192 | src/DOOM/p_spec.h | // Emacs style mode select -*- C++ -*-
//-----------------------------------------------------------------------------
//
// $Id:$
//
// Copyright (C) 1993-1996 by id Software, Inc.
//
// This source is available for distribution and/or modification
// only under the terms of the DOOM Source Code License as
// published by id Software. All rights reserved.
//
// The source is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// FITNESS FOR A PARTICULAR PURPOSE. See the DOOM Source Code License
// for more details.
//
// DESCRIPTION: none
// Implements special effects:
// Texture animation, height or lighting changes
// according to adjacent sectors, respective
// utility functions, etc.
//
//-----------------------------------------------------------------------------
#ifndef __P_SPEC__
#define __P_SPEC__
#include "p_mobj.h"
#include "r_defs.h"
//
// End-level timer (-TIMER option)
//
extern doom_boolean levelTimer;
extern int levelTimeCount;
// Define values for map objects
#define MO_TELEPORTMAN 14
// at game start
void P_InitPicAnims(void);
// at map load
void P_SpawnSpecials(void);
// every tic
void P_UpdateSpecials(void);
// when needed
doom_boolean P_UseSpecialLine(mobj_t* thing, line_t* line, int side);
void P_ShootSpecialLine(mobj_t* thing, line_t* line);
void P_CrossSpecialLine(int linenum, int side, mobj_t* thing);
void P_PlayerInSpecialSector(player_t* player);
int twoSided(int sector, int line);
sector_t* getSector(int currentSector, int line, int side);
side_t* getSide(int currentSector, int line, int side);
fixed_t P_FindLowestFloorSurrounding(sector_t* sec);
fixed_t P_FindHighestFloorSurrounding(sector_t* sec);
fixed_t P_FindNextHighestFloor(sector_t* sec, int currentheight);
fixed_t P_FindLowestCeilingSurrounding(sector_t* sec);
fixed_t P_FindHighestCeilingSurrounding(sector_t* sec);
int P_FindSectorFromLineTag(line_t* line, int start);
int P_FindMinSurroundingLight(sector_t* sector, int max);
sector_t* getNextSector(line_t* line, sector_t* sec);
//
// SPECIAL
//
int EV_DoDonut(line_t* line);
//
// P_LIGHTS
//
typedef struct
{
thinker_t thinker;
sector_t* sector;
int count;
int maxlight;
int minlight;
} fireflicker_t;
typedef struct
{
thinker_t thinker;
sector_t* sector;
int count;
int maxlight;
int minlight;
int maxtime;
int mintime;
} lightflash_t;
typedef struct
{
thinker_t thinker;
sector_t* sector;
int count;
int minlight;
int maxlight;
int darktime;
int brighttime;
} strobe_t;
typedef struct
{
thinker_t thinker;
sector_t* sector;
int minlight;
int maxlight;
int direction;
} glow_t;
#define GLOWSPEED 8
#define STROBEBRIGHT 5
#define FASTDARK 15
#define SLOWDARK 35
void P_SpawnFireFlicker(sector_t* sector);
void T_LightFlash(lightflash_t* flash);
void P_SpawnLightFlash(sector_t* sector);
void T_StrobeFlash(strobe_t* flash);
void P_SpawnStrobeFlash(sector_t* sector, int fastOrSlow, int inSync);
void EV_StartLightStrobing(line_t* line);
void EV_TurnTagLightsOff(line_t* line);
void EV_LightTurnOn(line_t* line, int bright);
void T_Glow(glow_t* g);
void P_SpawnGlowingLight(sector_t* sector);
//
// P_SWITCH
//
typedef struct
{
char name1[9];
char name2[9];
short episode;
} switchlist_t;
typedef enum
{
top,
middle,
bottom
} bwhere_e;
typedef struct
{
line_t* line;
bwhere_e where;
int btexture;
int btimer;
mobj_t* soundorg;
} button_t;
// max # of wall switches in a level
#define MAXSWITCHES 50
// 4 players, 4 buttons each at once, max.
#define MAXBUTTONS 16
// 1 second, in ticks.
#define BUTTONTIME 35
extern button_t buttonlist[MAXBUTTONS];
void P_ChangeSwitchTexture(line_t* line, int useAgain);
void P_InitSwitchList(void);
//
// P_PLATS
//
typedef enum
{
up,
down,
waiting,
in_stasis
} plat_e;
typedef enum
{
perpetualRaise,
downWaitUpStay,
raiseAndChange,
raiseToNearestAndChange,
blazeDWUS
} plattype_e;
typedef struct
{
thinker_t thinker;
sector_t* sector;
fixed_t speed;
fixed_t low;
fixed_t high;
int wait;
int count;
plat_e status;
plat_e oldstatus;
doom_boolean crush;
int tag;
plattype_e type;
} plat_t;
#define PLATWAIT 3
#define PLATSPEED FRACUNIT
#define MAXPLATS 30
extern plat_t* activeplats[MAXPLATS];
void T_PlatRaise(plat_t* plat);
int EV_DoPlat(line_t* line, plattype_e type, int amount);
void P_AddActivePlat(plat_t* plat);
void P_RemoveActivePlat(plat_t* plat);
void EV_StopPlat(line_t* line);
void P_ActivateInStasis(int tag);
//
// P_DOORS
//
typedef enum
{
door_normal,
close30ThenOpen,
door_close,
door_open,
raiseIn5Mins,
blazeRaise,
blazeOpen,
blazeClose
} vldoor_e;
typedef struct
{
thinker_t thinker;
vldoor_e type;
sector_t* sector;
fixed_t topheight;
fixed_t speed;
// 1 = up, 0 = waiting at top, -1 = down
int direction;
// tics to wait at the top
int topwait;
// (keep in case a door going down is reset)
// when it reaches 0, start going down
int topcountdown;
} vldoor_t;
#define VDOORSPEED FRACUNIT*2
#define VDOORWAIT 150
void EV_VerticalDoor(line_t* line, mobj_t* thing);
int EV_DoDoor(line_t* line, vldoor_e type);
int EV_DoLockedDoor(line_t* line, vldoor_e type, mobj_t* thing);
void T_VerticalDoor(vldoor_t* door);
void P_SpawnDoorCloseIn30(sector_t* sec);
void P_SpawnDoorRaiseIn5Mins(sector_t* sec, int secnum);
//
// P_CEILNG
//
typedef enum
{
lowerToFloor,
raiseToHighest,
lowerAndCrush,
crushAndRaise,
fastCrushAndRaise,
silentCrushAndRaise
} ceiling_e;
typedef struct
{
thinker_t thinker;
ceiling_e type;
sector_t* sector;
fixed_t bottomheight;
fixed_t topheight;
fixed_t speed;
doom_boolean crush;
// 1 = up, 0 = waiting, -1 = down
int direction;
// ID
int tag;
int olddirection;
} ceiling_t;
#define CEILSPEED FRACUNIT
#define CEILWAIT 150
#define MAXCEILINGS 30
extern ceiling_t* activeceilings[MAXCEILINGS];
int EV_DoCeiling(line_t* line, ceiling_e type);
void T_MoveCeiling(ceiling_t* ceiling);
void P_AddActiveCeiling(ceiling_t* c);
void P_RemoveActiveCeiling(ceiling_t* c);
int EV_CeilingCrushStop(line_t* line);
void P_ActivateInStasisCeiling(line_t* line);
//
// P_FLOOR
//
typedef enum
{
// lower floor to highest surrounding floor
lowerFloor,
// lower floor to lowest surrounding floor
lowerFloorToLowest,
// lower floor to highest surrounding floor VERY FAST
turboLower,
// raise floor to lowest surrounding CEILING
raiseFloor,
// raise floor to next highest surrounding floor
raiseFloorToNearest,
// raise floor to shortest height texture around it
raiseToTexture,
// lower floor to lowest surrounding floor
// and change floorpic
lowerAndChange,
raiseFloor24,
raiseFloor24AndChange,
raiseFloorCrush,
// raise to next highest floor, turbo-speed
raiseFloorTurbo,
donutRaise,
raiseFloor512
} floor_e;
typedef enum
{
build8, // slowly build by 8
turbo16 // quickly build by 16
} stair_e;
typedef struct
{
thinker_t thinker;
floor_e type;
doom_boolean crush;
sector_t* sector;
int direction;
int newspecial;
short texture;
fixed_t floordestheight;
fixed_t speed;
} floormove_t;
#define FLOORSPEED FRACUNIT
typedef enum
{
ok,
crushed,
pastdest
} result_e;
result_e T_MovePlane(sector_t* sector, fixed_t speed, fixed_t dest, doom_boolean crush, int floorOrCeiling, int direction);
int EV_BuildStairs(line_t* line, stair_e type);
int EV_DoFloor(line_t* line, floor_e floortype);
void T_MoveFloor(floormove_t* floor);
//
// P_TELEPT
//
int EV_Teleport(line_t* line, int side, mobj_t* thing);
#endif
//-----------------------------------------------------------------------------
//
// $Log:$
//
//-----------------------------------------------------------------------------
| 0 | 0.727168 | 1 | 0.727168 | game-dev | MEDIA | 0.832107 | game-dev | 0.670921 | 1 | 0.670921 |
tangziwen/CubeMiniGame | 5,589 | CubeEngine/External/Bullet/Bullet3OpenCL/NarrowphaseCollision/b3StridingMeshInterface.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef B3_STRIDING_MESHINTERFACE_H
#define B3_STRIDING_MESHINTERFACE_H
#include "Bullet3Common/b3Vector3.h"
#include "b3TriangleCallback.h"
//#include "b3ConcaveShape.h"
enum PHY_ScalarType {
PHY_FLOAT, PHY_DOUBLE, PHY_INTEGER, PHY_SHORT,
PHY_FIXEDPOINT88, PHY_UCHAR
};
/// The b3StridingMeshInterface is the interface class for high performance generic access to triangle meshes, used in combination with b3BvhTriangleMeshShape and some other collision shapes.
/// Using index striding of 3*sizeof(integer) it can use triangle arrays, using index striding of 1*sizeof(integer) it can handle triangle strips.
/// It allows for sharing graphics and collision meshes. Also it provides locking/unlocking of graphics meshes that are in gpu memory.
B3_ATTRIBUTE_ALIGNED16(class ) b3StridingMeshInterface
{
protected:
b3Vector3 m_scaling;
public:
B3_DECLARE_ALIGNED_ALLOCATOR();
b3StridingMeshInterface() :m_scaling(b3MakeVector3(b3Scalar(1.),b3Scalar(1.),b3Scalar(1.)))
{
}
virtual ~b3StridingMeshInterface();
virtual void InternalProcessAllTriangles(b3InternalTriangleIndexCallback* callback,const b3Vector3& aabbMin,const b3Vector3& aabbMax) const;
///brute force method to calculate aabb
void calculateAabbBruteForce(b3Vector3& aabbMin,b3Vector3& aabbMax);
/// get read and write access to a subpart of a triangle mesh
/// this subpart has a continuous array of vertices and indices
/// in this way the mesh can be handled as chunks of memory with striding
/// very similar to OpenGL vertexarray support
/// make a call to unLockVertexBase when the read and write access is finished
virtual void getLockedVertexIndexBase(unsigned char **vertexbase, int& numverts,PHY_ScalarType& type, int& stride,unsigned char **indexbase,int & indexstride,int& numfaces,PHY_ScalarType& indicestype,int subpart=0)=0;
virtual void getLockedReadOnlyVertexIndexBase(const unsigned char **vertexbase, int& numverts,PHY_ScalarType& type, int& stride,const unsigned char **indexbase,int & indexstride,int& numfaces,PHY_ScalarType& indicestype,int subpart=0) const=0;
/// unLockVertexBase finishes the access to a subpart of the triangle mesh
/// make a call to unLockVertexBase when the read and write access (using getLockedVertexIndexBase) is finished
virtual void unLockVertexBase(int subpart)=0;
virtual void unLockReadOnlyVertexBase(int subpart) const=0;
/// getNumSubParts returns the number of seperate subparts
/// each subpart has a continuous array of vertices and indices
virtual int getNumSubParts() const=0;
virtual void preallocateVertices(int numverts)=0;
virtual void preallocateIndices(int numindices)=0;
virtual bool hasPremadeAabb() const { return false; }
virtual void setPremadeAabb(const b3Vector3& aabbMin, const b3Vector3& aabbMax ) const
{
(void) aabbMin;
(void) aabbMax;
}
virtual void getPremadeAabb(b3Vector3* aabbMin, b3Vector3* aabbMax ) const
{
(void) aabbMin;
(void) aabbMax;
}
const b3Vector3& getScaling() const {
return m_scaling;
}
void setScaling(const b3Vector3& scaling)
{
m_scaling = scaling;
}
virtual int calculateSerializeBufferSize() const;
///fills the dataBuffer and returns the struct name (and 0 on failure)
//virtual const char* serialize(void* dataBuffer, b3Serializer* serializer) const;
};
struct b3IntIndexData
{
int m_value;
};
struct b3ShortIntIndexData
{
short m_value;
char m_pad[2];
};
struct b3ShortIntIndexTripletData
{
short m_values[3];
char m_pad[2];
};
struct b3CharIndexTripletData
{
unsigned char m_values[3];
char m_pad;
};
///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
struct b3MeshPartData
{
b3Vector3FloatData *m_vertices3f;
b3Vector3DoubleData *m_vertices3d;
b3IntIndexData *m_indices32;
b3ShortIntIndexTripletData *m_3indices16;
b3CharIndexTripletData *m_3indices8;
b3ShortIntIndexData *m_indices16;//backwards compatibility
int m_numTriangles;//length of m_indices = m_numTriangles
int m_numVertices;
};
///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
struct b3StridingMeshInterfaceData
{
b3MeshPartData *m_meshPartsPtr;
b3Vector3FloatData m_scaling;
int m_numMeshParts;
char m_padding[4];
};
B3_FORCE_INLINE int b3StridingMeshInterface::calculateSerializeBufferSize() const
{
return sizeof(b3StridingMeshInterfaceData);
}
#endif //B3_STRIDING_MESHINTERFACE_H
| 0 | 0.981438 | 1 | 0.981438 | game-dev | MEDIA | 0.745077 | game-dev | 0.739229 | 1 | 0.739229 |
Monkestation/Monkestation2.0 | 3,532 | monkestation/code/modules/antagonists/borers/code/abilities/evolution_tree.dm | /datum/action/cooldown/borer/evolution_tree
name = "Open Evolution Tree"
button_icon_state = "newability"
ability_explanation = "\
Allows you to evolve essential to survive abilities.\n\
Beware, as evolving a tier 3 path will lock you out of all other tier 3 paths.\n\
- The Diveworm path focuses on killing hosts, and making eggs in their corpses.\n\
- The Hivelord path focuses on making lots of eggs.\n\
- The Symbiote path focuses on helping their host, for mutual benefit.\n\
"
/datum/action/cooldown/borer/evolution_tree/Trigger(trigger_flags, atom/target)
. = ..()
if(!.)
return FALSE
ui_interact(owner)
/datum/action/cooldown/borer/evolution_tree/ui_interact(mob/user, datum/tgui/ui)
ui = SStgui.try_update_ui(user, src, ui)
if(!ui)
ui = new(user, src, "BorerEvolution", name)
ui.open()
/datum/action/cooldown/borer/evolution_tree/ui_data(mob/user)
var/list/data = list()
var/static/list/path_to_color = list(
BORER_EVOLUTION_DIVEWORM = "red",
BORER_EVOLUTION_HIVELORD = "purple",
BORER_EVOLUTION_SYMBIOTE = "green",
BORER_EVOLUTION_GENERAL = "label",
)
var/mob/living/basic/cortical_borer/cortical_owner = owner
data["evolution_points"] = cortical_owner.stat_evolution
for(var/datum/borer_evolution/evolution as anything in cortical_owner.get_possible_evolutions())
if(evolution in cortical_owner.past_evolutions)
continue
var/list/evo_data = list()
evo_data["path"] = evolution
evo_data["name"] = initial(evolution.name)
evo_data["desc"] = initial(evolution.desc)
evo_data["gainFlavor"] = initial(evolution.gain_text)
evo_data["cost"] = initial(evolution.evo_cost)
evo_data["disabled"] = ((initial(evolution.evo_cost) > cortical_owner.stat_evolution) || (initial(evolution.mutually_exclusive) && cortical_owner.genome_locked))
evo_data["evoPath"] = initial(evolution.evo_type)
evo_data["color"] = path_to_color[initial(evolution.evo_type)] || "grey"
evo_data["tier"] = initial(evolution.tier)
evo_data["exclusive"] = initial(evolution.mutually_exclusive)
data["learnableEvolution"] += list(evo_data)
for(var/path in cortical_owner.past_evolutions)
var/list/evo_data = list()
var/datum/borer_evolution/found_evolution = cortical_owner.past_evolutions[path]
if(cortical_owner.neutered && found_evolution.skip_for_neutered)
continue
evo_data["name"] = found_evolution.name
evo_data["desc"] = found_evolution.desc
evo_data["gainFlavor"] = found_evolution.gain_text
evo_data["cost"] = found_evolution.evo_cost
evo_data["evoPath"] = found_evolution.evo_type
evo_data["color"] = path_to_color[found_evolution.evo_type] || "grey"
evo_data["tier"] = found_evolution.tier
data["learnedEvolution"] += list(evo_data)
return data
/datum/action/cooldown/borer/evolution_tree/ui_act(action, params)
. = ..()
if(.)
return
var/mob/living/basic/cortical_borer/cortical_owner = owner
switch(action)
if("evolve")
var/datum/borer_evolution/to_evolve_path = text2path(params["path"])
if(!ispath(to_evolve_path))
CRASH("Cortical borer attempted to evolve with a non-evolution path! (Got: [to_evolve_path])")
if(initial(to_evolve_path.evo_cost) > cortical_owner.stat_evolution)
return
if(initial(to_evolve_path.mutually_exclusive) && cortical_owner.genome_locked)
return
if(!cortical_owner.do_evolution(to_evolve_path))
return
cortical_owner.stat_evolution -= initial(to_evolve_path.evo_cost)
return TRUE
/datum/action/cooldown/borer/evolution_tree/ui_state(mob/user)
return GLOB.always_state
| 0 | 0.864014 | 1 | 0.864014 | game-dev | MEDIA | 0.965296 | game-dev | 0.734221 | 1 | 0.734221 |
natbro/kaon | 9,117 | lsteamclient/lsteamclient/steamworks_sdk_146/isteamapps.h | //====== Copyright © 1996-2008, Valve Corporation, All rights reserved. =======
//
// Purpose: interface to app data in Steam
//
//=============================================================================
#ifndef ISTEAMAPPS_H
#define ISTEAMAPPS_H
#ifdef _WIN32
#pragma once
#endif
#include "steam_api_common.h"
const int k_cubAppProofOfPurchaseKeyMax = 240; // max supported length of a legacy cd key
//-----------------------------------------------------------------------------
// Purpose: interface to app data
//-----------------------------------------------------------------------------
class ISteamApps
{
public:
virtual bool BIsSubscribed() = 0;
virtual bool BIsLowViolence() = 0;
virtual bool BIsCybercafe() = 0;
virtual bool BIsVACBanned() = 0;
virtual const char *GetCurrentGameLanguage() = 0;
virtual const char *GetAvailableGameLanguages() = 0;
// only use this member if you need to check ownership of another game related to yours, a demo for example
virtual bool BIsSubscribedApp( AppId_t appID ) = 0;
// Takes AppID of DLC and checks if the user owns the DLC & if the DLC is installed
virtual bool BIsDlcInstalled( AppId_t appID ) = 0;
// returns the Unix time of the purchase of the app
virtual uint32 GetEarliestPurchaseUnixTime( AppId_t nAppID ) = 0;
// Checks if the user is subscribed to the current app through a free weekend
// This function will return false for users who have a retail or other type of license
// Before using, please ask your Valve technical contact how to package and secure your free weekened
virtual bool BIsSubscribedFromFreeWeekend() = 0;
// Returns the number of DLC pieces for the running app
virtual int GetDLCCount() = 0;
// Returns metadata for DLC by index, of range [0, GetDLCCount()]
virtual bool BGetDLCDataByIndex( int iDLC, AppId_t *pAppID, bool *pbAvailable, char *pchName, int cchNameBufferSize ) = 0;
// Install/Uninstall control for optional DLC
virtual void InstallDLC( AppId_t nAppID ) = 0;
virtual void UninstallDLC( AppId_t nAppID ) = 0;
// Request legacy cd-key for yourself or owned DLC. If you are interested in this
// data then make sure you provide us with a list of valid keys to be distributed
// to users when they purchase the game, before the game ships.
// You'll receive an AppProofOfPurchaseKeyResponse_t callback when
// the key is available (which may be immediately).
virtual void RequestAppProofOfPurchaseKey( AppId_t nAppID ) = 0;
virtual bool GetCurrentBetaName( char *pchName, int cchNameBufferSize ) = 0; // returns current beta branch name, 'public' is the default branch
virtual bool MarkContentCorrupt( bool bMissingFilesOnly ) = 0; // signal Steam that game files seems corrupt or missing
virtual uint32 GetInstalledDepots( AppId_t appID, DepotId_t *pvecDepots, uint32 cMaxDepots ) = 0; // return installed depots in mount order
// returns current app install folder for AppID, returns folder name length
virtual uint32 GetAppInstallDir( AppId_t appID, char *pchFolder, uint32 cchFolderBufferSize ) = 0;
virtual bool BIsAppInstalled( AppId_t appID ) = 0; // returns true if that app is installed (not necessarily owned)
// returns the SteamID of the original owner. If this CSteamID is different from ISteamUser::GetSteamID(),
// the user has a temporary license borrowed via Family Sharing
virtual CSteamID GetAppOwner() = 0;
// Returns the associated launch param if the game is run via steam://run/<appid>//?param1=value1¶m2=value2¶m3=value3 etc.
// Parameter names starting with the character '@' are reserved for internal use and will always return and empty string.
// Parameter names starting with an underscore '_' are reserved for steam features -- they can be queried by the game,
// but it is advised that you not param names beginning with an underscore for your own features.
// Check for new launch parameters on callback NewUrlLaunchParameters_t
virtual const char *GetLaunchQueryParam( const char *pchKey ) = 0;
// get download progress for optional DLC
virtual bool GetDlcDownloadProgress( AppId_t nAppID, uint64 *punBytesDownloaded, uint64 *punBytesTotal ) = 0;
// return the buildid of this app, may change at any time based on backend updates to the game
virtual int GetAppBuildId() = 0;
// Request all proof of purchase keys for the calling appid and asociated DLC.
// A series of AppProofOfPurchaseKeyResponse_t callbacks will be sent with
// appropriate appid values, ending with a final callback where the m_nAppId
// member is k_uAppIdInvalid (zero).
virtual void RequestAllProofOfPurchaseKeys() = 0;
STEAM_CALL_RESULT( FileDetailsResult_t )
virtual SteamAPICall_t GetFileDetails( const char* pszFileName ) = 0;
// Get command line if game was launched via Steam URL, e.g. steam://run/<appid>//<command line>/.
// This method of passing a connect string (used when joining via rich presence, accepting an
// invite, etc) is preferable to passing the connect string on the operating system command
// line, which is a security risk. In order for rich presence joins to go through this
// path and not be placed on the OS command line, you must set a value in your app's
// configuration on Steam. Ask Valve for help with this.
//
// If game was already running and launched again, the NewUrlLaunchParameters_t will be fired.
virtual int GetLaunchCommandLine( char *pszCommandLine, int cubCommandLine ) = 0;
// Check if user borrowed this game via Family Sharing, If true, call GetAppOwner() to get the lender SteamID
virtual bool BIsSubscribedFromFamilySharing() = 0;
};
#define STEAMAPPS_INTERFACE_VERSION "STEAMAPPS_INTERFACE_VERSION008"
// Global interface accessor
inline ISteamApps *SteamApps();
STEAM_DEFINE_USER_INTERFACE_ACCESSOR( ISteamApps *, SteamApps, STEAMAPPS_INTERFACE_VERSION );
// Global accessor for the gameserver client
inline ISteamApps *SteamGameServerApps();
STEAM_DEFINE_GAMESERVER_INTERFACE_ACCESSOR( ISteamApps *, SteamGameServerApps, STEAMAPPS_INTERFACE_VERSION );
// callbacks
#if defined( VALVE_CALLBACK_PACK_SMALL )
#pragma pack( push, 4 )
#elif defined( VALVE_CALLBACK_PACK_LARGE )
#pragma pack( push, 8 )
#else
#error steam_api_common.h should define VALVE_CALLBACK_PACK_xxx
#endif
//-----------------------------------------------------------------------------
// Purpose: posted after the user gains ownership of DLC & that DLC is installed
//-----------------------------------------------------------------------------
struct DlcInstalled_t
{
enum { k_iCallback = k_iSteamAppsCallbacks + 5 };
AppId_t m_nAppID; // AppID of the DLC
};
//-----------------------------------------------------------------------------
// Purpose: possible results when registering an activation code
//-----------------------------------------------------------------------------
enum ERegisterActivationCodeResult
{
k_ERegisterActivationCodeResultOK = 0,
k_ERegisterActivationCodeResultFail = 1,
k_ERegisterActivationCodeResultAlreadyRegistered = 2,
k_ERegisterActivationCodeResultTimeout = 3,
k_ERegisterActivationCodeAlreadyOwned = 4,
};
//-----------------------------------------------------------------------------
// Purpose: response to RegisterActivationCode()
//-----------------------------------------------------------------------------
struct RegisterActivationCodeResponse_t
{
enum { k_iCallback = k_iSteamAppsCallbacks + 8 };
ERegisterActivationCodeResult m_eResult;
uint32 m_unPackageRegistered; // package that was registered. Only set on success
};
//---------------------------------------------------------------------------------
// Purpose: posted after the user gains executes a Steam URL with command line or query parameters
// such as steam://run/<appid>//-commandline/?param1=value1¶m2=value2¶m3=value3 etc
// while the game is already running. The new params can be queried
// with GetLaunchQueryParam and GetLaunchCommandLine
//---------------------------------------------------------------------------------
struct NewUrlLaunchParameters_t
{
enum { k_iCallback = k_iSteamAppsCallbacks + 14 };
};
//-----------------------------------------------------------------------------
// Purpose: response to RequestAppProofOfPurchaseKey/RequestAllProofOfPurchaseKeys
// for supporting third-party CD keys, or other proof-of-purchase systems.
//-----------------------------------------------------------------------------
struct AppProofOfPurchaseKeyResponse_t
{
enum { k_iCallback = k_iSteamAppsCallbacks + 21 };
EResult m_eResult;
uint32 m_nAppID;
uint32 m_cchKeyLength;
char m_rgchKey[k_cubAppProofOfPurchaseKeyMax];
};
//-----------------------------------------------------------------------------
// Purpose: response to GetFileDetails
//-----------------------------------------------------------------------------
struct FileDetailsResult_t
{
enum { k_iCallback = k_iSteamAppsCallbacks + 23 };
EResult m_eResult;
uint64 m_ulFileSize; // original file size in bytes
uint8 m_FileSHA[20]; // original file SHA1 hash
uint32 m_unFlags; //
};
#pragma pack( pop )
#endif // ISTEAMAPPS_H
| 0 | 0.848445 | 1 | 0.848445 | game-dev | MEDIA | 0.760751 | game-dev | 0.541608 | 1 | 0.541608 |
hojat72elect/libgdx_games | 16,433 | Clumsy_UFO/core/src/com/nopalsoft/clumsy/game/arcade/GameScreenArcade.kt | package com.nopalsoft.clumsy.game.arcade
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.Input
import com.badlogic.gdx.graphics.g2d.TextureAtlas.AtlasRegion
import com.badlogic.gdx.math.Interpolation
import com.badlogic.gdx.scenes.scene2d.Group
import com.badlogic.gdx.scenes.scene2d.InputEvent
import com.badlogic.gdx.scenes.scene2d.InputListener
import com.badlogic.gdx.scenes.scene2d.actions.Actions
import com.badlogic.gdx.scenes.scene2d.actions.MoveToAction
import com.badlogic.gdx.scenes.scene2d.ui.Button
import com.badlogic.gdx.scenes.scene2d.ui.Image
import com.badlogic.gdx.scenes.scene2d.ui.Table
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable
import com.nopalsoft.clumsy.Assets
import com.nopalsoft.clumsy.ClumsyUfoGame
import com.nopalsoft.clumsy.Settings
import com.nopalsoft.clumsy.game.classic.ClassicGameScreen
import com.nopalsoft.clumsy.objects.Ufo
import com.nopalsoft.clumsy.screens.MainMenuScreen
import com.nopalsoft.clumsy.screens.Screens
class GameScreenArcade(game: ClumsyUfoGame) : Screens(game) {
val TIME_INC_GAMEOVER: Float = .0025f
var numIncGameOver: Int = 0
var comenzarIncrementarPuntuacionGameOver: Boolean
var oWorld: WorldGameArcade
var renderer: WorldGameRendererArcade
var salto: Boolean = false
var flashazo: Image
/* Game Over */
var medallsFondo: Group? = null
var gameOver: Image? = null
/* Ready */
var getReady: Image? = null
var tapCat: Image? = null
var btPlayClassic: Button? = null
var btPlayArcade: Button? = null
var btScore: Button? = null
var btRate: Button? = null
var btRestorePurchases: Button? = null
var btNoAds: Button? = null
var bottomMenu: Table? = null // rate,ads,restore purchses
var btShareFacebook: Button? = null
var btShareTwitter: Button? = null
var timeIncGameOver: Float
init {
Settings.numberOfTimesPlayed++
oWorld = WorldGameArcade()
renderer = WorldGameRendererArcade(batch, oWorld)
state = STATE_READY
comenzarIncrementarPuntuacionGameOver = false
timeIncGameOver = 0f
flashazo = Image(Assets.whiteDrawable)
flashazo.setSize(SCREEN_WIDTH.toFloat(), SCREEN_HEIGHT.toFloat())
flashazo.addAction(
Actions.sequence(
Actions.fadeOut(Ufo.HURT_DURATION),
Actions.run(object : Runnable {
override fun run() {
flashazo.remove()
}
})
)
)
inicializarGameOver()
inicializarReady()
}
private fun inicializarReady() {
getReady = Image(Assets.getReady)
getReady!!.setSize(320f, 100f)
getReady!!.setPosition(SCREEN_WIDTH / 2f - 160, SCREEN_HEIGHT / 2f + 50)
getReady!!.getColor().a = 0f
getReady!!.addAction(Actions.fadeIn(.4f))
tapCat = Image(Assets.tapCat)
tapCat!!.setSize(150f, 140f)
tapCat!!.setPosition(SCREEN_WIDTH / 2f - 75, SCREEN_HEIGHT / 2f - 100)
tapCat!!.getColor().a = 0f
tapCat!!.addAction(Actions.fadeIn(.4f))
stage.addActor(getReady)
stage.addActor(tapCat)
}
private fun inicializarGameOver() {
medallsFondo = Group()
medallsFondo!!.setSize(400f, 200f)
val background = Image(Assets.medalsBackground)
background.setSize(medallsFondo!!.getWidth(), medallsFondo!!.getHeight())
medallsFondo!!.setPosition(SCREEN_WIDTH / 2f - 200, -201f)
medallsFondo!!.addActor(background)
val action = Actions.action<MoveToAction>(MoveToAction::class.java)
action.interpolation = Interpolation.sine
action.setPosition(SCREEN_WIDTH / 2f - 200, 385f)
action.duration = .25f
medallsFondo!!.addAction(
Actions.sequence(
action, Actions.delay(.1f),
Actions.run(object : Runnable {
override fun run() {
comenzarIncrementarPuntuacionGameOver = true
if (numIncGameOver.toFloat() == oWorld.score) {
stage.addActor(btPlayClassic)
stage.addActor(btPlayArcade)
stage.addActor(btScore)
stage.addActor(btShareFacebook)
stage.addActor(btShareTwitter)
stage.addActor(bottomMenu)
}
}
})
)
)
btPlayClassic = Button(
TextureRegionDrawable(
Assets.buttonPlayClassic
)
)
btPlayClassic!!.setSize(160f, 95f)
btPlayClassic!!.setPosition(75f, 280f)
btPlayClassic!!.addListener(object : InputListener() {
override fun touchDown(
event: InputEvent?, x: Float, y: Float,
pointer: Int, button: Int
): Boolean {
btPlayClassic!!.setPosition(75f, 277f)
return true
}
override fun touchUp(
event: InputEvent?, x: Float, y: Float,
pointer: Int, button: Int
) {
btPlayClassic!!.setPosition(75f, 280f)
fadeOutButtons()
state = STATE_TRY_AGAIN
Assets.playSound(Assets.swooshing)
changeScreenWithFadeOut(ClassicGameScreen::class.java, game)
}
})
btPlayArcade = Button(
TextureRegionDrawable(Assets.buttonPlayArcade)
)
btPlayArcade!!.setSize(160f, 95f)
btPlayArcade!!.setPosition(250f, 280f)
btPlayArcade!!.addListener(object : InputListener() {
override fun touchDown(
event: InputEvent?, x: Float, y: Float,
pointer: Int, button: Int
): Boolean {
btPlayArcade!!.setPosition(250f, 277f)
return true
}
override fun touchUp(
event: InputEvent?, x: Float, y: Float,
pointer: Int, button: Int
) {
btPlayArcade!!.setPosition(250f, 280f)
fadeOutButtons()
state = STATE_TRY_AGAIN
Assets.playSound(Assets.swooshing)
changeScreenWithFadeOut(GameScreenArcade::class.java, game)
}
})
btScore = Button(TextureRegionDrawable(Assets.buttonLeaderboard))
btScore!!.setSize(160f, 95f)
btScore!!.setPosition(130f, 180f)
btScore!!.addListener(object : InputListener() {
override fun touchDown(
event: InputEvent?, x: Float, y: Float,
pointer: Int, button: Int
): Boolean {
btScore!!.setPosition(btScore!!.getX(), btScore!!.getY() - 3)
return true
}
override fun touchUp(
event: InputEvent?, x: Float, y: Float,
pointer: Int, button: Int
) {
btScore!!.setPosition(btScore!!.getX(), btScore!!.getY() + 3)
}
})
btShareFacebook = Button(
TextureRegionDrawable(
Assets.buttonFacebook
)
)
btShareFacebook!!.setSize(45f, 45f)
btShareFacebook!!.setPosition(295f, 230f)
btShareFacebook!!.addListener(object : InputListener() {
override fun touchDown(
event: InputEvent?, x: Float, y: Float,
pointer: Int, button: Int
): Boolean {
btShareFacebook!!.setPosition(295f, 227f)
return true
}
override fun touchUp(
event: InputEvent?, x: Float, y: Float,
pointer: Int, button: Int
) {
btShareFacebook!!.setPosition(295f, 230f)
}
})
btShareTwitter = Button(TextureRegionDrawable(Assets.buttonTwitter))
btShareTwitter!!.setSize(45f, 45f)
btShareTwitter!!.setPosition(295f, 181f)
btShareTwitter!!.addListener(object : InputListener() {
override fun touchDown(
event: InputEvent?, x: Float, y: Float,
pointer: Int, button: Int
): Boolean {
btShareTwitter!!.setPosition(
btShareTwitter!!.getX(),
btShareTwitter!!.getY() - 3
)
return true
}
override fun touchUp(
event: InputEvent?, x: Float, y: Float,
pointer: Int, button: Int
) {
btShareTwitter!!.setPosition(
btShareTwitter!!.getX(),
btShareTwitter!!.getY() + 3
)
}
})
btRate = Button(TextureRegionDrawable(Assets.buttonRate))
btRate!!.setSize(60f, 60f)
btRate!!.addListener(object : InputListener() {
override fun touchDown(
event: InputEvent?, x: Float, y: Float,
pointer: Int, button: Int
): Boolean {
btRate!!.setPosition(btRate!!.getX(), btRate!!.getY() - 3)
return true
}
override fun touchUp(
event: InputEvent?, x: Float, y: Float,
pointer: Int, button: Int
) {
btRate!!.setPosition(btRate!!.getX(), btRate!!.getY() + 3)
}
})
btNoAds = Button(TextureRegionDrawable(Assets.buttonNoAds))
if (Settings.didBuyNoAds) btNoAds!!.isVisible = false
btNoAds!!.setSize(60f, 60f)
btNoAds!!.addListener(object : InputListener() {
override fun touchDown(
event: InputEvent?, x: Float, y: Float,
pointer: Int, button: Int
): Boolean {
btNoAds!!.setPosition(btNoAds!!.getX(), btNoAds!!.getY() - 3)
return true
}
override fun touchUp(
event: InputEvent?, x: Float, y: Float,
pointer: Int, button: Int
) {
btNoAds!!.setPosition(btNoAds!!.getX(), btNoAds!!.getY() + 3)
}
})
btRestorePurchases = Button(TextureRegionDrawable(Assets.buttonRestorePurchases))
btRestorePurchases!!.setSize(60f, 60f)
btRestorePurchases!!.addListener(object : InputListener() {
override fun touchDown(
event: InputEvent?, x: Float, y: Float,
pointer: Int, button: Int
): Boolean {
btRestorePurchases!!.setPosition(
btRestorePurchases!!.getX(),
btRestorePurchases!!.getY() - 3
)
return true
}
override fun touchUp(
event: InputEvent?, x: Float, y: Float,
pointer: Int, button: Int
) {
btRestorePurchases!!.setPosition(
btRestorePurchases!!.getX(),
btRestorePurchases!!.getY() + 3
)
}
})
bottomMenu = Table()
bottomMenu!!.setPosition(1f, 1f)
bottomMenu!!.defaults().padRight(2.5f)
bottomMenu!!.add<Button?>(btRate)
bottomMenu!!.add<Button?>(btRestorePurchases)
bottomMenu!!.add<Button?>(btNoAds)
bottomMenu!!.pack()
gameOver = Image(Assets.gameover)
gameOver!!.setSize(320f, 100f)
gameOver!!.setPosition(SCREEN_WIDTH / 2f - 160, 600f)
}
private fun fadeOutButtons() {
medallsFondo!!.addAction(Actions.fadeOut(.2f))
btPlayClassic!!.addAction(Actions.fadeOut(.2f))
btPlayArcade!!.addAction(Actions.fadeOut(.2f))
btScore!!.addAction(Actions.fadeOut(.2f))
gameOver!!.addAction(Actions.fadeOut(.2f))
btShareFacebook!!.addAction(Actions.fadeOut(.2f))
btShareTwitter!!.addAction(Actions.fadeOut(.2f))
bottomMenu!!.addAction(Actions.fadeOut(.2f))
}
override fun update(delta: Float) {
if (Settings.didBuyNoAds) btNoAds!!.isVisible = false
when (state) {
STATE_READY -> updateReady()
STATE_RUNNING -> updateRunning(delta)
STATE_GAME_OVER -> updateGameOver(delta)
else -> {}
}
}
private fun updateReady() {
if (Gdx.input.justTouched()) {
getReady!!.remove()
tapCat!!.remove()
state = STATE_RUNNING
}
}
private fun updateGameOver(delta: Float) {
timeIncGameOver += delta
if (comenzarIncrementarPuntuacionGameOver
&& numIncGameOver < oWorld.score.toInt() && timeIncGameOver >= TIME_INC_GAMEOVER
) {
timeIncGameOver -= TIME_INC_GAMEOVER
numIncGameOver++
if (numIncGameOver == oWorld.score.toInt()) {
stage.addActor(btPlayClassic)
stage.addActor(btScore)
stage.addActor(btPlayArcade)
stage.addActor(btShareFacebook)
stage.addActor(btShareTwitter)
stage.addActor(bottomMenu)
if (oWorld.score >= 50) {
val med: AtlasRegion?
if (oWorld.score >= 250) med = Assets.med1
else if (oWorld.score >= 200) med = Assets.med2
else if (oWorld.score >= 100) med = Assets.med3
else med = Assets.med4
val medalla = Image(med)
medalla.setSize(90f, 90f)
medalla.setPosition(45f, 47f)
medallsFondo!!.addActor(medalla)
}
}
}
}
private fun updateRunning(delta: Float) {
if (Gdx.input.justTouched()) salto = true
oWorld.update(delta, salto)
if (oWorld.oUfo.state == Ufo.STATE_HURT) {
stage.addActor(flashazo)
oWorld.oUfo.die()
}
if (oWorld.state == WorldGameArcade.STATE_GAMEOVER) {
setGameover()
}
salto = false
}
private fun setGameover() {
state = STATE_GAME_OVER
if (Settings.bestScoreArcade < oWorld.score) Settings.bestScoreArcade = oWorld.score.toInt()
stage.addActor(medallsFondo)
stage.addActor(gameOver)
}
override fun draw(delta: Float) {
var delta = delta
if (state == STATE_PAUSED || state == STATE_GAME_OVER) delta = 0f
batch.begin()
batch.draw(Assets.background0, 0f, 0f, SCREEN_WIDTH.toFloat(), SCREEN_HEIGHT.toFloat())
batch.end()
renderer.render()
Assets.parallaxBackground.render(delta)
camera.update()
batch.setProjectionMatrix(camera.combined)
batch.begin()
if (state == STATE_READY) drawReady(delta)
if (state != STATE_GAME_OVER) drawScoreCentered(
0f, (SCREEN_HEIGHT - 65).toFloat(),
oWorld.score.toInt()
)
batch.end()
}
override fun render(delta: Float) {
super.render(delta)
if (state == STATE_GAME_OVER) {
batch.begin()
drawGameover()
batch.end()
}
}
private fun drawGameover() {
drawSmallScoreRightAligned(
medallsFondo!!.getX() + medallsFondo!!.getWidth() - 30,
medallsFondo!!.getY() + 40, Settings.bestScoreArcade
)
drawSmallScoreRightAligned(
medallsFondo!!.getX() + medallsFondo!!.getWidth() - 30,
medallsFondo!!.getY() + 110, numIncGameOver
)
}
private fun drawReady(delta: Float) {
oWorld.oUfo.update(delta, null)
}
override fun keyDown(keycode: Int): Boolean {
if (keycode == Input.Keys.SPACE) {
salto = true
return true
} else if (keycode == Input.Keys.BACK || keycode == Input.Keys.ESCAPE) game.setScreen(MainMenuScreen(game))
return false
}
companion object {
const val STATE_READY: Int = 1
const val STATE_RUNNING: Int = 2
const val STATE_PAUSED: Int = 3
const val STATE_GAME_OVER: Int = 4
const val STATE_TRY_AGAIN: Int = 5
var state: Int = 0
}
}
| 0 | 0.82895 | 1 | 0.82895 | game-dev | MEDIA | 0.943628 | game-dev | 0.97233 | 1 | 0.97233 |
FrostyToolsuite/FrostyToolsuite | 5,005 | FrostySdk/Managers/Infos/FileInfos/NonCasFileInfo.cs | using System;
using System.IO;
using Frosty.Sdk.Interfaces;
using Frosty.Sdk.IO;
using Frosty.Sdk.Utils;
namespace Frosty.Sdk.Managers.Infos.FileInfos;
public class NonCasFileInfo : IFileInfo
{
private readonly string m_superBundlePath;
private readonly long m_offset;
private readonly uint m_size;
private readonly uint m_logicalOffset;
private readonly bool m_isDelta;
private readonly string? m_superBundleBasePath;
private readonly long m_baseOffset;
private readonly uint m_baseSize;
private readonly int m_midInstructionSize;
private readonly string m_fullPath;
private readonly string? m_fullBasePath;
public NonCasFileInfo(string inSuperBundlePath, long inOffset, uint inSize, uint inLogicalOffset = 0)
{
m_superBundlePath = inSuperBundlePath;
m_offset = inOffset;
m_size = inSize;
m_logicalOffset = inLogicalOffset;
m_fullPath = Path.Combine(FileSystemManager.BasePath, m_superBundlePath);
}
public NonCasFileInfo(string inSuperBundlePath, string? inSuperBundleBasePath, long inDeltaOffset, uint inDeltaSize, long inBaseOffset, uint inBaseSize, int inMidInstructionSize, uint inLogicalOffset = 0)
{
m_isDelta = true;
m_superBundlePath = inSuperBundlePath;
m_superBundleBasePath = inSuperBundleBasePath;
m_offset = inDeltaOffset;
m_size = inDeltaSize;
m_baseOffset = inBaseOffset;
m_baseSize = inBaseSize;
m_midInstructionSize = inMidInstructionSize;
m_logicalOffset = inLogicalOffset;
m_fullPath = Path.Combine(FileSystemManager.BasePath, m_superBundlePath);
m_fullBasePath = m_superBundleBasePath is not null ? Path.Combine(FileSystemManager.BasePath, m_superBundleBasePath) : null;
}
public bool IsDelta() => m_isDelta;
public bool IsComplete() => m_logicalOffset == 0;
public bool FileExists() => true;
public long GetOriginalSize()
{
if (m_isDelta)
{
BlockStream? baseStream = null;
if (m_baseSize > 0)
{
baseStream = BlockStream.FromFile(m_fullBasePath!, m_baseOffset, (int)m_baseSize);
}
using (BlockStream deltaStream = BlockStream.FromFile(m_fullPath, m_offset, (int)m_size))
{
return Cas.GetOriginalSize(deltaStream, baseStream, m_midInstructionSize);
}
}
using (BlockStream stream = BlockStream.FromFile(m_fullPath, m_offset, (int)m_size))
{
return Cas.GetOriginalSize(stream);
}
}
public Block<byte> GetRawData()
{
if (m_isDelta)
{
throw new NotImplementedException();
}
using (FileStream stream = new(m_fullPath, FileMode.Open, FileAccess.Read))
{
stream.Position = m_offset;
Block<byte> retVal = new((int)m_size);
stream.ReadExactly(retVal);
return retVal;
}
}
public Block<byte> GetData(int inOriginalSize)
{
if (m_isDelta)
{
BlockStream? baseStream = null;
if (m_baseSize > 0)
{
baseStream = BlockStream.FromFile(m_fullBasePath!, m_baseOffset, (int)m_baseSize);
}
using (BlockStream deltaStream = BlockStream.FromFile(m_fullPath, m_offset, (int)m_size))
{
Block<byte> retVal = Cas.DecompressData(deltaStream, baseStream, inOriginalSize, m_midInstructionSize);
baseStream?.Dispose();
return retVal;
}
}
using (BlockStream stream = BlockStream.FromFile(m_fullPath, m_offset, (int)m_size))
{
return Cas.DecompressData(stream, inOriginalSize);
}
}
public void SerializeInternal(DataStream stream)
{
stream.WriteBoolean(m_isDelta);
stream.WriteNullTerminatedString(m_superBundlePath);
if (m_isDelta)
{
stream.WriteNullTerminatedString(m_superBundleBasePath ?? string.Empty);
}
stream.WriteInt64(m_offset);
stream.WriteUInt32(m_size);
if (m_isDelta)
{
stream.WriteInt64(m_baseOffset);
stream.WriteUInt32(m_baseSize);
stream.WriteInt32(m_midInstructionSize);
}
stream.WriteUInt32(m_logicalOffset);
}
public static NonCasFileInfo DeserializeInternal(DataStream stream)
{
bool isDelta = stream.ReadBoolean();
if (isDelta)
{
return new NonCasFileInfo(stream.ReadNullTerminatedString(), stream.ReadNullTerminatedString(),
stream.ReadInt64(), stream.ReadUInt32(), stream.ReadInt64(), stream.ReadUInt32(), stream.ReadInt32(),
stream.ReadUInt32());
}
return new NonCasFileInfo(stream.ReadNullTerminatedString(), stream.ReadInt64(), stream.ReadUInt32(),
stream.ReadUInt32());
}
} | 0 | 0.944741 | 1 | 0.944741 | game-dev | MEDIA | 0.59695 | game-dev | 0.94819 | 1 | 0.94819 |
prime31/Nez-Samples | 3,217 | Nez.Samples/Scenes/Samples/Pathfinding/Pathfinder.cs | using Nez.AI.Pathfinding;
using Microsoft.Xna.Framework;
using System.Collections.Generic;
using Nez.Tiled;
namespace Nez.Samples
{
/// <summary>
/// simple Component that finds a path on click and displays it via a series of rectangles
/// </summary>
public class Pathfinder : RenderableComponent, IUpdatable
{
// make sure we arent culled
public override float Width => 1000;
public override float Height => 1000;
UnweightedGridGraph _gridGraph;
List<Point> _breadthSearchPath;
WeightedGridGraph _weightedGraph;
List<Point> _weightedSearchPath;
AstarGridGraph _astarGraph;
List<Point> _astarSearchPath;
TmxMap _tilemap;
Point _start, _end;
public Pathfinder(TmxMap tilemap)
{
_tilemap = tilemap;
var layer = tilemap.GetLayer<TmxLayer>("main");
_start = new Point(1, 1);
_end = new Point(10, 10);
_gridGraph = new UnweightedGridGraph(layer);
_breadthSearchPath = _gridGraph.Search(_start, _end);
_weightedGraph = new WeightedGridGraph(layer);
_weightedSearchPath = _weightedGraph.Search(_start, _end);
_astarGraph = new AstarGridGraph(layer);
_astarSearchPath = _astarGraph.Search(_start, _end);
Debug.DrawTextFromBottom = true;
}
void IUpdatable.Update()
{
// on left click set our path end time
if (Input.LeftMouseButtonPressed)
_end = _tilemap.WorldToTilePosition(Input.MousePosition);
// on right click set our path start time
if (Input.RightMouseButtonPressed)
_start = _tilemap.WorldToTilePosition(Input.MousePosition);
// regenerate the path on either click
if (Input.LeftMouseButtonPressed || Input.RightMouseButtonPressed)
{
// time both path generations
var first = Debug.TimeAction(() => { _breadthSearchPath = _gridGraph.Search(_start, _end); });
var second = Debug.TimeAction(() => { _weightedSearchPath = _weightedGraph.Search(_start, _end); });
var third = Debug.TimeAction(() => { _astarSearchPath = _astarGraph.Search(_start, _end); });
// debug draw the times
Debug.DrawText("Breadth First: {0}\nDijkstra: {1}\nAstar: {2}", first, second, third);
Debug.Log("\nBreadth First: {0}\nDijkstra: {1}\nAstar: {2}", first, second, third);
}
}
public override void Render(Batcher batcher, Camera camera)
{
// if we have a path render all the nodes
if (_breadthSearchPath != null)
{
foreach (var node in _breadthSearchPath)
{
var x = node.X * _tilemap.TileWidth + _tilemap.TileWidth * 0.5f;
var y = node.Y * _tilemap.TileHeight + _tilemap.TileHeight * 0.5f;
batcher.DrawPixel(x + 2, y + 2, Color.Yellow, 4);
}
}
if (_weightedSearchPath != null)
{
foreach (var node in _weightedSearchPath)
{
var x = node.X * _tilemap.TileWidth + _tilemap.TileWidth * 0.5f;
var y = node.Y * _tilemap.TileHeight + _tilemap.TileHeight * 0.5f;
batcher.DrawPixel(x - 2, y - 2, Color.Blue, 4);
}
}
if (_astarSearchPath != null)
{
foreach (var node in _astarSearchPath)
{
var x = node.X * _tilemap.TileWidth + _tilemap.TileWidth * 0.5f;
var y = node.Y * _tilemap.TileHeight + _tilemap.TileHeight * 0.5f;
batcher.DrawPixel(x, y, Color.Orange, 4);
}
}
}
}
} | 0 | 0.899696 | 1 | 0.899696 | game-dev | MEDIA | 0.542799 | game-dev | 0.989544 | 1 | 0.989544 |
thingsbyfilip/nope | 1,782 | astar.py | # A* Pathfinding implementation in Python
# Adopted from original script by Christian Careaga (christian.careaga7@gmail.com)
# Source: http://code.activestate.com/recipes/578919-python-a-pathfinding-with-binary-heap/
# Released under the MIT License: https://opensource.org/licenses/MIT
# import numpy, random
from heapq import *
def heuristic(a, b):
#seed may vary!
return (b[0] - a[0]) ** 2 + (b[1] - a[1]) ** 2
def astar_path(array, start, goal):
# random.seed(1)
neighbors = [(0,1),(0,-1),(1,0),(-1,0)]
# neighbors = [(0,1),(0,-1),(1,0),(-1,0),(-1,-1),(-1,1),(1,-1),(1,1)]
close_set = set()
came_from = {}
gscore = {start: 0}
fscore = {start: heuristic(start, goal)}
oheap = []
heappush(oheap, (fscore[start], start))
while oheap:
current = heappop(oheap)[1]
if current == goal:
data = []
while current in came_from:
data.append(current)
current = came_from[current]
return data
close_set.add(current)
for i, j in neighbors:
neighbor = current[0] + i, current[1] + j
if 0 <= neighbor[0] < array.shape[0]:
if 0 <= neighbor[1] < array.shape[1]:
# if array[neighbor[0]][neighbor[1]] == 1:
if array[neighbor[0]][neighbor[1]] != 0:
continue
else:
# array bound y walls
continue
else:
# array bound x walls
continue
tentative_g_score = gscore[current] + heuristic(current, neighbor)
if neighbor in close_set and tentative_g_score >= gscore.get(neighbor, 0):
continue
if tentative_g_score < gscore.get(neighbor, 0) or neighbor not in [i[1]for i in oheap]:
came_from[neighbor] = current
gscore[neighbor] = tentative_g_score
fscore[neighbor] = tentative_g_score + heuristic(neighbor, goal)
heappush(oheap, (fscore[neighbor], neighbor))
return False | 0 | 0.753039 | 1 | 0.753039 | game-dev | MEDIA | 0.420567 | game-dev | 0.775254 | 1 | 0.775254 |
ricardomatias/ableton-live | 1,035 | lib/helpers/EventEmitter.ts | import mitt, {
Emitter,
EventType,
Handler,
EventHandlerMap,
} from 'mitt';
export type Arguments<T> = [T] extends [(...args: infer U) => any]
? U
: [T] extends [void] ? [] : [T]
export interface TypedEventEmitter<Events> {
on<E extends keyof Events>(event: E, listener: Events[E]): void
off<E extends keyof Events>(event: E, listener: Events[E]): void
emit<E extends keyof Events>(event: E, ...args: Arguments<Events[E]>): void
}
export class EventEmitter<Events extends Record<EventType, unknown>> {
private mitt: Emitter<Events>;
constructor(e?: EventHandlerMap<Events>) {
this.mitt = mitt(e);
}
get all(): EventHandlerMap<Events> {
return this.mitt.all;
}
on<Key extends keyof Events>(type: Key, handler: Handler<Events[Key]>): void {
this.mitt.on(type, handler);
}
off<Key extends keyof Events>(type: Key, handler?: Handler<Events[Key]>): void {
this.mitt.off(type, handler);
}
emit<T>(type: EventType, event?: T): void;
emit(type: '*', event?: any): void {
this.mitt.emit(type, event);
}
}
| 0 | 0.718783 | 1 | 0.718783 | game-dev | MEDIA | 0.257015 | game-dev | 0.855925 | 1 | 0.855925 |
CyclopsMC/IntegratedDynamics | 2,116 | src/main/java/org/cyclops/integrateddynamics/core/network/diagnostics/RawNetworkData.java | package org.cyclops.integrateddynamics.core.network.diagnostics;
import com.google.common.collect.Lists;
import lombok.Data;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.Tag;
import java.util.List;
/**
* @author rubensworks
*/
@Data
public class RawNetworkData implements IRawData {
private final boolean killed;
private final int id;
private final int cables;
private final List<RawPartData> parts;
private final List<RawObserverData> observers;
@Override
public String toString() {
return String.format("Network %s (cables: %s; elements: %s)", id, cables, parts.size());
}
public CompoundTag toNbt() {
CompoundTag tag = new CompoundTag();
tag.putBoolean("killed", killed);
tag.putInt("id", id);
tag.putLong("cables", cables);
ListTag listParts = new ListTag();
for (RawPartData part : parts) {
listParts.add(part.toNbt());
}
tag.put("parts", listParts);
ListTag listObservers = new ListTag();
for (RawObserverData observer : observers) {
listObservers.add(observer.toNbt());
}
tag.put("observers", listObservers);
return tag;
}
public static RawNetworkData fromNbt(CompoundTag tag) {
List<RawPartData> parts = Lists.newArrayList();
ListTag listParts = tag.getList("parts", Tag.TAG_COMPOUND);
for (int i = 0; i < listParts.size(); i++) {
CompoundTag partTag = listParts.getCompound(i);
parts.add(RawPartData.fromNbt(partTag));
}
List<RawObserverData> observers = Lists.newArrayList();
ListTag listObservers = tag.getList("observers", Tag.TAG_COMPOUND);
for (int i = 0; i < listObservers.size(); i++) {
CompoundTag observerTag = listObservers.getCompound(i);
observers.add(RawObserverData.fromNbt(observerTag));
}
return new RawNetworkData(tag.getBoolean("killed"), tag.getInt("id"),
tag.getInt("cables"), parts, observers);
}
}
| 0 | 0.540516 | 1 | 0.540516 | game-dev | MEDIA | 0.874457 | game-dev | 0.577314 | 1 | 0.577314 |
dqzg12300/unidbg_tools | 17,785 | unidbg-ios/src/main/java/com/github/unidbg/ios/DarwinSyscallHandler.java | package com.github.unidbg.ios;
import com.github.unidbg.Emulator;
import com.github.unidbg.arm.context.RegisterContext;
import com.github.unidbg.file.FileResult;
import com.github.unidbg.file.ios.DarwinFileIO;
import com.github.unidbg.file.ios.IOConstants;
import com.github.unidbg.ios.struct.VMStatistics;
import com.github.unidbg.ios.struct.kernel.*;
import com.github.unidbg.pointer.UnidbgPointer;
import com.github.unidbg.pointer.UnidbgStructure;
import com.github.unidbg.spi.SyscallHandler;
import com.github.unidbg.unix.UnixEmulator;
import com.github.unidbg.unix.UnixSyscallHandler;
import com.sun.jna.Pointer;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.Arrays;
abstract class DarwinSyscallHandler extends UnixSyscallHandler<DarwinFileIO> implements SyscallHandler<DarwinFileIO>, DarwinSyscall {
private static final Log log = LogFactory.getLog(DarwinSyscallHandler.class);
final long bootTime = System.currentTimeMillis();
protected final void exit(Emulator<?> emulator) {
RegisterContext context = emulator.getContext();
int status = context.getIntArg(0);
System.exit(status);
}
protected final int open_NOCANCEL(Emulator<DarwinFileIO> emulator, int offset) {
RegisterContext context = emulator.getContext();
Pointer pathname_p = context.getPointerArg(offset);
int oflags = context.getIntArg(offset + 1);
int mode = context.getIntArg(offset + 2);
String pathname = pathname_p.getString(0);
int fd = open(emulator, pathname, oflags);
if (log.isDebugEnabled()) {
log.debug("open_NOCANCEL pathname=" + pathname + ", oflags=0x" + Integer.toHexString(oflags) + ", mode=" + Integer.toHexString(mode) + ", fd=" + fd + ", LR=" + context.getLRPointer());
}
return fd;
}
private static final String[] MOUNTED_FS = {
"ABAAAAAAEADkvwcAAAAAAPAoAQAAAAAAGhUBAAAAAADivwcAAAAAABoVAQAAAAAAAgAAAREAAAAAAAAAEQAAAADQgAQDAAAAaGZzAAAAAAAAAAAAAAAAAC8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAvZGV2L2Rpc2swczFzMQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
"AAIAAAACAABmAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACyAAAAAAAAAAAAAAAAAAAAqOWUlhMAAAAAAAAAEwAAAAAQEAQAAAAAZGV2ZnMAAAAAAAAAAAAAAC9kZXYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABkZXZmcwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
"ABAAAAAAEAAcUDMAAAAAANTJLQAAAAAA1MktAAAAAAAaUDMAAAAAANTJLQAAAAAAAwAAAREAAAAAAAAAEQAAAICQgBQDAAAAaGZzAAAAAAAAAAAAAAAAAC9wcml2YXRlL3ZhcgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAvZGV2L2Rpc2swczFzMgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
};
protected int getfsstat64(Emulator<DarwinFileIO> emulator) {
RegisterContext context = emulator.getContext();
UnidbgPointer buf = context.getPointerArg(0);
int bufSize = context.getIntArg(1);
int flags = context.getIntArg(2);
if (log.isDebugEnabled()) {
log.debug("getfsstat64 buf=" + buf + ", bufSize=" + bufSize + ", flags=0x" + Integer.toHexString(flags));
}
if (buf == null) {
return MOUNTED_FS.length;
}
buf.setSize(bufSize);
Pointer pointer = buf;
int statfs_size = UnidbgStructure.calculateSize(StatFS.class);
for (int i = 0; i < MOUNTED_FS.length && bufSize >= statfs_size; i++, bufSize -= statfs_size, pointer = pointer.share(statfs_size)) {
byte[] data = Base64.decodeBase64(MOUNTED_FS[i]);
pointer.write(0, data, 0, data.length);
}
return MOUNTED_FS.length;
}
protected final int access(Emulator<DarwinFileIO> emulator) {
RegisterContext context = emulator.getContext();
Pointer pathname = context.getPointerArg(0);
int mode = context.getIntArg(1);
String path = pathname.getString(0);
if (log.isDebugEnabled()) {
log.debug("access pathname=" + path + ", mode=" + mode);
}
return faccessat(emulator, path);
}
protected final int faccessat(Emulator<DarwinFileIO> emulator, String pathname) {
FileResult<?> result = resolve(emulator, pathname, IOConstants.O_RDONLY);
if (result != null && result.isSuccess()) {
if (verbose) {
System.out.printf("File access '%s' from %s%n", pathname, emulator.getContext().getLRPointer());
}
return 0;
}
emulator.getMemory().setErrno(result != null ? result.errno : UnixEmulator.ENOENT);
if (verbose) {
System.out.printf("File access failed '%s' from %s%n", pathname, emulator.getContext().getLRPointer());
}
return -1;
}
protected final int listxattr(Emulator<DarwinFileIO> emulator) {
RegisterContext context = emulator.getContext();
Pointer path = context.getPointerArg(0);
UnidbgPointer namebuf = context.getPointerArg(1);
int size = context.getIntArg(2);
int options = context.getIntArg(3);
String pathname = path.getString(0);
FileResult<DarwinFileIO> result = resolve(emulator, pathname, IOConstants.O_RDONLY);
if (namebuf != null) {
namebuf.setSize(size);
}
if (result.isSuccess()) {
int ret = result.io.listxattr(namebuf, size, options);
if (ret == -1) {
log.info("listxattr path=" + pathname + ", namebuf=" + namebuf + ", size=" + size + ", options=" + options + ", LR=" + context.getLRPointer());
} else {
if (log.isDebugEnabled()) {
log.info("listxattr path=" + pathname + ", namebuf=" + namebuf + ", size=" + size + ", options=" + options + ", LR=" + context.getLRPointer());
}
}
return ret;
} else {
log.info("listxattr path=" + pathname + ", namebuf=" + namebuf + ", size=" + size + ", options=" + options + ", LR=" + context.getLRPointer());
emulator.getMemory().setErrno(UnixEmulator.ENOENT);
return -1;
}
}
protected final int chmod(Emulator<DarwinFileIO> emulator) {
RegisterContext context = emulator.getContext();
Pointer path = context.getPointerArg(0);
int mode = context.getIntArg(1) & 0xffff;
String pathname = path.getString(0);
FileResult<DarwinFileIO> result = resolve(emulator, pathname, IOConstants.O_RDONLY);
if (result.isSuccess()) {
int ret = result.io.chmod(mode);
if (ret == -1) {
log.info("chmod path=" + pathname + ", mode=0x" + Integer.toHexString(mode));
} else {
if (log.isDebugEnabled()) {
log.debug("chmod path=" + pathname + ", mode=0x" + Integer.toHexString(mode));
}
}
return ret;
} else {
log.info("chmod path=" + pathname + ", mode=0x" + Integer.toHexString(mode));
emulator.getMemory().setErrno(UnixEmulator.ENOENT);
return -1;
}
}
protected final boolean host_statistics(Pointer request, MachMsgHeader header) {
HostStatisticsRequest args = new HostStatisticsRequest(request);
args.unpack();
if (log.isDebugEnabled()) {
log.debug("host_statistics args=" + args);
}
if (args.flavor == HostStatisticsRequest.HOST_VM_INFO) {
int size = UnidbgStructure.calculateSize(VMStatistics.class);
HostStatisticsReply reply = new HostStatisticsReply(request, size);
reply.unpack();
header.setMsgBits(false);
header.msgh_size = header.size() + reply.size();
header.msgh_remote_port = header.msgh_local_port;
header.msgh_local_port = 0;
header.msgh_id += 100; // reply Id always equals reqId+100
header.pack();
reply.writeVMStatistics();
reply.retCode = 0;
reply.host_info_outCnt = size / 4;
reply.pack();
if (log.isDebugEnabled()) {
log.debug("host_statistics HOST_VM_INFO reply=" + reply);
}
return true;
}
return false;
}
static final int STATIC_PORT = 0x88;
final int vproc_mig_look_up2(Pointer request, MachMsgHeader header) {
VprocMigLookupRequest args = new VprocMigLookupRequest(request);
args.unpack();
String serviceName = args.getServiceName();
if (log.isDebugEnabled()) {
log.debug("vproc_mig_look_up2 args=" + args + ", serviceName=" + serviceName);
}
if ("cy:com.saurik.substrated".equals(serviceName)) {
return -1;
}
VprocMigLookupReply reply = new VprocMigLookupReply(request);
reply.unpack();
header.msgh_bits = (header.msgh_bits & 0xff) | MACH_MSGH_BITS_COMPLEX;
header.msgh_size = header.size() + reply.size();
header.msgh_remote_port = header.msgh_local_port;
header.msgh_local_port = 0;
header.msgh_id += 100; // reply Id always equals reqId+100
header.pack();
reply.body.msgh_descriptor_count = 1;
reply.sp.name = STATIC_PORT;
reply.sp.pad1 = 0;
reply.sp.pad2 = 0;
reply.sp.disposition = 17;
reply.sp.type = MACH_MSG_PORT_DESCRIPTOR;
reply.pack();
VprocMigLookupData data = new VprocMigLookupData(request.share(reply.size()));
data.size = 0x20;
Arrays.fill(data.au_tok.val, 0);
data.pack();
if (log.isDebugEnabled()) {
log.debug("vproc_mig_look_up2 reply=" + reply + ", data=" + data);
}
return MACH_MSG_SUCCESS;
}
}
| 0 | 0.923775 | 1 | 0.923775 | game-dev | MEDIA | 0.161305 | game-dev | 0.589197 | 1 | 0.589197 |
alexkulya/pandaria_5.4.8 | 8,722 | src/server/game/AuctionHouse/AuctionHouseMgr.h | /*
* 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/>.
*/
#ifndef SF_AUCTION_HOUSE_MGR_H
#define SF_AUCTION_HOUSE_MGR_H
#include <ace/Singleton.h>
#include "Common.h"
#include "DatabaseEnv.h"
#include "DBCStructure.h"
class Item;
class Player;
class WorldPacket;
class LogFile;
#define MIN_AUCTION_TIME (12 * HOUR)
#define MAX_AUCTION_ITEMS 32
#define AUCTION_SEARCH_DELAY 300 // time in MS till the player can search again
enum AuctionError
{
ERR_AUCTION_OK = 0,
ERR_AUCTION_INVENTORY = 1,
ERR_AUCTION_DATABASE_ERROR = 2,
ERR_AUCTION_NOT_ENOUGHT_MONEY = 3,
ERR_AUCTION_ITEM_NOT_FOUND = 4,
ERR_AUCTION_HIGHER_BID = 5,
ERR_AUCTION_BID_INCREMENT = 7,
ERR_AUCTION_BID_OWN = 10,
ERR_AUCTION_RESTRICTED_ACCOUNT = 13
};
enum AuctionAction
{
AUCTION_SELL_ITEM = 0,
AUCTION_CANCEL = 1,
AUCTION_PLACE_BID = 2
};
enum MailAuctionAnswers
{
AUCTION_OUTBIDDED = 0,
AUCTION_WON = 1,
AUCTION_SUCCESSFUL = 2,
AUCTION_EXPIRED = 3,
AUCTION_CANCELLED_TO_BIDDER = 4,
AUCTION_CANCELED = 5,
AUCTION_SALE_PENDING = 6
};
enum AuctionHouses
{
AUCTIONHOUSE_ALLIANCE = 2,
AUCTIONHOUSE_HORDE = 6,
AUCTIONHOUSE_NEUTRAL = 7
};
struct AuctionEntry
{
uint32 Id;
uint32 auctioneer; // creature low guid
uint32 itemGUIDLow;
uint32 itemEntry;
uint32 itemCount;
uint32 owner;
uint32 startbid; // maybe useless
uint32 bid;
uint32 buyout;
time_t expire_time;
uint32 bidder;
uint32 deposit; // deposit can be calculated only when creating auction
AuctionHouseEntry const* auctionHouseEntry; // in AuctionHouse.dbc
uint32 factionTemplateId;
// helpers
uint32 GetHouseId() const { return auctionHouseEntry->houseId; }
uint32 GetHouseFaction() const { return auctionHouseEntry->faction; }
uint32 GetAuctionCut() const;
uint32 GetAuctionOutBid() const;
bool BuildAuctionInfo(WorldPacket & data) const;
void DeleteFromDB(SQLTransaction& trans) const;
void SaveToDB(SQLTransaction& trans) const;
bool LoadFromDB(Field* fields);
bool LoadFromFieldList(Field* fields);
std::string BuildAuctionMailSubject(MailAuctionAnswers response) const;
std::string BuildAuctionMailBody(MailAuctionAnswers response) const;
};
struct AuctionQueryContext : public ACE_Method_Request
{
~AuctionQueryContext();
uint32 auctioneerFaction;
uint64 playerGuid;
LocaleConstant loc_idx;
LocaleConstant locdbc_idx;
std::string searchedname;
uint32 listfrom;
uint8 levelmin;
uint8 levelmax;
uint32 inventoryType;
uint32 itemClass;
uint32 itemSubClass;
uint32 quality;
bool getAll;
std::vector<int8> sortOrder;
int call();
};
//this class is used as auctionhouse instance
class AuctionHouseObject
{
public:
~AuctionHouseObject()
{
TRINITY_WRITE_GUARD(ACE_RW_Thread_Mutex, AuctionsMapLock);
for (AuctionEntryMap::iterator itr = AuctionsMap.begin(); itr != AuctionsMap.end(); ++itr)
delete itr->second;
}
typedef std::map<uint32, AuctionEntry*> AuctionEntryMap;
uint32 Getcount() const { return AuctionsMap.size(); }
AuctionEntryMap::iterator GetAuctionsBegin() {return AuctionsMap.begin();}
AuctionEntryMap::iterator GetAuctionsEnd() {return AuctionsMap.end();}
AuctionEntry* GetAuction(uint32 id, bool skipLock = false)
{
if (!skipLock)
AuctionsMapLock.acquire_read();
AuctionEntryMap::const_iterator itr = AuctionsMap.find(id);
AuctionEntry* result = itr != AuctionsMap.end() ? itr->second : NULL;
if (!skipLock)
AuctionsMapLock.release();
return result;
}
void AddAuction(AuctionEntry* auction, bool skipLock = false);
bool RemoveAuction(AuctionEntry* auction, bool skipLock = false);
void Update();
void BuildListBidderItems(WorldPacket& data, Player* player, uint32& count, uint32& totalcount);
void BuildListOwnerItems(WorldPacket& data, Player* player, uint32& count, uint32& totalcount);
bool BuildListAuctionItems(WorldPacket& data, Player* player, uint64 playerGuid, LocaleConstant loc_idx, LocaleConstant locdbc_idx,
std::string const& searchedname, uint32 listfrom, uint8 levelmin, uint8 levelmax, uint8 usable,
uint32 inventoryType, uint32 itemClass, uint32 itemSubClass, uint32 quality,
bool getAll, std::vector<int8> const& sortOrder,
uint32& count, uint32& totalcount, uint32& throttle);
private:
AuctionEntryMap AuctionsMap;
ACE_RW_Thread_Mutex AuctionsMapLock;
std::map<uint64, std::wstring> ItemNameCache[TOTAL_LOCALES];
ACE_RW_Thread_Mutex ItemNameCacheLock;
};
class AuctionHouseMgr
{
friend class ACE_Singleton<AuctionHouseMgr, ACE_Null_Mutex>;
private:
AuctionHouseMgr();
~AuctionHouseMgr();
public:
static AuctionHouseMgr* instance()
{
static AuctionHouseMgr _instance;
return &_instance;
}
void Unload();
typedef std::unordered_map<uint32, Item*> ItemMap;
AuctionHouseObject* GetAuctionsMap(uint32 factionTemplateId);
AuctionHouseObject* GetBidsMap(uint32 factionTemplateId);
Item* GetAItem(uint32 id)
{
TRINITY_READ_GUARD(ACE_RW_Thread_Mutex, mAitemsLock);
ItemMap::const_iterator itr = mAitems.find(id);
if (itr != mAitems.end())
return itr->second;
return NULL;
}
//auction messages
void SendAuctionWonMail(AuctionEntry* auction, SQLTransaction& trans);
void SendAuctionSalePendingMail(AuctionEntry* auction, SQLTransaction& trans);
void SendAuctionSuccessfulMail(AuctionEntry* auction, SQLTransaction& trans);
void SendAuctionExpiredMail(AuctionEntry* auction, SQLTransaction& trans);
void SendAuctionOutbiddedMail(AuctionEntry* auction, uint32 newPrice, Player* newBidder, SQLTransaction& trans);
void SendAuctionCancelledToBidderMail(AuctionEntry* auction, SQLTransaction& trans, Item* item);
static uint32 GetAuctionDeposit(AuctionHouseEntry const* entry, uint32 time, Item* pItem, uint32 count);
static AuctionHouseEntry const* GetAuctionHouseEntry(uint32 factionTemplateId, bool forClient = false);
public:
// Used primarily at server start to avoid loading a list of expired auctions
void DeleteExpiredAuctionsAtStartup();
//load first auction items, because of check if item exists, when loading
void LoadAuctionItems();
void LoadAuctions();
void AddAItem(Item* it);
bool RemoveAItem(uint32 id);
void Update();
void QueryAuctionItems(uint32 auctioneerFaction, Player* player,
std::string const& searchedname, uint32 listfrom, uint8 levelmin, uint8 levelmax, uint8 usable,
uint32 inventoryType, uint32 itemClass, uint32 itemSubClass, uint32 quality,
bool getAll, std::vector<int8> const& sortOrder);
LogFile* GetLogger() const { return logger.get(); }
private:
AuctionHouseObject mHordeAuctions;
AuctionHouseObject mAllianceAuctions;
AuctionHouseObject mNeutralAuctions;
ItemMap mAitems;
ACE_RW_Thread_Mutex mAitemsLock;
std::thread searchThread;
ACE_Activation_Queue searchQueries;
std::unique_ptr<LogFile> logger;
};
#define sAuctionMgr AuctionHouseMgr::instance()
#endif
| 0 | 0.841603 | 1 | 0.841603 | game-dev | MEDIA | 0.85644 | game-dev | 0.840991 | 1 | 0.840991 |
EliteMasterEric/PickHaxe | 3,279 | draft/net/minecraft/world/level/pathfinder/Node.hx | package net.minecraft.world.level.pathfinder;
@:native("net.minecraft.world.level.pathfinder.Node")
@:mapping("net.minecraft.class_9")
extern class Node
{
@:mapping("field_40")
public final x:Int;
@:mapping("field_39")
public final y:Int;
@:mapping("field_38")
public final z:Int;
/**
* The index in the PathHeap. -1 if not assigned.
*/
@:mapping("field_37")
public var heapIdx:Int;
/**
* The total cost of all path points up to this one. Corresponds to the A* g-score.
*/
@:mapping("field_36")
public var g:Float;
/**
* The estimated cost from this path point to the target. Corresponds to the A* h-score.
*/
@:mapping("field_34")
public var h:Float;
/**
* The total cost of the path containing this path point. Used as sort criteria in PathHeap. Corresponds to the A* f-score.
*/
@:mapping("field_47")
public var f:Float;
@:mapping("field_35")
public var cameFrom:net.minecraft.world.level.pathfinder.Node;
@:mapping("field_42")
public var closed:Bool;
@:mapping("field_46")
public var walkedDistance:Float;
/**
* The additional cost of the path point. If negative, the path point will be sorted out by NodeProcessors.
*/
@:mapping("field_43")
public var costMalus:Float;
@:mapping("field_41")
public var type:net.minecraft.world.level.pathfinder.BlockPathTypes;
public function new(i:Int, j:Int, k:Int);
@:mapping("method_26")
public function cloneAndMove(x:Int, y:Int, z:Int):net.minecraft.world.level.pathfinder.Node;
@:mapping("method_30")
public static function createHash(x:Int, y:Int, z:Int):Int;
/**
* Returns the linear distance to another path point
*/
@:mapping("method_31")
public overload function distanceTo(pathpoint:net.minecraft.world.level.pathfinder.Node):Float;
@:mapping("method_44022")
public function distanceToXZ(node:net.minecraft.world.level.pathfinder.Node):Float;
@:mapping("method_35494")
public overload function distanceTo(pos:net.minecraft.core.BlockPos):Float;
/**
* Returns the squared distance to another path point
*/
@:mapping("method_32")
public overload function distanceToSqr(pathpoint:net.minecraft.world.level.pathfinder.Node):Float;
@:mapping("method_35497")
public overload function distanceToSqr(pos:net.minecraft.core.BlockPos):Float;
@:mapping("method_21653")
public overload function distanceManhattan(pathpoint:net.minecraft.world.level.pathfinder.Node):Float;
@:mapping("method_21654")
public overload function distanceManhattan(pos:net.minecraft.core.BlockPos):Float;
@:mapping("method_22879")
public function asBlockPos():net.minecraft.core.BlockPos;
@:mapping("method_35496")
public function asVec3():net.minecraft.world.phys.Vec3;
public function equals(object:Dynamic):Bool;
public function hashCode():Int;
/**
* Returns `true` if this point has already been assigned to a path
*/
@:mapping("method_27")
public function inOpenSet():Bool;
public function toString():String;
@:mapping("method_35495")
public function writeToStream(buffer:net.minecraft.network.FriendlyByteBuf):Void;
@:mapping("method_28")
public static function createFromStream(buf:net.minecraft.network.FriendlyByteBuf):net.minecraft.world.level.pathfinder.Node;
}
| 0 | 0.589047 | 1 | 0.589047 | game-dev | MEDIA | 0.905426 | game-dev | 0.686914 | 1 | 0.686914 |
ResearchKit/ResearchKit | 3,758 | ResearchKitActiveTask/Spatial Span Memory/ORKSpatialSpanGame.m | /*
Copyright (c) 2015, Apple Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "ORKSpatialSpanGame.h"
#import "ORKHelpers_Internal.h"
@implementation ORKSpatialSpanGame {
NSInteger *_sequence;
}
+ (instancetype)new {
ORKThrowMethodUnavailableException();
}
- (instancetype)init {
ORKThrowMethodUnavailableException();
}
- (void)generateSequence {
_sequence = calloc(_gameSize, sizeof(NSInteger));
if (_sequence == NULL) {
return;
}
for (NSInteger i = 0; i < _gameSize; i++) {
_sequence[i] = i;
}
// Knuth algorithm: swap each with a random element elsewhere in the array.
// Note: we will only use the first _sequenceLength elements of this array
srandom(_seed);
for (NSInteger i = 0; i < _gameSize; i++) {
NSInteger rand_i = arc4random() % _gameSize;
NSInteger tmp = _sequence[i];
_sequence[i] = _sequence[rand_i];
_sequence[rand_i] = tmp;
}
}
- (void)dealloc {
if (_sequence != NULL) {
free(_sequence);
_sequence = NULL;
}
}
- (instancetype)initWithGameSize:(NSInteger)gameSize
sequenceLength:(NSInteger)sequenceLength
seed:(uint32_t)seed {
self = [super init];
if (self) {
_gameSize = gameSize;
_sequenceLength = sequenceLength;
NSParameterAssert(_gameSize > 0);
NSParameterAssert(_sequenceLength > 0);
NSParameterAssert(_sequenceLength < _gameSize);
_seed = seed;
if (_seed == 0) {
_seed = arc4random();
}
[self generateSequence];
if (_sequence == NULL) {
self = nil;
}
}
return self;
}
/// Step parameter is the step in the sequence; tileIndex is the value of that step of the sequence.
- (void)enumerateSequenceWithHandler:(void(^)(NSInteger step, NSInteger tileIndex, BOOL isLastStep, BOOL *stop))handler {
BOOL stop = NO;
for (NSInteger i = 0; i < _sequenceLength; i++) {
handler(i, _sequence[i], (i == _sequenceLength), &stop);
if (stop) break;
}
}
- (NSInteger)tileIndexForStep:(NSInteger)step {
return _sequence[step];
}
@end
| 0 | 0.806798 | 1 | 0.806798 | game-dev | MEDIA | 0.569982 | game-dev | 0.951789 | 1 | 0.951789 |
MatchaChoco010/UnityAnimationRiggingFullBodyController | 19,383 | Assets/Rig/RigConstraint/HandConstraint.cs | using Unity.Burst;
using UnityEngine;
using UnityEngine.Animations;
using UnityEngine.Animations.Rigging;
[DisallowMultipleComponent, AddComponentMenu ("Animation Rigging/Custom/Hand")]
public class HandConstraint : RigConstraint<HandConstraintJob, HandConstraintData, HandConstraintBinder> { }
[BurstCompile]
public struct HandConstraintJob : IWeightedAnimationJob {
public ReadWriteTransformHandle ProximalThumb;
public ReadWriteTransformHandle IntermediateThumb;
public ReadWriteTransformHandle DistalThumb;
public ReadWriteTransformHandle ProximalIndex;
public ReadWriteTransformHandle IntermediateIndex;
public ReadWriteTransformHandle DistalIndex;
public ReadWriteTransformHandle ProximalMiddle;
public ReadWriteTransformHandle IntermediateMiddle;
public ReadWriteTransformHandle DistalMiddle;
public ReadWriteTransformHandle ProximalRing;
public ReadWriteTransformHandle IntermediateRing;
public ReadWriteTransformHandle DistalRing;
public ReadWriteTransformHandle ProximalLittle;
public ReadWriteTransformHandle IntermediateLittle;
public ReadWriteTransformHandle DistalLittle;
public Vector2 ProximalThumbXRotationRange;
public Vector2 ProximalThumbZRotationRange;
public Vector2 IntermediateThumbXRotationRange;
public Vector2 DistalThumbXRotationRange;
public Vector2 ProximalIndexXRotationRange;
public Vector2 ProximalIndexZRotationRange;
public Vector2 IntermediateIndexXRotationRange;
public Vector2 DistalIndexXRotationRange;
public Vector2 ProximalMiddleXRotationRange;
public Vector2 ProximalMiddleZRotationRange;
public Vector2 IntermediateMiddleXRotationRange;
public Vector2 DistalMiddleXRotationRange;
public Vector2 ProximalRingXRotationRange;
public Vector2 ProximalRingZRotationRange;
public Vector2 IntermediateRingXRotationRange;
public Vector2 DistalRingXRotationRange;
public Vector2 ProximalLittleXRotationRange;
public Vector2 ProximalLittleZRotationRange;
public Vector2 IntermediateLittleXRotationRange;
public Vector2 DistalLittleXRotationRange;
public ReadWriteTransformHandle ThumbHandle;
public ReadWriteTransformHandle IndexHandle;
public ReadWriteTransformHandle MiddleHandle;
public ReadWriteTransformHandle RingHandle;
public ReadWriteTransformHandle LittleHandle;
public ReadWriteTransformHandle HandleA;
public ReadWriteTransformHandle HandleB;
public FloatProperty jobWeight { get; set; }
public void ProcessRootMotion (AnimationStream stream) { }
public void ProcessAnimation (AnimationStream stream) {
var w = jobWeight.Get (stream);
var thumbHandlePos = ThumbHandle.GetLocalPosition (stream);
var thumbT = Mathf.Clamp01 (thumbHandlePos.y);
ThumbHandle.SetLocalPosition (stream, new Vector3 (0, thumbT, 0));
var indexHandlePos = IndexHandle.GetLocalPosition (stream);
var indexT = Mathf.Clamp01 (indexHandlePos.y);
IndexHandle.SetLocalPosition (stream, new Vector3 (0, indexT, 0));
var middleHandlePos = MiddleHandle.GetLocalPosition (stream);
var middleT = Mathf.Clamp01 (middleHandlePos.y);
MiddleHandle.SetLocalPosition (stream, new Vector3 (0, middleT, 0));
var ringHandlePos = RingHandle.GetLocalPosition (stream);
var ringT = Mathf.Clamp01 (ringHandlePos.y);
RingHandle.SetLocalPosition (stream, new Vector3 (0, ringT, 0));
var littleHandlePos = LittleHandle.GetLocalPosition (stream);
var littleT = Mathf.Clamp01 (littleHandlePos.y);
LittleHandle.SetLocalPosition (stream, new Vector3 (0, littleT, 0));
var handleAPos = HandleA.GetLocalPosition (stream);
var aT = Mathf.Clamp01 (handleAPos.y);
HandleA.SetLocalPosition (stream, new Vector3 (0, aT, 0));
var handleBPos = HandleB.GetLocalPosition (stream);
var bT = Mathf.Clamp01 (handleBPos.y);
HandleB.SetLocalPosition (stream, new Vector3 (0, bT, 0));
if (w > 0) {
// Thumb
var proximalThumbHandleRot = Quaternion.Euler (
Mathf.Lerp (ProximalThumbXRotationRange.x, ProximalThumbXRotationRange.y, thumbT * aT),
0,
Mathf.Lerp (ProximalThumbZRotationRange.x, ProximalThumbZRotationRange.y, bT)
);
var proximalThumbRot = ProximalThumb.GetLocalRotation (stream);
ProximalThumb.SetLocalRotation (stream, Quaternion.Lerp (
proximalThumbRot,
proximalThumbRot * proximalThumbHandleRot,
w
));
var intermediateThumbHandleRot = Quaternion.Euler (
Mathf.Lerp (IntermediateThumbXRotationRange.x, IntermediateThumbXRotationRange.y, thumbT * aT),
0,
0
);
var intermediateThumbRot = IntermediateThumb.GetLocalRotation (stream);
IntermediateThumb.SetLocalRotation (stream, Quaternion.Lerp (
intermediateThumbRot,
intermediateThumbRot * intermediateThumbHandleRot,
w
));
var distalThumbHandleRot = Quaternion.Euler (
Mathf.Lerp (DistalThumbXRotationRange.x, DistalThumbXRotationRange.y, thumbT * aT),
0,
0
);
var distalThumbRot = DistalThumb.GetLocalRotation (stream);
DistalThumb.SetLocalRotation (stream, Quaternion.Lerp (
distalThumbRot,
distalThumbRot * distalThumbHandleRot,
w
));
// Index
var proximalIndexHandleRot = Quaternion.Euler (
Mathf.Lerp (ProximalIndexXRotationRange.x, ProximalIndexXRotationRange.y, indexT * aT),
0,
Mathf.Lerp (ProximalIndexZRotationRange.x, ProximalIndexZRotationRange.y, bT)
);
var proximalIndexRot = ProximalIndex.GetLocalRotation (stream);
ProximalIndex.SetLocalRotation (stream, Quaternion.Lerp (
proximalIndexRot,
proximalIndexRot * proximalIndexHandleRot,
w
));
var intermediateIndexHandleRot = Quaternion.Euler (
Mathf.Lerp (IntermediateIndexXRotationRange.x, IntermediateIndexXRotationRange.y, indexT * aT),
0,
0
);
var intermediateIndexRot = IntermediateIndex.GetLocalRotation (stream);
IntermediateIndex.SetLocalRotation (stream, Quaternion.Lerp (
intermediateIndexRot,
intermediateIndexRot * intermediateIndexHandleRot,
w
));
var distalIndexHandleRot = Quaternion.Euler (
Mathf.Lerp (DistalIndexXRotationRange.x, DistalIndexXRotationRange.y, indexT * aT),
0,
0
);
var distalIndexRot = DistalIndex.GetLocalRotation (stream);
DistalIndex.SetLocalRotation (stream, Quaternion.Lerp (
distalIndexRot,
distalIndexRot * distalIndexHandleRot,
w
));
// Middle
var proximalMiddleHandleRot = Quaternion.Euler (
Mathf.Lerp (ProximalMiddleXRotationRange.x, ProximalMiddleXRotationRange.y, middleT * aT),
0,
Mathf.Lerp (ProximalMiddleZRotationRange.x, ProximalMiddleZRotationRange.y, bT)
);
var proximalMiddleRot = ProximalMiddle.GetLocalRotation (stream);
ProximalMiddle.SetLocalRotation (stream, Quaternion.Lerp (
proximalMiddleRot,
proximalMiddleRot * proximalMiddleHandleRot,
w
));
var intermediateMiddleHandleRot = Quaternion.Euler (
Mathf.Lerp (IntermediateMiddleXRotationRange.x, IntermediateMiddleXRotationRange.y, middleT * aT),
0,
0
);
var intermediateMiddleRot = IntermediateMiddle.GetLocalRotation (stream);
IntermediateMiddle.SetLocalRotation (stream, Quaternion.Lerp (
intermediateMiddleRot,
intermediateMiddleRot * intermediateMiddleHandleRot,
w
));
var distalMiddleHandleRot = Quaternion.Euler (
Mathf.Lerp (DistalMiddleXRotationRange.x, DistalMiddleXRotationRange.y, middleT * aT),
0,
0
);
var distalMiddleRot = DistalMiddle.GetLocalRotation (stream);
DistalMiddle.SetLocalRotation (stream, Quaternion.Lerp (
distalMiddleRot,
distalMiddleRot * distalMiddleHandleRot,
w
));
// Ring
var proximalRingHandleRot = Quaternion.Euler (
Mathf.Lerp (ProximalRingXRotationRange.x, ProximalRingXRotationRange.y, ringT * aT),
0,
Mathf.Lerp (ProximalRingZRotationRange.x, ProximalRingZRotationRange.y, bT)
);
var proximalRingRot = ProximalRing.GetLocalRotation (stream);
ProximalRing.SetLocalRotation (stream, Quaternion.Lerp (
proximalRingRot,
proximalRingRot * proximalRingHandleRot,
w
));
var intermediateRingHandleRot = Quaternion.Euler (
Mathf.Lerp (IntermediateRingXRotationRange.x, IntermediateRingXRotationRange.y, ringT * aT),
0,
0
);
var intermediateRingRot = IntermediateRing.GetLocalRotation (stream);
IntermediateRing.SetLocalRotation (stream, Quaternion.Lerp (
intermediateRingRot,
intermediateRingRot * intermediateRingHandleRot,
w
));
var distalRingHandleRot = Quaternion.Euler (
Mathf.Lerp (DistalRingXRotationRange.x, DistalRingXRotationRange.y, ringT * aT),
0,
0
);
var distalRingRot = DistalRing.GetLocalRotation (stream);
DistalRing.SetLocalRotation (stream, Quaternion.Lerp (
distalRingRot,
distalRingRot * distalRingHandleRot,
w
));
// Little
var proximalLittleHandleRot = Quaternion.Euler (
Mathf.Lerp (ProximalLittleXRotationRange.x, ProximalLittleXRotationRange.y, littleT * aT),
0,
Mathf.Lerp (ProximalLittleZRotationRange.x, ProximalLittleZRotationRange.y, bT)
);
var proximalLittleRot = ProximalLittle.GetLocalRotation (stream);
ProximalLittle.SetLocalRotation (stream, Quaternion.Lerp (
proximalLittleRot,
proximalLittleRot * proximalLittleHandleRot,
w
));
var intermediateLittleHandleRot = Quaternion.Euler (
Mathf.Lerp (IntermediateLittleXRotationRange.x, IntermediateLittleXRotationRange.y, littleT * aT),
0,
0
);
var intermediateLittleRot = IntermediateLittle.GetLocalRotation (stream);
IntermediateLittle.SetLocalRotation (stream, Quaternion.Lerp (
intermediateLittleRot,
intermediateLittleRot * intermediateLittleHandleRot,
w
));
var distalLittleHandleRot = Quaternion.Euler (
Mathf.Lerp (DistalLittleXRotationRange.x, DistalLittleXRotationRange.y, littleT * aT),
0,
0
);
var distalLittleRot = DistalLittle.GetLocalRotation (stream);
DistalLittle.SetLocalRotation (stream, Quaternion.Lerp (
distalLittleRot,
distalLittleRot * distalLittleHandleRot,
w
));
}
}
}
[System.Serializable]
public struct HandConstraintData : IAnimationJobData {
public Transform ProximalThumb;
public Transform IntermediateThumb;
public Transform DistalThumb;
public Transform ProximalIndex;
public Transform IntermediateIndex;
public Transform DistalIndex;
public Transform ProximalMiddle;
public Transform IntermediateMiddle;
public Transform DistalMiddle;
public Transform ProximalRing;
public Transform IntermediateRing;
public Transform DistalRing;
public Transform ProximalLittle;
public Transform IntermediateLittle;
public Transform DistalLittle;
public Vector2 ProximalThumbXRotationRange;
public Vector2 ProximalThumbZRotationRange;
public Vector2 IntermediateThumbXRotationRange;
public Vector2 DistalThumbXRotationRange;
public Vector2 ProximalIndexXRotationRange;
public Vector2 ProximalIndexZRotationRange;
public Vector2 IntermediateIndexXRotationRange;
public Vector2 DistalIndexXRotationRange;
public Vector2 ProximalMiddleXRotationRange;
public Vector2 ProximalMiddleZRotationRange;
public Vector2 IntermediateMiddleXRotationRange;
public Vector2 DistalMiddleXRotationRange;
public Vector2 ProximalRingXRotationRange;
public Vector2 ProximalRingZRotationRange;
public Vector2 IntermediateRingXRotationRange;
public Vector2 DistalRingXRotationRange;
public Vector2 ProximalLittleXRotationRange;
public Vector2 ProximalLittleZRotationRange;
public Vector2 IntermediateLittleXRotationRange;
public Vector2 DistalLittleXRotationRange;
[SyncSceneToStream] public Transform ThumbHandle;
[SyncSceneToStream] public Transform IndexHandle;
[SyncSceneToStream] public Transform MiddleHandle;
[SyncSceneToStream] public Transform RingHandle;
[SyncSceneToStream] public Transform LittleHandle;
[SyncSceneToStream] public Transform HandleA;
[SyncSceneToStream] public Transform HandleB;
public bool IsValid () => !(
ProximalThumb == null ||
IntermediateThumb == null ||
DistalThumb == null ||
ProximalIndex == null ||
IntermediateIndex == null ||
DistalIndex == null ||
ProximalMiddle == null ||
IntermediateMiddle == null ||
DistalMiddle == null ||
ProximalRing == null ||
IntermediateRing == null ||
DistalRing == null ||
ProximalLittle == null ||
IntermediateLittle == null ||
DistalLittle == null ||
ProximalThumbXRotationRange == null ||
ProximalThumbZRotationRange == null ||
IntermediateThumbXRotationRange == null ||
DistalThumbXRotationRange == null ||
ProximalIndexXRotationRange == null ||
ProximalIndexZRotationRange == null ||
IntermediateIndexXRotationRange == null ||
DistalIndexXRotationRange == null ||
ProximalMiddleXRotationRange == null ||
ProximalMiddleZRotationRange == null ||
IntermediateMiddleXRotationRange == null ||
DistalMiddleXRotationRange == null ||
ProximalRingXRotationRange == null ||
ProximalRingZRotationRange == null ||
IntermediateRingXRotationRange == null ||
DistalRingXRotationRange == null ||
ProximalLittleXRotationRange == null ||
ProximalLittleZRotationRange == null ||
IntermediateLittleXRotationRange == null ||
DistalLittleXRotationRange == null ||
ThumbHandle == null ||
IndexHandle == null ||
MiddleHandle == null ||
RingHandle == null ||
LittleHandle == null ||
HandleA == null ||
HandleB == null);
public void SetDefaultValues () {
ProximalThumb = null;
IntermediateThumb = null;
DistalThumb = null;
ProximalIndex = null;
IntermediateIndex = null;
DistalIndex = null;
ProximalMiddle = null;
IntermediateMiddle = null;
DistalMiddle = null;
ProximalRing = null;
IntermediateRing = null;
DistalRing = null;
ProximalLittle = null;
IntermediateLittle = null;
DistalLittle = null;
ProximalThumbXRotationRange = Vector2.zero;
ProximalThumbZRotationRange = Vector2.zero;
IntermediateThumbXRotationRange = Vector2.zero;
DistalThumbXRotationRange = Vector2.zero;
ProximalIndexXRotationRange = Vector2.zero;
ProximalIndexZRotationRange = Vector2.zero;
IntermediateIndexXRotationRange = Vector2.zero;
DistalIndexXRotationRange = Vector2.zero;
ProximalMiddleXRotationRange = Vector2.zero;
ProximalMiddleZRotationRange = Vector2.zero;
IntermediateMiddleXRotationRange = Vector2.zero;
DistalMiddleXRotationRange = Vector2.zero;
ProximalRingXRotationRange = Vector2.zero;
ProximalRingZRotationRange = Vector2.zero;
IntermediateRingXRotationRange = Vector2.zero;
DistalRingXRotationRange = Vector2.zero;
ProximalLittleXRotationRange = Vector2.zero;
ProximalLittleZRotationRange = Vector2.zero;
IntermediateLittleXRotationRange = Vector2.zero;
DistalLittleXRotationRange = Vector2.zero;
ThumbHandle = null;
IndexHandle = null;
MiddleHandle = null;
RingHandle = null;
LittleHandle = null;
HandleA = null;
HandleB = null;
}
}
public class HandConstraintBinder : AnimationJobBinder<HandConstraintJob, HandConstraintData> {
public override HandConstraintJob Create (Animator animator, ref HandConstraintData data, Component component) {
var job = new HandConstraintJob ();
job.ProximalThumb = ReadWriteTransformHandle.Bind (animator, data.ProximalThumb);
job.IntermediateThumb = ReadWriteTransformHandle.Bind (animator, data.IntermediateThumb);
job.DistalThumb = ReadWriteTransformHandle.Bind (animator, data.DistalThumb);
job.ProximalIndex = ReadWriteTransformHandle.Bind (animator, data.ProximalIndex);
job.IntermediateIndex = ReadWriteTransformHandle.Bind (animator, data.IntermediateIndex);
job.DistalIndex = ReadWriteTransformHandle.Bind (animator, data.DistalIndex);
job.ProximalMiddle = ReadWriteTransformHandle.Bind (animator, data.ProximalMiddle);
job.IntermediateMiddle = ReadWriteTransformHandle.Bind (animator, data.IntermediateMiddle);
job.DistalMiddle = ReadWriteTransformHandle.Bind (animator, data.DistalMiddle);
job.ProximalRing = ReadWriteTransformHandle.Bind (animator, data.ProximalRing);
job.IntermediateRing = ReadWriteTransformHandle.Bind (animator, data.IntermediateRing);
job.DistalRing = ReadWriteTransformHandle.Bind (animator, data.DistalRing);
job.ProximalLittle = ReadWriteTransformHandle.Bind (animator, data.ProximalLittle);
job.IntermediateLittle = ReadWriteTransformHandle.Bind (animator, data.IntermediateLittle);
job.DistalLittle = ReadWriteTransformHandle.Bind (animator, data.DistalLittle);
job.ProximalThumbXRotationRange = data.ProximalThumbXRotationRange;
job.ProximalThumbZRotationRange = data.ProximalThumbZRotationRange;
job.IntermediateThumbXRotationRange = data.IntermediateThumbXRotationRange;
job.DistalThumbXRotationRange = data.DistalThumbXRotationRange;
job.ProximalIndexXRotationRange = data.ProximalIndexXRotationRange;
job.ProximalIndexZRotationRange = data.ProximalIndexZRotationRange;
job.IntermediateIndexXRotationRange = data.IntermediateIndexXRotationRange;
job.DistalIndexXRotationRange = data.DistalIndexXRotationRange;
job.ProximalMiddleXRotationRange = data.ProximalMiddleXRotationRange;
job.ProximalMiddleZRotationRange = data.ProximalMiddleZRotationRange;
job.IntermediateMiddleXRotationRange = data.IntermediateMiddleXRotationRange;
job.DistalMiddleXRotationRange = data.DistalMiddleXRotationRange;
job.ProximalRingXRotationRange = data.ProximalRingXRotationRange;
job.ProximalRingZRotationRange = data.ProximalRingZRotationRange;
job.IntermediateRingXRotationRange = data.IntermediateRingXRotationRange;
job.DistalRingXRotationRange = data.DistalRingXRotationRange;
job.ProximalLittleXRotationRange = data.ProximalLittleXRotationRange;
job.ProximalLittleZRotationRange = data.ProximalLittleZRotationRange;
job.IntermediateLittleXRotationRange = data.IntermediateLittleXRotationRange;
job.DistalLittleXRotationRange = data.DistalLittleXRotationRange;
job.ThumbHandle = ReadWriteTransformHandle.Bind (animator, data.ThumbHandle);
job.IndexHandle = ReadWriteTransformHandle.Bind (animator, data.IndexHandle);
job.MiddleHandle = ReadWriteTransformHandle.Bind (animator, data.MiddleHandle);
job.RingHandle = ReadWriteTransformHandle.Bind (animator, data.RingHandle);
job.LittleHandle = ReadWriteTransformHandle.Bind (animator, data.LittleHandle);
job.HandleA = ReadWriteTransformHandle.Bind (animator, data.HandleA);
job.HandleB = ReadWriteTransformHandle.Bind (animator, data.HandleB);
return job;
}
public override void Destroy (HandConstraintJob job) { }
}
| 0 | 0.923597 | 1 | 0.923597 | game-dev | MEDIA | 0.848537 | game-dev | 0.9386 | 1 | 0.9386 |
microsoft/MixedRealityToolkit-Unity | 3,499 | Assets/MRTK/SDK/Features/Input/Handlers/BaseEyeFocusHandler.cs | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Input
{
/// <summary>
/// Base Component for handling Eye Focus on <see href="https://docs.unity3d.com/ScriptReference/GameObject.html">GameObject</see>s.
/// </summary>
public abstract class BaseEyeFocusHandler : BaseFocusHandler
{
[Tooltip("Configurable duration to trigger an event if a user has been looking at the target for more than this duration.")]
[SerializeField]
[Range(0, 20)]
private float timeToTriggerDwellInSec = 5;
private DateTime dwellTimer;
private bool isDwelling = false;
private bool hadFocus = false;
/// <summary>
/// Handles highlighting targets when the cursor enters its hit box.
/// </summary>
protected virtual void Update()
{
if (!HasFocus && hadFocus)
{
OnEyeFocusStop();
isDwelling = false;
hadFocus = false;
}
else if (HasFocus)
{
if (!hadFocus)
{
OnEyeFocusStart();
dwellTimer = DateTime.UtcNow;
hadFocus = true;
}
else
{
OnEyeFocusStay();
if (!isDwelling && (DateTime.UtcNow - dwellTimer).TotalSeconds > timeToTriggerDwellInSec)
{
OnEyeFocusDwell();
isDwelling = true;
}
}
}
}
/// <inheritdoc />
public override void OnBeforeFocusChange(FocusEventData eventData)
{
// If we're the new target object,
// add the pointer to the list of focusers.
if (eventData.NewFocusedObject == gameObject && eventData.Pointer.InputSourceParent.SourceType == InputSourceType.Eyes)
{
eventData.Pointer.FocusTarget = this;
Focusers.Add(eventData.Pointer);
}
// If we're the old focused target object,
// remove the pointer from our list.
else if (eventData.OldFocusedObject == gameObject)
{
Focusers.Remove(eventData.Pointer);
// If there is no new focused target
// clear the FocusTarget field from the Pointer.
if (eventData.NewFocusedObject == null)
{
eventData.Pointer.FocusTarget = null;
}
}
}
/// <summary>
/// Triggered once the eye gaze ray starts intersecting with this target's collider.
/// </summary>
protected virtual void OnEyeFocusStart() { }
/// <summary>
/// Triggered while the eye gaze ray is intersecting with this target's collider.
/// </summary>
protected virtual void OnEyeFocusStay() { }
/// <summary>
/// Triggered once the eye gaze ray stops intersecting with this target's collider.
/// </summary>
protected virtual void OnEyeFocusStop() { }
/// <summary>
/// Triggered once the eye gaze ray has intersected with this target's collider for a specified amount of time.
/// </summary>
protected virtual void OnEyeFocusDwell() { }
}
}
| 0 | 0.973493 | 1 | 0.973493 | game-dev | MEDIA | 0.828172 | game-dev | 0.978729 | 1 | 0.978729 |
linuxdeepin/dde-file-manager | 1,274 | src/plugins/common/dfmplugin-menu/extendmenuscene/extendmenuscene.h | // SPDX-FileCopyrightText: 2022 - 2023 UnionTech Software Technology Co., Ltd.
//
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef EXTENDMENUSCENE_H
#define EXTENDMENUSCENE_H
#include "dfmplugin_menu_global.h"
#include <dfm-base/interfaces/abstractmenuscene.h>
#include <dfm-base/interfaces/abstractscenecreator.h>
#include <mutex>
namespace dfmplugin_menu {
class DCustomActionParser;
class ExtendMenuCreator : public DFMBASE_NAMESPACE::AbstractSceneCreator
{
public:
static QString name()
{
return "ExtendMenu";
}
DFMBASE_NAMESPACE::AbstractMenuScene *create() override;
protected:
DCustomActionParser *customParser = nullptr;
std::once_flag loadFlag;
};
class ExtendMenuScenePrivate;
class ExtendMenuScene : public DFMBASE_NAMESPACE::AbstractMenuScene
{
public:
explicit ExtendMenuScene(DCustomActionParser *parser, QObject *parent = nullptr);
QString name() const override;
bool initialize(const QVariantHash ¶ms) override;
AbstractMenuScene *scene(QAction *action) const override;
bool create(QMenu *parent) override;
void updateState(QMenu *parent) override;
bool triggered(QAction *action) override;
private:
ExtendMenuScenePrivate *const d = nullptr;
};
}
#endif // EXTENDMENUSCENE_H
| 0 | 0.905303 | 1 | 0.905303 | game-dev | MEDIA | 0.447571 | game-dev | 0.57507 | 1 | 0.57507 |
KryptonMC/Krypton | 2,180 | server/src/main/kotlin/org/kryptonmc/krypton/command/brigadier/KryptonArgumentBuilder.kt | /*
* This file is part of the Krypton project, licensed under the Apache License v2.0
*
* Copyright (C) 2021-2023 KryptonMC and the contributors of the Krypton 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.
*/
package org.kryptonmc.krypton.command.brigadier
import com.mojang.brigadier.arguments.ArgumentType
import com.mojang.brigadier.builder.ArgumentBuilder
import com.mojang.brigadier.suggestion.SuggestionProvider
import com.mojang.brigadier.tree.CommandNode
class KryptonArgumentBuilder<S, T> private constructor(
private val name: String,
private val type: ArgumentType<T>
) : ArgumentBuilder<S, KryptonArgumentBuilder<S, T>>() {
private var suggestionsProvider: SuggestionProvider<S>? = null
fun suggests(provider: SuggestionProvider<S>?): KryptonArgumentBuilder<S, T> = apply { suggestionsProvider = provider }
override fun then(argument: ArgumentBuilder<S, *>?): KryptonArgumentBuilder<S, T> {
throw UnsupportedOperationException("Cannot add children to a greedy node!")
}
override fun then(argument: CommandNode<S>?): KryptonArgumentBuilder<S, T> {
throw UnsupportedOperationException("Cannot add children to a greedy node!")
}
override fun getThis(): KryptonArgumentBuilder<S, T> = this
override fun build(): KryptonArgumentCommandNode<S, T> =
KryptonArgumentCommandNode(name, type, command, requirement, contextRequirement, redirect, redirectModifier, isFork, suggestionsProvider)
companion object {
@JvmStatic
fun <S, T> kryptonArgument(name: String, type: ArgumentType<T>): KryptonArgumentBuilder<S, T> = KryptonArgumentBuilder(name, type)
}
}
| 0 | 0.559588 | 1 | 0.559588 | game-dev | MEDIA | 0.312944 | game-dev | 0.723085 | 1 | 0.723085 |
GerritCodeReview/gerrit | 3,548 | java/com/google/gerrit/sshd/DispatchCommandProvider.java | // Copyright (C) 2009 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.
package com.google.gerrit.sshd;
import com.google.common.collect.Maps;
import com.google.gerrit.extensions.registration.RegistrationHandle;
import com.google.inject.Binding;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Provider;
import com.google.inject.TypeLiteral;
import java.lang.annotation.Annotation;
import java.util.List;
import java.util.concurrent.ConcurrentMap;
import org.apache.sshd.server.command.Command;
/** Creates DispatchCommand using commands registered by {@link CommandModule}. */
public class DispatchCommandProvider implements Provider<DispatchCommand> {
@Inject private Injector injector;
@Inject private DispatchCommand.Factory factory;
private final CommandName parent;
private volatile ConcurrentMap<String, CommandProvider> map;
public DispatchCommandProvider(CommandName cn) {
this.parent = cn;
}
@Override
public DispatchCommand get() {
return factory.create(getMap());
}
public RegistrationHandle register(CommandName name, Provider<Command> cmd) {
final ConcurrentMap<String, CommandProvider> m = getMap();
final CommandProvider commandProvider = new CommandProvider(cmd, null);
if (m.putIfAbsent(name.value(), commandProvider) != null) {
throw new IllegalArgumentException(name.value() + " exists");
}
return () -> m.remove(name.value(), commandProvider);
}
public RegistrationHandle replace(CommandName name, Provider<Command> cmd) {
final ConcurrentMap<String, CommandProvider> m = getMap();
final CommandProvider commandProvider = new CommandProvider(cmd, null);
m.put(name.value(), commandProvider);
return () -> m.remove(name.value(), commandProvider);
}
ConcurrentMap<String, CommandProvider> getMap() {
if (map == null) {
synchronized (this) {
if (map == null) {
map = createMap();
}
}
}
return map;
}
@SuppressWarnings("unchecked")
private ConcurrentMap<String, CommandProvider> createMap() {
ConcurrentMap<String, CommandProvider> m = Maps.newConcurrentMap();
for (Binding<?> b : allCommands()) {
final Annotation annotation = b.getKey().getAnnotation();
if (annotation instanceof CommandName) {
final CommandName n = (CommandName) annotation;
if (!Commands.CMD_ROOT.equals(n) && Commands.isChild(parent, n)) {
String descr = null;
if (annotation instanceof Commands.NestedCommandNameImpl) {
Commands.NestedCommandNameImpl impl = ((Commands.NestedCommandNameImpl) annotation);
descr = impl.descr();
}
m.put(n.value(), new CommandProvider((Provider<Command>) b.getProvider(), descr));
}
}
}
return m;
}
private static final TypeLiteral<Command> type = new TypeLiteral<>() {};
private List<Binding<Command>> allCommands() {
return injector.findBindingsByType(type);
}
}
| 0 | 0.92771 | 1 | 0.92771 | game-dev | MEDIA | 0.624486 | game-dev,networking | 0.95709 | 1 | 0.95709 |
kwsch/NHSE | 4,807 | NHSE.WinForms/Subforms/Map/VillagerHouseEditor.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using NHSE.Core;
namespace NHSE.WinForms
{
public partial class VillagerHouseEditor : Form
{
private readonly MainSave SAV;
private readonly IVillagerHouse[] Houses;
private readonly IReadOnlyList<IVillager> Villagers;
private int Index;
public VillagerHouseEditor(IVillagerHouse[] houses, IReadOnlyList<IVillager> villagers, MainSave sav, int index)
{
InitializeComponent();
this.TranslateInterface(GameInfo.CurrentLanguage);
SAV = sav;
Houses = houses;
Villagers = villagers;
DialogResult = DialogResult.Cancel;
foreach (var obj in Houses)
LB_Items.Items.Add(GetHouseSummary(obj));
var hIndex = Array.FindIndex(houses, z => z.NPC1 == index);
if (hIndex < 0)
hIndex = 0;
LB_Items.SelectedIndex = hIndex;
}
private void B_Cancel_Click(object sender, EventArgs e) => Close();
private void B_Save_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.OK;
Close();
}
private void LB_Items_SelectedIndexChanged(object sender, EventArgs e)
{
if (LB_Items.SelectedIndex < 0)
return;
PG_Item.SelectedObject = Houses[Index = LB_Items.SelectedIndex];
}
private void PG_Item_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
{
LB_Items.Items[Index] = GetHouseSummary(Houses[Index]);
}
private string GetHouseSummary(IVillagerHouse house) => $"{GetVillagerName(house)}'s House";
private string GetVillagerName(IVillagerHouse house)
{
var villagerIndex = house.NPC1;
var v = (uint) villagerIndex >= Villagers.Count ? "???" : Villagers[villagerIndex].InternalName;
var name = GameInfo.Strings.GetVillager(v);
return name;
}
private void B_DumpHouse_Click(object sender, EventArgs e)
{
if (ModifierKeys == Keys.Shift)
{
using var fbd = new FolderBrowserDialog();
if (fbd.ShowDialog() != DialogResult.OK)
return;
var dir = Path.GetDirectoryName(fbd.SelectedPath);
if (dir == null || !Directory.Exists(dir))
return;
SAV.DumpVillagerHouses(fbd.SelectedPath);
return;
}
var h = Houses[Index];
var name = GetVillagerName(h);
using var sfd = new SaveFileDialog
{
Filter = "New Horizons Villager House (*.nhvh)|*.nhvh|" +
"New Horizons Villager House (*.nhvh2)|*.nhvh2|" +
"All files (*.*)|*.*",
FileName = $"{name}.{h.Extension}",
};
if (sfd.ShowDialog() != DialogResult.OK)
return;
var data = h.Write();
File.WriteAllBytes(sfd.FileName, data);
}
private void B_LoadHouse_Click(object sender, EventArgs e)
{
var h = Houses[Index];
var name = GetVillagerName(Houses[Index]);
if (name == "???")
name = "*";
using var ofd = new OpenFileDialog
{
Filter = "New Horizons Villager House (*.nhvh)|*.nhvh|" +
"New Horizons Villager House (*.nhvh2)|*.nhvh2|" +
"All files (*.*)|*.*",
FileName = $"{name}.{h.Extension}",
};
if (ofd.ShowDialog() != DialogResult.OK)
return;
var path = ofd.FileName;
var expectLength = SAV.Offsets.VillagerHouseSize;
var fi = new FileInfo(path);
if (!VillagerHouseConverter.IsCompatible((int)fi.Length, expectLength))
{
WinFormsUtil.Error(string.Format(MessageStrings.MsgDataSizeMismatchImport, fi.Length, expectLength), path);
return;
}
var data = File.ReadAllBytes(ofd.FileName);
data = VillagerHouseConverter.GetCompatible(data, expectLength);
if (data.Length != expectLength)
{
WinFormsUtil.Error(string.Format(MessageStrings.MsgDataSizeMismatchImport, fi.Length, expectLength), path);
return;
}
h = SAV.Offsets.ReadVillagerHouse(data);
var current = Houses[Index];
h.NPC1 = current.NPC1;
Houses[Index] = h;
PG_Item.SelectedObject = h;
}
}
}
| 0 | 0.558673 | 1 | 0.558673 | game-dev | MEDIA | 0.565796 | game-dev | 0.809658 | 1 | 0.809658 |
Geforce132/SecurityCraft | 2,336 | src/main/java/net/geforcemods/securitycraft/blocks/OwnableBlock.java | package net.geforcemods.securitycraft.blocks;
import com.mojang.serialization.MapCodec;
import net.geforcemods.securitycraft.api.OwnableBlockEntity;
import net.geforcemods.securitycraft.misc.OwnershipEvent;
import net.geforcemods.securitycraft.util.BlockUtils;
import net.minecraft.core.BlockPos;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.BaseEntityBlock;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraft.world.level.block.state.BlockState;
import net.neoforged.neoforge.common.NeoForge;
public class OwnableBlock extends BaseEntityBlock {
private static float destroyTimeTempStorage = -1.0F;
protected final float destroyTimeForOwner;
public OwnableBlock(BlockBehaviour.Properties properties) {
super(withReinforcedDestroyTime(properties));
destroyTimeForOwner = getStoredDestroyTime();
}
@Override
public float getDestroyProgress(BlockState state, Player player, BlockGetter level, BlockPos pos) {
return BlockUtils.getDestroyProgress(super::getDestroyProgress, destroyTimeForOwner, state, player, level, pos);
}
public float defaultDestroyProgress(BlockState state, Player player, BlockGetter level, BlockPos pos) {
return super.getDestroyProgress(state, player, level, pos);
}
@Override
public void setPlacedBy(Level level, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) {
if (placer instanceof Player player)
NeoForge.EVENT_BUS.post(new OwnershipEvent(level, pos, player));
}
@Override
public BlockEntity newBlockEntity(BlockPos pos, BlockState state) {
return new OwnableBlockEntity(pos, state);
}
@Override
protected MapCodec<? extends BaseEntityBlock> codec() {
return null;
}
public static BlockBehaviour.Properties withReinforcedDestroyTime(BlockBehaviour.Properties properties) {
destroyTimeTempStorage = properties.destroyTime;
return properties.destroyTime(-1.0F);
}
public static float getStoredDestroyTime() {
float storedDestroyTime = destroyTimeTempStorage;
destroyTimeTempStorage = -1.0F;
return storedDestroyTime;
}
}
| 0 | 0.739941 | 1 | 0.739941 | game-dev | MEDIA | 0.998938 | game-dev | 0.552546 | 1 | 0.552546 |
ParadiseSS13/Paradise | 3,605 | code/modules/buildmode/submodes/tilt.dm | /datum/buildmode_mode/tilting
key = "tilt"
/// The thing we're tilting over
var/atom/movable/tilter
var/crush_damage = 25
var/crit_chance = 0
var/datum/tilt_crit/forced_crit
var/weaken_time = 4 SECONDS
var/knockdown_time = 14 SECONDS
var/ignore_gravity = TRUE
var/should_rotate = TRUE
var/rotation_angle
var/rightable = TRUE
var/block_interactions_until_righted = TRUE
/datum/buildmode_mode/tilting/show_help(mob/user)
to_chat(user, "<span class='notice'>***********************************************************</span>")
to_chat(user, "<span class='notice'>Left Mouse Button on obj/mob = Select atom to tilt</span>")
to_chat(user, "<span class='notice'>Right Mouse Button on turf/obj/mob = Tilt selected atom onto target</span>")
to_chat(user, "<span class='notice'>Right Mouse Button + Alt = Untilt selected atom</span>")
to_chat(user, "<span class='warning'>Right-click the main action button to customize tilting behavior.</span>")
to_chat(user, "<span class='notice'>***********************************************************</span>")
/datum/buildmode_mode/tilting/change_settings(mob/user)
crush_damage = tgui_input_number(user, "Crush Damage", "Damage", initial(crush_damage))
crit_chance = tgui_input_number(user, "Crit Chance (out of 100)", "Crit chance", 0)
if(crit_chance > 0)
var/forced_crit_path = tgui_input_list(user, "Force a specific crit?", "Forced Crit", list(GLOB.tilt_crits))
if(forced_crit_path)
forced_crit = GLOB.tilt_crits[forced_crit_path]
weaken_time = tgui_input_number(user, "How long to weaken (in seconds)?", "Weaken Time", 4)
weaken_time = weaken_time SECONDS
knockdown_time = tgui_input_number(user, "How long to knockdown (in seconds)?", "Knockdown Time", 12)
knockdown_time = knockdown_time SECONDS
ignore_gravity = tgui_alert(user, "Ignore gravity?", "Ignore gravity", list("Yes", "No")) == "Yes"
should_rotate = tgui_alert(user, "Should it rotate on falling?", "Should rotate", list("Yes", "No")) == "Yes"
if(should_rotate)
rotation_angle = tgui_input_number(user, "Which angle to rotate at? (if empty, defaults to 90 degrees in either direction)", "Rotation angle", 0)
rightable = tgui_alert(user, "Should it be rightable with alt-click?", "Rightable", list("Yes", "No")) == "Yes"
if(rightable)
block_interactions_until_righted = tgui_alert(user, "Should it block interactions until righted (by alt-clicking)?", "Block interactions", list("Yes", "No")) == "Yes"
/datum/buildmode_mode/tilting/handle_click(mob/user, params, atom/movable/object)
var/list/pa = params2list(params)
var/left_click = pa.Find("left")
var/right_click = pa.Find("right")
var/alt_click = pa.Find("alt")
if(left_click)
if(!ismovable(object))
return
tilter = object
to_chat(user, "Selected object '[tilter]' to tilt.")
if(right_click)
if(!tilter)
to_chat(user, "<span class='warning'>You need to select something to tilt (or untilt) first.</span>")
return
if(tilter.GetComponent(/datum/component/tilted) && alt_click)
tilter.untilt(duration = 0)
log_admin("Build Mode: [key_name(user)] has righted [tilter] ([tilter.x],[tilter.y],[tilter.z])")
return
if(!object || isnull(get_turf(object)))
to_chat(user, "<span class='warning'>You need to select a target first.</span>")
return
tilter.fall_and_crush(get_turf(object), crush_damage, prob(crit_chance), 2, forced_crit, weaken_time, knockdown_time, ignore_gravity, should_rotate, rotation_angle, rightable, block_interactions_until_righted)
log_admin("Build Mode: [key_name(user)] tilted [tilter] onto [ADMIN_COORDJMP(object)]")
| 0 | 0.954954 | 1 | 0.954954 | game-dev | MEDIA | 0.9219 | game-dev | 0.93045 | 1 | 0.93045 |
AzureMarker/shaku | 2,958 | shaku/src/module/module_builder.rs | use crate::component::Interface;
use crate::module::{ComponentMap, ParameterMap};
use crate::parameters::ComponentParameters;
use crate::provider::ProviderFn;
use crate::{Component, ComponentFn, HasComponent, HasProvider, Module, ModuleBuildContext};
use std::marker::PhantomData;
use std::sync::Arc;
/// Builds a [`Module`]. Component parameters can be set, and both components and providers
/// implementations can be overridden.
///
/// [`Module`]: trait.Module.html
pub struct ModuleBuilder<M: Module> {
parameters: ParameterMap,
submodules: M::Submodules,
component_overrides: ComponentMap,
component_fn_overrides: ComponentMap,
provider_overrides: ComponentMap,
_module: PhantomData<M>,
}
impl<M: Module> ModuleBuilder<M> {
/// Create a ModuleBuilder by providing the module's submodules.
pub fn with_submodules(submodules: M::Submodules) -> Self {
ModuleBuilder {
parameters: ParameterMap::new(),
submodules,
component_overrides: ComponentMap::new(),
component_fn_overrides: ComponentMap::new(),
provider_overrides: ComponentMap::new(),
_module: PhantomData,
}
}
/// Set the parameters of the specified component. If the parameters are not
/// manually set, the defaults will be used.
pub fn with_component_parameters<C: Component<M>>(mut self, params: C::Parameters) -> Self
where
M: HasComponent<C::Interface>,
{
self.parameters
.insert(ComponentParameters::<C, C::Parameters>::new(params));
self
}
/// Override a component implementation. This method is best used when the
/// overriding component has no injected dependencies.
pub fn with_component_override<I: Interface + ?Sized>(mut self, component: Box<I>) -> Self
where
M: HasComponent<I>,
{
self.component_overrides
.insert::<Arc<I>>(Arc::from(component));
self
}
/// Override a component implementation. This method is best used when the
/// overriding component has injected dependencies.
pub fn with_component_override_fn<I: Interface + ?Sized>(
mut self,
component_fn: ComponentFn<M, I>,
) -> Self
where
M: HasComponent<I>,
{
self.component_fn_overrides.insert(component_fn);
self
}
/// Override a provider implementation.
pub fn with_provider_override<I: 'static + ?Sized>(
mut self,
provider_fn: ProviderFn<M, I>,
) -> Self
where
M: HasProvider<I>,
{
self.provider_overrides.insert(Arc::new(provider_fn));
self
}
/// Build the module
pub fn build(self) -> M {
M::build(ModuleBuildContext::new(
self.parameters,
self.component_overrides,
self.component_fn_overrides,
self.provider_overrides,
self.submodules,
))
}
}
| 0 | 0.750542 | 1 | 0.750542 | game-dev | MEDIA | 0.274676 | game-dev | 0.784938 | 1 | 0.784938 |
sea-boat/mysql-protocol | 1,565 | src/main/java/com/seaboat/mysql/protocol/util/RandomUtil.java | package com.seaboat.mysql.protocol.util;
/**
*
* <pre><b>a random util.</b></pre>
* @author
* <pre>seaboat</pre>
* <pre><b>email: </b>849586227@qq.com</pre>
* <pre><b>blog: </b>http://blog.csdn.net/wangyangzhizhou</pre>
* @version 1.0
*/
public class RandomUtil {
private static final byte[] bytes = { '1', '2', '3', '4', '5', '6', '7',
'8', '9', '0', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p',
'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'z', 'x', 'c', 'v',
'b', 'n', 'm', 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P',
'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Z', 'X', 'C', 'V',
'B', 'N', 'M' };
private static final long multiplier = 0x5DEECE66DL;
private static final long addend = 0xBL;
private static final long mask = (1L << 48) - 1;
private static final long integerMask = (1L << 33) - 1;
private static final long seedUniquifier = 8682522807148012L;
private static long seed;
static {
long s = seedUniquifier + System.nanoTime();
s = (s ^ multiplier) & mask;
seed = s;
}
public static final byte[] randomBytes(int size) {
byte[] bb = bytes;
byte[] ab = new byte[size];
for (int i = 0; i < size; i++) {
ab[i] = randomByte(bb);
}
return ab;
}
private static byte randomByte(byte[] b) {
int ran = (int) ((next() & integerMask) >>> 16);
return b[ran % b.length];
}
private static long next() {
long oldSeed = seed;
long nextSeed = 0L;
do {
nextSeed = (oldSeed * multiplier + addend) & mask;
} while (oldSeed == nextSeed);
seed = nextSeed;
return nextSeed;
}
}
| 0 | 0.757603 | 1 | 0.757603 | game-dev | MEDIA | 0.229791 | game-dev | 0.909041 | 1 | 0.909041 |
BitBuf/nbt | 11,290 | src/main/java/dev/dewy/nbt/tags/collection/ListTag.java | package dev.dewy.nbt.tags.collection;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import dev.dewy.nbt.api.Tag;
import dev.dewy.nbt.api.json.JsonSerializable;
import dev.dewy.nbt.api.registry.TagTypeRegistry;
import dev.dewy.nbt.api.registry.TagTypeRegistryException;
import dev.dewy.nbt.api.snbt.SnbtConfig;
import dev.dewy.nbt.api.snbt.SnbtSerializable;
import dev.dewy.nbt.tags.TagType;
import dev.dewy.nbt.utils.StringUtils;
import lombok.AllArgsConstructor;
import lombok.NonNull;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.*;
import java.util.function.Consumer;
/**
* The list tag (type ID 9) is used for storing an ordered list of unnamed NBT tags all of the same type.
*
* @author dewy
*/
@AllArgsConstructor
public class ListTag<T extends Tag> extends Tag implements SnbtSerializable, JsonSerializable, Iterable<T> {
private @NonNull List<T> value;
private byte type;
/**
* Constructs an empty, unnamed list tag.
*/
public ListTag() {
this(null);
}
/**
* Constructs an empty list tag with a given name.
*
* @param name the tag's name.
*/
public ListTag(String name) {
this(name, new LinkedList<>());
}
/**
* Constructs a list tag with a given name and {@code List<>} value.
*
* @param name the tag's name.
* @param value the tag's {@code List<>} value.
*/
public ListTag(String name, @NonNull List<T> value) {
if (value.isEmpty()) {
this.type = 0;
} else {
this.type = value.get(0).getTypeId();
}
this.setName(name);
this.setValue(value);
}
@Override
public byte getTypeId() {
return TagType.LIST.getId();
}
@Override
public List<T> getValue() {
return this.value;
}
/**
* Returns the ID of the NBT tag type this list holds.
*
* @return the ID of the NBT tag type this list holds.
*/
public byte getListType() {
return this.type;
}
/**
* Sets the {@code List<>} value of this list tag.
*
* @param value new {@code List<>} value to be set.
*/
public void setValue(@NonNull List<T> value) {
if (value.isEmpty()) {
this.type = 0;
} else {
this.type = value.get(0).getTypeId();
}
this.value = value;
}
@Override
public void write(DataOutput output, int depth, TagTypeRegistry registry) throws IOException {
if (depth > 512) {
throw new IOException("NBT structure too complex (depth > 512).");
}
output.writeByte(this.type);
output.writeInt(this.value.size());
for (T tag : this) {
tag.write(output, depth + 1, registry);
}
}
@Override
public ListTag<T> read(DataInput input, int depth, TagTypeRegistry registry) throws IOException {
if (depth > 512) {
throw new IOException("NBT structure too complex (depth > 512).");
}
List<T> tags = new ArrayList<>();
byte tagType = input.readByte();
int length = input.readInt();
T next;
for (int i = 0; i < length; i++) {
Class<? extends Tag> tagClass = registry.getClassFromId(tagType);
if (tagClass == null) {
throw new IOException("Tag type with ID " + tagType + " not present in tag type registry.");
}
try {
next = (T) registry.instantiate(tagClass);
} catch (TagTypeRegistryException e) {
throw new IOException(e);
}
next.read(input, depth + 1, registry);
next.setName(null);
tags.add(next);
}
if (tags.isEmpty()) {
this.type = 0;
} else {
this.type = tagType;
}
this.value = tags;
return this;
}
@Override
public String toSnbt(int depth, TagTypeRegistry registry, SnbtConfig config) {
StringBuilder sb = new StringBuilder("[");
if (config.isPrettyPrint()) {
sb.append('\n').append(StringUtils.multiplyIndent(depth + 1, config));
}
for (int i = 0; i < this.value.size(); ++i) {
if (i != 0) {
if (config.isPrettyPrint()) {
sb.append(",\n").append(StringUtils.multiplyIndent(depth + 1, config));
} else {
sb.append(',');
}
}
sb.append(((SnbtSerializable) this.value.get(i)).toSnbt(depth + 1, registry, config));
}
if (config.isPrettyPrint()) {
sb.append("\n").append(StringUtils.multiplyIndent(depth , config)).append(']');
} else {
sb.append(']');
}
return sb.toString();
}
@Override
public JsonObject toJson(int depth, TagTypeRegistry registry) throws IOException {
if (depth > 512) {
throw new IOException("NBT structure too complex (depth > 512).");
}
JsonObject json = new JsonObject();
JsonArray value = new JsonArray();
json.addProperty("type", this.getTypeId());
json.addProperty("listType", this.getListType());
if (this.getName() != null) {
json.addProperty("name", this.getName());
}
for (T tag : this) {
tag.setName(null);
value.add(((JsonSerializable) tag).toJson(depth + 1, registry));
}
json.add("value", value);
return json;
}
@Override
public ListTag<T> fromJson(JsonObject json, int depth, TagTypeRegistry registry) throws IOException {
if (depth > 512) {
throw new IOException("NBT structure too complex (depth > 512).");
}
this.clear();
if (json.has("name")) {
this.setName(json.getAsJsonPrimitive("name").getAsString());
} else {
this.setName(null);
}
byte listType = json.get("listType").getAsByte();
List<T> tags = new LinkedList<>();
T nextTag;
for (JsonElement element : json.getAsJsonArray("value")) {
Class<? extends Tag> tagClass = registry.getClassFromId(listType);
if (tagClass == null) {
throw new IOException("Tag type with ID " + listType + " not present in tag type registry.");
}
try {
nextTag = (T) registry.instantiate(tagClass);
} catch (TagTypeRegistryException e) {
throw new IOException(e);
}
((JsonSerializable) nextTag).fromJson((JsonObject) element, depth + 1, registry);
tags.add(nextTag);
}
if (tags.isEmpty()) {
this.type = 0;
} else {
this.type = listType;
}
this.value = tags;
return this;
}
/**
* Returns the number of elements in this list tag.
*
* @return the number of elements in this list tag.
*/
public int size() {
return this.value.size();
}
/**
* Returns true if this list tag is empty, false otherwise.
*
* @return true if this list tag is empty, false otherwise.
*/
public boolean isEmpty() {
return this.value.isEmpty();
}
/**
* Appends the specified tag to the end of the list. Returns true if added successfully.
*
* @param tag the tag to be added.
* @return true if added successfully.
*/
public boolean add(@NonNull T tag) {
if (this.value.isEmpty()) {
this.type = tag.getTypeId();
}
if (tag.getTypeId() != this.type) {
return false;
}
return this.value.add(tag);
}
/**
* Inserts the specified tag at the specified position in this list.
* Shifts the tag currently at that position and any subsequent tags to the right.
*
* @param index index at which the tag is to be inserted.
* @param tag tag to be inserted.
*/
public void insert(int index, @NonNull T tag) {
if (this.value.isEmpty()) {
this.type = tag.getTypeId();
}
if (tag.getTypeId() != this.type) {
return;
}
this.value.add(index, tag);
}
/**
* Removes a given tag from the list. Returns true if removed successfully, false otherwise.
*
* @param tag the tag to be removed.
* @return true if the tag was removed successfully, false otherwise.
*/
public boolean remove(@NonNull T tag) {
boolean success = this.value.remove(tag);
if (this.value.isEmpty()) {
this.type = 0;
}
return success;
}
/**
* Removes a tag from the list based on the tag's index. Returns the removed tag.
*
* @param index the index of the tag to be removed.
* @return the removed tag.
*/
public T remove(int index) {
T previous = this.value.remove(index);
if (this.value.isEmpty()) {
this.type = 0;
}
return previous;
}
/**
* Retrieves a tag from its index in the list.
*
* @param index the index of the tag to be retrieved.
* @return the tag at the specified index.
*/
public T get(int index) {
return this.value.get(index);
}
/**
* Returns true if this list contains the tag, false otherwise.
*
* @param tag the tag to check for.
* @return true if this list contains the tag, false otherwise.
*/
public boolean contains(@NonNull T tag) {
return this.value.contains(tag);
}
/**
* Returns true if this list contains all tags in the collection, false otherwise.
*
* @param tags the tags to be checked for.
* @return true if this list contains all tags in the collection, false otherwise.
*/
public boolean containsAll(@NonNull Collection<T> tags) {
return this.value.containsAll(tags);
}
/**
* Removes all tags from the list. The list will be empty after this call returns.
*/
public void clear() {
this.type = 0;
this.value.clear();
}
@Override
public Iterator<T> iterator() {
return this.value.iterator();
}
@Override
public void forEach(Consumer<? super T> action) {
this.value.forEach(action);
}
@Override
public Spliterator<T> spliterator() {
return this.value.spliterator();
}
@Override
public String toString() {
return this.toSnbt(0, new TagTypeRegistry(), new SnbtConfig());
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ListTag<?> listTag = (ListTag<?>) o;
if (type != listTag.type) return false;
return Objects.equals(value, listTag.value);
}
@Override
public int hashCode() {
int result = value != null ? value.hashCode() : 0;
result = 31 * result + (int) type;
return result;
}
}
| 0 | 0.908477 | 1 | 0.908477 | game-dev | MEDIA | 0.517607 | game-dev | 0.943439 | 1 | 0.943439 |
DragonKnightOfBreeze/Paradox-Language-Support | 3,857 | src/main/kotlin/icu/windea/pls/ep/tools/exporter/ParadoxGameJsonExporter.kt | package icu.windea.pls.ep.tools.exporter
import com.intellij.openapi.fileChooser.FileSaverDescriptor
import icu.windea.pls.PlsBundle
import icu.windea.pls.PlsFacade
import icu.windea.pls.core.normalizePath
import icu.windea.pls.ep.tools.model.Constants
import icu.windea.pls.ep.tools.model.ContentLoadJson
import icu.windea.pls.ep.tools.model.DlcLoadJson
import icu.windea.pls.lang.util.ParadoxMetadataManager
import icu.windea.pls.model.ParadoxGameType
import icu.windea.pls.model.tools.ParadoxModSetInfo
import java.nio.file.Path
import kotlin.io.path.exists
/**
* 导出模组信息到游戏的 JSON 配置文件。
*
* 数据文件默认位于游戏数据目录下,且按照游戏使用的模组描述符文件,选用不同的文件:
* - `.metadata/metadata.json`(VIC3):`content_load.json`
* - `descriptor.mod`(其他游戏):`dlc_load.json`
*
* 参见:[JsonExporter.cs](https://github.com/bcssov/IronyModManager/blob/master/src/IronyModManager.IO/Mods/Exporter/JsonExporter.cs)
*/
class ParadoxGameJsonExporter : ParadoxJsonBasedModExporter() {
override val text: String = PlsBundle.message("mod.exporter.game")
override suspend fun execute(filePath: Path, modSetInfo: ParadoxModSetInfo): ParadoxModExporter.Result {
val gameType = modSetInfo.gameType
val gameDataDirPath = PlsFacade.getDataProvider().getGameDataPath(gameType.title)
?: throw IllegalStateException(PlsBundle.message("mod.importer.error.gameDataDir0"))
val enabledMods = modSetInfo.mods.filter { it.enabled }
// 基于当前游戏数据目录构建一次映射
val descriptorMapping = ParadoxMetadataManager.buildDescriptorMapping(gameDataDirPath)
// 依据游戏类型选择不同的 JSON 结构
return if (ParadoxMetadataManager.useDescriptorMod(gameType)) {
// dlc_load.json: enabled_mods 是字符串列表
val enabledModPaths = enabledMods.mapNotNull { modInfo ->
val modDir = modInfo.modDirectory?.normalizePath()
descriptorMapping[modDir] ?: modInfo.remoteId?.let { "mod/ugc_${it}.mod" }
}
val data = DlcLoadJson(
disabledDlcs = emptyList(),
enabledMods = enabledModPaths,
)
writeData(filePath, data)
ParadoxModExporter.Result(total = enabledMods.size, actualTotal = enabledModPaths.size)
} else {
// content_load.json: enabledMods 是对象列表,字段为 path
val enabledModEntries = enabledMods.mapNotNull { modInfo ->
val modDir = modInfo.modDirectory?.normalizePath()
val path = descriptorMapping[modDir] ?: modInfo.remoteId?.let { "mod/ugc_${it}.mod" }
path?.let { ContentLoadJson.EnabledMod(path = it) }
}
val data = ContentLoadJson(
disabledDlcs = emptyList(),
enabledMods = enabledModEntries,
enabledUgc = emptyList(),
)
writeData(filePath, data)
ParadoxModExporter.Result(total = enabledMods.size, actualTotal = enabledModEntries.size)
}
}
override fun createFileSaverDescriptor(gameType: ParadoxGameType): FileSaverDescriptor {
val jsonFileName = getJsonFileName(gameType)
return FileSaverDescriptor(PlsBundle.message("mod.exporter.game.title", jsonFileName), "", "json")
}
override fun getSavedBaseDir(gameType: ParadoxGameType): Path? {
// 游戏数据目录
val gameDataPath = PlsFacade.getDataProvider().getGameDataPath(gameType.title)?.takeIf { it.exists() } ?: return null
return gameDataPath
}
override fun getSavedFileName(gameType: ParadoxGameType): String {
// 对应的 JSON 文件
return getJsonFileName(gameType)
}
private fun getJsonFileName(gameType: ParadoxGameType): String {
return when {
ParadoxMetadataManager.useDescriptorMod(gameType) -> Constants.dlcLoadPath
else -> Constants.contentLoadPath
}
}
}
| 0 | 0.804158 | 1 | 0.804158 | game-dev | MEDIA | 0.720431 | game-dev | 0.834382 | 1 | 0.834382 |
finmath/finmath-lib | 40,281 | src/main/java/net/finmath/montecarlo/automaticdifferentiation/backward/alternative/RandomVariableAAD.java | package net.finmath.montecarlo.automaticdifferentiation.backward.alternative;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.DoubleBinaryOperator;
import java.util.function.DoubleUnaryOperator;
import java.util.function.IntToDoubleFunction;
import java.util.stream.DoubleStream;
import net.finmath.functions.DoubleTernaryOperator;
import net.finmath.montecarlo.RandomVariableFromDoubleArray;
import net.finmath.stochastic.RandomVariable;
/**
* Implementation of <code>RandomVariable</code> having the additional feature to calculate the backward algorithmic differentiation.
*
* For construction use the factory method <code>constructNewAADRandomVariable</code>.
*
* @author Stefan Sedlmair
* @version 1.0
*/
public class RandomVariableAAD implements RandomVariable {
private static final long serialVersionUID = 2459373647785530657L;
/* static elements of the class are shared between all members */
private static ArrayList<RandomVariableAAD> arrayListOfAllAADRandomVariables = new ArrayList<>();
private static AtomicInteger indexOfNextRandomVariable = new AtomicInteger(0);
private enum OperatorType {
ADD, MULT, DIV, SUB, SQUARED, SQRT, LOG, SIN, COS, EXP, INVERT, CAP, FLOOR, ABS,
ADDPRODUCT, ADDRATIO, SUBRATIO, BARRIER, DISCOUNT, ACCRUE, POW, AVERAGE, VARIANCE,
STDEV, MIN, MAX, STDERROR, SVARIANCE
}
/* index of corresponding random variable in the static array list*/
private final RandomVariable ownRandomVariable;
private final int ownIndexInList;
/* this could maybe be outsourced to own class ParentElement */
private final int[] parentIndices;
private final OperatorType parentOperator;
private ArrayList<Integer> childrenIndices;
private boolean isConstant;
private RandomVariableAAD(final int ownIndexInList, final RandomVariable ownRandomVariable,
final int[] parentIndices, final OperatorType parentOperator, final ArrayList<Integer> childrenIndices ,final boolean isConstant) {
super();
this.ownIndexInList = ownIndexInList;
this.ownRandomVariable = ownRandomVariable;
this.parentIndices = parentIndices;
this.parentOperator = parentOperator;
this.childrenIndices = childrenIndices;
this.isConstant = isConstant;
}
public static RandomVariableAAD constructNewAADRandomVariable(final RandomVariable randomVariable, final int[] parentIndices,
final OperatorType parentOperator, final ArrayList<Integer> childrenIndices, final boolean isConstant){
/* TODO how to handle cases with different realization lengths? */
if(!arrayListOfAllAADRandomVariables.isEmpty()){
if(arrayListOfAllAADRandomVariables.get(0).size() != randomVariable.size() && !randomVariable.isDeterministic()) {
throw new IllegalArgumentException("RandomVariables with different sizes are not supported at the moment!");
}
}
/* get index of this random variable */
final int indexOfThisAADRandomVariable = indexOfNextRandomVariable.getAndIncrement();
final RandomVariableAAD newAADRandomVariable = new RandomVariableAAD(indexOfThisAADRandomVariable, randomVariable,
parentIndices, parentOperator, childrenIndices, isConstant);
/* add random variable to static list for book keeping */
arrayListOfAllAADRandomVariables.add(indexOfThisAADRandomVariable, newAADRandomVariable);
/* return a new random variable */
return newAADRandomVariable;
}
public static RandomVariableAAD constructNewAADRandomVariable(final double value){
return constructNewAADRandomVariable(new RandomVariableFromDoubleArray(value), /*parentRandomVariables*/ null, /*parentOperator*/ null, /*childrenIndices*/ null ,/*isConstant*/ true);
}
public static RandomVariableAAD constructNewAADRandomVariable(final RandomVariable randomVariable) {
return constructNewAADRandomVariable(randomVariable, /* no parents*/ null,
/*no parent operator*/ null, /*no childrenIndices*/ null, /*not constant*/ false);
}
public static RandomVariableAAD constructNewAADRandomVariable(final double time, final double[] realisations) {
return constructNewAADRandomVariable(new RandomVariableFromDoubleArray(time, realisations), /* no parents*/ null,
/*no parent operator*/ null, /*no childrenIndices*/ null, /*not constant*/ false);
}
private RandomVariableAAD[] getParentAADRandomVariables(){
if(getParentIDs() == null) {
return null;
}
final int[] parentIndices = getParentIDs();
final RandomVariableAAD[] parentAADRandomVariables = new RandomVariableAAD[getNumberOfParentVariables()];
for(int i=0; i < parentAADRandomVariables.length; i++){
parentAADRandomVariables[i] = getAADRandomVariableFromList(parentIndices[i]);
}
return parentAADRandomVariables;
}
/**
* @return
*/
private RandomVariable[] getParentRandomVariableInderfaces(){
final RandomVariableAAD[] parentAADRandomVariables = getParentAADRandomVariables();
final RandomVariable[] parentRandomVariableInderfaces = new RandomVariable[parentAADRandomVariables.length];
for(int i=0;i<parentAADRandomVariables.length;i++){
parentRandomVariableInderfaces[i] = parentAADRandomVariables[i].getRandomVariableInterface();
}
return parentRandomVariableInderfaces;
}
private RandomVariable apply(final OperatorType operator, final RandomVariable[] randomVariableInterfaces){
final RandomVariableAAD[] aadRandomVariables = new RandomVariableAAD[randomVariableInterfaces.length];
final int[] futureParentIndices = new int[aadRandomVariables.length];
for(int randomVariableIndex = 0; randomVariableIndex < randomVariableInterfaces.length; randomVariableIndex++){
aadRandomVariables[randomVariableIndex] = (randomVariableInterfaces[randomVariableIndex] instanceof RandomVariableAAD) ?
(RandomVariableAAD)randomVariableInterfaces[randomVariableIndex] : constructNewAADRandomVariable(randomVariableInterfaces[randomVariableIndex]);
futureParentIndices[randomVariableIndex] = aadRandomVariables[randomVariableIndex].getFunctionIndex();
}
RandomVariable resultrandomvariable;
RandomVariable X,Y,Z;
if(randomVariableInterfaces.length == 1){
X = aadRandomVariables[0].getRandomVariableInterface();
switch(operator){
case SQUARED:
resultrandomvariable = X.squared();
break;
case SQRT:
resultrandomvariable = X.sqrt();
break;
case EXP:
resultrandomvariable = X.exp();
break;
case LOG:
resultrandomvariable = X.log();
break;
case SIN:
resultrandomvariable = X.sin();
break;
case COS:
resultrandomvariable = X.cos();
break;
case ABS:
resultrandomvariable = X.abs();
break;
case INVERT:
resultrandomvariable = X.invert();
break;
case AVERAGE:
resultrandomvariable = new RandomVariableFromDoubleArray(X.getAverage());
break;
case STDERROR:
resultrandomvariable = new RandomVariableFromDoubleArray(X.getStandardError());
break;
case STDEV:
resultrandomvariable = new RandomVariableFromDoubleArray(X.getStandardDeviation());
break;
case VARIANCE:
resultrandomvariable = new RandomVariableFromDoubleArray(X.getVariance());
break;
case SVARIANCE:
resultrandomvariable = new RandomVariableFromDoubleArray(X.getSampleVariance());
break;
default:
throw new IllegalArgumentException();
}
} else if (randomVariableInterfaces.length == 2){
X = aadRandomVariables[0].getRandomVariableInterface();
Y = aadRandomVariables[1].getRandomVariableInterface();
switch(operator){
case ADD:
resultrandomvariable = X.add(Y);
break;
case SUB:
resultrandomvariable = X.sub(Y);
break;
case MULT:
resultrandomvariable = X.mult(Y);
break;
case DIV:
resultrandomvariable = X.div(Y);
break;
case CAP:
resultrandomvariable = X.cap( /* argument is deterministic random variable */ Y.getAverage());
break;
case FLOOR:
resultrandomvariable = X.floor( /* argument is deterministic random variable */ Y.getAverage());
break;
case POW:
resultrandomvariable = X.pow( /* argument is deterministic random variable */ Y.getAverage());
break;
case AVERAGE:
resultrandomvariable = new RandomVariableFromDoubleArray(X.getAverage(Y));
break;
case STDERROR:
resultrandomvariable = new RandomVariableFromDoubleArray(X.getStandardError(Y));
break;
case STDEV:
resultrandomvariable = new RandomVariableFromDoubleArray(X.getStandardDeviation(Y));
break;
case VARIANCE:
resultrandomvariable = new RandomVariableFromDoubleArray(X.getVariance(Y));
break;
default:
throw new IllegalArgumentException();
}
} else if(randomVariableInterfaces.length == 3){
X = aadRandomVariables[0].getRandomVariableInterface();
Y = aadRandomVariables[1].getRandomVariableInterface();
Z = aadRandomVariables[2].getRandomVariableInterface();
switch(operator){
case ADDPRODUCT:
resultrandomvariable = X.addProduct(Y,Z);
break;
case ADDRATIO:
resultrandomvariable = X.addRatio(Y, Z);
break;
case SUBRATIO:
resultrandomvariable = X.subRatio(Y, Z);
break;
case ACCRUE:
resultrandomvariable = X.accrue(Y, /* second argument is deterministic anyway */ Z.getAverage());
break;
case DISCOUNT:
resultrandomvariable = X.discount(Y, /* second argument is deterministic anyway */ Z.getAverage());
break;
default:
throw new IllegalArgumentException();
}
} else {
/* if non of the above throw exception */
throw new IllegalArgumentException("Operation not supported!\n");
}
/* create new RandomVariableUniqueVariable which is definitely NOT Constant */
final RandomVariableAAD newRandomVariableAAD = constructNewAADRandomVariable(resultrandomvariable, futureParentIndices, operator, /*no children*/ null ,/*not constant*/ false);
/* add new variable (or at least its index) as child to its parents */
for(final RandomVariableAAD parentRandomVariable:aadRandomVariables) {
parentRandomVariable.addToChildrenIndices(newRandomVariableAAD.getFunctionIndex());
}
/* return new RandomVariableFromDoubleArray */
return newRandomVariableAAD;
}
@Override
public String toString(){
return super.toString() + "\n" +
"time: " + getFiltrationTime() + "\n" +
"realizations: " + Arrays.toString(getRealizations()) + "\n" +
"variableID: " + getFunctionIndex() + "\n" +
"parentIDs: " + Arrays.toString(getParentIDs()) + ((getParentIDs() == null) ? "" : (" type: " + parentOperator.name())) + "\n" +
"isTrueVariable: " + isVariable() + "\n";
}
private RandomVariable getPartialDerivative(final int functionIndex, final int variableIndex){
return getFunctionList().get(functionIndex).partialDerivativeWithRespectTo(variableIndex);
}
private RandomVariable partialDerivativeWithRespectTo(final int variableIndex){
/* parentIDsSorted needs to be sorted for binarySearch! */
final int[] parentIDsSorted = (getParentIDs() == null) ? new int[]{} : getParentIDs().clone();
Arrays.sort(parentIDsSorted);
/* if random variable not dependent on variable or it is constant anyway return 0.0 */
if((Arrays.binarySearch(parentIDsSorted, variableIndex) < 0) || isConstant) {
return new RandomVariableFromDoubleArray(0.0);
}
RandomVariable resultrandomvariable = null;
RandomVariable X,Y,Z;
final double[] resultRandomVariableRealizations;
if(getParentIDs().length == 1){
X = getRandomVariableInterfaceOfIndex(getParentIDs()[0]);
switch(parentOperator){
/* functions with one argument */
case SQUARED:
resultrandomvariable = X.mult(2.0);
break;
case SQRT:
resultrandomvariable = X.sqrt().invert().mult(0.5);
break;
case EXP:
resultrandomvariable = X.exp();
break;
case LOG:
resultrandomvariable = X.invert();
break;
case SIN:
resultrandomvariable = X.cos();
break;
case COS:
resultrandomvariable = X.sin().mult(-1.0);
break;
case AVERAGE:
resultrandomvariable = new RandomVariableFromDoubleArray(X.size()).invert();
break;
case VARIANCE:
resultrandomvariable = X.sub(X.getAverage()*(2.0*X.size()-1.0)/X.size()).mult(2.0/X.size());
break;
case STDEV:
resultrandomvariable = X.sub(X.getAverage()*(2.0*X.size()-1.0)/X.size()).mult(2.0/X.size()).mult(0.5).div(Math.sqrt(X.getVariance()));
break;
case MIN:
resultrandomvariable = X.apply(new DoubleUnaryOperator() {
@Override
public double applyAsDouble(final double x) {
return (x == X.getMin()) ? 1.0 : 0.0;
}
});
// resultRandomVariableRealizations = new double[X.size()];
// for(int i = 0; i < X.size(); i++) resultRandomVariableRealizations[i] = (X.getRealizations()[i] == X.getMin()) ? 1.0 : 0.0;
// resultrandomvariable = new RandomVariableFromDoubleArray(X.getFiltrationTime(), resultRandomVariableRealizations);
break;
case MAX:
resultrandomvariable = X.apply(new DoubleUnaryOperator() {
@Override
public double applyAsDouble(final double x) {
return (x == X.getMax()) ? 1.0 : 0.0;
}
});
// resultRandomVariableRealizations = new double[X.size()];
// for(int i = 0; i < X.size(); i++) resultRandomVariableRealizations[i] = (X.getRealizations()[i] == X.getMax()) ? 1.0 : 0.0;
// resultrandomvariable = new RandomVariableFromDoubleArray(X.getFiltrationTime(), resultRandomVariableRealizations);
break;
case ABS:
resultrandomvariable = X.apply(new DoubleUnaryOperator() {
@Override
public double applyAsDouble(final double x) {
return (x > 0.0) ? 1.0 : (x < 0) ? -1.0 : 0.0;
}
});
// resultRandomVariableRealizations = new double[X.size()];
// for(int i = 0; i < X.size(); i++) resultRandomVariableRealizations[i] = (X.getRealizations()[i] > 0) ? 1.0 : (X.getRealizations()[i] < 0) ? -1.0 : 0.0;
// resultrandomvariable = new RandomVariableFromDoubleArray(X.getFiltrationTime(), resultRandomVariableRealizations);
break;
case STDERROR:
resultrandomvariable = X.sub(X.getAverage()*(2.0*X.size()-1.0)/X.size()).mult(2.0/X.size()).mult(0.5).div(Math.sqrt(X.getVariance() * X.size()));
break;
case SVARIANCE:
resultrandomvariable = X.sub(X.getAverage()*(2.0*X.size()-1.0)/X.size()).mult(2.0/(X.size()-1));
break;
default:
break;
}
} else if(getParentIDs().length == 2){
X = getRandomVariableInterfaceOfIndex(getParentIDs()[0]);
Y = getRandomVariableInterfaceOfIndex(getParentIDs()[1]);
switch(parentOperator){
case ADD:
resultrandomvariable = new RandomVariableFromDoubleArray(1.0);
break;
case SUB:
resultrandomvariable = new RandomVariableFromDoubleArray((variableIndex == getParentIDs()[0]) ? 1.0 : -1.0);
break;
case MULT:
resultrandomvariable = (variableIndex == getParentIDs()[0]) ? Y : X;
break;
case DIV:
resultrandomvariable = (variableIndex == getParentIDs()[0]) ? Y.invert() : X.div(Y.squared()).mult(-1);
break;
case CAP:
resultrandomvariable = X.apply(new DoubleUnaryOperator() {
@Override
public double applyAsDouble(final double x) {
return (x > Y.getAverage()) ? 0.0 : 1.0;
}
});
// resultRandomVariableRealizations = new double[X.size()];
// for(int i = 0; i < X.size(); i++) resultRandomVariableRealizations[i] = (X.getRealizations()[i] > Y.getAverage()) ? 0.0 : 1.0;
// resultrandomvariable = new RandomVariableFromDoubleArray(X.getFiltrationTime(), resultRandomVariableRealizations);
break;
case FLOOR:
resultrandomvariable = X.apply(new DoubleUnaryOperator() {
@Override
public double applyAsDouble(final double x) {
return (x > Y.getAverage()) ? 1.0 : 0.0;
}
});
// resultRandomVariableRealizations = new double[X.size()];
// for(int i = 0; i < X.size(); i++) resultRandomVariableRealizations[i] = (X.getRealizations()[i] > Y.getAverage()) ? 1.0 : 0.0;
// resultrandomvariable = new RandomVariableFromDoubleArray(X.getFiltrationTime(), resultRandomVariableRealizations);
break;
case AVERAGE:
resultrandomvariable = (variableIndex == getParentIDs()[0]) ? Y : X;
break;
case VARIANCE:
resultrandomvariable = (variableIndex == getParentIDs()[0]) ? Y.mult(2.0).mult(X.mult(Y.add(X.getAverage(Y)*(X.size()-1)).sub(X.getAverage(Y)))) :
X.mult(2.0).mult(Y.mult(X.add(Y.getAverage(X)*(X.size()-1)).sub(Y.getAverage(X))));
break;
case STDEV:
resultrandomvariable = (variableIndex == getParentIDs()[0]) ? Y.mult(2.0).mult(X.mult(Y.add(X.getAverage(Y)*(X.size()-1)).sub(X.getAverage(Y)))).div(Math.sqrt(X.getVariance(Y))) :
X.mult(2.0).mult(Y.mult(X.add(Y.getAverage(X)*(X.size()-1)).sub(Y.getAverage(X)))).div(Math.sqrt(Y.getVariance(X)));
break;
case STDERROR:
resultrandomvariable = (variableIndex == getParentIDs()[0]) ? Y.mult(2.0).mult(X.mult(Y.add(X.getAverage(Y)*(X.size()-1)).sub(X.getAverage(Y)))).div(Math.sqrt(X.getVariance(Y) * X.size())) :
X.mult(2.0).mult(Y.mult(X.add(Y.getAverage(X)*(X.size()-1)).sub(Y.getAverage(X)))).div(Math.sqrt(Y.getVariance(X) * Y.size()));
break;
case POW:
/* second argument will always be deterministic and constant! */
resultrandomvariable = (variableIndex == getParentIDs()[0]) ? Y.mult(X.pow(Y.getAverage() - 1.0)) : new RandomVariableFromDoubleArray(0.0);
break;
default:
break;
}
} else if(getParentIDs().length == 3){
X = getRandomVariableInterfaceOfIndex(getParentIDs()[0]);
Y = getRandomVariableInterfaceOfIndex(getParentIDs()[1]);
Z = getRandomVariableInterfaceOfIndex(getParentIDs()[2]);
switch(parentOperator){
case ADDPRODUCT:
if(variableIndex == getParentIDs()[0]){
resultrandomvariable = new RandomVariableFromDoubleArray(1.0);
} else if(variableIndex == getParentIDs()[1]){
resultrandomvariable = Z;
} else {
resultrandomvariable = Y;
}
break;
case ADDRATIO:
if(variableIndex == getParentIDs()[0]){
resultrandomvariable = new RandomVariableFromDoubleArray(1.0);
} else if(variableIndex == getParentIDs()[0]){
resultrandomvariable = Z.invert();
} else {
resultrandomvariable = Y.div(Z.squared());
}
break;
case SUBRATIO:
if(variableIndex == getParentIDs()[0]){
resultrandomvariable = new RandomVariableFromDoubleArray(1.0);
} else if(variableIndex == getParentIDs()[1]){
resultrandomvariable = Z.invert().mult(-1.0);
} else {
resultrandomvariable = Y.div(Z.squared()).mult(-1.0);
}
break;
case ACCRUE:
if(variableIndex == getParentIDs()[0]){
resultrandomvariable = Y.mult(Z).add(1.0);
} else if(variableIndex == getParentIDs()[1]){
resultrandomvariable = X.mult(Z);
} else {
resultrandomvariable = X.mult(Y);
}
break;
case DISCOUNT:
if(variableIndex == getParentIDs()[0]){
resultrandomvariable = Y.mult(Z).add(1.0).invert();
} else if(variableIndex == getParentIDs()[1]){
resultrandomvariable = X.mult(Z).div(Y.mult(Z).add(1.0).squared());
} else {
resultrandomvariable = X.mult(Y).div(Y.mult(Z).add(1.0).squared());
}
break;
case BARRIER:
if(variableIndex == getParentIDs()[0]){
resultrandomvariable = X.apply(new DoubleUnaryOperator() {
@Override
public double applyAsDouble(final double x) {
return (x == 0.0) ? Double.POSITIVE_INFINITY : 0.0;
}
});
} else if(variableIndex == getParentIDs()[1]){
resultrandomvariable = X.choose(new RandomVariableFromDoubleArray(1.0), new RandomVariableFromDoubleArray(0.0));
} else {
resultrandomvariable = X.choose(new RandomVariableFromDoubleArray(0.0), new RandomVariableFromDoubleArray(1.0));
}
default:
break;
}
} else {
/* if non of the above throw exception */
throw new IllegalArgumentException("Operation not supported!\n");
}
return resultrandomvariable;
}
/**
* Implements the AAD Algorithm
* @return HashMap where the key is the internal index of the random variable with respect to which the partial derivative was computed. This key then gives access to the actual derivative.
* */
public Map<Integer, RandomVariable> getGradient(){
final int numberOfCalculationSteps = getFunctionList().size();
final RandomVariable[] omegaHat = new RandomVariable[numberOfCalculationSteps];
omegaHat[numberOfCalculationSteps-1] = new RandomVariableFromDoubleArray(1.0);
for(int variableIndex = numberOfCalculationSteps-2; variableIndex >= 0; variableIndex--){
omegaHat[variableIndex] = new RandomVariableFromDoubleArray(0.0);
final ArrayList<Integer> childrenList = getAADRandomVariableFromList(variableIndex).getChildrenIndices();
for(final int functionIndex:childrenList){
final RandomVariable D_i_j = getPartialDerivative(functionIndex, variableIndex);
omegaHat[variableIndex] = omegaHat[variableIndex].addProduct(D_i_j, omegaHat[functionIndex]);
}
}
final ArrayList<Integer> arrayListOfAllIndicesOfDependentRandomVariables = getArrayListOfAllIndicesOfDependentRandomVariables();
final Map<Integer, RandomVariable> gradient = new HashMap<>();
for(final Integer indexOfDependentRandomVariable: arrayListOfAllIndicesOfDependentRandomVariables){
gradient.put(indexOfDependentRandomVariable, omegaHat[arrayListOfAllIndicesOfDependentRandomVariables.get(indexOfDependentRandomVariable)]);
}
return gradient;
}
private ArrayList<Integer> getArrayListOfAllIndicesOfDependentRandomVariables(){
final ArrayList<Integer> arrayListOfAllIndicesOfDependentRandomVariables = new ArrayList<>();
for(int index = 0; index < getNumberOfParentVariables(); index++){
final int currentParentIndex = getParentIDs()[index];
/* if current index belongs to a true variable and is not yet in the list: add it*/
if(getAADRandomVariableFromList(currentParentIndex).isVariable() &&
!arrayListOfAllIndicesOfDependentRandomVariables.contains(currentParentIndex)){
arrayListOfAllIndicesOfDependentRandomVariables.add(currentParentIndex);
} else {
arrayListOfAllIndicesOfDependentRandomVariables.addAll(
getAADRandomVariableFromList(currentParentIndex).getArrayListOfAllIndicesOfDependentRandomVariables());
}
}
return arrayListOfAllIndicesOfDependentRandomVariables;
}
/* for all functions that need to be differentiated and are returned as double in the Interface, write a method to return it as RandomVariableAAD
* that is deterministic by its nature. For their double-returning pendant just return the average of the deterministic RandomVariableAAD */
public RandomVariable getAverageAsRandomVariableAAD(final RandomVariable probabilities){
/*returns deterministic AAD random variable */
return apply(OperatorType.AVERAGE, new RandomVariable[]{this, probabilities});
}
public RandomVariable getVarianceAsRandomVariableAAD(final RandomVariable probabilities){
/*returns deterministic AAD random variable */
return apply(OperatorType.VARIANCE, new RandomVariable[]{this, probabilities});
}
public RandomVariable getStandardDeviationAsRandomVariableAAD(final RandomVariable probabilities){
/*returns deterministic AAD random variable */
return apply(OperatorType.STDEV, new RandomVariable[]{this, probabilities});
}
public RandomVariable getStandardErrorAsRandomVariableAAD(final RandomVariable probabilities){
/*returns deterministic AAD random variable */
return apply(OperatorType.STDERROR, new RandomVariable[]{this, probabilities});
}
public RandomVariable getAverageAsRandomVariableAAD(){
/*returns deterministic AAD random variable */
return apply(OperatorType.AVERAGE, new RandomVariable[]{this});
}
public RandomVariable getVarianceAsRandomVariableAAD(){
/*returns deterministic AAD random variable */
return apply(OperatorType.VARIANCE, new RandomVariable[]{this});
}
public RandomVariable getSampleVarianceAsRandomVariableAAD() {
/*returns deterministic AAD random variable */
return apply(OperatorType.SVARIANCE, new RandomVariable[]{this});
}
public RandomVariable getStandardDeviationAsRandomVariableAAD(){
/*returns deterministic AAD random variable */
return apply(OperatorType.STDEV, new RandomVariable[]{this});
}
public RandomVariable getStandardErrorAsRandomVariableAAD(){
/*returns deterministic AAD random variable */
return apply(OperatorType.STDERROR, new RandomVariable[]{this});
}
public RandomVariable getMinAsRandomVariableAAD(){
/*returns deterministic AAD random variable */
return apply(OperatorType.MIN, new RandomVariable[]{this});
}
public RandomVariable getMaxAsRandomVariableAAD(){
/*returns deterministic AAD random variable */
return apply(OperatorType.MAX, new RandomVariable[]{this});
}
/* setter and getter */
private OperatorType getParentOperator(){
return parentOperator;
}
private boolean isConstant(){
return isConstant;
}
private boolean isVariable() {
return (isConstant() == false && getParentIDs() == null);
}
private ArrayList<RandomVariableAAD> getFunctionList(){
return arrayListOfAllAADRandomVariables;
}
public static void resetArrayListOfAllAADRandomVariables(){
synchronized (arrayListOfAllAADRandomVariables) {
arrayListOfAllAADRandomVariables = new ArrayList<>();
indexOfNextRandomVariable = new AtomicInteger(0);
}
}
public void setIsConstantTo(final boolean isConstant){
this.isConstant = isConstant;
}
private RandomVariable getRandomVariableInterface(){
return ownRandomVariable;
}
private RandomVariable getRandomVariableInterfaceOfIndex(final int index){
return getFunctionList().get(index).getRandomVariableInterface();
}
private int getFunctionIndex(){
return ownIndexInList;
}
private int[] getParentIDs(){
return parentIndices;
}
private ArrayList<Integer> getChildrenIndices(){
if(childrenIndices == null) {
childrenIndices = new ArrayList<>();
}
return childrenIndices;
}
private int getNumberOfParentVariables(){
if(getParentIDs() == null) {
return 0;
}
return getParentIDs().length;
}
private RandomVariableAAD getAADRandomVariableFromList(final int index){
return getFunctionList().get(index);
}
private void addToChildrenIndices(final int index){
getChildrenIndices().add(index);
}
/*--------------------------------------------------------------------------------------------------------------------------------------------------*/
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#equals(net.finmath.stochastic.RandomVariable)
*/
@Override
public boolean equals(final RandomVariable randomVariable) {
return getRandomVariableInterface().equals(randomVariable);
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#getFiltrationTime()
*/
@Override
public double getFiltrationTime() {
return getRandomVariableInterface().getFiltrationTime();
}
@Override
public int getTypePriority() {
return 3;
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#get(int)
*/
@Override
public double get(final int pathOrState) {
return getRandomVariableInterface().get(pathOrState);
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#size()
*/
@Override
public int size() {
return getRandomVariableInterface().size();
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#isDeterministic()
*/
@Override
public boolean isDeterministic() {
return getRandomVariableInterface().isDeterministic();
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#getRealizations()
*/
@Override
public double[] getRealizations() {
return getRandomVariableInterface().getRealizations();
}
@Override
public Double doubleValue() {
return getRandomVariableInterface().doubleValue();
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#getMin()
*/
@Override
public double getMin() {
return ((RandomVariableAAD) getMinAsRandomVariableAAD()).getRandomVariableInterface().getAverage();
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#getMax()
*/
@Override
public double getMax() {
return ((RandomVariableAAD) getMaxAsRandomVariableAAD()).getRandomVariableInterface().getAverage();
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#getAverage()
*/
@Override
public double getAverage() {
return ((RandomVariableAAD) getAverageAsRandomVariableAAD()).getRandomVariableInterface().getAverage();
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#getAverage(net.finmath.stochastic.RandomVariable)
*/
@Override
public double getAverage(final RandomVariable probabilities) {
return ((RandomVariableAAD) getAverageAsRandomVariableAAD(probabilities)).getRandomVariableInterface().getAverage();
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#getVariance()
*/
@Override
public double getVariance() {
return ((RandomVariableAAD) getVarianceAsRandomVariableAAD()).getRandomVariableInterface().getAverage();
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#getVariance(net.finmath.stochastic.RandomVariable)
*/
@Override
public double getVariance(final RandomVariable probabilities) {
return ((RandomVariableAAD) getAverageAsRandomVariableAAD(probabilities)).getRandomVariableInterface().getAverage();
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#getSampleVariance()
*/
@Override
public double getSampleVariance() {
return ((RandomVariableAAD) getSampleVarianceAsRandomVariableAAD()).getRandomVariableInterface().getAverage();
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#getStandardDeviation()
*/
@Override
public double getStandardDeviation() {
return ((RandomVariableAAD) getStandardDeviationAsRandomVariableAAD()).getRandomVariableInterface().getAverage();
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#getStandardDeviation(net.finmath.stochastic.RandomVariable)
*/
@Override
public double getStandardDeviation(final RandomVariable probabilities) {
return ((RandomVariableAAD) getStandardDeviationAsRandomVariableAAD(probabilities)).getRandomVariableInterface().getAverage();
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#getStandardError()
*/
@Override
public double getStandardError() {
return ((RandomVariableAAD) getStandardErrorAsRandomVariableAAD()).getRandomVariableInterface().getAverage();
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#getStandardError(net.finmath.stochastic.RandomVariable)
*/
@Override
public double getStandardError(final RandomVariable probabilities) {
return ((RandomVariableAAD) getStandardErrorAsRandomVariableAAD(probabilities)).getRandomVariableInterface().getAverage();
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#getQuantile(double)
*/
@Override
public double getQuantile(final double quantile) {
return ((RandomVariableAAD) getRandomVariableInterface()).getRandomVariableInterface().getQuantile(quantile);
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#getQuantile(double, net.finmath.stochastic.RandomVariable)
*/
@Override
public double getQuantile(final double quantile, final RandomVariable probabilities) {
return ((RandomVariableAAD) getRandomVariableInterface()).getRandomVariableInterface().getQuantile(quantile, probabilities);
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#getQuantileExpectation(double, double)
*/
@Override
public double getQuantileExpectation(final double quantileStart, final double quantileEnd) {
return ((RandomVariableAAD) getRandomVariableInterface()).getRandomVariableInterface().getQuantileExpectation(quantileStart, quantileEnd);
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#getHistogram(double[])
*/
@Override
public double[] getHistogram(final double[] intervalPoints) {
return getRandomVariableInterface().getHistogram(intervalPoints);
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#getHistogram(int, double)
*/
@Override
public double[][] getHistogram(final int numberOfPoints, final double standardDeviations) {
return getRandomVariableInterface().getHistogram(numberOfPoints, standardDeviations);
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#cache()
*/
@Override
public RandomVariable cache() {
return this;
}
@Override
public RandomVariable cap(final double cap) {
return apply(OperatorType.CAP, new RandomVariable[]{this, constructNewAADRandomVariable(cap)});
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#floor(double)
*/
@Override
public RandomVariable floor(final double floor) {
return apply(OperatorType.FLOOR, new RandomVariable[]{this, constructNewAADRandomVariable(floor)});
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#add(double)
*/
@Override
public RandomVariable add(final double value) {
return apply(OperatorType.ADD, new RandomVariable[]{this, constructNewAADRandomVariable(value)});
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#sub(double)
*/
@Override
public RandomVariable sub(final double value) {
return apply(OperatorType.SUB, new RandomVariable[]{this, constructNewAADRandomVariable(value)});
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#mult(double)
*/
@Override
public RandomVariable mult(final double value) {
return apply(OperatorType.MULT, new RandomVariable[]{this, constructNewAADRandomVariable(value)});
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#div(double)
*/
@Override
public RandomVariable div(final double value) {
return apply(OperatorType.DIV, new RandomVariable[]{this, constructNewAADRandomVariable(value)});
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#pow(double)
*/
@Override
public RandomVariable pow(final double exponent) {
return apply(OperatorType.POW, new RandomVariable[]{this, constructNewAADRandomVariable(exponent)});
}
@Override
public RandomVariable average() {
return apply(OperatorType.AVERAGE, new RandomVariable[]{this});
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#squared()
*/
@Override
public RandomVariable squared() {
return apply(OperatorType.SQUARED, new RandomVariable[]{this});
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#sqrt()
*/
@Override
public RandomVariable sqrt() {
return apply(OperatorType.SQRT, new RandomVariable[]{this});
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#exp()
*/
@Override
public RandomVariable exp() {
return apply(OperatorType.EXP, new RandomVariable[]{this});
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#log()
*/
@Override
public RandomVariable log() {
return apply(OperatorType.LOG, new RandomVariable[]{this});
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#sin()
*/
@Override
public RandomVariable sin() {
return apply(OperatorType.SIN, new RandomVariable[]{this});
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#cos()
*/
@Override
public RandomVariable cos() {
return apply(OperatorType.COS, new RandomVariable[]{this});
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#add(net.finmath.stochastic.RandomVariable)
*/
@Override
public RandomVariable add(final RandomVariable randomVariable) {
return apply(OperatorType.ADD, new RandomVariable[]{this, randomVariable});
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#sub(net.finmath.stochastic.RandomVariable)
*/
@Override
public RandomVariable sub(final RandomVariable randomVariable) {
return apply(OperatorType.SUB, new RandomVariable[]{this, randomVariable});
}
@Override
public RandomVariable bus(final RandomVariable randomVariable) {
return apply(OperatorType.SUB, new RandomVariable[]{randomVariable,this}); // SUB with swapped arguments
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#mult(net.finmath.stochastic.RandomVariable)
*/
@Override
public RandomVariable mult(final RandomVariable randomVariable) {
return apply(OperatorType.MULT, new RandomVariable[]{this, randomVariable});
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#div(net.finmath.stochastic.RandomVariable)
*/
@Override
public RandomVariable div(final RandomVariable randomVariable) {
return apply(OperatorType.DIV, new RandomVariable[]{this, randomVariable});
}
@Override
public RandomVariable vid(final RandomVariable randomVariable) {
return apply(OperatorType.DIV, new RandomVariable[]{randomVariable, this}); // DIV with swapped arguments
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#cap(net.finmath.stochastic.RandomVariable)
*/
@Override
public RandomVariable cap(final RandomVariable cap) {
return apply(OperatorType.CAP, new RandomVariable[]{this, cap});
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#floor(net.finmath.stochastic.RandomVariable)
*/
@Override
public RandomVariable floor(final RandomVariable floor) {
return apply(OperatorType.FLOOR, new RandomVariable[]{this, floor});
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#accrue(net.finmath.stochastic.RandomVariable, double)
*/
@Override
public RandomVariable accrue(final RandomVariable rate, final double periodLength) {
return apply(OperatorType.ACCRUE, new RandomVariable[]{this, rate, constructNewAADRandomVariable(periodLength)});
}
/* (non-Javadoc)
* @see net.finmath.stochastic.RandomVariable#discount(net.finmath.stochastic.RandomVariable, double)
*/
@Override
public RandomVariable discount(final RandomVariable rate, final double periodLength) {
return apply(OperatorType.DISCOUNT, new RandomVariable[]{this, rate, constructNewAADRandomVariable(periodLength)});
}
@Override
public RandomVariable choose(final RandomVariable valueIfTriggerNonNegative, final RandomVariable valueIfTriggerNegative) {
return apply(OperatorType.BARRIER, new RandomVariable[]{this, valueIfTriggerNonNegative, valueIfTriggerNegative});
}
@Override
public RandomVariable invert() {
return apply(OperatorType.INVERT, new RandomVariable[]{this});
}
@Override
public RandomVariable abs() {
return apply(OperatorType.ABS, new RandomVariable[]{this});
}
@Override
public RandomVariable addProduct(final RandomVariable factor1, final double factor2) {
return apply(OperatorType.ADDPRODUCT, new RandomVariable[]{this, factor1, constructNewAADRandomVariable(factor2)});
}
@Override
public RandomVariable addProduct(final RandomVariable factor1, final RandomVariable factor2) {
return apply(OperatorType.ADDPRODUCT, new RandomVariable[]{this, factor1, factor2});
}
@Override
public RandomVariable addRatio(final RandomVariable numerator, final RandomVariable denominator) {
return apply(OperatorType.ADDRATIO, new RandomVariable[]{this, numerator, denominator});
}
@Override
public RandomVariable subRatio(final RandomVariable numerator, final RandomVariable denominator) {
return apply(OperatorType.SUBRATIO, new RandomVariable[]{this, numerator, denominator});
}
@Override
public RandomVariable isNaN() {
return getRandomVariableInterface().isNaN();
}
@Override
public IntToDoubleFunction getOperator() {
throw new UnsupportedOperationException("Not supported.");
}
@Override
public DoubleStream getRealizationsStream() {
throw new UnsupportedOperationException("Not supported.");
}
@Override
public RandomVariable apply(final DoubleUnaryOperator operator) {
throw new UnsupportedOperationException("Applying functions is not supported.");
}
@Override
public RandomVariable apply(final DoubleBinaryOperator operator, final RandomVariable argument) {
throw new UnsupportedOperationException("Applying functions is not supported.");
}
@Override
public RandomVariable apply(final DoubleTernaryOperator operator, final RandomVariable argument1, final RandomVariable argument2) {
throw new UnsupportedOperationException("Applying functions is not supported.");
}
}
| 0 | 0.898033 | 1 | 0.898033 | game-dev | MEDIA | 0.377389 | game-dev | 0.896162 | 1 | 0.896162 |
gomint/gomint | 1,468 | gomint-server/src/main/java/io/gomint/server/enchant/EnchantmentBlastProtection.java | /*
* Copyright (c) 2020, GoMint, BlackyPaw and geNAZt
*
* This code is licensed under the BSD license found in the
* LICENSE file in the root directory of this source tree.
*/
package io.gomint.server.enchant;
import io.gomint.enchant.Rarity;
import io.gomint.server.inventory.item.ItemStack;
import io.gomint.server.registry.RegisterInfo;
/**
* @author geNAZt
* @version 1.0
*/
@RegisterInfo( id = 3 )
public class EnchantmentBlastProtection extends Enchantment implements io.gomint.enchant.EnchantmentBlastProtection {
/**
* Create new enchantment blast protection
*/
public EnchantmentBlastProtection() {
super( (short) 4 );
}
@Override
public int minEnchantAbility( short level ) {
return (byte) ( 5 + ( level - 1 ) * 8 );
}
@Override
public int maxEnchantAbility( short level ) {
return (byte) ( minEnchantAbility( level ) + 12 );
}
@Override
public boolean canBeApplied(ItemStack<?> itemStack ) {
return EnchantmentHelper.canBeAppliedArmor(itemStack);
}
@Override
public Rarity rarity() {
return Rarity.RARE;
}
@Override
public boolean collidesWith(Enchantment enchantment) {
return enchantment instanceof EnchantmentProtection ||
enchantment instanceof EnchantmentFireProtection ||
enchantment instanceof EnchantmentProjectileProtection ||
super.collidesWith(enchantment);
}
}
| 0 | 0.748749 | 1 | 0.748749 | game-dev | MEDIA | 0.702076 | game-dev | 0.631686 | 1 | 0.631686 |
CMU-SAFARI/PiDRAM | 27,149 | fpga-zynq/rocket-chip/riscv-tools/riscv-gnu-toolchain/riscv-qemu/tcg/tci/tcg-target.inc.c | /*
* Tiny Code Generator for QEMU
*
* Copyright (c) 2009, 2011 Stefan Weil
*
* 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 "tcg-be-null.h"
/* TODO list:
* - See TODO comments in code.
*/
/* Marker for missing code. */
#define TODO() \
do { \
fprintf(stderr, "TODO %s:%u: %s()\n", \
__FILE__, __LINE__, __func__); \
tcg_abort(); \
} while (0)
/* Bitfield n...m (in 32 bit value). */
#define BITS(n, m) (((0xffffffffU << (31 - n)) >> (31 - n + m)) << m)
/* Macros used in tcg_target_op_defs. */
#define R "r"
#define RI "ri"
#if TCG_TARGET_REG_BITS == 32
# define R64 "r", "r"
#else
# define R64 "r"
#endif
#if TARGET_LONG_BITS > TCG_TARGET_REG_BITS
# define L "L", "L"
# define S "S", "S"
#else
# define L "L"
# define S "S"
#endif
/* TODO: documentation. */
static const TCGTargetOpDef tcg_target_op_defs[] = {
{ INDEX_op_exit_tb, { NULL } },
{ INDEX_op_goto_tb, { NULL } },
{ INDEX_op_br, { NULL } },
{ INDEX_op_ld8u_i32, { R, R } },
{ INDEX_op_ld8s_i32, { R, R } },
{ INDEX_op_ld16u_i32, { R, R } },
{ INDEX_op_ld16s_i32, { R, R } },
{ INDEX_op_ld_i32, { R, R } },
{ INDEX_op_st8_i32, { R, R } },
{ INDEX_op_st16_i32, { R, R } },
{ INDEX_op_st_i32, { R, R } },
{ INDEX_op_add_i32, { R, RI, RI } },
{ INDEX_op_sub_i32, { R, RI, RI } },
{ INDEX_op_mul_i32, { R, RI, RI } },
#if TCG_TARGET_HAS_div_i32
{ INDEX_op_div_i32, { R, R, R } },
{ INDEX_op_divu_i32, { R, R, R } },
{ INDEX_op_rem_i32, { R, R, R } },
{ INDEX_op_remu_i32, { R, R, R } },
#elif TCG_TARGET_HAS_div2_i32
{ INDEX_op_div2_i32, { R, R, "0", "1", R } },
{ INDEX_op_divu2_i32, { R, R, "0", "1", R } },
#endif
/* TODO: Does R, RI, RI result in faster code than R, R, RI?
If both operands are constants, we can optimize. */
{ INDEX_op_and_i32, { R, RI, RI } },
#if TCG_TARGET_HAS_andc_i32
{ INDEX_op_andc_i32, { R, RI, RI } },
#endif
#if TCG_TARGET_HAS_eqv_i32
{ INDEX_op_eqv_i32, { R, RI, RI } },
#endif
#if TCG_TARGET_HAS_nand_i32
{ INDEX_op_nand_i32, { R, RI, RI } },
#endif
#if TCG_TARGET_HAS_nor_i32
{ INDEX_op_nor_i32, { R, RI, RI } },
#endif
{ INDEX_op_or_i32, { R, RI, RI } },
#if TCG_TARGET_HAS_orc_i32
{ INDEX_op_orc_i32, { R, RI, RI } },
#endif
{ INDEX_op_xor_i32, { R, RI, RI } },
{ INDEX_op_shl_i32, { R, RI, RI } },
{ INDEX_op_shr_i32, { R, RI, RI } },
{ INDEX_op_sar_i32, { R, RI, RI } },
#if TCG_TARGET_HAS_rot_i32
{ INDEX_op_rotl_i32, { R, RI, RI } },
{ INDEX_op_rotr_i32, { R, RI, RI } },
#endif
#if TCG_TARGET_HAS_deposit_i32
{ INDEX_op_deposit_i32, { R, "0", R } },
#endif
{ INDEX_op_brcond_i32, { R, RI } },
{ INDEX_op_setcond_i32, { R, R, RI } },
#if TCG_TARGET_REG_BITS == 64
{ INDEX_op_setcond_i64, { R, R, RI } },
#endif /* TCG_TARGET_REG_BITS == 64 */
#if TCG_TARGET_REG_BITS == 32
/* TODO: Support R, R, R, R, RI, RI? Will it be faster? */
{ INDEX_op_add2_i32, { R, R, R, R, R, R } },
{ INDEX_op_sub2_i32, { R, R, R, R, R, R } },
{ INDEX_op_brcond2_i32, { R, R, RI, RI } },
{ INDEX_op_mulu2_i32, { R, R, R, R } },
{ INDEX_op_setcond2_i32, { R, R, R, RI, RI } },
#endif
#if TCG_TARGET_HAS_not_i32
{ INDEX_op_not_i32, { R, R } },
#endif
#if TCG_TARGET_HAS_neg_i32
{ INDEX_op_neg_i32, { R, R } },
#endif
#if TCG_TARGET_REG_BITS == 64
{ INDEX_op_ld8u_i64, { R, R } },
{ INDEX_op_ld8s_i64, { R, R } },
{ INDEX_op_ld16u_i64, { R, R } },
{ INDEX_op_ld16s_i64, { R, R } },
{ INDEX_op_ld32u_i64, { R, R } },
{ INDEX_op_ld32s_i64, { R, R } },
{ INDEX_op_ld_i64, { R, R } },
{ INDEX_op_st8_i64, { R, R } },
{ INDEX_op_st16_i64, { R, R } },
{ INDEX_op_st32_i64, { R, R } },
{ INDEX_op_st_i64, { R, R } },
{ INDEX_op_add_i64, { R, RI, RI } },
{ INDEX_op_sub_i64, { R, RI, RI } },
{ INDEX_op_mul_i64, { R, RI, RI } },
#if TCG_TARGET_HAS_div_i64
{ INDEX_op_div_i64, { R, R, R } },
{ INDEX_op_divu_i64, { R, R, R } },
{ INDEX_op_rem_i64, { R, R, R } },
{ INDEX_op_remu_i64, { R, R, R } },
#elif TCG_TARGET_HAS_div2_i64
{ INDEX_op_div2_i64, { R, R, "0", "1", R } },
{ INDEX_op_divu2_i64, { R, R, "0", "1", R } },
#endif
{ INDEX_op_and_i64, { R, RI, RI } },
#if TCG_TARGET_HAS_andc_i64
{ INDEX_op_andc_i64, { R, RI, RI } },
#endif
#if TCG_TARGET_HAS_eqv_i64
{ INDEX_op_eqv_i64, { R, RI, RI } },
#endif
#if TCG_TARGET_HAS_nand_i64
{ INDEX_op_nand_i64, { R, RI, RI } },
#endif
#if TCG_TARGET_HAS_nor_i64
{ INDEX_op_nor_i64, { R, RI, RI } },
#endif
{ INDEX_op_or_i64, { R, RI, RI } },
#if TCG_TARGET_HAS_orc_i64
{ INDEX_op_orc_i64, { R, RI, RI } },
#endif
{ INDEX_op_xor_i64, { R, RI, RI } },
{ INDEX_op_shl_i64, { R, RI, RI } },
{ INDEX_op_shr_i64, { R, RI, RI } },
{ INDEX_op_sar_i64, { R, RI, RI } },
#if TCG_TARGET_HAS_rot_i64
{ INDEX_op_rotl_i64, { R, RI, RI } },
{ INDEX_op_rotr_i64, { R, RI, RI } },
#endif
#if TCG_TARGET_HAS_deposit_i64
{ INDEX_op_deposit_i64, { R, "0", R } },
#endif
{ INDEX_op_brcond_i64, { R, RI } },
#if TCG_TARGET_HAS_ext8s_i64
{ INDEX_op_ext8s_i64, { R, R } },
#endif
#if TCG_TARGET_HAS_ext16s_i64
{ INDEX_op_ext16s_i64, { R, R } },
#endif
#if TCG_TARGET_HAS_ext32s_i64
{ INDEX_op_ext32s_i64, { R, R } },
#endif
#if TCG_TARGET_HAS_ext8u_i64
{ INDEX_op_ext8u_i64, { R, R } },
#endif
#if TCG_TARGET_HAS_ext16u_i64
{ INDEX_op_ext16u_i64, { R, R } },
#endif
#if TCG_TARGET_HAS_ext32u_i64
{ INDEX_op_ext32u_i64, { R, R } },
#endif
{ INDEX_op_ext_i32_i64, { R, R } },
{ INDEX_op_extu_i32_i64, { R, R } },
#if TCG_TARGET_HAS_bswap16_i64
{ INDEX_op_bswap16_i64, { R, R } },
#endif
#if TCG_TARGET_HAS_bswap32_i64
{ INDEX_op_bswap32_i64, { R, R } },
#endif
#if TCG_TARGET_HAS_bswap64_i64
{ INDEX_op_bswap64_i64, { R, R } },
#endif
#if TCG_TARGET_HAS_not_i64
{ INDEX_op_not_i64, { R, R } },
#endif
#if TCG_TARGET_HAS_neg_i64
{ INDEX_op_neg_i64, { R, R } },
#endif
#endif /* TCG_TARGET_REG_BITS == 64 */
{ INDEX_op_qemu_ld_i32, { R, L } },
{ INDEX_op_qemu_ld_i64, { R64, L } },
{ INDEX_op_qemu_st_i32, { R, S } },
{ INDEX_op_qemu_st_i64, { R64, S } },
#if TCG_TARGET_HAS_ext8s_i32
{ INDEX_op_ext8s_i32, { R, R } },
#endif
#if TCG_TARGET_HAS_ext16s_i32
{ INDEX_op_ext16s_i32, { R, R } },
#endif
#if TCG_TARGET_HAS_ext8u_i32
{ INDEX_op_ext8u_i32, { R, R } },
#endif
#if TCG_TARGET_HAS_ext16u_i32
{ INDEX_op_ext16u_i32, { R, R } },
#endif
#if TCG_TARGET_HAS_bswap16_i32
{ INDEX_op_bswap16_i32, { R, R } },
#endif
#if TCG_TARGET_HAS_bswap32_i32
{ INDEX_op_bswap32_i32, { R, R } },
#endif
{ INDEX_op_mb, { } },
{ -1 },
};
static const int tcg_target_reg_alloc_order[] = {
TCG_REG_R0,
TCG_REG_R1,
TCG_REG_R2,
TCG_REG_R3,
#if 0 /* used for TCG_REG_CALL_STACK */
TCG_REG_R4,
#endif
TCG_REG_R5,
TCG_REG_R6,
TCG_REG_R7,
#if TCG_TARGET_NB_REGS >= 16
TCG_REG_R8,
TCG_REG_R9,
TCG_REG_R10,
TCG_REG_R11,
TCG_REG_R12,
TCG_REG_R13,
TCG_REG_R14,
TCG_REG_R15,
#endif
};
#if MAX_OPC_PARAM_IARGS != 5
# error Fix needed, number of supported input arguments changed!
#endif
static const int tcg_target_call_iarg_regs[] = {
TCG_REG_R0,
TCG_REG_R1,
TCG_REG_R2,
TCG_REG_R3,
#if 0 /* used for TCG_REG_CALL_STACK */
TCG_REG_R4,
#endif
TCG_REG_R5,
#if TCG_TARGET_REG_BITS == 32
/* 32 bit hosts need 2 * MAX_OPC_PARAM_IARGS registers. */
TCG_REG_R6,
TCG_REG_R7,
#if TCG_TARGET_NB_REGS >= 16
TCG_REG_R8,
TCG_REG_R9,
TCG_REG_R10,
#else
# error Too few input registers available
#endif
#endif
};
static const int tcg_target_call_oarg_regs[] = {
TCG_REG_R0,
#if TCG_TARGET_REG_BITS == 32
TCG_REG_R1
#endif
};
#ifdef CONFIG_DEBUG_TCG
static const char *const tcg_target_reg_names[TCG_TARGET_NB_REGS] = {
"r00",
"r01",
"r02",
"r03",
"r04",
"r05",
"r06",
"r07",
#if TCG_TARGET_NB_REGS >= 16
"r08",
"r09",
"r10",
"r11",
"r12",
"r13",
"r14",
"r15",
#if TCG_TARGET_NB_REGS >= 32
"r16",
"r17",
"r18",
"r19",
"r20",
"r21",
"r22",
"r23",
"r24",
"r25",
"r26",
"r27",
"r28",
"r29",
"r30",
"r31"
#endif
#endif
};
#endif
static void patch_reloc(tcg_insn_unit *code_ptr, int type,
intptr_t value, intptr_t addend)
{
/* tcg_out_reloc always uses the same type, addend. */
tcg_debug_assert(type == sizeof(tcg_target_long));
tcg_debug_assert(addend == 0);
tcg_debug_assert(value != 0);
if (TCG_TARGET_REG_BITS == 32) {
tcg_patch32(code_ptr, value);
} else {
tcg_patch64(code_ptr, value);
}
}
/* Parse target specific constraints. */
static int target_parse_constraint(TCGArgConstraint *ct, const char **pct_str)
{
const char *ct_str = *pct_str;
switch (ct_str[0]) {
case 'r':
case 'L': /* qemu_ld constraint */
case 'S': /* qemu_st constraint */
ct->ct |= TCG_CT_REG;
tcg_regset_set32(ct->u.regs, 0, BIT(TCG_TARGET_NB_REGS) - 1);
break;
default:
return -1;
}
ct_str++;
*pct_str = ct_str;
return 0;
}
#if defined(CONFIG_DEBUG_TCG_INTERPRETER)
/* Show current bytecode. Used by tcg interpreter. */
void tci_disas(uint8_t opc)
{
const TCGOpDef *def = &tcg_op_defs[opc];
fprintf(stderr, "TCG %s %u, %u, %u\n",
def->name, def->nb_oargs, def->nb_iargs, def->nb_cargs);
}
#endif
/* Write value (native size). */
static void tcg_out_i(TCGContext *s, tcg_target_ulong v)
{
if (TCG_TARGET_REG_BITS == 32) {
tcg_out32(s, v);
} else {
tcg_out64(s, v);
}
}
/* Write opcode. */
static void tcg_out_op_t(TCGContext *s, TCGOpcode op)
{
tcg_out8(s, op);
tcg_out8(s, 0);
}
/* Write register. */
static void tcg_out_r(TCGContext *s, TCGArg t0)
{
tcg_debug_assert(t0 < TCG_TARGET_NB_REGS);
tcg_out8(s, t0);
}
/* Write register or constant (native size). */
static void tcg_out_ri(TCGContext *s, int const_arg, TCGArg arg)
{
if (const_arg) {
tcg_debug_assert(const_arg == 1);
tcg_out8(s, TCG_CONST);
tcg_out_i(s, arg);
} else {
tcg_out_r(s, arg);
}
}
/* Write register or constant (32 bit). */
static void tcg_out_ri32(TCGContext *s, int const_arg, TCGArg arg)
{
if (const_arg) {
tcg_debug_assert(const_arg == 1);
tcg_out8(s, TCG_CONST);
tcg_out32(s, arg);
} else {
tcg_out_r(s, arg);
}
}
#if TCG_TARGET_REG_BITS == 64
/* Write register or constant (64 bit). */
static void tcg_out_ri64(TCGContext *s, int const_arg, TCGArg arg)
{
if (const_arg) {
tcg_debug_assert(const_arg == 1);
tcg_out8(s, TCG_CONST);
tcg_out64(s, arg);
} else {
tcg_out_r(s, arg);
}
}
#endif
/* Write label. */
static void tci_out_label(TCGContext *s, TCGLabel *label)
{
if (label->has_value) {
tcg_out_i(s, label->u.value);
tcg_debug_assert(label->u.value);
} else {
tcg_out_reloc(s, s->code_ptr, sizeof(tcg_target_ulong), label, 0);
s->code_ptr += sizeof(tcg_target_ulong);
}
}
static void tcg_out_ld(TCGContext *s, TCGType type, TCGReg ret, TCGReg arg1,
intptr_t arg2)
{
uint8_t *old_code_ptr = s->code_ptr;
if (type == TCG_TYPE_I32) {
tcg_out_op_t(s, INDEX_op_ld_i32);
tcg_out_r(s, ret);
tcg_out_r(s, arg1);
tcg_out32(s, arg2);
} else {
tcg_debug_assert(type == TCG_TYPE_I64);
#if TCG_TARGET_REG_BITS == 64
tcg_out_op_t(s, INDEX_op_ld_i64);
tcg_out_r(s, ret);
tcg_out_r(s, arg1);
tcg_debug_assert(arg2 == (int32_t)arg2);
tcg_out32(s, arg2);
#else
TODO();
#endif
}
old_code_ptr[1] = s->code_ptr - old_code_ptr;
}
static void tcg_out_mov(TCGContext *s, TCGType type, TCGReg ret, TCGReg arg)
{
uint8_t *old_code_ptr = s->code_ptr;
tcg_debug_assert(ret != arg);
#if TCG_TARGET_REG_BITS == 32
tcg_out_op_t(s, INDEX_op_mov_i32);
#else
tcg_out_op_t(s, INDEX_op_mov_i64);
#endif
tcg_out_r(s, ret);
tcg_out_r(s, arg);
old_code_ptr[1] = s->code_ptr - old_code_ptr;
}
static void tcg_out_movi(TCGContext *s, TCGType type,
TCGReg t0, tcg_target_long arg)
{
uint8_t *old_code_ptr = s->code_ptr;
uint32_t arg32 = arg;
if (type == TCG_TYPE_I32 || arg == arg32) {
tcg_out_op_t(s, INDEX_op_movi_i32);
tcg_out_r(s, t0);
tcg_out32(s, arg32);
} else {
tcg_debug_assert(type == TCG_TYPE_I64);
#if TCG_TARGET_REG_BITS == 64
tcg_out_op_t(s, INDEX_op_movi_i64);
tcg_out_r(s, t0);
tcg_out64(s, arg);
#else
TODO();
#endif
}
old_code_ptr[1] = s->code_ptr - old_code_ptr;
}
static inline void tcg_out_call(TCGContext *s, tcg_insn_unit *arg)
{
uint8_t *old_code_ptr = s->code_ptr;
tcg_out_op_t(s, INDEX_op_call);
tcg_out_ri(s, 1, (uintptr_t)arg);
old_code_ptr[1] = s->code_ptr - old_code_ptr;
}
static void tcg_out_op(TCGContext *s, TCGOpcode opc, const TCGArg *args,
const int *const_args)
{
uint8_t *old_code_ptr = s->code_ptr;
tcg_out_op_t(s, opc);
switch (opc) {
case INDEX_op_exit_tb:
tcg_out64(s, args[0]);
break;
case INDEX_op_goto_tb:
if (s->tb_jmp_insn_offset) {
/* Direct jump method. */
tcg_debug_assert(args[0] < ARRAY_SIZE(s->tb_jmp_insn_offset));
/* Align for atomic patching and thread safety */
s->code_ptr = QEMU_ALIGN_PTR_UP(s->code_ptr, 4);
s->tb_jmp_insn_offset[args[0]] = tcg_current_code_size(s);
tcg_out32(s, 0);
} else {
/* Indirect jump method. */
TODO();
}
tcg_debug_assert(args[0] < ARRAY_SIZE(s->tb_jmp_reset_offset));
s->tb_jmp_reset_offset[args[0]] = tcg_current_code_size(s);
break;
case INDEX_op_br:
tci_out_label(s, arg_label(args[0]));
break;
case INDEX_op_setcond_i32:
tcg_out_r(s, args[0]);
tcg_out_r(s, args[1]);
tcg_out_ri32(s, const_args[2], args[2]);
tcg_out8(s, args[3]); /* condition */
break;
#if TCG_TARGET_REG_BITS == 32
case INDEX_op_setcond2_i32:
/* setcond2_i32 cond, t0, t1_low, t1_high, t2_low, t2_high */
tcg_out_r(s, args[0]);
tcg_out_r(s, args[1]);
tcg_out_r(s, args[2]);
tcg_out_ri32(s, const_args[3], args[3]);
tcg_out_ri32(s, const_args[4], args[4]);
tcg_out8(s, args[5]); /* condition */
break;
#elif TCG_TARGET_REG_BITS == 64
case INDEX_op_setcond_i64:
tcg_out_r(s, args[0]);
tcg_out_r(s, args[1]);
tcg_out_ri64(s, const_args[2], args[2]);
tcg_out8(s, args[3]); /* condition */
break;
#endif
case INDEX_op_ld8u_i32:
case INDEX_op_ld8s_i32:
case INDEX_op_ld16u_i32:
case INDEX_op_ld16s_i32:
case INDEX_op_ld_i32:
case INDEX_op_st8_i32:
case INDEX_op_st16_i32:
case INDEX_op_st_i32:
case INDEX_op_ld8u_i64:
case INDEX_op_ld8s_i64:
case INDEX_op_ld16u_i64:
case INDEX_op_ld16s_i64:
case INDEX_op_ld32u_i64:
case INDEX_op_ld32s_i64:
case INDEX_op_ld_i64:
case INDEX_op_st8_i64:
case INDEX_op_st16_i64:
case INDEX_op_st32_i64:
case INDEX_op_st_i64:
tcg_out_r(s, args[0]);
tcg_out_r(s, args[1]);
tcg_debug_assert(args[2] == (int32_t)args[2]);
tcg_out32(s, args[2]);
break;
case INDEX_op_add_i32:
case INDEX_op_sub_i32:
case INDEX_op_mul_i32:
case INDEX_op_and_i32:
case INDEX_op_andc_i32: /* Optional (TCG_TARGET_HAS_andc_i32). */
case INDEX_op_eqv_i32: /* Optional (TCG_TARGET_HAS_eqv_i32). */
case INDEX_op_nand_i32: /* Optional (TCG_TARGET_HAS_nand_i32). */
case INDEX_op_nor_i32: /* Optional (TCG_TARGET_HAS_nor_i32). */
case INDEX_op_or_i32:
case INDEX_op_orc_i32: /* Optional (TCG_TARGET_HAS_orc_i32). */
case INDEX_op_xor_i32:
case INDEX_op_shl_i32:
case INDEX_op_shr_i32:
case INDEX_op_sar_i32:
case INDEX_op_rotl_i32: /* Optional (TCG_TARGET_HAS_rot_i32). */
case INDEX_op_rotr_i32: /* Optional (TCG_TARGET_HAS_rot_i32). */
tcg_out_r(s, args[0]);
tcg_out_ri32(s, const_args[1], args[1]);
tcg_out_ri32(s, const_args[2], args[2]);
break;
case INDEX_op_deposit_i32: /* Optional (TCG_TARGET_HAS_deposit_i32). */
tcg_out_r(s, args[0]);
tcg_out_r(s, args[1]);
tcg_out_r(s, args[2]);
tcg_debug_assert(args[3] <= UINT8_MAX);
tcg_out8(s, args[3]);
tcg_debug_assert(args[4] <= UINT8_MAX);
tcg_out8(s, args[4]);
break;
#if TCG_TARGET_REG_BITS == 64
case INDEX_op_add_i64:
case INDEX_op_sub_i64:
case INDEX_op_mul_i64:
case INDEX_op_and_i64:
case INDEX_op_andc_i64: /* Optional (TCG_TARGET_HAS_andc_i64). */
case INDEX_op_eqv_i64: /* Optional (TCG_TARGET_HAS_eqv_i64). */
case INDEX_op_nand_i64: /* Optional (TCG_TARGET_HAS_nand_i64). */
case INDEX_op_nor_i64: /* Optional (TCG_TARGET_HAS_nor_i64). */
case INDEX_op_or_i64:
case INDEX_op_orc_i64: /* Optional (TCG_TARGET_HAS_orc_i64). */
case INDEX_op_xor_i64:
case INDEX_op_shl_i64:
case INDEX_op_shr_i64:
case INDEX_op_sar_i64:
case INDEX_op_rotl_i64: /* Optional (TCG_TARGET_HAS_rot_i64). */
case INDEX_op_rotr_i64: /* Optional (TCG_TARGET_HAS_rot_i64). */
tcg_out_r(s, args[0]);
tcg_out_ri64(s, const_args[1], args[1]);
tcg_out_ri64(s, const_args[2], args[2]);
break;
case INDEX_op_deposit_i64: /* Optional (TCG_TARGET_HAS_deposit_i64). */
tcg_out_r(s, args[0]);
tcg_out_r(s, args[1]);
tcg_out_r(s, args[2]);
tcg_debug_assert(args[3] <= UINT8_MAX);
tcg_out8(s, args[3]);
tcg_debug_assert(args[4] <= UINT8_MAX);
tcg_out8(s, args[4]);
break;
case INDEX_op_div_i64: /* Optional (TCG_TARGET_HAS_div_i64). */
case INDEX_op_divu_i64: /* Optional (TCG_TARGET_HAS_div_i64). */
case INDEX_op_rem_i64: /* Optional (TCG_TARGET_HAS_div_i64). */
case INDEX_op_remu_i64: /* Optional (TCG_TARGET_HAS_div_i64). */
TODO();
break;
case INDEX_op_div2_i64: /* Optional (TCG_TARGET_HAS_div2_i64). */
case INDEX_op_divu2_i64: /* Optional (TCG_TARGET_HAS_div2_i64). */
TODO();
break;
case INDEX_op_brcond_i64:
tcg_out_r(s, args[0]);
tcg_out_ri64(s, const_args[1], args[1]);
tcg_out8(s, args[2]); /* condition */
tci_out_label(s, arg_label(args[3]));
break;
case INDEX_op_bswap16_i64: /* Optional (TCG_TARGET_HAS_bswap16_i64). */
case INDEX_op_bswap32_i64: /* Optional (TCG_TARGET_HAS_bswap32_i64). */
case INDEX_op_bswap64_i64: /* Optional (TCG_TARGET_HAS_bswap64_i64). */
case INDEX_op_not_i64: /* Optional (TCG_TARGET_HAS_not_i64). */
case INDEX_op_neg_i64: /* Optional (TCG_TARGET_HAS_neg_i64). */
case INDEX_op_ext8s_i64: /* Optional (TCG_TARGET_HAS_ext8s_i64). */
case INDEX_op_ext8u_i64: /* Optional (TCG_TARGET_HAS_ext8u_i64). */
case INDEX_op_ext16s_i64: /* Optional (TCG_TARGET_HAS_ext16s_i64). */
case INDEX_op_ext16u_i64: /* Optional (TCG_TARGET_HAS_ext16u_i64). */
case INDEX_op_ext32s_i64: /* Optional (TCG_TARGET_HAS_ext32s_i64). */
case INDEX_op_ext32u_i64: /* Optional (TCG_TARGET_HAS_ext32u_i64). */
case INDEX_op_ext_i32_i64:
case INDEX_op_extu_i32_i64:
#endif /* TCG_TARGET_REG_BITS == 64 */
case INDEX_op_neg_i32: /* Optional (TCG_TARGET_HAS_neg_i32). */
case INDEX_op_not_i32: /* Optional (TCG_TARGET_HAS_not_i32). */
case INDEX_op_ext8s_i32: /* Optional (TCG_TARGET_HAS_ext8s_i32). */
case INDEX_op_ext16s_i32: /* Optional (TCG_TARGET_HAS_ext16s_i32). */
case INDEX_op_ext8u_i32: /* Optional (TCG_TARGET_HAS_ext8u_i32). */
case INDEX_op_ext16u_i32: /* Optional (TCG_TARGET_HAS_ext16u_i32). */
case INDEX_op_bswap16_i32: /* Optional (TCG_TARGET_HAS_bswap16_i32). */
case INDEX_op_bswap32_i32: /* Optional (TCG_TARGET_HAS_bswap32_i32). */
tcg_out_r(s, args[0]);
tcg_out_r(s, args[1]);
break;
case INDEX_op_div_i32: /* Optional (TCG_TARGET_HAS_div_i32). */
case INDEX_op_divu_i32: /* Optional (TCG_TARGET_HAS_div_i32). */
case INDEX_op_rem_i32: /* Optional (TCG_TARGET_HAS_div_i32). */
case INDEX_op_remu_i32: /* Optional (TCG_TARGET_HAS_div_i32). */
tcg_out_r(s, args[0]);
tcg_out_ri32(s, const_args[1], args[1]);
tcg_out_ri32(s, const_args[2], args[2]);
break;
case INDEX_op_div2_i32: /* Optional (TCG_TARGET_HAS_div2_i32). */
case INDEX_op_divu2_i32: /* Optional (TCG_TARGET_HAS_div2_i32). */
TODO();
break;
#if TCG_TARGET_REG_BITS == 32
case INDEX_op_add2_i32:
case INDEX_op_sub2_i32:
tcg_out_r(s, args[0]);
tcg_out_r(s, args[1]);
tcg_out_r(s, args[2]);
tcg_out_r(s, args[3]);
tcg_out_r(s, args[4]);
tcg_out_r(s, args[5]);
break;
case INDEX_op_brcond2_i32:
tcg_out_r(s, args[0]);
tcg_out_r(s, args[1]);
tcg_out_ri32(s, const_args[2], args[2]);
tcg_out_ri32(s, const_args[3], args[3]);
tcg_out8(s, args[4]); /* condition */
tci_out_label(s, arg_label(args[5]));
break;
case INDEX_op_mulu2_i32:
tcg_out_r(s, args[0]);
tcg_out_r(s, args[1]);
tcg_out_r(s, args[2]);
tcg_out_r(s, args[3]);
break;
#endif
case INDEX_op_brcond_i32:
tcg_out_r(s, args[0]);
tcg_out_ri32(s, const_args[1], args[1]);
tcg_out8(s, args[2]); /* condition */
tci_out_label(s, arg_label(args[3]));
break;
case INDEX_op_qemu_ld_i32:
tcg_out_r(s, *args++);
tcg_out_r(s, *args++);
if (TARGET_LONG_BITS > TCG_TARGET_REG_BITS) {
tcg_out_r(s, *args++);
}
tcg_out_i(s, *args++);
break;
case INDEX_op_qemu_ld_i64:
tcg_out_r(s, *args++);
if (TCG_TARGET_REG_BITS == 32) {
tcg_out_r(s, *args++);
}
tcg_out_r(s, *args++);
if (TARGET_LONG_BITS > TCG_TARGET_REG_BITS) {
tcg_out_r(s, *args++);
}
tcg_out_i(s, *args++);
break;
case INDEX_op_qemu_st_i32:
tcg_out_r(s, *args++);
tcg_out_r(s, *args++);
if (TARGET_LONG_BITS > TCG_TARGET_REG_BITS) {
tcg_out_r(s, *args++);
}
tcg_out_i(s, *args++);
break;
case INDEX_op_qemu_st_i64:
tcg_out_r(s, *args++);
if (TCG_TARGET_REG_BITS == 32) {
tcg_out_r(s, *args++);
}
tcg_out_r(s, *args++);
if (TARGET_LONG_BITS > TCG_TARGET_REG_BITS) {
tcg_out_r(s, *args++);
}
tcg_out_i(s, *args++);
break;
case INDEX_op_mb:
break;
case INDEX_op_mov_i32: /* Always emitted via tcg_out_mov. */
case INDEX_op_mov_i64:
case INDEX_op_movi_i32: /* Always emitted via tcg_out_movi. */
case INDEX_op_movi_i64:
case INDEX_op_call: /* Always emitted via tcg_out_call. */
default:
tcg_abort();
}
old_code_ptr[1] = s->code_ptr - old_code_ptr;
}
static void tcg_out_st(TCGContext *s, TCGType type, TCGReg arg, TCGReg arg1,
intptr_t arg2)
{
uint8_t *old_code_ptr = s->code_ptr;
if (type == TCG_TYPE_I32) {
tcg_out_op_t(s, INDEX_op_st_i32);
tcg_out_r(s, arg);
tcg_out_r(s, arg1);
tcg_out32(s, arg2);
} else {
tcg_debug_assert(type == TCG_TYPE_I64);
#if TCG_TARGET_REG_BITS == 64
tcg_out_op_t(s, INDEX_op_st_i64);
tcg_out_r(s, arg);
tcg_out_r(s, arg1);
tcg_out32(s, arg2);
#else
TODO();
#endif
}
old_code_ptr[1] = s->code_ptr - old_code_ptr;
}
static inline bool tcg_out_sti(TCGContext *s, TCGType type, TCGArg val,
TCGReg base, intptr_t ofs)
{
return false;
}
/* Test if a constant matches the constraint. */
static int tcg_target_const_match(tcg_target_long val, TCGType type,
const TCGArgConstraint *arg_ct)
{
/* No need to return 0 or 1, 0 or != 0 is good enough. */
return arg_ct->ct & TCG_CT_CONST;
}
static void tcg_target_init(TCGContext *s)
{
#if defined(CONFIG_DEBUG_TCG_INTERPRETER)
const char *envval = getenv("DEBUG_TCG");
if (envval) {
qemu_set_log(strtol(envval, NULL, 0));
}
#endif
/* The current code uses uint8_t for tcg operations. */
tcg_debug_assert(tcg_op_defs_max <= UINT8_MAX);
/* Registers available for 32 bit operations. */
tcg_regset_set32(tcg_target_available_regs[TCG_TYPE_I32], 0,
BIT(TCG_TARGET_NB_REGS) - 1);
/* Registers available for 64 bit operations. */
tcg_regset_set32(tcg_target_available_regs[TCG_TYPE_I64], 0,
BIT(TCG_TARGET_NB_REGS) - 1);
/* TODO: Which registers should be set here? */
tcg_regset_set32(tcg_target_call_clobber_regs, 0,
BIT(TCG_TARGET_NB_REGS) - 1);
tcg_regset_clear(s->reserved_regs);
tcg_regset_set_reg(s->reserved_regs, TCG_REG_CALL_STACK);
tcg_add_target_add_op_defs(tcg_target_op_defs);
/* We use negative offsets from "sp" so that we can distinguish
stores that might pretend to be call arguments. */
tcg_set_frame(s, TCG_REG_CALL_STACK,
-CPU_TEMP_BUF_NLONGS * sizeof(long),
CPU_TEMP_BUF_NLONGS * sizeof(long));
}
/* Generate global QEMU prologue and epilogue code. */
static inline void tcg_target_qemu_prologue(TCGContext *s)
{
}
| 0 | 0.866116 | 1 | 0.866116 | game-dev | MEDIA | 0.201642 | game-dev | 0.873464 | 1 | 0.873464 |
daid/EmptyEpsilon | 401,585 | scripts/scenario_88_chaos.lua | -- Name: Chaos of War
-- Description: Two, three or four species battle for ultimate dominion. Designed as a replayable player versus player (PVP) scenario for individuals or teams. Terrain is randomly symmetrically generated for every game.
---
--- Use Gamemaster (GM) screen to adjust parameters. The GM screen covers all of the parameters on the next page plus a variety of others.
---
--- Get the player ship access codes from the GM screen after you generate the terrain
---
--- Version 2.2
-- Type: PvP
-- Setting[Difficulty]: Determines the degree the environment helps or hinders the players
-- Difficulty[Normal|Default]: Normal difficulty
-- Difficulty[Easy]: More resources, services and reputation
-- Difficulty[Hard]: Fewer resources, services and reputation
-- Setting[Teams]: Number of teams. Each team may have one or more player ships on it. Default: 2 teams
-- Teams[2|Default]: Two teams
-- Teams[3]: Three teams
-- Teams[4]: Four teams
-- Setting[Players]: Number of player ships per team. 32 total max. Get player ship control codes from Game master screen. Default: 2 per team
-- Players[1]: One player ship per team. Get player ship control codes from Game master screen
-- Players[2|Default]: Two player ships per team. Get player ship control codes from Game master screen
-- Players[3]: Three player ships per team. Get player ship control codes from Game master screen
-- Players[4]: Four player ships per team. Get player ship control codes from Game master screen
-- Players[5]: Five player ships per team. Get player ship control codes from Game master screen
-- Players[6]: Six player ships per team. Get player ship control codes from Game master screen
-- Players[7]: Seven player ships per team. Get player ship control codes from Game master screen
-- Players[8]: Eight player ships per team. Get player ship control codes from Game master screen
-- Players[9]: Nine player ships per team. Get player ship control codes from Game master screen
-- Players[10]: Ten player ships per team. Get player ship control codes from Game master screen
-- Players[11]: Eleven player ships per team. Get player ship control codes from Game master screen
-- Players[12]: Twelve player ships per team. Get player ship control codes from Game master screen
-- Players[13]: Thirteen player ships per team. Get player ship control codes from Game master screen
-- Players[14]: Fourteen player ships per team. Get player ship control codes from Game master screen
-- Players[15]: Fifteen player ships per team. Get player ship control codes from Game master screen
-- Players[16]: Sixteen player ships per team. Get player ship control codes from Game master screen
-- Setting[Respawn]: How a player ship returns to the game after being destroyed. Default: Lindworm
-- Respawn[Lindworm|Default]: Destroyed player returns in a weak, but fast Lindworm
-- Respawn[Self]: Destroyed player returns as the same type of ship they originally started in
-- Setting[Station Sensors]: Determines range at which station sensors will warn friendly ships about enemy ships via messages. Default: 20U
-- Station Sensors[Zero]: Stations don't warn friendly players of enemies
-- Station Sensors[5U]: Stations warn friendly players of enemies within 5 units
-- Station Sensors[10U]: Stations warn friendly players of enemies within 10 units
-- Station Sensors[20U|Default]: Stations warn friendly players of enemies within 20 units
-- Station Sensors[30U]: Stations warn friendly players of enemies within 30 units
-- Setting[Time]: Determines how long the game will last. Default: 50 minutes
-- Time[20]: Game ends in 20 minutes
-- Time[30]: Game ends in 30 minutes
-- Time[40]: Game ends in 40 minutes
-- Time[50|Default]: Game ends in 50 minutes
-- Time[60]: Game ends in 60 minutes (one hour)
-- Time[70]: Game ends in 70 minutes (one hour and 10 minutes)
-- Time[80]: Game ends in 80 minutes (one hour and 20 minutes)
-- Time[90]: Game ends in 90 minutes (one hour and 30 minutes)
-- Time[100]: Game ends in 100 minutes (one hour and 40 minutes)
--------------------------------------------------------------------------------------------------------
-- Note: This script requires a version of supply_drop.lua that handles the variable jump_freighter --
-- See pull request 1185 --
--------------------------------------------------------------------------------------------------------
require("utils.lua")
require("place_station_scenario_utility.lua")
require("generate_call_sign_scenario_utility.lua")
require("cpu_ship_diversification_scenario_utility.lua")
function init()
scenario_version = "2.2.5"
ee_version = "2024.12.08"
print(string.format(" ---- Scenario: Chaos of War ---- Version %s ---- Tested with EE version %s ----",scenario_version,ee_version))
if _VERSION ~= nil then
print("Lua version:",_VERSION)
end
setVariations()
setConstants()
setStaticScienceDatabase()
setGMButtons()
end
function setVariations()
if getEEVersion() == 2021623 then
local svs = getScenarioVariation() --scenario variation string
if string.find(svs,"Easy") then
difficulty = .5
base_reputation = 50
elseif string.find(svs,"Hard") then
difficulty = 2
base_reputation = 10
else
difficulty = 1 --default (normal)
base_reputation = 20
end
else
local enemies = {
["Normal"] ={difficulty = 1, rep = 20},
["Easy"] = {difficulty = .5, rep = 50},
["Hard"] = {difficulty = 2, rep = 10},
}
difficulty = enemies[getScenarioSetting("Difficulty")].difficulty
base_reputation = enemies[getScenarioSetting("Difficulty")].rep
local teams = {
["2"] = 2,
["3"] = 3,
["4"] = 4,
}
player_team_count = teams[getScenarioSetting("Teams")]
local player_count_options = {
["1"] = 1,
["2"] = 2,
["3"] = 3,
["4"] = 4,
["5"] = 5,
["6"] = 6,
["7"] = 7,
["8"] = 8,
["9"] = 9,
["10"] = 10,
["11"] = 11,
["12"] = 12,
["13"] = 13,
["14"] = 14,
["15"] = 15,
["16"] = 16,
}
ships_per_team = player_count_options[getScenarioSetting("Players")]
max_ships_per_team = {32,16,10,8} --engine supports 32 player ships
if ships_per_team > max_ships_per_team[player_team_count] then
ships_per_team = max_ships_per_team[player_team_count]
end
local respawn_options = {
["Lindworm"] = "lindworm",
["Self"] = "self",
}
respawn_type = respawn_options[getScenarioSetting("Respawn")]
local station_sensor_options = {
["Zero"] = 0,
["5U"] = 5000,
["10U"] = 10000,
["20U"] = 20000,
["30U"] = 30000,
}
station_sensor_range = station_sensor_options[getScenarioSetting("Station Sensors")]
game_time_limit = getScenarioSetting("Time")*60
end
end
function setConstants()
thresh = .2 --leading/trailing completion threshold percentage for game
if game_time_limit == nil then
game_time_limit = 45*60
end
if station_sensor_range == nil then
station_sensor_range = 20000
end
if respawn_type == nil then
respawn_type = "lindworm"
end
if ships_per_team == nil then
ships_per_team = 2
player_team_count = 2
end
max_game_time = game_time_limit
game_state = "paused" --then moves to "terrain generated" then to "running"
respawn_count = 0
storage = getScriptStorage()
storage.gatherStats = gatherStats
predefined_player_ships = {
{name = "Damocles", control_code = "SWORD265"},
{name = "Endeavor", control_code = "TRY558"},
{name = "Hyperion", control_code = "SQUIRREL777"},
{name = "Liberty", control_code = "BELL432"},
{name = "Prismatic", control_code = "COLOR180"},
{name = "Visionary", control_code = "EYE909"},
}
f2s = { --faction name to short name
["Human Navy"] = "human",
["Kraylor"] = "kraylor",
["Exuari"] = "exuari",
["Ktlitans"] = "ktlitan",
}
death_penalty = {}
death_penalty["Human Navy"] = 0
death_penalty["Kraylor"] = 0
death_penalty["Exuari"] = 0
death_penalty["Ktlitans"] = 0
terrain_generated = false
advanced_intel = false
missile_availability = "unlimited"
defense_platform_count_index = 10
defense_platform_count_options = {
{count = 0, distance = 0, player = 4500},
{count = 3, distance = 2000, player = 2500},
{count = 4, distance = 2400, player = 3000},
{count = 5, distance = 3000, player = 3500},
{count = 6, distance = 4300, player = 2500},
{count = 8, distance = 7000, player = 4000},
{count = 9, distance = 7800, player = 4500},
{count = 10, distance = 9000, player = 4000},
{count = 12, distance = 10000, player = 4500},
{count = "random", distance = 0, player = 0},
}
dp_comms_data = { --defense platform comms data
weapon_available = {
Homing = random(1,13)<=(3-difficulty),
HVLI = random(1,13)<=(6-difficulty),
Mine = false,
Nuke = false,
EMP = false,
},
services = {
supplydrop = "friend",
reinforcements = "friend",
jumpsupplydrop = "friend",
},
service_cost = {
supplydrop = math.random(80,120),
reinforcements = math.random(125,175),
jumpsupplydrop = math.random(110,140),
},
jump_overcharge = false,
probe_launch_repair = random(1,13)<=(3-difficulty),
hack_repair = random(1,13)<=(3-difficulty),
scan_repair = random(1,13)<=(3-difficulty),
combat_maneuver_repair= random(1,13)<=(3-difficulty),
self_destruct_repair = random(1,13)<=(3-difficulty),
tube_slow_down_repair = random(1,13)<=(3-difficulty),
reputation_cost_multipliers = {
friend = 1.0,
neutral = 3.0,
},
goods = {},
trade = {},
}
defense_fleet_list = {
["Small Station"] = {
{DF1 = "MT52 Hornet",DF2 = "MU52 Hornet",DF3 = "MT52 Hornet",DF4 = "MU52 Hornet",},
{DF1 = "MT52 Hornet",DF2 = "MT52 Hornet",DF3 = "MT52 Hornet",DF4 = "MU52 Hornet",},
{DF1 = "MT52 Hornet",DF2 = "MU52 Hornet",DF3 = "MU52 Hornet",DF4 = "Nirvana R5A",},
},
["Medium Station"] = {
{DF1 = "Adder MK5",DF2 = "MU52 Hornet",DF3 = "MT52 Hornet",DF4 = "Adder MK4",DF5 = "Adder MK6",},
{DF1 = "Adder MK5",DF2 = "MU52 Hornet",DF3 = "Nirvana R5A",DF4 = "Adder MK4",DF5 = "Adder MK6",},
{DF1 = "Adder MK5",DF2 = "MU52 Hornet",DF3 = "Nirvana R5A",DF4 = "WX-Lindworm",DF5 = "Adder MK6",},
},
["Large Station"] = {
{DF1 = "Adder MK5",DF2 = "MU52 Hornet",DF3 = "MT52 Hornet",DF4 = "Adder MK4",DF5 = "Adder MK6",DF6 = "Phobos T3",DF7 = "Adder MK7",DF8 = "Adder MK8",},
{DF1 = "Adder MK5",DF2 = "MU52 Hornet",DF3 = "Adder MK9",DF4 = "Adder MK4",DF5 = "Adder MK6",DF6 = "Phobos T3",DF7 = "Adder MK7",DF8 = "Adder MK8",},
{DF1 = "Adder MK5",DF2 = "MU52 Hornet",DF3 = "Nirvana R5A",DF4 = "Adder MK4",DF5 = "Adder MK6",DF6 = "Phobos T3",DF7 = "Adder MK7",DF8 = "Adder MK8",},
},
["Huge Station"] = {
{DF1 = "Adder MK5",DF2 = "MU52 Hornet",DF3 = "MT52 Hornet",DF4 = "Adder MK4",DF5 = "Adder MK6",DF6 = "Phobos T3",DF7 = "Adder MK7",DF8 = "Adder MK8",DF9 = "Fiend G4",DF10 = "Stalker R7",DF11 = "Stalker Q7"},
{DF1 = "Adder MK5",DF2 = "MU52 Hornet",DF3 = "Nirvana R5A",DF4 = "Adder MK4",DF5 = "Adder MK6",DF6 = "Phobos T3",DF7 = "Adder MK7",DF8 = "Adder MK8",DF9 = "Fiend G4",DF10 = "Stalker R7",DF11 = "Stalker Q7"},
{DF1 = "Adder MK5",DF2 = "MU52 Hornet",DF3 = "Phobos T3",DF4 = "Adder MK4",DF5 = "Adder MK6",DF6 = "Phobos T3",DF7 = "Adder MK7",DF8 = "Adder MK8",DF9 = "Fiend G4",DF10 = "Stalker R7",DF11 = "Stalker Q7"},
},
}
station_list = {}
primary_station_size_index = 1
primary_station_size_options = {"random","Small Station","Medium Station","Large Station","Huge Station"}
primary_jammers = "random"
player_ship_types = "default"
custom_player_ship_type = "Heavy"
default_player_ship_sets = {
{"Crucible"},
{"Maverick","Flavia P.Falcon"},
{"Atlantis","Phobos M3P","Crucible"},
{"Atlantis","Maverick","Phobos M3P","Flavia P.Falcon"},
{"Atlantis","Player Cruiser","Maverick","Crucible","Phobos M3P"},
{"Atlantis","Hathcock","Flavia P.Falcon","Player Missile Cr.","Maverick","Phobos M3P"},
{"Atlantis","Repulse","Maverick","Player Missile Cr.","Phobos M3P","Flavia P.Falcon","Crucible"},
{"Atlantis","Player Cruiser","Hathcock","Player Fighter","Phobos M3P","Maverick","Crucible","Flavia P.Falcon"},
{"Atlantis","Player Cruiser","Repulse","Player Missile Cr.","Player Fighter","Phobos M3P","Crucible","Flavia P.Falcon","Maverick"},
{"Atlantis","Player Cruiser","Piranha","Player Missile Cr.","Player Fighter","Phobos M3P","Crucible","Flavia P.Falcon","Maverick","Phobos M3P"},
{"Atlantis","Player Cruiser","Hathcock","Repulse","Player Fighter","Player Missile Cr.","Crucible","Flavia P.Falcon","Maverick","Phobos M3P","Flavia P.Falcon"},
{"Atlantis","Player Cruiser","Piranha","Repulse","Player Fighter","Player Missile Cr.","Crucible","Flavia P.Falcon","Maverick","Phobos M3P","Flavia P.Falcon","Phobos M3P"},
{"Atlantis","Player Cruiser","Piranha","Hathcock","Player Fighter","Player Missile Cr.","Crucible","Flavia P.Falcon","Maverick","Phobos M3P","Flavia P.Falcon","Phobos M3P","Crucible"},
{"Atlantis","Player Cruiser","Hathcock","Repulse","Piranha","Player Missile Cr.","Crucible","Flavia P.Falcon","Maverick","Phobos M3P","Flavia P.Falcon","Phobos M3P","Crucible","Player Fighter"},
{"Atlantis","Player Cruiser","Hathcock","Repulse","Nautilus","Player Missile Cr.","Crucible","Flavia P.Falcon","Maverick","Phobos M3P","Flavia P.Falcon","Phobos M3P","Crucible","Player Fighter","MP52 Hornet"},
{"Atlantis","Player Cruiser","Nautilus","Repulse","Piranha","Player Missile Cr.","Crucible","Flavia P.Falcon","Maverick","Phobos M3P","Flavia P.Falcon","Phobos M3P","Crucible","Player Fighter","MP52 Hornet","Maverick"},
}
custom_player_ship_sets = {
["Jump"] = {
{"Atlantis"},
{"Atlantis","Player Cruiser"},
{"Atlantis","Player Cruiser","Hathcock"},
{"Atlantis","Player Cruiser","Hathcock","Repulse"},
{"Atlantis","Player Cruiser","Hathcock","Repulse","Piranha"},
{"Atlantis","Player Cruiser","Hathcock","Repulse","Piranha","Nautilus"},
{"Atlantis","Player Cruiser","Hathcock","Repulse","Piranha","Nautilus","Repulse"},
{"Atlantis","Player Cruiser","Hathcock","Repulse","Piranha","Nautilus","Repulse","Player Cruiser"},
{"Atlantis","Player Cruiser","Hathcock","Repulse","Piranha","Nautilus","Repulse","Player Cruiser","Piranha"},
{"Atlantis","Player Cruiser","Hathcock","Repulse","Piranha","Nautilus","Repulse","Player Cruiser","Piranha","Atlantis"},
{"Atlantis","Player Cruiser","Hathcock","Repulse","Piranha","Nautilus","Repulse","Player Cruiser","Piranha","Atlantis","Nautilus"},
{"Atlantis","Player Cruiser","Hathcock","Repulse","Piranha","Nautilus","Repulse","Player Cruiser","Piranha","Atlantis","Nautilus","Hathcock"},
{"Atlantis","Player Cruiser","Hathcock","Repulse","Piranha","Nautilus","Repulse","Player Cruiser","Piranha","Atlantis","Nautilus","Hathcock","Atlantis"},
{"Atlantis","Player Cruiser","Hathcock","Repulse","Piranha","Nautilus","Repulse","Player Cruiser","Piranha","Atlantis","Nautilus","Hathcock","Atlantis","Player Cruiser"},
{"Atlantis","Player Cruiser","Hathcock","Repulse","Piranha","Nautilus","Repulse","Player Cruiser","Piranha","Atlantis","Nautilus","Hathcock","Atlantis","Player Cruiser","Piranha"},
{"Atlantis","Player Cruiser","Hathcock","Repulse","Piranha","Nautilus","Repulse","Player Cruiser","Piranha","Atlantis","Nautilus","Hathcock","Atlantis","Player Cruiser","Piranha","Hathcock"},
},
["Warp"] = {
{"Crucible"},
{"Crucible","Maverick"},
{"Crucible","Maverick","Phobos M3P"},
{"Crucible","Maverick","Phobos M3P","Flavia P.Falcon"},
{"Crucible","Maverick","Phobos M3P","Flavia P.Falcon","MP52 Hornet"},
{"Crucible","Maverick","Phobos M3P","Flavia P.Falcon","MP52 Hornet","Player Missile Cr."},
{"Crucible","Maverick","Phobos M3P","Flavia P.Falcon","MP52 Hornet","Player Missile Cr.","Maverick"},
{"Crucible","Maverick","Phobos M3P","Flavia P.Falcon","MP52 Hornet","Player Missile Cr.","Maverick","Phobos M3P"},
{"Crucible","Maverick","Phobos M3P","Flavia P.Falcon","MP52 Hornet","Player Missile Cr.","Maverick","Phobos M3P","Crucible"},
{"Crucible","Maverick","Phobos M3P","Flavia P.Falcon","MP52 Hornet","Player Missile Cr.","Maverick","Phobos M3P","Crucible","MP52 Hornet"},
{"Crucible","Maverick","Phobos M3P","Flavia P.Falcon","MP52 Hornet","Player Missile Cr.","Maverick","Phobos M3P","Crucible","MP52 Hornet","Player Missile Cr."},
{"Crucible","Maverick","Phobos M3P","Flavia P.Falcon","MP52 Hornet","Player Missile Cr.","Maverick","Phobos M3P","Crucible","MP52 Hornet","Player Missile Cr.","Flavia P.Falcon"},
{"Crucible","Maverick","Phobos M3P","Flavia P.Falcon","MP52 Hornet","Player Missile Cr.","Maverick","Phobos M3P","Crucible","MP52 Hornet","Player Missile Cr.","Flavia P.Falcon","Player Missile Cr."},
{"Crucible","Maverick","Phobos M3P","Flavia P.Falcon","MP52 Hornet","Player Missile Cr.","Maverick","Phobos M3P","Crucible","MP52 Hornet","Player Missile Cr.","Flavia P.Falcon","Player Missile Cr.","Maverick"},
{"Crucible","Maverick","Phobos M3P","Flavia P.Falcon","MP52 Hornet","Player Missile Cr.","Maverick","Phobos M3P","Crucible","MP52 Hornet","Player Missile Cr.","Flavia P.Falcon","Player Missile Cr.","Maverick","Crucible"},
{"Crucible","Maverick","Phobos M3P","Flavia P.Falcon","MP52 Hornet","Player Missile Cr.","Maverick","Phobos M3P","Crucible","MP52 Hornet","Player Missile Cr.","Flavia P.Falcon","Player Missile Cr.","Maverick","Crucible","Phobos M3P"},
},
["Heavy"] = {
{"Maverick"},
{"Maverick","Crucible"},
{"Maverick","Crucible","Atlantis"},
{"Maverick","Crucible","Atlantis","Player Missile Cr."},
{"Maverick","Crucible","Atlantis","Player Missile Cr.","Player Cruiser"},
{"Maverick","Crucible","Atlantis","Player Missile Cr.","Player Cruiser","Piranha"},
{"Maverick","Crucible","Atlantis","Player Missile Cr.","Player Cruiser","Piranha","Maverick"},
{"Maverick","Crucible","Atlantis","Player Missile Cr.","Player Cruiser","Piranha","Maverick","Player Missile Cr."},
{"Maverick","Crucible","Atlantis","Player Missile Cr.","Player Cruiser","Piranha","Maverick","Player Missile Cr.","Atlantis"},
{"Maverick","Crucible","Atlantis","Player Missile Cr.","Player Cruiser","Piranha","Maverick","Player Missile Cr.","Atlantis","Crucible"},
{"Maverick","Crucible","Atlantis","Player Missile Cr.","Player Cruiser","Piranha","Maverick","Player Missile Cr.","Atlantis","Crucible","Player Cruiser"},
{"Maverick","Crucible","Atlantis","Player Missile Cr.","Player Cruiser","Piranha","Maverick","Player Missile Cr.","Atlantis","Crucible","Player Cruiser","Piranha"},
{"Maverick","Crucible","Atlantis","Player Missile Cr.","Player Cruiser","Piranha","Maverick","Player Missile Cr.","Atlantis","Crucible","Player Cruiser","Piranha","Crucible"},
{"Maverick","Crucible","Atlantis","Player Missile Cr.","Player Cruiser","Piranha","Maverick","Player Missile Cr.","Atlantis","Crucible","Player Cruiser","Piranha","Crucible","Atlantis"},
{"Maverick","Crucible","Atlantis","Player Missile Cr.","Player Cruiser","Piranha","Maverick","Player Missile Cr.","Atlantis","Crucible","Player Cruiser","Piranha","Crucible","Atlantis","Maverick"},
{"Maverick","Crucible","Atlantis","Player Missile Cr.","Player Cruiser","Piranha","Maverick","Player Missile Cr.","Atlantis","Crucible","Player Cruiser","Piranha","Crucible","Atlantis","Maverick","Player Missile Cr."},
},
["Light"] = {
{"Phobos M3P"},
{"Phobos M3P","MP52 Hornet"},
{"Phobos M3P","MP52 Hornet","Flavia P.Falcon"},
{"Phobos M3P","MP52 Hornet","Flavia P.Falcon","Hathcock"},
{"Phobos M3P","MP52 Hornet","Flavia P.Falcon","Hathcock","Nautilus"},
{"Phobos M3P","MP52 Hornet","Flavia P.Falcon","Hathcock","Nautilus","Repulse"},
{"Phobos M3P","MP52 Hornet","Flavia P.Falcon","Hathcock","Nautilus","Repulse","Flavia P. Falcon"},
{"Phobos M3P","MP52 Hornet","Flavia P.Falcon","Hathcock","Nautilus","Repulse","Flavia P. Falcon","MP52 Hornet"},
{"Phobos M3P","MP52 Hornet","Flavia P.Falcon","Hathcock","Nautilus","Repulse","Flavia P. Falcon","MP52 Hornet","Phobos M3P"},
{"Phobos M3P","MP52 Hornet","Flavia P.Falcon","Hathcock","Nautilus","Repulse","Flavia P. Falcon","MP52 Hornet","Phobos M3P","Repulse"},
{"Phobos M3P","MP52 Hornet","Flavia P.Falcon","Hathcock","Nautilus","Repulse","Flavia P. Falcon","MP52 Hornet","Phobos M3P","Repulse","Hathcock"},
{"Phobos M3P","MP52 Hornet","Flavia P.Falcon","Hathcock","Nautilus","Repulse","Flavia P. Falcon","MP52 Hornet","Phobos M3P","Repulse","Hathcock","Nautilus"},
{"Phobos M3P","MP52 Hornet","Flavia P.Falcon","Hathcock","Nautilus","Repulse","Flavia P. Falcon","MP52 Hornet","Phobos M3P","Repulse","Hathcock","Nautilus","Flavia P. Falcon"},
{"Phobos M3P","MP52 Hornet","Flavia P.Falcon","Hathcock","Nautilus","Repulse","Flavia P. Falcon","MP52 Hornet","Phobos M3P","Repulse","Hathcock","Nautilus","Flavia P. Falcon","Phobos M3P"},
{"Phobos M3P","MP52 Hornet","Flavia P.Falcon","Hathcock","Nautilus","Repulse","Flavia P. Falcon","MP52 Hornet","Phobos M3P","Repulse","Hathcock","Nautilus","Flavia P. Falcon","Phobos M3P","MP52 Hornet"},
{"Phobos M3P","MP52 Hornet","Flavia P.Falcon","Hathcock","Nautilus","Repulse","Flavia P. Falcon","MP52 Hornet","Phobos M3P","Repulse","Hathcock","Nautilus","Flavia P. Falcon","Phobos M3P","MP52 Hornet","Repulse"},
},
["Custom"] = {
{"Holmes"},
{"Holmes","Phobos T2"},
{"Holmes","Phobos T2","Striker LX"},
{"Holmes","Phobos T2","Striker LX","Maverick XP"},
{"Holmes","Phobos T2","Striker LX","Maverick XP","Focus"},
{"Holmes","Phobos T2","Striker LX","Maverick XP","Focus","Repulse"},
{"Holmes","Phobos T2","Striker LX","Maverick XP","Focus","Repulse","Flavia P. Falcon"},
{"Holmes","Phobos T2","Striker LX","Maverick XP","Focus","Repulse","Flavia P. Falcon","Player Fighter"},
{"Holmes","Phobos T2","Striker LX","Maverick XP","Focus","Repulse","Flavia P. Falcon","Player Fighter","Phobos M3P"},
{"Holmes","Phobos T2","Striker LX","Maverick XP","Focus","Repulse","Flavia P. Falcon","Player Fighter","Phobos M3P","Repulse"},
{"Holmes","Phobos T2","Striker LX","Maverick XP","Focus","Repulse","Flavia P. Falcon","Player Fighter","Phobos M3P","Repulse","Hathcock"},
{"Holmes","Phobos T2","Striker LX","Maverick XP","Focus","Repulse","Flavia P. Falcon","Player Fighter","Phobos M3P","Repulse","Hathcock","Nautilus"},
{"Holmes","Phobos T2","Striker LX","Maverick XP","Focus","Repulse","Flavia P. Falcon","Player Fighter","Phobos M3P","Repulse","Hathcock","Nautilus","Flavia P. Falcon"},
{"Holmes","Phobos T2","Striker LX","Maverick XP","Focus","Repulse","Flavia P. Falcon","Player Fighter","Phobos M3P","Repulse","Hathcock","Nautilus","Flavia P. Falcon","Phobos M3P"},
{"Holmes","Phobos T2","Striker LX","Maverick XP","Focus","Repulse","Flavia P. Falcon","Player Fighter","Phobos M3P","Repulse","Hathcock","Nautilus","Flavia P. Falcon","Phobos M3P","MP52 Hornet"},
{"Holmes","Phobos T2","Striker LX","Maverick XP","Focus","Repulse","Flavia P. Falcon","Player Fighter","Phobos M3P","Repulse","Hathcock","Nautilus","Flavia P. Falcon","Phobos M3P","MP52 Hornet","Repulse"},
}
}
rwc_player_ship_names = { --rwc: random within category
["Atlantis"] = {"Formidable","Thrasher","Punisher","Vorpal","Protang","Drummond","Parchim","Coronado"},
["Benedict"] = {"Elizabeth","Ford","Avenger","Washington","Lincoln","Garibaldi","Eisenhower"},
["Crucible"] = {"Sling", "Stark", "Torrid", "Kicker", "Flummox"},
["Ender"] = {"Mongo","Godzilla","Leviathan","Kraken","Jupiter","Saturn"},
["Flavia P.Falcon"] = {"Ladyhawke","Hunter","Seeker","Gyrefalcon","Kestrel","Magpie","Bandit","Buccaneer"},
["Hathcock"] = {"Hayha", "Waldron", "Plunkett", "Mawhinney", "Furlong", "Zaytsev", "Pavlichenko", "Fett", "Hawkeye", "Hanzo"},
["Kiriya"] = {"Cavour","Reagan","Gaulle","Paulo","Truman","Stennis","Kuznetsov","Roosevelt","Vinson","Old Salt"},
["MP52 Hornet"] = {"Dragonfly","Scarab","Mantis","Yellow Jacket","Jimminy","Flik","Thorny","Buzz"},
["Maverick"] = {"Angel", "Thunderbird", "Roaster", "Magnifier", "Hedge"},
["Nautilus"] = {"October", "Abdiel", "Manxman", "Newcon", "Nusret", "Pluton", "Amiral", "Amur", "Heinkel", "Dornier"},
["Phobos M3P"] = {"Blinder","Shadow","Distortion","Diemos","Ganymede","Castillo","Thebe","Retrograde"},
["Piranha"] = {"Razor","Biter","Ripper","Voracious","Carnivorous","Characid","Vulture","Predator"},
["Player Cruiser"] = {"Excelsior","Velociraptor","Thunder","Kona","Encounter","Perth","Aspern","Panther"},
["Player Fighter"] = {"Buzzer","Flitter","Zippiticus","Hopper","Molt","Stinger","Stripe"},
["Player Missile Cr."] = {"Projectus","Hurlmeister","Flinger","Ovod","Amatola","Nakhimov","Antigone"},
["Repulse"] = {"Fiddler","Brinks","Loomis","Mowag","Patria","Pandur","Terrex","Komatsu","Eitan"},
["Striker"] = {"Sparrow","Sizzle","Squawk","Crow","Snowbird","Hawk"},
["ZX-Lindworm"] = {"Seagull","Catapult","Blowhard","Flapper","Nixie","Pixie","Tinkerbell"},
["Unknown"] = {
"Foregone",
"Righteous",
"Masher",
"Lancer",
"Horizon",
"Osiris",
"Athena",
"Poseidon",
"Heracles",
"Constitution",
"Stargazer",
"Horatio",
"Socrates",
"Galileo",
"Newton",
"Beethoven",
"Rabin",
"Spector",
"Akira",
"Thunderchild",
"Ambassador",
"Adelphi",
"Exeter",
"Ghandi",
"Valdemar",
"Yamaguchi",
"Zhukov",
"Andromeda",
"Drake",
"Prokofiev",
"Antares",
"Apollo",
"Ajax",
"Clement",
"Bradbury",
"Gage",
"Buran",
"Kearsarge",
-- "Cheyenne",
"Ahwahnee",
"Constellation",
"Gettysburg",
"Hathaway",
"Magellan",
"Farragut",
"Kongo",
"Lexington",
"Potempkin",
"Yorktown",
"Daedalus",
"Archon",
"Carolina",
"Essex",
"Danube",
"Gander",
"Ganges",
"Mekong",
"Orinoco",
"Rubicon",
"Shenandoah",
"Volga",
"Yangtzee Kiang",
"Yukon",
"Valiant",
"Deneva",
"Arcos",
"LaSalle",
"Al-Batani",
"Cairo",
"Charlseton",
"Crazy Horse",
"Crockett",
"Fearless",
"Fredrickson",
-- "Gorkon",
"Hood",
"Lakota",
"Malinche",
"Melbourne",
"Freedom",
"Concorde",
-- "Firebrand",
"Galaxy",
"Challenger",
"Odyssey",
"Trinculo",
"Venture",
"Yamato",
"Hokule'a",
"Tripoli",
"Hope",
"Nobel",
"Pasteur",
"Bellerophon",
"Voyager",
"Istanbul",
"Constantinople",
"Havana",
"Sarajevo",
"Korolev",
"Goddard",
"Luna",
"Titan",
"Mediterranean",
"Lalo",
"Wyoming",
"Merced",
"Trieste",
"Miranda",
"Brattain",
"Helin",
"Lantree",
"Majestic",
"Reliant",
"Saratoga",
"ShirKahr",
"Sitak",
"Tian An Men",
"Trial",
"Nebula",
"Bonchune",
"Capricorn",
"Hera",
"Honshu",
"Interceptor",
"Leeds",
"Merrimack",
"Prometheus",
"Proxima",
"Sutherland",
"T'Kumbra",
"Ulysses",
"New Orleans",
"Kyushu",
"Renegade",
"Rutledge",
"Thomas Paine",
"Niagra",
"Princeton",
"Wellington",
"Norway",
"Budapest",
"Nova",
"Equinox",
"Rhode Island",
"Columbia",
"Oberth",
"Biko",
"Cochraine",
"Copernicus",
"Grissom",
"Pegasus",
"Raman",
"Yosemite",
"Renaissance",
"Aries",
"Maryland",
"Rigel",
"Akagi",
"Tolstoy",
"Yeager",
"Sequoia",
"Sovereign",
"Soyuz",
"Bozeman",
"Springfield",
"Chekov",
"Steamrunner",
"Appalachia",
"Surak",
"Zapata",
"Sydney",
"Jenolen",
"Nash",
"Wambundu",
"Fleming",
"Wells",
"Relativity",
"Yorkshire",
"Denver",
"Zodiac",
"Centaur",
"Cortez",
"Republic",
"Peregrine",
"Calypso",
"Cousteau",
"Waverider",
"Scimitar",
},
}
player_ship_stats = {
["Atlantis"] = { strength = 52, cargo = 6, distance = 400, long_range_radar = 30000, short_range_radar = 5000, probes = 10, long_jump = 50, short_jump = 5, warp = 0, stock = true, },
["Benedict"] = { strength = 10, cargo = 9, distance = 400, long_range_radar = 30000, short_range_radar = 5000, probes = 10, long_jump = 90, short_jump = 5, warp = 0, stock = true, },
["Crucible"] = { strength = 45, cargo = 5, distance = 200, long_range_radar = 20000, short_range_radar = 6000, probes = 9, long_jump = 0, short_jump = 0, warp = 750, stock = true, },
["Ender"] = { strength = 100, cargo = 20, distance = 2000,long_range_radar = 45000, short_range_radar = 7000, probes = 12, long_jump = 50, short_jump = 5, warp = 0, stock = true, },
["Flavia P.Falcon"] = { strength = 13, cargo = 15, distance = 200, long_range_radar = 40000, short_range_radar = 5000, probes = 8, long_jump = 0, short_jump = 0, warp = 500, stock = true, },
["Hathcock"] = { strength = 30, cargo = 6, distance = 200, long_range_radar = 35000, short_range_radar = 6000, probes = 8, long_jump = 60, short_jump = 6, warp = 0, stock = true, },
["Kiriya"] = { strength = 10, cargo = 9, distance = 400, long_range_radar = 35000, short_range_radar = 5000, probes = 10, long_jump = 0, short_jump = 0, warp = 750, stock = true, },
["Maverick"] = { strength = 45, cargo = 5, distance = 200, long_range_radar = 20000, short_range_radar = 4000, probes = 9, long_jump = 0, short_jump = 0, warp = 800, stock = true, },
["MP52 Hornet"] = { strength = 7, cargo = 3, distance = 100, long_range_radar = 18000, short_range_radar = 4000, probes = 5, long_jump = 0, short_jump = 0, warp = 1000, stock = true, },
["Nautilus"] = { strength = 12, cargo = 7, distance = 200, long_range_radar = 22000, short_range_radar = 4000, probes = 10, long_jump = 70, short_jump = 5, warp = 0, stock = true, },
["Phobos M3P"] = { strength = 19, cargo = 10, distance = 200, long_range_radar = 25000, short_range_radar = 5000, probes = 6, long_jump = 0, short_jump = 0, warp = 900, stock = true, },
["Piranha"] = { strength = 16, cargo = 8, distance = 200, long_range_radar = 25000, short_range_radar = 6000, probes = 6, long_jump = 50, short_jump = 5, warp = 0, stock = true, },
["Player Cruiser"] = { strength = 40, cargo = 6, distance = 400, long_range_radar = 30000, short_range_radar = 5000, probes = 10, long_jump = 80, short_jump = 5, warp = 0, stock = true, },
["Player Missile Cr."] = { strength = 45, cargo = 8, distance = 200, long_range_radar = 35000, short_range_radar = 6000, probes = 9, long_jump = 0, short_jump = 0, warp = 800, stock = true, },
["Player Fighter"] = { strength = 7, cargo = 3, distance = 100, long_range_radar = 15000, short_range_radar = 4500, probes = 4, long_jump = 40, short_jump = 3, warp = 0, stock = true, },
["Repulse"] = { strength = 14, cargo = 12, distance = 200, long_range_radar = 38000, short_range_radar = 5000, probes = 8, long_jump = 50, short_jump = 5, warp = 0, stock = true, },
["Striker"] = { strength = 8, cargo = 4, distance = 200, long_range_radar = 35000, short_range_radar = 5000, probes = 6, long_jump = 40, short_jump = 3, warp = 0, stock = true, },
["ZX-Lindworm"] = { strength = 8, cargo = 3, distance = 100, long_range_radar = 18000, short_range_radar = 5500, probes = 4, long_jump = 0, short_jump = 0, warp = 950, stock = true, },
-- Stock above, custom below
["Focus"] = { strength = 35, cargo = 4, distance = 200, long_range_radar = 32000, short_range_radar = 5000, probes = 8, long_jump = 25, short_jump = 2.5, warp = 0, stock = false, },
["Holmes"] = { strength = 35, cargo = 6, distance = 200, long_range_radar = 35000, short_range_radar = 4000, probes = 8, long_jump = 0, short_jump = 0, warp = 750, stock = false, },
["Maverick XP"] = { strength = 23, cargo = 5, distance = 200, long_range_radar = 25000, short_range_radar = 7000, probes = 10, long_jump = 20, short_jump = 2, warp = 0, stock = false, },
["Phobos T2"] = { strength = 19, cargo = 9, distance = 200, long_range_radar = 25000, short_range_radar = 5000, probes = 5, long_jump = 25, short_jump = 2, warp = 0, stock = false, },
["Striker LX"] = { strength = 16, cargo = 4, distance = 200, long_range_radar = 20000, short_range_radar = 4000, probes = 7, long_jump = 20, short_jump = 2, warp = 0, stock = false, },
}
npc_ships = false
npc_lower = 30
npc_upper = 60
scientist_list = {}
scientist_count = 0
scientist_score_value = 10
scientist_names = { --fictional
"Gertrude Goodall",
"John Kruger",
"Lisa Forsythe",
"Ethan Williams",
"Ameilia Martinez",
"Felix Mertens",
"Marie Novak",
"Mathias Evans",
"Clara Heikkinen",
"Vicente Martin",
"Catalina Fischer",
"Marek Varga",
"Ewa Olsen",
"Oscar Stewart",
"Alva Rodriguez",
"Aiden Johansson",
"Zoey Smith",
"Jorge Romero",
"Rosa Wong",
"Julian Acharya",
"Hannah Ginting",
"Anton Dewala",
"Camille Silva",
"Aleksi Gideon",
"Ella Dasgupta",
"Gunnar Smirnov",
"Telma Lozano",
"Kaito Fabroa",
"Misaki Kapia",
"Ronald Sanada",
"Janice Tesfaye",
"Alvaro Hassan",
"Valeria Dinh",
"Sergei Mokri",
"Yulia Karga",
"Arnav Dixon",
"Sanvi Saetan",
}
scientist_topics = {
"Mathematics",
"Miniaturization",
"Exotic materials",
"Warp theory",
"Particle theory",
"Power systems",
"Energy fields",
"Subatomic physics",
"Stellar phenomena",
"Gravity dynamics",
"Information science",
"Computer protocols",
}
upgrade_requirements = {
"talk", --talk
"talk primary", --talk then upgrade at primary station
"meet", --meet
"meet primary", --meet then upgrade at primary station
"transport", --transport to primary station
"confer", --transport to primary station, then confer with another scientist
}
upgrade_list = {
{action = hullStrengthUpgrade, name = _("station-comms","hull strength upgrade")},
{action = shieldStrengthUpgrade, name = _("station-comms","shield strength upgrade")},
{action = missileLoadSpeedUpgrade, name = _("station-comms","missile load speed upgrade")},
{action = beamDamageUpgrade, name = _("station-comms","beam damage upgrade")},
{action = beamRangeUpgrade, name = _("station-comms","beam range upgrade")},
{action = batteryEfficiencyUpgrade, name = _("station-comms","battery efficiency upgrade")},
{action = fasterImpulseUpgrade, name = _("station-comms","faster impulse upgrade")},
{action = longerSensorsUpgrade, name = _("station-comms","longer sensor range upgrade")},
{action = fasterSpinUpgrade, name = _("station-comms","faster maneuvering speed upgrade")},
}
upgrade_automated_applications = {
"single", --automatically applied only to the player that completed the requirements
"players", --automatically applied to allied players
"all", --automatically applied to players and NPCs (where applicable)
}
prefix_length = 0
suffix_index = 0
formation_delta = {
["square"] = {
x = {0,1,0,-1, 0,1,-1, 1,-1,2,0,-2, 0,2,-2, 2,-2,2, 2,-2,-2,1,-1, 1,-1,0, 0,3,-3,1, 1,3,-3,-1,-1, 3,-3,2, 2,3,-3,-2,-2, 3,-3,3, 3,-3,-3,4,0,-4, 0,4,-4, 4,-4,-4,-4,-4,-4,-4,-4,4, 4,4, 4,4, 4, 1,-1, 2,-2, 3,-3,1,-1,2,-2,3,-3,5,-5,0, 0,5, 5,-5,-5,-5,-5,-5,-5,-5,-5,-5,-5,5, 5,5, 5,5, 5,5, 5, 1,-1, 2,-2, 3,-3, 4,-4,1,-1,2,-2,3,-3,4,-4},
y = {0,0,1, 0,-1,1,-1,-1, 1,0,2, 0,-2,2,-2,-2, 2,1,-1, 1,-1,2, 2,-2,-2,3,-3,0, 0,3,-3,1, 1, 3,-3,-1,-1,3,-3,2, 2, 3,-3,-2,-2,3,-3, 3,-3,0,4, 0,-4,4,-4,-4, 4, 1,-1, 2,-2, 3,-3,1,-1,2,-2,3,-3,-4,-4,-4,-4,-4,-4,4, 4,4, 4,4, 4,0, 0,5,-5,5,-5, 5,-5, 1,-1, 2,-2, 3,-3, 4,-4,1,-1,2,-2,3,-3,4,-4,-5,-5,-5,-5,-5,-5,-5,-5,5, 5,5, 5,5, 5,5, 5},
},
["hexagonal"] = {
x = {0,2,-2,1,-1, 1,-1,4,-4,0, 0,2,-2,-2, 2,3,-3, 3,-3,6,-6,1,-1, 1,-1,3,-3, 3,-3,4,-4, 4,-4,5,-5, 5,-5,8,-8,4,-4, 4,-4,5,5 ,-5,-5,2, 2,-2,-2,0, 0,6, 6,-6,-6,7, 7,-7,-7,10,-10,5, 5,-5,-5,6, 6,-6,-6,7, 7,-7,-7,8, 8,-8,-8,9, 9,-9,-9,3, 3,-3,-3,1, 1,-1,-1,12,-12,6,-6, 6,-6,7,-7, 7,-7,8,-8, 8,-8,9,-9, 9,-9,10,-10,10,-10,11,-11,11,-11,4,-4, 4,-4,2,-2, 2,-2,0, 0},
y = {0,0, 0,1, 1,-1,-1,0, 0,2,-2,2,-2, 2,-2,1,-1,-1, 1,0, 0,3, 3,-3,-3,3,-3,-3, 3,2,-2,-2, 2,1,-1,-1, 1,0, 0,4,-4,-4, 4,3,-3, 3,-3,4,-4, 4,-4,4,-4,2,-2, 2,-2,1,-1, 1,-1, 0, 0,5,-5, 5,-5,4,-4, 4,-4,3,-3, 3,-7,2,-2, 2,-2,1,-1, 1,-1,5,-5, 5,-5,5,-5, 5,-5, 0, 0,6, 6,-6,-6,5, 5,-5,-5,4, 4,-4,-4,3, 3,-3,-3, 2, 2,-2, -2, 1, 1,-1, -1,6, 6,-6,-6,6, 6,-6,-6,6,-6},
},
}
fleet_group = {
["adder"] = "Adders",
["Adders"] = "adder",
["missiler"] = "Missilers",
["Missilers"] = "missiler",
["beamer"] = "Beamers",
["Beamers"] = "beamer",
["frigate"] = "Frigates",
["Frigates"] = "frigate",
["chaser"] = "Chasers",
["Chasers"] = "chaser",
["fighter"] = "Fighters",
["Fighters"] = "fighter",
["drone"] = "Drones",
["Drones"] = "drone",
}
ship_template = { --ordered by relative strength
["Gnat"] = {strength = 2, adder = false, missiler = false, beamer = true, frigate = false, chaser = false, fighter = true, drone = true, unusual = false, base = false, create = gnat},
["Lite Drone"] = {strength = 3, adder = false, missiler = false, beamer = true, frigate = false, chaser = false, fighter = true, drone = true, unusual = false, base = false, create = droneLite},
["Jacket Drone"] = {strength = 4, adder = false, missiler = false, beamer = true, frigate = false, chaser = false, fighter = true, drone = true, unusual = false, base = false, create = droneJacket},
["Ktlitan Drone"] = {strength = 4, adder = false, missiler = false, beamer = true, frigate = false, chaser = false, fighter = true, drone = true, unusual = false, base = false, create = stockTemplate},
["Heavy Drone"] = {strength = 5, adder = false, missiler = false, beamer = true, frigate = false, chaser = false, fighter = true, drone = true, unusual = false, base = false, create = droneHeavy},
["Adder MK3"] = {strength = 5, adder = true, missiler = false, beamer = false, frigate = false, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["MT52 Hornet"] = {strength = 5, adder = false, missiler = false, beamer = true, frigate = false, chaser = false, fighter = true, drone = false, unusual = false, base = false, create = stockTemplate},
["MU52 Hornet"] = {strength = 5, adder = false, missiler = false, beamer = true, frigate = false, chaser = false, fighter = true, drone = false, unusual = false, base = false, create = stockTemplate},
["MV52 Hornet"] = {strength = 6, adder = false, missiler = false, beamer = true, frigate = false, chaser = false, fighter = true, drone = false, unusual = false, base = false, create = hornetMV52},
["Adder MK4"] = {strength = 6, adder = true, missiler = false, beamer = false, frigate = false, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["Fighter"] = {strength = 6, adder = false, missiler = false, beamer = true, frigate = false, chaser = false, fighter = true, drone = false, unusual = false, base = false, create = stockTemplate},
["Ktlitan Fighter"] = {strength = 6, adder = false, missiler = false, beamer = true, frigate = false, chaser = false, fighter = true, drone = false, unusual = false, base = false, create = stockTemplate},
["K2 Fighter"] = {strength = 7, adder = false, missiler = false, beamer = true, frigate = false, chaser = false, fighter = true, drone = false, unusual = false, base = false, create = k2fighter},
["Adder MK5"] = {strength = 7, adder = true, missiler = false, beamer = false, frigate = false, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["WX-Lindworm"] = {strength = 7, adder = false, missiler = true, beamer = false, frigate = false, chaser = false, fighter = true, drone = false, unusual = false, base = false, create = stockTemplate},
["K3 Fighter"] = {strength = 8, adder = false, missiler = false, beamer = true, frigate = false, chaser = false, fighter = true, drone = false, unusual = false, base = false, create = k3fighter},
["Adder MK6"] = {strength = 8, adder = true, missiler = false, beamer = false, frigate = false, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["Ktlitan Scout"] = {strength = 8, adder = false, missiler = false, beamer = true, frigate = false, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["WZ-Lindworm"] = {strength = 9, adder = false, missiler = true, beamer = false, frigate = false, chaser = false, fighter = true, drone = false, unusual = false, base = false, create = wzLindworm},
["Adder MK7"] = {strength = 9, adder = true, missiler = false, beamer = false, frigate = false, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["Adder MK8"] = {strength = 10, adder = true, missiler = false, beamer = false, frigate = false, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["Adder MK9"] = {strength = 11, adder = true, missiler = false, beamer = false, frigate = false, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["Nirvana R3"] = {strength = 12, adder = false, missiler = false, beamer = true, frigate = false, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["Phobos R2"] = {strength = 13, adder = false, missiler = false, beamer = false, frigate = true, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = phobosR2},
["Missile Cruiser"] = {strength = 14, adder = false, missiler = true, beamer = false, frigate = true, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["Waddle 5"] = {strength = 15, adder = true, missiler = false, beamer = false, frigate = false, chaser = true, fighter = false, drone = false, unusual = false, base = false, create = waddle5},
["Jade 5"] = {strength = 15, adder = true, missiler = false, beamer = false, frigate = false, chaser = true, fighter = false, drone = false, unusual = false, base = false, create = jade5},
["Phobos T3"] = {strength = 15, adder = false, missiler = false, beamer = false, frigate = true, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["Piranha F8"] = {strength = 15, adder = false, missiler = true, beamer = false, frigate = true, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["Piranha F12"] = {strength = 15, adder = false, missiler = true, beamer = false, frigate = true, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["Piranha F12.M"] = {strength = 16, adder = false, missiler = true, beamer = false, frigate = true, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["Phobos M3"] = {strength = 16, adder = false, missiler = false, beamer = false, frigate = true, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["Farco 3"] = {strength = 16, adder = false, missiler = false, beamer = false, frigate = true, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = farco3},
["Farco 5"] = {strength = 16, adder = false, missiler = false, beamer = false, frigate = true, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = farco5},
["Karnack"] = {strength = 17, adder = false, missiler = false, beamer = true, frigate = true, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["Gunship"] = {strength = 17, adder = false, missiler = false, beamer = false, frigate = true, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["Phobos T4"] = {strength = 18, adder = false, missiler = false, beamer = false, frigate = true, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = phobosT4},
["Cruiser"] = {strength = 18, adder = true, missiler = false, beamer = true, frigate = true, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["Nirvana R5"] = {strength = 19, adder = false, missiler = false, beamer = true, frigate = true, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["Farco 8"] = {strength = 19, adder = false, missiler = false, beamer = false, frigate = true, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = farco8},
["Ktlitan Worker"] = {strength = 20, adder = false, missiler = false, beamer = true, frigate = false, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["Nirvana R5A"] = {strength = 20, adder = false, missiler = false, beamer = true, frigate = true, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["Adv. Gunship"] = {strength = 20, adder = false, missiler = false, beamer = false, frigate = true, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["Farco 11"] = {strength = 21, adder = false, missiler = false, beamer = false, frigate = true, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = farco11},
["Storm"] = {strength = 22, adder = false, missiler = true, beamer = false, frigate = true, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["Stalker R5"] = {strength = 22, adder = false, missiler = false, beamer = true, frigate = true, chaser = true, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["Stalker Q5"] = {strength = 22, adder = false, missiler = false, beamer = true, frigate = true, chaser = true, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["Farco 13"] = {strength = 24, adder = false, missiler = false, beamer = false, frigate = true, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = farco13},
["Ranus U"] = {strength = 25, adder = false, missiler = true, beamer = false, frigate = true, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["Stalker Q7"] = {strength = 25, adder = false, missiler = false, beamer = true, frigate = true, chaser = true, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["Stalker R7"] = {strength = 25, adder = false, missiler = false, beamer = true, frigate = true, chaser = true, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["Whirlwind"] = {strength = 26, adder = false, missiler = true, beamer = false, frigate = true, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = whirlwind},
["Adv. Striker"] = {strength = 27, adder = false, missiler = false, beamer = true, frigate = true, chaser = true, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["Elara P2"] = {strength = 28, adder = false, missiler = false, beamer = false, frigate = true, chaser = true, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["Tempest"] = {strength = 30, adder = false, missiler = true, beamer = false, frigate = true, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = tempest},
["Strikeship"] = {strength = 30, adder = false, missiler = false, beamer = true, frigate = true, chaser = true, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["Fiend G3"] = {strength = 33, adder = false, missiler = false, beamer = false, frigate = true, chaser = true, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["Fiend G4"] = {strength = 35, adder = false, missiler = false, beamer = false, frigate = true, chaser = true, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["Cucaracha"] = {strength = 36, adder = false, missiler = false, beamer = true, frigate = false, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = cucaracha},
["Fiend G5"] = {strength = 37, adder = false, missiler = false, beamer = false, frigate = true, chaser = true, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["Fiend G6"] = {strength = 39, adder = false, missiler = false, beamer = false, frigate = true, chaser = true, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["Predator"] = {strength = 42, adder = false, missiler = false, beamer = false, frigate = true, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = predator},
["Ktlitan Breaker"] = {strength = 45, adder = false, missiler = false, beamer = false, frigate = false, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["Hurricane"] = {strength = 46, adder = false, missiler = true, beamer = false, frigate = true, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = hurricane},
["Ktlitan Feeder"] = {strength = 48, adder = false, missiler = false, beamer = true, frigate = false, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["Atlantis X23"] = {strength = 50, adder = false, missiler = false, beamer = false, frigate = false, chaser = true, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["K2 Breaker"] = {strength = 55, adder = false, missiler = false, beamer = false, frigate = false, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = k2breaker},
["Ktlitan Destroyer"] = {strength = 50, adder = false, missiler = false, beamer = false, frigate = false, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["Atlantis Y42"] = {strength = 60, adder = false, missiler = false, beamer = false, frigate = false, chaser = true, fighter = false, drone = false, unusual = false, base = false, create = atlantisY42},
["Blockade Runner"] = {strength = 65, adder = false, missiler = false, beamer = true, frigate = false, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["Starhammer II"] = {strength = 70, adder = false, missiler = false, beamer = false, frigate = false, chaser = true, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["Enforcer"] = {strength = 75, adder = false, missiler = false, beamer = false, frigate = true, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = enforcer},
["Dreadnought"] = {strength = 80, adder = false, missiler = false, beamer = true, frigate = false, chaser = false, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["Starhammer III"] = {strength = 85, adder = false, missiler = false, beamer = false, frigate = false, chaser = true, fighter = false, drone = false, unusual = false, base = false, create = starhammerIII},
["Starhammer V"] = {strength = 90, adder = false, missiler = false, beamer = false, frigate = false, chaser = true, fighter = false, drone = false, unusual = false, base = false, create = starhammerV},
["Battlestation"] = {strength = 100,adder = false, missiler = false, beamer = true, frigate = false, chaser = true, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
["Tyr"] = {strength = 150,adder = false, missiler = false, beamer = true, frigate = false, chaser = true, fighter = false, drone = false, unusual = false, base = false, create = tyr},
["Odin"] = {strength = 250,adder = false, missiler = false, beamer = false, frigate = false, chaser = true, fighter = false, drone = false, unusual = false, base = false, create = stockTemplate},
}
control_code_stem = { --All control codes must use capital letters or they will not work.
"ALWAYS",
"BLACK",
"BLUE",
"BRIGHT",
"BROWN",
"CHAIN",
"CHURCH",
"DOORWAY",
"DULL",
"ELBOW",
"EMPTY",
"EPSILON",
"FLOWER",
"FLY",
"FROZEN",
"GREEN",
"GLOW",
"HAMMER",
"HORIZON",
"INK",
"JUMP",
"KEY",
"LETTER",
"LIST",
"MORNING",
"NEXT",
"OPEN",
"ORANGE",
"OUTSIDE",
"PURPLE",
"QUARTER",
"QUIET",
"RED",
"SHINE",
"SIGMA",
"STAR",
"STARSHIP",
"STREET",
"TOKEN",
"THIRSTY",
"UNDER",
"VANISH",
"WHITE",
"WRENCH",
"YELLOW",
}
healthCheckTimerInterval = 10
healthCheckTimer = healthCheckTimerInterval
commonGoods = {"food","medicine","nickel","platinum","gold","dilithium","tritanium","luxury","cobalt","impulse","warp","shield","tractor","repulsor","beam","optic","robotic","filament","transporter","sensor","communication","autodoc","lifter","android","nanites","software","circuit","battery"}
componentGoods = {"impulse","warp","shield","tractor","repulsor","beam","optic","robotic","filament","transporter","sensor","communication","autodoc","lifter","android","nanites","software","circuit","battery"}
mineralGoods = {"nickel","platinum","gold","dilithium","tritanium","cobalt"}
good_desc = {
["food"] = _("trade-comms","food"),
["medicine"] = _("trade-comms","medicine"),
["luxury"] = _("trade-comms","luxury"),
["cobalt"] = _("trade-comms","cobalt"),
["dilithium"] = _("trade-comms","dilithium"),
["gold"] = _("trade-comms","gold"),
["nickel"] = _("trade-comms","nickel"),
["platinum"] = _("trade-comms","platinum"),
["tritanium"] = _("trade-comms","tritanium"),
["autodoc"] = _("trade-comms","autodoc"),
["android"] = _("trade-comms","android"),
["battery"] = _("trade-comms","battery"),
["beam"] = _("trade-comms","beam"),
["circuit"] = _("trade-comms","circuit"),
["communication"] = _("trade-comms","communication"),
["filament"] = _("trade-comms","filament"),
["impulse"] = _("trade-comms","impulse"),
["lifter"] = _("trade-comms","lifter"),
["nanites"] = _("trade-comms","nanites"),
["optic"] = _("trade-comms","optic"),
["repulsor"] = _("trade-comms","repulsor"),
["robotic"] = _("trade-comms","robotic"),
["sensor"] = _("trade-comms","sensor"),
["shield"] = _("trade-comms","shield"),
["software"] = _("trade-comms","software"),
["tractor"] = _("trade-comms","tractor"),
["transporter"] = _("trade-comms","transporter"),
["warp"] = _("trade-comms","warp"),
}
end
function setStaticScienceDatabase()
--------------------------------------------------------------------------------------
-- Generic station descriptions: text and details from shipTemplates_stations.lua --
--------------------------------------------------------------------------------------
local station_db = queryScienceDatabase("Stations")
if station_db == nil then
station_db = ScienceDatabase():setName("Stations")
station_db:setLongDescription("Stations are places for ships to dock, get repaired and replenished, interact with station personnel, etc. They are like oases, service stations, villages, towns, cities, etc.")
station_db:addEntry("Small")
local small_station_db = queryScienceDatabase("Stations","Small")
small_station_db:setLongDescription("Stations of this size are often used as research outposts, listening stations, and security checkpoints. Crews turn over frequently in a small station's cramped accommodatations, but they are small enough to look like ships on many long-range sensors, and organized raiders sometimes take advantage of this by placing small stations in nebulae to serve as raiding bases. They are lightly shielded and vulnerable to swarming assaults.")
small_station_db:setImage("smallstation.png")
small_station_db:setKeyValue("Class","Small")
small_station_db:setKeyValue("Size",300)
small_station_db:setKeyValue("Shield",300)
small_station_db:setKeyValue("Hull",150)
station_db:addEntry("Medium")
local medium_station_db = queryScienceDatabase("Stations","Medium")
medium_station_db:setLongDescription("Large enough to accommodate small crews for extended periods of times, stations of this size are often trading posts, refuelling bases, mining operations, and forward military bases. While their shields are strong, concerted attacks by many ships can bring them down quickly.")
medium_station_db:setImage("mediumstation.png")
medium_station_db:setKeyValue("Class","Medium")
medium_station_db:setKeyValue("Size",1000)
medium_station_db:setKeyValue("Shield",800)
medium_station_db:setKeyValue("Hull",400)
station_db:addEntry("Large")
local large_station_db = queryScienceDatabase("Stations","Large")
large_station_db:setLongDescription("These spaceborne communities often represent permanent bases in a sector. Stations of this size can be military installations, commercial hubs, deep-space settlements, and small shipyards. Only a concentrated attack can penetrate a large station's shields, and its hull can withstand all but the most powerful weaponry.")
large_station_db:setImage("largestation.png")
large_station_db:setKeyValue("Class","Large")
large_station_db:setKeyValue("Size",1300)
large_station_db:setKeyValue("Shield","1000/1000/1000")
large_station_db:setKeyValue("Hull",500)
station_db:addEntry("Huge")
local huge_station_db = queryScienceDatabase("Stations","Huge")
huge_station_db:setLongDescription("The size of a sprawling town, stations at this scale represent a faction's center of spaceborne power in a region. They serve many functions at once and represent an extensive investment of time, money, and labor. A huge station's shields and thick hull can keep it intact long enough for reinforcements to arrive, even when faced with an ongoing siege or massive, perfectly coordinated assault.")
huge_station_db:setImage("hugestation.png")
huge_station_db:setKeyValue("Class","Huge")
huge_station_db:setKeyValue("Size",1500)
huge_station_db:setKeyValue("Shield","1200/1200/1200/1200")
huge_station_db:setKeyValue("Hull",800)
end
-----------------------------------------------------------------------------------
-- Template ship category descriptions: text from other shipTemplates... files --
-----------------------------------------------------------------------------------
local ships_db = queryScienceDatabase("Ships")
if ships_db == nil then
ships_db = ScienceDatabase():setName("Ships")
end
local fighter_db = queryScienceDatabase("Ships","Starfighter")
if fighter_db == nil then
ships_db:addEntry("Starfighter")
fighter_db = queryScienceDatabase("Ships","Starfighter")
end
local generic_starfighter_description = "Starfighters are single to 3 person small ships. These are most commonly used as light firepower roles.\nThey are common in larger groups, and need a close by station or support ship, as they lack long time life support.\nIt's rare to see starfighters with more then one shield section.\n\nOne of the most well known starfighters is the X-Wing.\n\nStarfighters come in 3 subclasses:\n* Interceptors: Fast, low on firepower, high on manouverability\n* Gunship: Equipped with more weapons, but trades in manouverability because of it.\n* Bomber: Slowest of all starfighters, but pack a large punch in a small package. Usually come without any lasers, but the largers bombers have been known to deliver nukes."
fighter_db:setLongDescription(generic_starfighter_description)
local frigate_db = queryScienceDatabase("Ships","Frigate")
if frigate_db == nil then
ships_db:addEntry("Frigate")
frigate_db = queryScienceDatabase("Ships","Frigate")
end
local generic_frigate_description = "Frigates are one size up from starfighters. They require a crew from 3 to 20 people.\nThink, Firefly, millennium falcon, slave I (Boba fett's ship).\n\nThey generally have 2 or more shield sections, but hardly ever more than 4.\n\nThis class of ships is normally not fitted with jump or warp drives. But in some cases ships are modified to include these, or for certain roles it is built in.\n\nThey are divided in 3 different sub-classes:\n* Cruiser: Weaponized frigates, focused on combat. These come in various roles.\n* Light transport: Small transports, like transporting up to 50 soldiers in spartan conditions or a few diplomats in luxury. Depending on the role it can have some weaponry.\n* Support: Support types come in many varieties. They are simply a frigate hull fitted with whatever was needed. Anything from mine-layers to science vessels."
frigate_db:setLongDescription(generic_frigate_description)
local corvette_db = queryScienceDatabase("Ships","Corvette")
if corvette_db == nil then
ships_db:addEntry("Corvette")
corvette_db = queryScienceDatabase("Ships","Corvette")
end
local generic_corvette_description = "Corvettes are the common large ships. Larger then a frigate, smaller then a dreadnaught.\nThey generally have 4 or more shield sections. Run with a crew of 20 to 250.\nThis class generally has jumpdrives or warpdrives. But lack the maneuverability that is seen in frigates.\n\nThey come in 3 different subclasses:\n* Destroyer: Combat oriented ships. No science, no transport. Just death in a large package.\n* Support: Large scale support roles. Drone carriers fall in this category, as well as mobile repair centers.\n* Freighter: Large scale transport ships. Most common here are the jump freighters, using specialized jumpdrives to cross large distances with large amounts of cargo."
corvette_db:setLongDescription(generic_corvette_description)
local dreadnought_db = queryScienceDatabase("Ships","Dreadnought")
if dreadnought_db == nil then
ships_db:addEntry("Dreadnought")
dreadnought_db = queryScienceDatabase("Ships","Dreadnought")
end
dreadnought_db:setLongDescription("Dreadnoughts are the largest ships.\nThey are so large and uncommon that every type is pretty much their own subclass.\nThey usually come with 6 or more shield sections, require a crew of 250+ to operate.\n\nThink: Stardestroyer.")
--------------------------
-- Stock player ships --
--------------------------
ships_db:addEntry("Mainstream")
local stock_db = queryScienceDatabase("Ships","Mainstream")
stock_db:setLongDescription("Mainstream ships are those ship types that are commonly available to crews serving on the front lines or in well established areas")
---- Starfighters
stock_db:addEntry("Starfighter")
local fighter_stock_db = queryScienceDatabase("Ships","Mainstream","Starfighter")
fighter_stock_db:setLongDescription(generic_starfighter_description)
-- MP52 Hornet
fighter_stock_db:addEntry("MP52 Hornet")
local mp52_hornet_db = queryScienceDatabase("Ships","Mainstream","Starfighter","MP52 Hornet")
mp52_hornet_db:setLongDescription("The MP52 Hornet is a significantly upgraded version of MU52 Hornet, with nearly twice the hull strength, nearly three times the shielding, better acceleration, impulse boosters, and a second laser cannon.")
mp52_hornet_db:setKeyValue("Class","Starfighter")
mp52_hornet_db:setKeyValue("Sub-class","Interceptor")
mp52_hornet_db:setKeyValue("Size","30")
mp52_hornet_db:setKeyValue("Shield","60")
mp52_hornet_db:setKeyValue("Hull","70")
mp52_hornet_db:setKeyValue("Repair Crew",1)
mp52_hornet_db:setKeyValue("Warp Speed","60 U/min") --1000 (added for scenario)
mp52_hornet_db:setKeyValue("Battery Capacity",400)
mp52_hornet_db:setKeyValue("Sensor Ranges","Long: 18 U / Short: 4 U")
mp52_hornet_db:setKeyValue("Move speed","7.5 U/min") --125 (value * 60 / 1000 = units per minute)
mp52_hornet_db:setKeyValue("Turn speed","32 deg/sec")
mp52_hornet_db:setKeyValue("Beam weapon 355:30","Rng:.9 Dmg:2.5 Cyc:4")
mp52_hornet_db:setKeyValue("Beam weapon 5:30","Rng:.9 Dmg:2.5 Cyc:4")
mp52_hornet_db:setImage("radar/fighter.png")
-- Player Fighter
fighter_stock_db:addEntry("Player Fighter")
local player_fighter_db = queryScienceDatabase("Ships","Mainstream","Starfighter","Player Fighter")
player_fighter_db:setLongDescription("A fairly standard fighter with strong beams and a tube for HVLIs. The sensors aren't that great, but it often has a warp drive bolted on making it extraordinarily fast")
player_fighter_db:setKeyValue("Class","Starfighter")
player_fighter_db:setKeyValue("Size","40")
player_fighter_db:setKeyValue("Shield","40")
player_fighter_db:setKeyValue("Hull","60")
player_fighter_db:setKeyValue("Repair Crew",3)
player_fighter_db:setKeyValue("Warp Speed","60 U/min") --1000 (added for scenario)
player_fighter_db:setKeyValue("Battery Capacity",400)
player_fighter_db:setKeyValue("Sensor Ranges","Long: 15 U / Short: 4.5 U")
player_fighter_db:setKeyValue("Move speed","6.6 U/min") --110 (value * 60 / 1000 = units per minute)
player_fighter_db:setKeyValue("Turn speed","20 deg/sec")
player_fighter_db:setKeyValue("Beam weapon 0:40","Rng:.5 Dmg:4 Cyc:6") --modified for scenario: added short forward beam so others balance
player_fighter_db:setKeyValue("Beam weapon 10:40","Rng:1 Dmg:8 Cyc:6")
player_fighter_db:setKeyValue("Beam weapon 350:40","Rng:1 Dmg:8 Cyc:6")
player_fighter_db:setKeyValue("Tube 0","10 sec")
player_fighter_db:setKeyValue("Storage HVLI","4")
player_fighter_db:setImage("radar/fighter.png")
-- Striker
fighter_stock_db:addEntry("Striker")
local striker_db = queryScienceDatabase("Ships","Mainstream","Starfighter","Striker")
striker_db:setLongDescription("The Striker is the predecessor to the advanced striker, slow but agile, but does not do an extreme amount of damage, and lacks in shields")
striker_db:setKeyValue("Class","Starfighter")
striker_db:setKeyValue("Size","140")
striker_db:setKeyValue("Shield","50/30")
striker_db:setKeyValue("Hull","120")
striker_db:setKeyValue("Repair Crew",2)
striker_db:setKeyValue("Jump Range","3 - 40 U") --modified for scenario
striker_db:setKeyValue("Battery Capacity",500)
striker_db:setKeyValue("Sensor Ranges","Long: 35 U / Short: 5 U")
striker_db:setKeyValue("Move speed","2.7 U/min") --45
striker_db:setKeyValue("Turn speed","15 deg/sec")
striker_db:setKeyValue("Beam weapon 345:100","Rng:1 Dmg:6 Cyc:6 Tur:6")
striker_db:setKeyValue("Beam weapon 15:100","Rng:1 Dmg:6 Cyc:6 Tur:6")
striker_db:setImage("radar_adv_striker.png")
-- ZX-Lindworm
fighter_stock_db:addEntry("ZX-Lindworm")
local zx_lindworm_db = queryScienceDatabase("Ships","Mainstream","Starfighter","ZX-Lindworm")
zx_lindworm_db:setLongDescription("The ZX model is an improvement on the WX-Lindworm with stronger hull and shields, faster impulse and tubes, more missiles and a single weak, turreted beam. The 'Worm' as it's often called, is a bomber-class starfighter. While one of the least-shielded starfighters in active duty, the Worm's launchers can pack quite a punch. Its goal is to fly in, destroy its target, and fly out or be destroyed.")
zx_lindworm_db:setKeyValue("Class","Starfighter")
zx_lindworm_db:setKeyValue("Sub-class","Bomber")
zx_lindworm_db:setKeyValue("Size","30")
zx_lindworm_db:setKeyValue("Shield","40")
zx_lindworm_db:setKeyValue("Hull","75")
zx_lindworm_db:setKeyValue("Repair Crew",1)
zx_lindworm_db:setKeyValue("Warp Speed","57 U/min") --950 (added for scenario)
zx_lindworm_db:setKeyValue("Battery Capacity",400)
zx_lindworm_db:setKeyValue("Sensor Ranges","Long: 18 U / Short: 5.5 U")
zx_lindworm_db:setKeyValue("Move speed","4.2 U/min") --70 (value * 60 / 1000 = units per minute)
zx_lindworm_db:setKeyValue("Turn speed","15 deg/sec")
zx_lindworm_db:setKeyValue("Beam weapon 180:270","Rng:.7 Dmg:2 Cyc:6")
zx_lindworm_db:setKeyValue("Small Tube 0","10 sec")
zx_lindworm_db:setKeyValue("Small Tube 359","10 sec")
zx_lindworm_db:setKeyValue("Small Tube 1","10 sec")
zx_lindworm_db:setKeyValue("Storage Homing","3")
zx_lindworm_db:setKeyValue("Storage HVLI","12")
zx_lindworm_db:setImage("radar/fighter.png")
---- Frigates
stock_db:addEntry("Frigate")
local frigate_stock_db = queryScienceDatabase("Ships","Mainstream","Frigate")
frigate_stock_db:setLongDescription(generic_frigate_description)
-- Flavia P.Falcon
frigate_stock_db:addEntry("Flavia P.Falcon")
local flavia_p_falcon_db = queryScienceDatabase("Ships","Mainstream","Frigate","Flavia P.Falcon")
flavia_p_falcon_db:setLongDescription("Popular among traders and smugglers, the Flavia is a small cargo and passenger transport. It's cheaper than a freighter for small loads and short distances, and is often used to carry high-value cargo discreetly.\n\nThe Flavia Falcon is a Flavia transport modified for faster flight, and adds rear-mounted lasers to keep enemies off its back.\n\nThe Flavia P.Falcon has a nuclear-capable rear-facing weapon tube and a warp drive.")
flavia_p_falcon_db:setKeyValue("Class","Frigate")
flavia_p_falcon_db:setKeyValue("Sub-class","Cruiser: Light Transport")
flavia_p_falcon_db:setKeyValue("Size","80")
flavia_p_falcon_db:setKeyValue("Shield","70/70")
flavia_p_falcon_db:setKeyValue("Hull","100")
flavia_p_falcon_db:setKeyValue("Repair Crew",8)
flavia_p_falcon_db:setKeyValue("Warp Speed","30 U/min") --500
flavia_p_falcon_db:setKeyValue("Sensor Ranges","Long: 40 U / Short: 5 U")
flavia_p_falcon_db:setKeyValue("Move speed","3.6 U/min") --60
flavia_p_falcon_db:setKeyValue("Turn speed","10 deg/sec")
flavia_p_falcon_db:setKeyValue("Beam weapon 170:40","Rng:1.2 Dmg:6 Cyc:6")
flavia_p_falcon_db:setKeyValue("Beam weapon 190:40","Rng:1.2 Dmg:6 Cyc:6")
flavia_p_falcon_db:setKeyValue("Tube 180","20 sec")
flavia_p_falcon_db:setKeyValue("Storage Homing","3")
flavia_p_falcon_db:setKeyValue("Storage Nuke","1")
flavia_p_falcon_db:setKeyValue("Storage Mine","1")
flavia_p_falcon_db:setKeyValue("Storage HVLI","5")
flavia_p_falcon_db:setImage("radar/tug.png")
-- Hathcock
frigate_stock_db:addEntry("Hathcock")
local hathcock_db = queryScienceDatabase("Ships","Mainstream","Frigate","Hathcock")
hathcock_db:setLongDescription("Long range narrow beam and some point defense beams, broadside missiles. Agile for a frigate")
hathcock_db:setKeyValue("Class","Frigate")
hathcock_db:setKeyValue("Sub-class","Cruiser: Sniper")
hathcock_db:setKeyValue("Size","80")
hathcock_db:setKeyValue("Shield","70/70")
hathcock_db:setKeyValue("Hull","120")
hathcock_db:setKeyValue("Repair Crew",2)
hathcock_db:setKeyValue("Jump Range","6 - 60 U") --modified for scenario
hathcock_db:setKeyValue("Sensor Ranges","Long: 35 U / Short: 6 U")
hathcock_db:setKeyValue("Move speed","3 U/min") --50
hathcock_db:setKeyValue("Turn speed","15 deg/sec")
hathcock_db:setKeyValue("Beam weapon 0:4","Rng:1.4 Dmg:4 Cyc:6")
hathcock_db:setKeyValue("Beam weapon 0:20","Rng:1.2 Dmg:4 Cyc:6")
hathcock_db:setKeyValue("Beam weapon 0:60","Rng:1.0 Dmg:4 Cyc:6")
hathcock_db:setKeyValue("Beam weapon 0:90","Rng:0.8 Dmg:4 Cyc:6")
hathcock_db:setKeyValue("Tube 270","15 sec")
hathcock_db:setKeyValue("Tube 90","15 sec")
hathcock_db:setKeyValue("Storage Homing","4")
hathcock_db:setKeyValue("Storage Nuke","1")
hathcock_db:setKeyValue("Storage EMP","2")
hathcock_db:setKeyValue("Storage HVLI","8")
hathcock_db:setImage("radar/piranha.png")
-- Nautilus
frigate_stock_db:addEntry("Nautilus")
local nautilus_db = queryScienceDatabase("Ships","Mainstream","Frigate","Nautilus")
nautilus_db:setLongDescription("Small mine laying vessel with minimal armament, shields and hull")
nautilus_db:setKeyValue("Class","Frigate")
nautilus_db:setKeyValue("Sub-class","Mine Layer")
nautilus_db:setKeyValue("Size","80")
nautilus_db:setKeyValue("Shield","60/60")
nautilus_db:setKeyValue("Hull","100")
nautilus_db:setKeyValue("Repair Crew",4)
nautilus_db:setKeyValue("Jump Range","5 - 70 U") --modified for scenario
nautilus_db:setKeyValue("Sensor Ranges","Long: 22 U / Short: 4 U")
nautilus_db:setKeyValue("Move speed","6 U/min") --100
nautilus_db:setKeyValue("Turn speed","10 deg/sec")
nautilus_db:setKeyValue("Beam weapon 35:90","Rng:1 Dmg:6 Cyc:6 Tur:6")
nautilus_db:setKeyValue("Beam weapon 325:90","Rng:1 Dmg:6 Cyc:6 Tur:6")
nautilus_db:setKeyValue("Tube 180","10 sec / Mine")
nautilus_db:setKeyValue(" Tube 180","10 sec / Mine")
nautilus_db:setKeyValue(" Tube 180","10 sec / Mine")
nautilus_db:setKeyValue("Storage Mine","12")
nautilus_db:setImage("radar/tug.png")
-- Phobos M3P
frigate_stock_db:addEntry("Phobos M3P")
local phobos_m3p_db = queryScienceDatabase("Ships","Mainstream","Frigate","Phobos M3P")
phobos_m3p_db:setLongDescription("Player variant of the Phobos M3. Not as strong as the Atlantis, but has front firing tubes, making it an easier to use ship in some scenarios.")
phobos_m3p_db:setKeyValue("Class","Frigate")
phobos_m3p_db:setKeyValue("Sub-class","Cruiser")
phobos_m3p_db:setKeyValue("Size","80")
phobos_m3p_db:setKeyValue("Shield","100/100")
phobos_m3p_db:setKeyValue("Hull","200")
phobos_m3p_db:setKeyValue("Repair Crew",3)
phobos_m3p_db:setKeyValue("Warp Speed","54 U/min") --900 (added for scenario)
phobos_m3p_db:setKeyValue("Sensor Ranges","Long: 25 U / Short: 5 U")
phobos_m3p_db:setKeyValue("Move speed","4.8 U/min") --80
phobos_m3p_db:setKeyValue("Turn speed","10 deg/sec")
phobos_m3p_db:setKeyValue("Beam weapon 345:90","Rng:1.2 Dmg:6 Cyc:8")
phobos_m3p_db:setKeyValue("Beam weapon 15:90","Rng:1.2 Dmg:6 Cyc:8")
phobos_m3p_db:setKeyValue("Tube 359","10 sec")
phobos_m3p_db:setKeyValue("Tube 1","10 sec")
phobos_m3p_db:setKeyValue("Tube 180","10 sec / Mine")
phobos_m3p_db:setKeyValue("Storage Homing","10")
phobos_m3p_db:setKeyValue("Storage Nuke","2")
phobos_m3p_db:setKeyValue("Storage Mine","4")
phobos_m3p_db:setKeyValue("Storage EMP","3")
phobos_m3p_db:setKeyValue("Storage HVLI","20")
phobos_m3p_db:setImage("radar/cruiser.png")
-- Piranha
frigate_stock_db:addEntry("Piranha")
local piranha_db = queryScienceDatabase("Ships","Mainstream","Frigate","Piranha")
piranha_db:setLongDescription("This combat-specialized Piranha F12 adds mine-laying tubes, combat maneuvering systems, and a jump drive.")
piranha_db:setKeyValue("Class","Frigate")
piranha_db:setKeyValue("Sub-class","Cruiser: Light Artillery")
piranha_db:setKeyValue("Size","80")
piranha_db:setKeyValue("Shield","70/70")
piranha_db:setKeyValue("Hull","120")
piranha_db:setKeyValue("Repair Crew",2)
piranha_db:setKeyValue("Jump Range","5 - 50 U")
piranha_db:setKeyValue("Sensor Ranges","Long: 25 U / Short: 6 U")
piranha_db:setKeyValue("Move speed","3.6 U/min") --60
piranha_db:setKeyValue("Turn speed","10 deg/sec")
piranha_db:setKeyValue("Large Tube 270","8 sec / Homing,HVLI")
piranha_db:setKeyValue("Tube 270","8 sec")
piranha_db:setKeyValue(" LargeTube 270","8 sec / Homing,HVLI")
piranha_db:setKeyValue("Large Tube 90","8 sec / Homing,HVLI")
piranha_db:setKeyValue("Tube 90","8 sec")
piranha_db:setKeyValue(" LargeTube 90","8 sec / Homing,HVLI")
piranha_db:setKeyValue("Tube 170","8 sec / Mine")
piranha_db:setKeyValue("Tube 190","8 sec / Mine")
piranha_db:setKeyValue("Storage Homing","12")
piranha_db:setKeyValue("Storage Nuke","6")
piranha_db:setKeyValue("Storage Mine","8")
piranha_db:setKeyValue("Storage HVLI","20")
piranha_db:setImage("radar/piranha.png")
-- Repulse
frigate_stock_db:addEntry("Repulse")
local repulse_db = queryScienceDatabase("Ships","Mainstream","Frigate","Repulse")
repulse_db:setLongDescription("A Flavia P. Falcon with better hull and shields, a jump drive, two turreted beams covering both sides and a forward and rear tube. The nukes and mines are gone")
repulse_db:setKeyValue("Class","Frigate")
repulse_db:setKeyValue("Sub-class","Cruiser: Armored Transport")
repulse_db:setKeyValue("Size","80")
repulse_db:setKeyValue("Shield","80/80")
repulse_db:setKeyValue("Hull","120")
repulse_db:setKeyValue("Repair Crew",8)
repulse_db:setKeyValue("Jump Range","5 - 50 U")
repulse_db:setKeyValue("Sensor Ranges","Long: 38 U / Short: 5 U")
repulse_db:setKeyValue("Move speed","3.3 U/min") --55
repulse_db:setKeyValue("Turn speed","9 deg/sec")
repulse_db:setKeyValue("Beam weapon 90:200","Rng:1.2 Dmg:5 Cyc:6")
repulse_db:setKeyValue("Beam weapon 270:200","Rng:1.2 Dmg:5 Cyc:6")
repulse_db:setKeyValue("Tube 0","20 sec")
repulse_db:setKeyValue("Tube 180","20 sec")
repulse_db:setKeyValue("Storage Homing","4")
repulse_db:setKeyValue("Storage HVLI","6")
repulse_db:setImage("radar/tug.png")
---- Corvettes
stock_db:addEntry("Corvette")
local corvette_stock_db = queryScienceDatabase("Ships","Mainstream","Corvette")
corvette_stock_db:setLongDescription(generic_corvette_description)
-- Atlantis
corvette_stock_db:addEntry("Atlantis")
local atlantis_db = queryScienceDatabase("Ships","Mainstream","Corvette","Atlantis")
atlantis_db:setLongDescription("A refitted Atlantis X23 for more general tasks. The large shield system has been replaced with an advanced combat maneuvering systems and improved impulse engines. Its missile loadout is also more diverse. Mistaking the modified Atlantis for an Atlantis X23 would be a deadly mistake.")
atlantis_db:setKeyValue("Class","Corvette")
atlantis_db:setKeyValue("Sub-class","Destroyer")
atlantis_db:setKeyValue("Size","200")
atlantis_db:setKeyValue("Shield","200/200")
atlantis_db:setKeyValue("Hull","250")
atlantis_db:setKeyValue("Repair Crew",3)
atlantis_db:setKeyValue("Jump Range","5 - 50 U")
atlantis_db:setKeyValue("Sensor Ranges","Long: 30 U / Short: 5 U")
atlantis_db:setKeyValue("Move speed","5.4 U/min") --100
atlantis_db:setKeyValue("Turn speed","10 deg/sec")
atlantis_db:setKeyValue("Beam weapon 340:100","Rng:1.5 Dmg:8 Cyc:6")
atlantis_db:setKeyValue("Beam weapon 20:100","Rng:1.5 Dmg:8 Cyc:6")
atlantis_db:setKeyValue("Tube 270","10 sec")
atlantis_db:setKeyValue(" Tube 270","10 sec")
atlantis_db:setKeyValue("Tube 90","10 sec")
atlantis_db:setKeyValue(" Tube 90","10 sec")
atlantis_db:setKeyValue("Tube 180","10 sec / Mine")
atlantis_db:setKeyValue("Storage Homing","12")
atlantis_db:setKeyValue("Storage Nuke","4")
atlantis_db:setKeyValue("Storage Mine","8")
atlantis_db:setKeyValue("Storage EMP","6")
atlantis_db:setKeyValue("Storage HVLI","20")
atlantis_db:setImage("radar/dread.png")
-- Benedict
corvette_stock_db:addEntry("Benedict")
local benedict_db = queryScienceDatabase("Ships","Mainstream","Corvette","Benedict")
benedict_db:setLongDescription("Benedict is Jump Carrier with a shorter range, but with stronger shields and hull and with minimal armament")
benedict_db:setKeyValue("Class","Corvette")
benedict_db:setKeyValue("Sub-class","Freighter/Carrier")
benedict_db:setKeyValue("Size","200")
benedict_db:setKeyValue("Shield","70/70")
benedict_db:setKeyValue("Hull","200")
benedict_db:setKeyValue("Repair Crew",6)
benedict_db:setKeyValue("Jump Range","5 - 90 U")
benedict_db:setKeyValue("Sensor Ranges","Long: 30 U / Short: 5 U")
benedict_db:setKeyValue("Move speed","3.6 U/min") --60
benedict_db:setKeyValue("Turn speed","6 deg/sec")
benedict_db:setKeyValue("Beam weapon 0:90","Rng:1.5 Dmg:4 Cyc:6 Tur:6")
benedict_db:setKeyValue("Beam weapon 180:90","Rng:1.5 Dmg:4 Cyc:6 Tur:6")
benedict_db:setImage("radar/transport.png")
-- Crucible
corvette_stock_db:addEntry("Crucible")
local crucible_db = queryScienceDatabase("Ships","Mainstream","Corvette","Crucible")
crucible_db:setLongDescription("A number of missile tubes range around this ship. Beams were deemed lower priority, though they are still present. Stronger defenses than a frigate, but not as strong as the Atlantis")
crucible_db:setKeyValue("Class","Corvette")
crucible_db:setKeyValue("Sub-class","Popper")
crucible_db:setKeyValue("Size","80")
crucible_db:setKeyValue("Shield","160/160")
crucible_db:setKeyValue("Hull","160")
crucible_db:setKeyValue("Repair Crew",4)
crucible_db:setKeyValue("Warp Speed","45 U/min") --750
crucible_db:setKeyValue("Sensor Ranges","Long: 20 U / Short: 6 U")
crucible_db:setKeyValue("Move speed","4.8 U/min") --80
crucible_db:setKeyValue("Turn speed","15 deg/sec")
crucible_db:setKeyValue("Beam weapon 330:70","Rng:1 Dmg:5 Cyc:6")
crucible_db:setKeyValue("Beam weapon 30:70","Rng:1 Dmg:5 Cyc:6")
crucible_db:setKeyValue("Small Tube 0","8 sec / HVLI")
crucible_db:setKeyValue("Tube 0","8 sec / HVLI")
crucible_db:setKeyValue("Large Tube 0","8 sec / HVLI")
crucible_db:setKeyValue("Tube 270","8 sec")
crucible_db:setKeyValue("Tube 90","8 sec")
crucible_db:setKeyValue("Tube 180","8 sec / Mine")
crucible_db:setKeyValue("Storage Missiles","H:8 N:4 M:6 E:6 L:24")
crucible_db:setImage("radar/laser.png")
-- Kiriya
corvette_stock_db:addEntry("Kiriya")
local kiriya_db = queryScienceDatabase("Ships","Mainstream","Corvette","Kiriya")
kiriya_db:setLongDescription("Kiriya is Warp Carrier based on the jump carrier with stronger shields and hull and with minimal armament")
kiriya_db:setKeyValue("Class","Corvette")
kiriya_db:setKeyValue("Sub-class","Freighter/Carrier")
kiriya_db:setKeyValue("Size","200")
kiriya_db:setKeyValue("Shield","70/70")
kiriya_db:setKeyValue("Hull","200")
kiriya_db:setKeyValue("Repair Crew",6)
kiriya_db:setKeyValue("Warp Speed","45 U/min") --750
kiriya_db:setKeyValue("Sensor Ranges","Long: 35 U / Short: 5 U")
kiriya_db:setKeyValue("Move speed","3.6 U/min") --60
kiriya_db:setKeyValue("Turn speed","6 deg/sec")
kiriya_db:setKeyValue("Beam weapon 0:90","Rng:1.5 Dmg:4 Cyc:6 Tur:6")
kiriya_db:setKeyValue("Beam weapon 180:90","Rng:1.5 Dmg:4 Cyc:6 Tur:6")
kiriya_db:setImage("radar/transport.png")
-- Maverick
corvette_stock_db:addEntry("Maverick")
local maverick_db = queryScienceDatabase("Ships","Mainstream","Corvette","Maverick")
maverick_db:setLongDescription("A number of beams bristle from various points on this gunner. Missiles were deemed lower priority, though they are still present. Stronger defenses than a frigate, but not as strong as the Atlantis")
maverick_db:setKeyValue("Class","Corvette")
maverick_db:setKeyValue("Sub-class","Gunner")
maverick_db:setKeyValue("Size","80")
maverick_db:setKeyValue("Shield","160/160")
maverick_db:setKeyValue("Hull","160")
maverick_db:setKeyValue("Repair Crew",4)
maverick_db:setKeyValue("Warp Speed","48 U/min") --800
maverick_db:setKeyValue("Sensor Ranges","Long: 20 U / Short: 4 U")
maverick_db:setKeyValue("Move speed","4.8 U/min") --80
maverick_db:setKeyValue("Turn speed","15 deg/sec")
maverick_db:setKeyValue("Beam weapon 0:10","Rng:2 Dmg:6 Cyc:6")
maverick_db:setKeyValue("Beam weapon 340:90","Rng:1.5 Dmg:8 Cyc:6")
maverick_db:setKeyValue("Beam weapon 20:90","Rng:1.5 Dmg:8 Cyc:6")
maverick_db:setKeyValue("Beam weapon 290:40","Rng:1 Dmg:6 Cyc:4")
maverick_db:setKeyValue("Beam weapon 70:40","Rng:1 Dmg:6 Cyc:4")
maverick_db:setKeyValue("Beam weapon 180:180","Rng:.8 Dmg:4 Cyc:6 Tur:.5")
maverick_db:setKeyValue("Tube 270","8 sec")
maverick_db:setKeyValue("Tube 90","8 sec")
maverick_db:setKeyValue("Tube 180","8 sec / Mine")
maverick_db:setKeyValue("Storage Missiles","H:6 N:2 M:2 E:4 L:10")
maverick_db:setImage("radar/laser.png")
-- Player Cruiser
corvette_stock_db:addEntry("Player Cruiser")
local player_cruiser_db = queryScienceDatabase("Ships","Mainstream","Corvette","Player Cruiser")
player_cruiser_db:setLongDescription("A fairly standard cruiser. Stronger than average beams, weaker than average shields, farther than average jump drive range")
player_cruiser_db:setKeyValue("Class","Corvette")
player_cruiser_db:setKeyValue("Size","200")
player_cruiser_db:setKeyValue("Shield","80/80")
player_cruiser_db:setKeyValue("Hull","200")
player_cruiser_db:setKeyValue("Repair Crew",3)
player_cruiser_db:setKeyValue("Jump Range","5 - 80 U") --modified for scenario
player_cruiser_db:setKeyValue("Sensor Ranges","Long: 30 U / Short: 5 U")
player_cruiser_db:setKeyValue("Move speed","5.4 U/min") --90
player_cruiser_db:setKeyValue("Turn speed","10 deg/sec")
player_cruiser_db:setKeyValue("Beam weapon 345:90","Rng:1 Dmg:10 Cyc:6")
player_cruiser_db:setKeyValue("Beam weapon 15:90","Rng:1 Dmg:10 Cyc:6")
player_cruiser_db:setKeyValue("Tube 355","8 sec")
player_cruiser_db:setKeyValue("Tube 5","8 sec")
player_cruiser_db:setKeyValue("Tube 180","8 sec / Mine")
player_cruiser_db:setKeyValue("Storage Homing","12")
player_cruiser_db:setKeyValue("Storage Nuke","4")
player_cruiser_db:setKeyValue("Storage Mine","8")
player_cruiser_db:setKeyValue("Storage EMP","6")
player_cruiser_db:setImage("radar/cruiser.png")
-- Player Missile Cruiser
corvette_stock_db:addEntry("Player Missile Cr.")
local player_missile_cruiser_db = queryScienceDatabase("Ships","Mainstream","Corvette","Player Missile Cr.")
player_missile_cruiser_db:setLongDescription("It's all about the missiles for this model. Broadside tubes shoot homing missiles (30!), front, homing, EMP and nuke. Comparatively weak shields, especially in the rear. Sluggish impulse drive.")
player_missile_cruiser_db:setKeyValue("Class","Corvette")
player_missile_cruiser_db:setKeyValue("Size","100")
player_missile_cruiser_db:setKeyValue("Shield","110/70")
player_missile_cruiser_db:setKeyValue("Hull","200")
player_missile_cruiser_db:setKeyValue("Repair Crew",3)
player_missile_cruiser_db:setKeyValue("Warp Speed","48 U/min") --800
player_missile_cruiser_db:setKeyValue("Sensor Ranges","Long: 35 U / Short: 6 U")
player_missile_cruiser_db:setKeyValue("Move speed","3.6 U/min") --60
player_missile_cruiser_db:setKeyValue("Turn speed","8 deg/sec")
player_missile_cruiser_db:setKeyValue("Tube 0","8 sec")
player_missile_cruiser_db:setKeyValue(" Tube 0","8 sec")
player_missile_cruiser_db:setKeyValue("Tube 90","8 sec / Homing")
player_missile_cruiser_db:setKeyValue(" Tube 90","8 sec / Homing")
player_missile_cruiser_db:setKeyValue("Tube 270","8 sec / Homing")
player_missile_cruiser_db:setKeyValue(" Tube 270","8 sec / Homing")
player_missile_cruiser_db:setKeyValue("Tube 180","8 sec / Mine")
player_missile_cruiser_db:setKeyValue("Storage Homing","30")
player_missile_cruiser_db:setKeyValue("Storage Nuke","8")
player_missile_cruiser_db:setKeyValue("Storage Mine","12")
player_missile_cruiser_db:setKeyValue("Storage EMP","10")
player_missile_cruiser_db:setImage("radar/cruiser.png")
---------------------------
-- Custom player ships --
---------------------------
ships_db:addEntry("Prototype")
local prototype_db = queryScienceDatabase("Ships","Prototype")
prototype_db:setLongDescription("Prototype ships are those that are under development or are otherwise considered experimental. Some have been through several iterations after being tested in the field. Many have been scrapped due to poor design, the ravages of space or perhaps the simple passage of time.")
prototype_db:setImage("gui/icons/station-engineering.png")
---- Starfighters
prototype_db:addEntry("Starfighter")
local fighter_prototype_db = queryScienceDatabase("Ships","Prototype","Starfighter")
fighter_prototype_db:setLongDescription(generic_starfighter_description)
-- Striker LX
fighter_prototype_db:addEntry("Striker LX")
local striker_lx_db = queryScienceDatabase("Ships","Prototype","Starfighter","Striker LX")
striker_lx_db:setLongDescription("The Striker is the predecessor to the advanced striker, slow but agile, but does not do an extreme amount of damage, and lacks in shields. The Striker LX is a modification of the Striker: stronger shields, more energy, jump drive (vs none), faster impulse, slower turret, two rear tubes (vs none)")
striker_lx_db:setKeyValue("Class","Starfighter")
striker_lx_db:setKeyValue("Sub-class","Patrol")
striker_lx_db:setKeyValue("Size","140")
striker_lx_db:setKeyValue("Shield","100/100")
striker_lx_db:setKeyValue("Hull","100")
striker_lx_db:setKeyValue("Repair Crew",3)
striker_lx_db:setKeyValue("Battery Capacity",600)
striker_lx_db:setKeyValue("Jump Range","2 - 20 U")
striker_lx_db:setKeyValue("Sensor Ranges","Long: 20 U / Short: 4 U")
striker_lx_db:setKeyValue("Move speed","3.9 U/min") --65 (value * 60 / 1000 = units per minute)
striker_lx_db:setKeyValue("Turn speed","35 deg/sec")
striker_lx_db:setKeyValue("Beam weapon 345:100","Rng:1.1 Dmg:6.5 Cyc:6 Tur:.2")
striker_lx_db:setKeyValue("Beam weapon 15:100","Rng:1.1 Dmg:6.5 Cyc:6 Tur:.2")
striker_lx_db:setKeyValue("Tube 180","10 sec")
striker_lx_db:setKeyValue(" Tube 180","10 sec")
striker_lx_db:setKeyValue("Storage Homing","4")
striker_lx_db:setKeyValue("Storage Nuke","2")
striker_lx_db:setKeyValue("Storage Mine","3")
striker_lx_db:setKeyValue("Storage EMP","3")
striker_lx_db:setKeyValue("Storage HVLI","6")
striker_lx_db:setImage("radar/adv_striker.png")
---- Frigates
prototype_db:addEntry("Frigate")
local frigate_prototype_db = queryScienceDatabase("Ships","Prototype","Frigate")
frigate_prototype_db:setLongDescription(generic_frigate_description)
-- Phobos T2
frigate_prototype_db:addEntry("Phobos T2")
local phobos_t2_db = queryScienceDatabase("Ships","Prototype","Frigate","Phobos T2")
phobos_t2_db:setLongDescription("Based on Phobos M3P with these differences: more repair crew, a jump drive, faster spin, stronger front shield, weaker rear shield, less maximum energy, turreted and faster beams, one fewer tube forward, and fewer missiles")
phobos_t2_db:setKeyValue("Class","Frigate")
phobos_t2_db:setKeyValue("Sub-class","Cruiser")
phobos_t2_db:setKeyValue("Size","80")
phobos_t2_db:setKeyValue("Shield","120/80")
phobos_t2_db:setKeyValue("Hull","200")
phobos_t2_db:setKeyValue("Repair Crew",4)
phobos_t2_db:setKeyValue("Battery Capacity",800)
phobos_t2_db:setKeyValue("Jump Range","2 - 25 U")
phobos_t2_db:setKeyValue("Sensor Ranges","Long: 25 U / Short: 5 U")
phobos_t2_db:setKeyValue("Move speed","4.8 U/min") --80
phobos_t2_db:setKeyValue("Turn speed","20 deg/sec")
phobos_t2_db:setKeyValue("Beam weapon 330:40","Rng:1.2 Dmg:6 Cyc:4 Tur:.2")
phobos_t2_db:setKeyValue("Beam weapon 30:40","Rng:1.2 Dmg:6 Cyc:4 Tur:.2")
phobos_t2_db:setKeyValue("Tube 0","10 sec")
phobos_t2_db:setKeyValue("Tube 180","10 sec / Mine")
phobos_t2_db:setKeyValue("Storage Homing",8)
phobos_t2_db:setKeyValue("Storage Nuke",2)
phobos_t2_db:setKeyValue("Storage Mine",4)
phobos_t2_db:setKeyValue("Storage EMP",3)
phobos_t2_db:setKeyValue("Storage HVLI",16)
phobos_t2_db:setImage("radar/cruiser.png")
---- Corvettes
prototype_db:addEntry("Corvette")
local corvette_prototype_db = queryScienceDatabase("Ships","Prototype","Corvette")
corvette_prototype_db:setLongDescription(generic_corvette_description)
-- Focus
corvette_prototype_db:addEntry("Focus")
local focus_db = queryScienceDatabase("Ships","Prototype","Corvette","Focus")
focus_db:setLongDescription("Adjusted Crucible: short jump drive (no warp), faster impulse and spin, weaker shields and hull, narrower beams, fewer tubes. The large tube accomodates nukes, EMPs and homing missiles")
focus_db:setKeyValue("Class","Corvette")
focus_db:setKeyValue("Sub-class","Popper")
focus_db:setKeyValue("Size","200")
focus_db:setKeyValue("Shield","100/100")
focus_db:setKeyValue("Hull","100")
focus_db:setKeyValue("Repair Crew",4)
focus_db:setKeyValue("Jump Range","2.5 - 25 U")
focus_db:setKeyValue("Sensor Ranges","Long: 32 U / Short: 5 U")
focus_db:setKeyValue("Move speed","4.2 U/min") --70
focus_db:setKeyValue("Turn speed","20 deg/sec")
focus_db:setKeyValue("Beam weapon 340:60","Rng:1 Dmg:5 Cyc:6")
focus_db:setKeyValue("Beam weapon 20:60","Rng:1 Dmg:5 Cyc:6")
focus_db:setKeyValue("Small Tube 0","8 sec / HVLI")
focus_db:setKeyValue("Tube 0","8 sec / HVLI")
focus_db:setKeyValue("Large Tube 0","8 sec")
focus_db:setKeyValue("Tube 180","8 sec / Mine")
focus_db:setKeyValue("Storage Homing",8)
focus_db:setKeyValue("Storage Nuke",1)
focus_db:setKeyValue("Storage Mine",6)
focus_db:setKeyValue("Storage EMP",2)
focus_db:setKeyValue("Storage HVLI",24)
focus_db:setImage("radar/laser.png")
-- Holmes
corvette_prototype_db:addEntry("Holmes")
local holmes_db = queryScienceDatabase("Ships","Prototype","Corvette","Holmes")
holmes_db:setLongDescription("Revised Crucible: weaker shields, side beams, fewer tubes, fewer missiles, EMPs and Nukes in front middle tube and large homing missiles")
holmes_db:setKeyValue("Class","Corvette")
holmes_db:setKeyValue("Sub-class","Popper")
holmes_db:setKeyValue("Size","200")
holmes_db:setKeyValue("Shield","160/160")
holmes_db:setKeyValue("Hull","160")
holmes_db:setKeyValue("Repair Crew",4)
holmes_db:setKeyValue("Warp Speed","45.0 U/min") --750
holmes_db:setKeyValue("Sensor Ranges","Long: 35 U / Short: 4 U")
holmes_db:setKeyValue("Move speed","4.2 U/min") --70
holmes_db:setKeyValue("Turn speed","15 deg/sec")
holmes_db:setKeyValue("Beam weapon 275:50","Rng:.9 Dmg:5 Cyc:6")
holmes_db:setKeyValue("Beam weapon 265:50","Rng:.9 Dmg:5 Cyc:6")
holmes_db:setKeyValue("Beam weapon 85:50","Rng:.9 Dmg:5 Cyc:6")
holmes_db:setKeyValue("Beam weapon 95:50","Rng:.9 Dmg:5 Cyc:6")
holmes_db:setKeyValue("Small Tube 0","8 sec / Homing")
holmes_db:setKeyValue("Tube 0","8 sec / Homing")
holmes_db:setKeyValue("Large Tube 0","8 sec / Homing")
holmes_db:setKeyValue("Tube 180","8 sec / Mine")
holmes_db:setKeyValue("Storage Homing",10)
holmes_db:setKeyValue("Storage Mine",6)
holmes_db:setImage("radar/laser.png")
-- Maverick XP
corvette_prototype_db:addEntry("Maverick XP")
local maverick_xp_db = queryScienceDatabase("Ships","Prototype","Corvette","Maverick XP")
maverick_xp_db:setLongDescription("Based on Maverick: slower impulse, jump (no warp), one heavy slow turreted beam (not 6 beams)")
maverick_xp_db:setKeyValue("Class","Corvette")
maverick_xp_db:setKeyValue("Sub-class","Gunner")
maverick_xp_db:setKeyValue("Size","200")
maverick_xp_db:setKeyValue("Shield","160/160")
maverick_xp_db:setKeyValue("Hull","160")
maverick_xp_db:setKeyValue("Repair Crew",4)
maverick_xp_db:setKeyValue("Jump Range","2 - 20 U")
maverick_xp_db:setKeyValue("Sensor Ranges","Long: 25 U / Short: 7 U")
maverick_xp_db:setKeyValue("Move speed","3.9 U/min") --65
maverick_xp_db:setKeyValue("Turn speed","15 deg/sec")
maverick_xp_db:setKeyValue("Beam weapon 0:270","Rng:1 Dmg:20 Cyc:20 Tur:.2")
maverick_xp_db:setKeyValue("Tube 270","8 sec")
maverick_xp_db:setKeyValue("Tube 90","8 sec")
maverick_xp_db:setKeyValue("Tube 180","8 sec / Mine")
maverick_xp_db:setKeyValue("Storage Homing",6)
maverick_xp_db:setKeyValue("Storage Nuke",2)
maverick_xp_db:setKeyValue("Storage Mine",2)
maverick_xp_db:setKeyValue("Storage EMP",4)
maverick_xp_db:setKeyValue("Storage HVLI",10)
maverick_xp_db:setImage("radar/laser.png")
end
------------------
-- GM Buttons --
------------------
function setGMButtons()
mainGMButtons = mainGMButtonsDuringPause
mainGMButtons()
end
function mainGMButtonsDuringPause()
clearGMFunctions()
local button_label = ""
addGMFunction(string.format(_("buttonGM", "Version %s"),scenario_version),function()
local version_message = string.format(_("msgGM", "Scenario version %s\n LUA version %s"),scenario_version,_VERSION)
addGMMessage(version_message)
print(version_message)
end)
if not terrain_generated then
addGMFunction(_("buttonGM", "+Player Config"),setPlayerConfig)
button_label = _("buttonGM", "+NPC Ships: 0")
if npc_ships then
button_label = string.format(_("buttonGM", "+NPC Ships: %i-%i"),npc_lower,npc_upper)
end
addGMFunction(button_label,setNPCShips)
addGMFunction(_("buttonGM", "+Terrain"),setTerrainParameters)
addGMFunction(string.format(_("buttonGM", "Respawn: %s"),respawn_type),function()
if respawn_type == "lindworm" then
respawn_type = "self"
elseif respawn_type == "self" then
respawn_type = "lindworm"
end
mainGMButtons()
end)
else
addGMFunction(_("buttonGM", "Show control codes"),showControlCodes)
addGMFunction(_("buttonGM", "Show Human codes"),showHumanCodes)
addGMFunction(_("buttonGM", "Show Kraylor codes"),showKraylorCodes)
if exuari_angle ~= nil then
addGMFunction(_("buttonGM", "Show Exuari codes"),showExuariCodes)
end
if ktlitan_angle ~= nil then
addGMFunction(_("buttonGM", "Show Ktlitan codes"),showKtlitanCodes)
end
addGMFunction("Reset control codes",resetControlCodes)
end
addGMFunction(string.format(_("buttonGM", "+Stn Sensors %iU"),station_sensor_range/1000),setStationSensorRange)
addGMFunction(string.format(_("buttonGM", "+Game Time %i"),game_time_limit/60),setGameTimeLimit)
button_label = _("buttonGM", "No")
if advanced_intel then
button_label = _("buttonGM", "Yes")
end
addGMFunction(string.format(_("buttonGM", "+Advance Intel %s"),button_label),setAdvanceIntel)
addGMFunction(_("buttonGM", "Explain"),function()
if terrain_generated then
addGMMessage(_("msgGM", "The version button just provides scenario version information on the text of the button plus the Lua version when you click it. Explanations for Stn sensors, Game time and Advance intel may be obtained by clicking those buttons.\n\nThe various control codes buttons show the control codes for the various player ships: all or by team faction."))
else
addGMMessage(_("msgGM", "The version button just provides scenario version information on the text of the button plus the Lua version when you click it. Explanations for NPC Ships, Terrain, Stn sensors, Game time and Advance intel may be obtained by clicking those buttons.\n\nThe Respawn button determines how a player ship is respawned if it is destroyed. The Lindworm option means the players come back in a Lindworm. The Self option means the players come back as the same type of ship they started in."))
end
end)
end
function setPlayerConfig()
clearGMFunctions()
addGMFunction(_("buttonGM", "-Main from P. Config"),mainGMButtons)
if not terrain_generated then
addGMFunction(string.format(_("buttonGM", "+Player Teams: %i"),player_team_count),setPlayerTeamCount)
addGMFunction(string.format(_("buttonGM", "+Player Ships: %i (%i)"),ships_per_team,ships_per_team*player_team_count),setPlayerShipCount)
addGMFunction(string.format(_("buttonGM", "+P.Ship Types: %s"),player_ship_types),setPlayerShipTypes)
if predefined_player_ships ~= nil then
addGMFunction(_("buttonGM", "Random PShip Names"),function()
addGMMessage(_("msgGM", "Player ship names will be selected at random"))
predefined_player_ships = nil
setPlayerConfig()
end)
addGMFunction(_("buttonGM", "Explain"),function()
addGMMessage(_("msgGM", "Player teams is the number of player teams. Player ships and player ship types are explained after you click those buttons.\n\nThe button 'Random PShip Names' switches from a fixed list of player ship names to selecting player ship names at random from a pool of player ship names. There is no going back to the fixed player ship names once you click this button unless you restart the server."))
end)
end
end
end
function mainGMButtonsAfterPause()
clearGMFunctions()
addGMFunction(string.format(_("buttonGM", "Version %s"),scenario_version),function()
local version_message = string.format(_("msgGM", "Scenario version %s\n LUA version %s"),scenario_version,_VERSION)
addGMMessage(version_message)
print(version_message)
end)
addGMFunction(_("buttonGM", "Show control codes"),showControlCodes)
addGMFunction(_("buttonGM", "Show Human codes"),showHumanCodes)
addGMFunction(_("buttonGM", "Show Kraylor codes"),showKraylorCodes)
if exuari_angle ~= nil then
addGMFunction(_("buttonGM", "Show Exuari codes"),showExuariCodes)
end
if ktlitan_angle ~= nil then
addGMFunction(_("buttonGM", "Show Ktlitan codes"),showKtlitanCodes)
end
addGMFunction(_("buttonGM", "Statistics Summary"),function()
local stat_list = gatherStats()
local out = _("buttonGM", "Current Scores:")
out = string.format(_("msgGM", "%s\n Human Navy: %.2f (%.1f%%)"),out,stat_list.human.weighted_score,stat_list.human.weighted_score/original_score["Human Navy"]*100)
out = string.format(_("msgGM", "%s\n Kraylor: %.2f (%.1f%%)"),out,stat_list.kraylor.weighted_score,stat_list.kraylor.weighted_score/original_score["Kraylor"]*100)
if exuari_angle ~= nil then
out = string.format(_("msgGM", "%s\n Exuari: %.2f (%.1f%%)"),out,stat_list.exuari.weighted_score,stat_list.exuari.weighted_score/original_score["Exuari"]*100)
end
if ktlitan_angle ~= nil then
out = string.format(_("msgGM", "\n Ktlitans: %.2f (%.1f%%)"),out,stat_list.ktlitan.weighted_score,stat_list.ktlitan.weighted_score/original_score["Ktlitans"]*100)
end
local out = string.format(_("msgGM", "%s\nOriginal scores:"),out)
out = string.format(_("msgGM", "%s\n Human Navy: %.2f"),out,original_score["Human Navy"])
out = string.format(_("msgGM", "%s\n Kraylor: %.2f"),out,original_score["Kraylor"])
if exuari_angle ~= nil then
out = string.format(_("msgGM", "%s\n Exuari: %.2f"),out,original_score["Exuari"])
end
if ktlitan_angle ~= nil then
out = string.format(_("msgGM", "%s\n Ktlitans: %.2f"),out,original_score["Ktlitans"])
end
addGMMessage(out)
end)
addGMFunction(_("buttonGM", "Statistics Details"),function()
local stat_list = gatherStats()
local tie_breaker = {}
for i,p in ipairs(getActivePlayerShips()) do
tie_breaker[p:getFaction()] = p:getReputationPoints()/10000
end
out = _("msgGM", "Human Navy:\n Stations: (score value, type, name)")
print("Human Navy:")
print(" Stations: (score value, type, name)")
for name, details in pairs(stat_list.human.station) do
out = string.format(_("msgGM", "%s\n %i %s %s"),out,details.score_value,details.template_type,name)
print(" ",details.score_value,details.template_type,name)
end
local weighted_stations = stat_list.human.station_score_total * stat_list.weight.station
out = string.format(_("msgGM", "%s\n Station Total:%i Weight:%.1f Weighted total:%.2f"),out,stat_list.human.station_score_total,stat_list.weight.station,weighted_stations)
print(" Station Total:",stat_list.human.station_score_total,"Weight:",stat_list.weight.station,"Weighted Total:",weighted_stations)
out = string.format(_("msgGM", "%s\n Player Ships: (score value, type, name)"),out)
print(" Player Ships: (score value, type, name)")
for name, details in pairs(stat_list.human.ship) do
out = string.format(_("msgGM", "%s\n %i %s %s"),out,details.score_value,details.template_type,name)
print(" ",details.score_value,details.template_type,name)
end
local weighted_players = stat_list.human.ship_score_total * stat_list.weight.ship
out = string.format(_("msgGM", "%s\n Player Ship Total:%i Weight:%.1f Weighted total:%.2f"),out,stat_list.human.ship_score_total,stat_list.weight.ship,weighted_players)
print(" Player Ship Total:",stat_list.human.ship_score_total,"Weight:",stat_list.weight.ship,"Weighted Total:",weighted_players)
out = string.format(_("msgGM", "%s\n NPC Assets: score value, type, name (location)"),out)
print(" NPC Assets: score value, type, name (location)")
for name, details in pairs(stat_list.human.npc) do
if details.template_type ~= nil then
out = string.format(_("msgGM", "%s\n %i %s %s"),out,details.score_value,details.template_type,name)
print(" ",details.score_value,details.template_type,name)
elseif details.topic ~= nil then
out = string.format(_("msgGM", "%s\n %i %s %s (%s)"),out,details.score_value,details.topic,name,details.location_name)
print(" ",details.score_value,details.topic,name,"(" .. details.location_name .. ")")
end
end
local weighted_npcs = stat_list.human.npc_score_total * stat_list.weight.npc
out = string.format(_("msgGM", "%s\n NPC Asset Total:%i Weight:%.1f Weighted total:%.2f"),out,stat_list.human.npc_score_total,stat_list.weight.npc,weighted_npcs)
print(" NPC Asset Total:",stat_list.human.npc_score_total,"Weight:",stat_list.weight.npc,"Weighted Total:",weighted_npcs)
if respawn_type == "self" then
local weighted_death_penalty = stat_list.human.death_penalty * stat_list.weight.ship
out = string.format(_("msgGM","%s\n Player ship death penalty:%i Weight:%.1f Weighted Total:%,2f"),out,stat_list.human.death_penalty,stat_list.weight.ship,weighted_death_penalty)
print(" Player ship death penalty:",stat_list.human.death_penalty,"Weight:",stat_list.weight.ship,"Weighted Total:",weighted_death_penalty)
end
out = string.format(_("msgGM", "%s\n----Human weighted total:%.1f Original:%.1f Change:%.2f%%"),out,stat_list.human.weighted_score,original_score["Human Navy"],stat_list.human.weighted_score/original_score["Human Navy"]*100)
print("----Human weighted total:",stat_list.human.weighted_score,"Original:",original_score["Human Navy"],"Change:",stat_list.human.weighted_score/original_score["Human Navy"]*100 .. "%")
out = string.format(_("msgGM","%sHuman tie breaker points:%f"),out,tie_breaker["Human Navy"])
print("Human tie breaker points:",tie_breaker["Human Navy"])
out = string.format(_("msgGM", "%s\nKraylor:\n Stations: (score value, type, name)"),out)
print("Kraylor:")
print(" Stations: (score value, type, name)")
for name, details in pairs(stat_list.kraylor.station) do
out = string.format(_("msgGM", "%s\n %i %s %s"),out,details.score_value,details.template_type,name)
print(" ",details.score_value,details.template_type,name)
end
local weighted_stations = stat_list.kraylor.station_score_total * stat_list.weight.station
out = string.format(_("msgGM", "%s\n Station Total:%i Weight:%.1f Weighted total:%.2f"),out,stat_list.kraylor.station_score_total,stat_list.weight.station,weighted_stations)
print(" Station Total:",stat_list.kraylor.station_score_total,"Weight:",stat_list.weight.station,"Weighted Total:",weighted_stations)
out = string.format(_("msgGM", "%s\n Player Ships: (score value, type, name)"),out)
print(" Player Ships: (score value, type, name)")
for name, details in pairs(stat_list.kraylor.ship) do
out = string.format(_("msgGM", "\n %i %s %s"),out,details.score_value,details.template_type,name)
print(" ",details.score_value,details.template_type,name)
end
local weighted_players = stat_list.kraylor.ship_score_total * stat_list.weight.ship
out = string.format(_("msgGM", "%s\n Player Ship Total:%i Weight:%.1f Weighted total:%.2f"),out,stat_list.kraylor.ship_score_total,stat_list.weight.ship,weighted_players)
print(" Player Ship Total:",stat_list.kraylor.ship_score_total,"Weight:",stat_list.weight.ship,"Weighted Total:",weighted_players)
out = string.format(_("msgGM", "%s\n NPC Assets: score value, type, name (location)"),out)
print(" NPC Assets: score value, type, name (location)")
for name, details in pairs(stat_list.kraylor.npc) do
if details.template_type ~= nil then
out = string.format(_("msgGM", "%s\n %i %s %s"),out,details.score_value,details.template_type,name)
print(" ",details.score_value,details.template_type,name)
elseif details.topic ~= nil then
out = string.format(_("msgGM", "%s\n %i %s %s (%s)"),out,details.score_value,details.topic,name,details.location_name)
print(" ",details.score_value,details.topic,name,"(" .. details.location_name .. ")")
end
end
local weighted_npcs = stat_list.kraylor.npc_score_total * stat_list.weight.npc
out = string.format(_("msgGM", "%s\n NPC Asset Total:%i Weight:%.1f Weighted total:%.2f"),out,stat_list.kraylor.npc_score_total,stat_list.weight.npc,weighted_npcs)
print(" NPC Asset Total:",stat_list.kraylor.npc_score_total,"Weight:",stat_list.weight.npc,"Weighted Total:",weighted_npcs)
if respawn_type == "self" then
local weighted_death_penalty = stat_list.kraylor.death_penalty * stat_list.weight.ship
out = string.format(_("msgGM","%s\n Player ship death penalty:%i Weight:%.1f Weighted Total:%,2f"),out,stat_list.kraylor.death_penalty,stat_list.weight.ship,weighted_death_penalty)
print(" Player ship death penalty:",stat_list.kraylor.death_penalty,"Weight:",stat_list.weight.ship,"Weighted Total:",weighted_death_penalty)
end
out = string.format(_("msgGM", "%s\n----Kraylor weighted total:%.1f Original:%.1f Change:%.2f%%"),out,stat_list.kraylor.weighted_score,original_score["Kraylor"],stat_list.kraylor.weighted_score/original_score["Kraylor"]*100)
print("----Kraylor weighted total:",stat_list.kraylor.weighted_score,"Original:",original_score["Kraylor"],"Change:",stat_list.kraylor.weighted_score/original_score["Kraylor"]*100 .. "%")
out = string.format(_("msgGM","%sKraylor tie breaker points:%f"),out,tie_breaker["Kraylor"])
print("Kraylor tie breaker points:",tie_breaker["Kraylor"])
if exuari_angle ~= nil then
out = string.format(_("msgGM", "%s\nExuari:\n Stations: (score value, type, name)"),out)
print("Exuari:")
print(" Stations: (score value, type, name)")
for name, details in pairs(stat_list.exuari.station) do
out = string.format(_("msgGM", "%s\n %i %s %s"),out,details.score_value,details.template_type,name)
print(" ",details.score_value,details.template_type,name)
end
local weighted_stations = stat_list.exuari.station_score_total * stat_list.weight.station
out = string.format(_("msgGM", "%s\n Station Total:%i Weight:%.1f Weighted total:%.2f"),out,stat_list.exuari.station_score_total,stat_list.weight.station,weighted_stations)
print(" Station Total:",stat_list.exuari.station_score_total,"Weight:",stat_list.weight.station,"Weighted Total:",weighted_stations)
out = string.format(_("msgGM", "\n Player Ships: (score value, type, name)"),out)
print(" Player Ships: (score value, type, name)")
for name, details in pairs(stat_list.exuari.ship) do
out = string.format(_("msgGM", "%s\n %i %s %s"),out,details.score_value,details.template_type,name)
print(" ",details.score_value,details.template_type,name)
end
local weighted_players = stat_list.exuari.ship_score_total * stat_list.weight.ship
out = string.format(_("msgGM", "%s\n Player Ship Total:%i Weight:%.1f Weighted total:%.2f"),out,stat_list.exuari.ship_score_total,stat_list.weight.ship,weighted_players)
print(" Player Ship Total:",stat_list.exuari.ship_score_total,"Weight:",stat_list.weight.ship,"Weighted Total:",weighted_players)
out = string.format(_("msgGM", "%s\n NPC Assets: score value, type, name (location)"),out)
print(" NPC Assets: score value, type, name (location)")
for name, details in pairs(stat_list.exuari.npc) do
if details.template_type ~= nil then
out = string.format(_("msgGM", "%s\n %i %s %s"),out,details.score_value,details.template_type,name)
print(" ",details.score_value,details.template_type,name)
elseif details.topic ~= nil then
out = string.format(_("msgGM", "%s\n %i %s %s (%s)"),out,details.score_value,details.topic,name,details.location_name)
print(" ",details.score_value,details.topic,name,"(" .. details.location_name .. ")")
end
end
local weighted_npcs = stat_list.exuari.npc_score_total * stat_list.weight.npc
out = string.format(_("msgGM", "%s\n NPC Asset Total:%i Weight:%.1f Weighted total:%.2f"),out,stat_list.exuari.npc_score_total,stat_list.weight.npc,weighted_npcs)
print(" NPC Asset Total:",stat_list.exuari.npc_score_total,"Weight:",stat_list.weight.npc,"Weighted Total:",weighted_npcs)
if respawn_type == "self" then
local weighted_death_penalty = stat_list.exuari.death_penalty * stat_list.weight.ship
out = string.format(_("msgGM","%s\n Player ship death penalty:%i Weight:%.1f Weighted Total:%,2f"),out,stat_list.exuari.death_penalty,stat_list.weight.ship,weighted_death_penalty)
print(" Player ship death penalty:",stat_list.exuari.death_penalty,"Weight:",stat_list.weight.ship,"Weighted Total:",weighted_death_penalty)
end
out = string.format(_("msgGM", "%s\n----Exuari weighted total:%.1f Original:%.1f Change:%.2f%%"),out,stat_list.exuari.weighted_score,original_score["Exuari"],stat_list.exuari.weighted_score/original_score["Exuari"]*100)
print("----Exuari weighted total:",stat_list.exuari.weighted_score,"Original:",original_score["Exuari"],"Change:",stat_list.exuari.weighted_score/original_score["Exuari"]*100 .. "%")
out = string.format(_("msgGM","%sExuari tie breaker points:%f"),out,tie_breaker["Exuari"])
print("Exuari tie breaker points:",tie_breaker["Exuari"])
end
if ktlitan_angle ~= nil then
out = string.format(_("msgGM", "\nKtlitan:\n Stations: (score value, type, name)"),out)
print("Ktlitan:")
print(" Stations: (score value, type, name)")
for name, details in pairs(stat_list.ktlitan.station) do
out = string.format(_("msgGM", "%s\n %i %s %s"),out,details.score_value,details.template_type,name)
print(" ",details.score_value,details.template_type,name)
end
local weighted_stations = stat_list.ktlitan.station_score_total * stat_list.weight.station
out = string.format(_("msgGM", "%s\n Station Total:%i Weight:%.1f Weighted total:%.2f"),out,stat_list.ktlitan.station_score_total,stat_list.weight.station,weighted_stations)
print(" Station Total:",stat_list.ktlitan.station_score_total,"Weight:",stat_list.weight.station,"Weighted Total:",weighted_stations)
out = string.format(_("msgGM", "%s\n Player Ships: (score value, type, name)"),out)
print(" Player Ships: (score value, type, name)")
for name, details in pairs(stat_list.ktlitan.ship) do
out = string.format(_("msgGM", "%s\n %i %s %s"),out,details.score_value,details.template_type,name)
print(" ",details.score_value,details.template_type,name)
end
local weighted_players = stat_list.ktlitan.ship_score_total * stat_list.weight.ship
out = string.format(_("msgGM", "%s\n Player Ship Total:%i Weight:%.1f Weighted total:%.2f"),out,stat_list.ktlitan.ship_score_total,stat_list.weight.ship,weighted_players)
print(" Player Ship Total:",stat_list.ktlitan.ship_score_total,"Weight:",stat_list.weight.ship,"Weighted Total:",weighted_players)
out = string.format(_("msgGM", "%s\n NPC Assets: score value, type, name (location)"),out)
print(" NPC Assets: score value, type, name (location)")
for name, details in pairs(stat_list.ktlitan.npc) do
if details.template_type ~= nil then
out = string.format(_("msgGM", "%s\n %i %s %s"),out,details.score_value,details.template_type,name)
print(" ",details.score_value,details.template_type,name)
elseif details.topic ~= nil then
out = string.format(_("msgGM", "%s\n %i %s %s (%s)"),out,details.score_value,details.topic,name,details.location_name)
print(" ",details.score_value,details.topic,name,"(" .. details.location_name .. ")")
end
end
local weighted_npcs = stat_list.ktlitan.npc_score_total * stat_list.weight.npc
out = string.format(_("msgGM", "%s\n NPC Asset Total:%i Weight:%.1f Weighted total:%.2f"),out,stat_list.ktlitan.npc_score_total,stat_list.weight.npc,weighted_npcs)
print(" NPC Asset Total:",stat_list.ktlitan.npc_score_total,"Weight:",stat_list.weight.npc,"Weighted Total:",weighted_npcs)
if respawn_type == "self" then
local weighted_death_penalty = stat_list.ktlitan.death_penalty * stat_list.weight.ship
out = string.format(_("msgGM","%s\n Player ship death penalty:%i Weight:%.1f Weighted Total:%,2f"),out,stat_list.ktlitan.death_penalty,stat_list.weight.ship,weighted_death_penalty)
print(" Player ship death penalty:",stat_list.ktlitan.death_penalty,"Weight:",stat_list.weight.ship,"Weighted Total:",weighted_death_penalty)
end
out = string.format(_("msgGM", "%s\n----Ktlitan weighted total:%.1f Original:%.1f Change:%.2f%%"),out,stat_list.ktlitan.weighted_score,original_score["Ktlitans"],stat_list.ktlitan.weighted_score/original_score["Ktlitans"]*100)
print("----Ktlitan weighted total:",stat_list.ktlitan.weighted_score,"Original:",original_score["Ktlitans"],"Change:",stat_list.ktlitan.weighted_score/original_score["Ktlitans"]*100 .. "%")
out = string.format(_("msgGM","%sKtlitan tie breaker points:%f"),out,tie_breaker["Ktlitans"])
print("Ktlitan tie breaker points:",tie_breaker["Ktlitans"])
end
addGMMessage(out)
end)
end
-- Player related GM configuration functions
function setPlayerTeamCount()
clearGMFunctions()
addGMFunction(_("buttonGM", "-Main from Teams"),mainGMButtons)
local button_label = _("buttonGM", "2")
if player_team_count == 2 then
button_label = button_label .. _("buttonGM", "*")
end
addGMFunction(button_label,function()
player_team_count = 2
setPlayerConfig()
end)
local button_label = _("buttonGM", "3")
if player_team_count == 3 then
button_label = button_label .. _("buttonGM", "*")
end
addGMFunction(button_label,function()
player_team_count = 3
if ships_per_team > max_ships_per_team[player_team_count] then
ships_per_team = max_ships_per_team[player_team_count]
if player_ship_types == "spawned" then
addGMMessage(_("msgGM", "Switching player ship type to default"))
player_ship_types = "default"
end
end
setPlayerConfig()
end)
local button_label = _("buttonGM", "4")
if player_team_count == 4 then
button_label = button_label .. _("buttonGM", "*")
end
addGMFunction(button_label,function()
player_team_count = 4
if ships_per_team > max_ships_per_team[player_team_count] then
ships_per_team = max_ships_per_team[player_team_count]
if player_ship_types == "spawned" then
addGMMessage(_("msgGM", "Switching player ship type to default"))
player_ship_types = "default"
end
end
setPlayerConfig()
end)
end
function setPlayerShipCount()
clearGMFunctions()
addGMFunction(_("buttonGM", "-Main from Ships"),mainGMButtons)
addGMFunction(_("buttonGM", "-Player Config"),setPlayerConfig)
if ships_per_team < max_ships_per_team[player_team_count] then
addGMFunction(string.format(_("buttonGM", "%i ships add -> %i"),ships_per_team,ships_per_team + 1),function()
ships_per_team = ships_per_team + 1
if player_ship_types == "spawned" then
addGMMessage(_("msgGM", "Switching player ship type to default"))
player_ship_types = "default"
end
setPlayerShipCount()
end)
end
if ships_per_team > 1 then
addGMFunction(string.format(_("buttonGM", "%i ships del -> %i"),ships_per_team,ships_per_team - 1),function()
ships_per_team = ships_per_team - 1
if player_ship_types == "spawned" then
addGMMessage(_("msgGM", "Switching player ship type to default"))
player_ship_types = "default"
end
setPlayerShipCount()
end)
end
addGMFunction(_("buttonGM", "Explain"),function()
addGMMessage(_("msgGM", "This is where you set the number of player ships per team. The number of non-player ships is set under NPC Ships."))
end)
end
function setPlayerShipTypes()
clearGMFunctions()
addGMFunction(_("buttonGM", "-Main from Ship Types"),mainGMButtons)
addGMFunction(_("buttonGM", "-Player Config"),setPlayerConfig)
local button_label = "default"
if player_ship_types == button_label then
button_label = button_label .. _("buttonGM", "*")
end
addGMFunction(button_label,function()
player_ship_types = "default"
local player_plural = "players"
local type_plural = "types"
if ships_per_team == 1 then
player_plural = "player"
type_plural = "type"
end
local out = string.format(_("msgGM", "Default ship %s for a team of %i %s:"),type_plural,ships_per_team,player_plural)
for i=1,ships_per_team do
out = out .. "\n " .. i .. ") " .. default_player_ship_sets[ships_per_team][i]
end
addGMMessage(out)
setPlayerShipTypes()
end)
button_label = "spawned"
if player_ship_types == button_label then
button_label = button_label .. _("buttonGM", "*")
end
addGMFunction(button_label,function()
player_ship_types = "spawned"
local out = _("msgGM", "Spawned ship type(s):")
local player_count = 0
for pidx=1,32 do
local p = getPlayerShip(pidx)
if p ~= nil and p:isValid() then
player_count = player_count + 1
out = out .. "\n " .. player_count .. ") " .. p:getTypeName()
end
end
if player_count < ships_per_team then
if player_count == 0 then
out = string.format(_("msgGM", "%i player ships spawned. %i are required.\n\nUsing default ship set.\n\n%s"),player_count,ships_per_team,out)
elseif player_count == 1 then
out = string.format(_("msgGM", "Only %i player ship spawned. %i are required.\n\nUsing default ship set.\n\n%s"),player_count,ships_per_team,out)
else
out = string.format(_("msgGM", "Only %i player ships spawned. %i are required.\n\nUsing default ship set.\n\n%s"),player_count,ships_per_team,out)
end
player_ship_types = "default"
elseif player_count > ships_per_team then
if ships_per_team == 1 then
out = string.format(_("msgGM", "%i player ships spawned. Only %i is required.\n\nUsing default ship set.\n\n%s"),player_count,ships_per_team,out)
else
out = string.format(_("msgGM", "%i player ships spawned. Only %i are required.\n\nUsing default ship set.\n\n%s"),player_count,ships_per_team,out)
end
player_ship_types = "default"
end
addGMMessage(out)
setPlayerShipTypes()
end)
button_label = "custom"
if player_ship_types == button_label then
button_label = button_label .. _("buttonGM", "*")
end
addGMFunction(string.format("+%s",button_label),setCustomPlayerShipSet)
addGMFunction(_("buttonGM", "Explain"),function()
addGMMessage(_("msgGM", "This is where you determine the kinds of ships the players will use.\n\nDefault: There is a default set of ships depending on the number of players and the number of teams.\n\nSpawned: Whatever is spawned from the first screen for one team will be replicated for the other team or teams. If the number of ships spawned does not match the team size selected, the default player ship set will be used.\n\nCustom: There are several sets of defaults under custom: Warp (ships equipped with warp drive), Jump (ships equipped with jump drive), Light (ships that are not as heavily armed or armored) and Heavy (ships that are more heavily armed or armored). There is also custom button where you can select the ship or ships you want from a list. To set up the list, use the +Customize Custom button."))
end)
end
function setCustomPlayerShipSet()
clearGMFunctions()
addGMFunction(_("buttonGM", "-Main from Custom"),mainGMButtons)
addGMFunction(_("buttonGM", "-Ship Types"),setPlayerShipTypes)
addGMFunction(_("buttonGM", "+Customize Custom"),setCustomSet)
for ship_set_type,list in pairs(custom_player_ship_sets) do
local button_label = ship_set_type
if ship_set_type == custom_player_ship_type then
button_label = button_label .. _("buttonGM", "*")
end
addGMFunction(button_label,function()
player_ship_types = "custom"
custom_player_ship_type = ship_set_type
local out = ""
if ships_per_team == 1 then
out = string.format(_("msgGM", "Ship type set %s for %i player:"),custom_player_ship_type,ships_per_team)
else
out = string.format(_("msgGM", "Ship type set %s for %i players:"),custom_player_ship_type,ships_per_team)
end
for index, ship_type in ipairs(custom_player_ship_sets[custom_player_ship_type][ships_per_team]) do
-- print("index:",index,"ship type:",ship_type)
out = out .. "\n " .. index .. ") " .. ship_type
end
addGMMessage(out)
setCustomPlayerShipSet()
end)
end
end
function setCustomSet()
clearGMFunctions()
addGMFunction(_("buttonGM", "-Main from Custom"),mainGMButtons)
addGMFunction(_("buttonGM", "-Ship Types"),setPlayerShipTypes)
addGMFunction(_("buttonGM", "-Custom Set"),setCustomPlayerShipSet)
if template_out == nil then
template_out = custom_player_ship_sets["Custom"][ships_per_team][1]
else
local match_in_set = false
for i=1,#custom_player_ship_sets["Custom"][ships_per_team] do
if custom_player_ship_sets["Custom"][ships_per_team][i] == template_out then
match_in_set = true
end
end
if not match_in_set then
template_out = custom_player_ship_sets["Custom"][ships_per_team][1]
end
end
if template_in == nil then
for name, details in pairs(player_ship_stats) do
template_in = name
break
end
end
addGMFunction(string.format(_("buttonGM", "+Out %s"),template_out),setTemplateOut)
addGMFunction(string.format(_("buttonGM", "+In %s"),template_in),setTemplateIn)
addGMFunction("Swap",function()
for i=1,#custom_player_ship_sets["Custom"][ships_per_team] do
if custom_player_ship_sets["Custom"][ships_per_team][i] == template_out then
custom_player_ship_sets["Custom"][ships_per_team][i] = template_in
template_in = template_out
template_out = custom_player_ship_sets["Custom"][ships_per_team][i]
break
end
end
setCustomSet()
end)
addGMFunction(_("buttonGM", "Explain"),function()
addGMMessage(_("msgGM", "The +Out button shows the current list of player ships. The ship named on the button or the one with the asterisk if you click the +Out button is the ship in the list that you can swap with another.\n\nThe +In button shows the list of ships that you might want to put in the custom list of ships. The ship on the button or the one with the asterisk if you click the +In button is the ship you can place in the custom list.\n\nThe Swap button swaps the ships on the +In and +Out buttons removing the ship on the +Out button from the custom list to be used in the game and putting the ship on the +In button in the custom list of ships to be used.\n\nNotice that some of the ships that can be swapped in to the custom list are not stock Empty Epsilon ships, but are specialized versions of stock Empty Epsilon ships."))
end)
end
function setTemplateOut()
clearGMFunctions()
table.sort(custom_player_ship_sets["Custom"][ships_per_team])
for i=1,#custom_player_ship_sets["Custom"][ships_per_team] do
local button_label = custom_player_ship_sets["Custom"][ships_per_team][i]
if template_out == custom_player_ship_sets["Custom"][ships_per_team][i] then
button_label = button_label .. _("buttonGM", "*")
end
addGMFunction(button_label,function()
template_out = custom_player_ship_sets["Custom"][ships_per_team][i]
setCustomSet()
end)
end
end
function setTemplateIn()
clearGMFunctions()
local sorted_templates = {}
for name, details in pairs(player_ship_stats) do
table.insert(sorted_templates,name)
end
table.sort(sorted_templates)
for idx, name in ipairs(sorted_templates) do
local button_label = name
if template_in == name then
button_label = button_label .. _("buttonGM", "*")
end
addGMFunction(button_label,function()
template_in = name
setCustomSet()
end)
end
end
function setAdvanceIntel()
clearGMFunctions()
addGMFunction(_("buttonGM", "-Main"),mainGMButtons)
local button_label = _("buttonGM", "Advance Intel Yes")
if advanced_intel then
button_label = button_label .. _("buttonGM", "*")
end
addGMFunction(button_label,function()
advanced_intel = true
setAdvanceIntel()
end)
button_label = _("buttonGM", "Advance Intel No")
if not advanced_intel then
button_label = button_label .. _("buttonGM", "*")
end
addGMFunction(button_label,function()
advanced_intel = false
setAdvanceIntel()
end)
addGMFunction(_("buttonGM", "Explain"),function()
addGMMessage(_("msgGM", "This setting determines whether or not the players will receive a message at the start of the game indicating the location of their opponent's home base. Useful if players feel that they spend too much time at the start looking for their opponents."))
end)
end
-- Terrain related GM configuration functions
function setTerrainParameters()
clearGMFunctions()
addGMFunction(_("buttonGM", "-Main from Terrain"),mainGMButtons)
addGMFunction(string.format(_("buttonGM", "+Missiles: %s"),missile_availability),setMissileAvailability)
addGMFunction(_("buttonGM", "+Primary Station"),setPrimaryStationParameters)
addGMFunction(_("buttonGM", "Generate"),function()
generateTerrain()
mainGMButtons()
end)
addGMFunction(_("buttonGM", "Explain"),function()
addGMMessage(_("msgGM", "Explanations for missiles and primary station available by clicking those buttons.\n\nClicking the generate button will generate the terrain based on the number of player teams selected, the number of ships on a team and the terrain parameters selected.\n\nAfter you generate the terrain, you cannot change the player ships, or the terrain unless you restart the server. You will be able to get the player ship access control codes after you generate the terrain."))
end)
end
function setStationSensorRange()
clearGMFunctions()
local button_label = _("buttonGM", "Zero")
if station_sensor_range == 0 then
button_label = button_label .. _("buttonGM", "*")
end
addGMFunction(button_label,function()
station_sensor_range = 0
mainGMButtons()
end)
button_label = _("buttonGM", "5U")
if station_sensor_range == 5000 then
button_label = button_label .. _("buttonGM", "*")
end
addGMFunction(button_label,function()
station_sensor_range = 5000
mainGMButtons()
end)
button_label = _("buttonGM", "10U")
if station_sensor_range == 10000 then
button_label = button_label .. _("buttonGM", "*")
end
addGMFunction(button_label,function()
station_sensor_range = 10000
mainGMButtons()
end)
button_label = _("buttonGM", "20U")
if station_sensor_range == 20000 then
button_label = button_label .. _("buttonGM", "*")
end
addGMFunction(button_label,function()
station_sensor_range = 20000
mainGMButtons()
end)
button_label = _("buttonGM", "30U")
if station_sensor_range == 30000 then
button_label = button_label .. _("buttonGM", "*")
end
addGMFunction(button_label,function()
station_sensor_range = 30000
mainGMButtons()
end)
addGMFunction(_("buttonGM", "Explain"),function()
addGMMessage(_("msgGM", "This is where you set the station enemy detection range. Stations that detect enemies will send a warning message to friendly player ships."))
end)
end
function setPrimaryStationParameters()
clearGMFunctions()
addGMFunction(_("buttonGM", "-Main from Prm Stn"),mainGMButtons)
addGMFunction(_("buttonGM", "-Terrain"),setTerrainParameters)
if defense_platform_count_options[defense_platform_count_index].count == "random" then
addGMFunction(_("buttonGM", "+Platforms: Random"),setDefensePlatformCount)
else
addGMFunction(string.format(_("buttonGM", "+Platforms: %i"),defense_platform_count_options[defense_platform_count_index].count),setDefensePlatformCount)
end
if primary_station_size_index == 1 then
addGMFunction(_("buttonGM", "Random Size ->"),function()
primary_station_size_index = primary_station_size_index + 1
setPrimaryStationParameters()
end)
else
addGMFunction(string.format(_("buttonGM", "%s ->"),primary_station_size_options[primary_station_size_index]),function()
primary_station_size_index = primary_station_size_index + 1
if primary_station_size_index > #primary_station_size_options then
primary_station_size_index = 1
end
setPrimaryStationParameters()
end)
end
addGMFunction(string.format(_("buttonGM", "Jammer: %s ->"),primary_jammers),function()
if primary_jammers == "random" then
primary_jammers = "on"
elseif primary_jammers == "on" then
primary_jammers = "off"
elseif primary_jammers == "off" then
primary_jammers = "random"
end
setPrimaryStationParameters()
end)
addGMFunction(_("buttonGM", "Explain"),function()
addGMMessage(_("msgGM", "An explanation for platforms can be obtained by clicking the platforms button.\nJust under the platforms, you can choose the primary station size from the options of random, small, medium, large and huge. The label on the button indicates the current selection.\nThe Jammer button determines the presence of warp jammers around the primary station from the options of random, on or off. The label on the button indicates the current selection."))
end)
end
function setDefensePlatformCount()
clearGMFunctions()
addGMFunction(_("buttonGM", "-Main from Platforms"),mainGMButtons)
addGMFunction(_("buttonGM", "-Terrain"),setTerrainParameters)
addGMFunction(_("buttonGM", "-Primary Station"),setPrimaryStationParameters)
if defense_platform_count_index < #defense_platform_count_options then
if defense_platform_count_options[defense_platform_count_index + 1].count == "random" then
addGMFunction(string.format(_("buttonGM", "%i Platforms + -> Rnd"),defense_platform_count_options[defense_platform_count_index].count),function()
defense_platform_count_index = defense_platform_count_index + 1
setDefensePlatformCount()
end)
else
addGMFunction(string.format(_("buttonGM", "%i Platforms + -> %i"),defense_platform_count_options[defense_platform_count_index].count,defense_platform_count_options[defense_platform_count_index + 1].count),function()
defense_platform_count_index = defense_platform_count_index + 1
setDefensePlatformCount()
end)
end
end
if defense_platform_count_index > 1 then
if defense_platform_count_options[defense_platform_count_index].count == "random" then
addGMFunction(string.format(_("buttonGM", "Rnd Platforms - -> %i"),defense_platform_count_options[defense_platform_count_index - 1].count),function()
defense_platform_count_index = defense_platform_count_index - 1
setDefensePlatformCount()
end)
else
addGMFunction(string.format(_("buttonGM", "%i Platforms - -> %i"),defense_platform_count_options[defense_platform_count_index].count,defense_platform_count_options[defense_platform_count_index - 1].count),function()
defense_platform_count_index = defense_platform_count_index - 1
setDefensePlatformCount()
end)
end
end
addGMFunction(_("buttonGM", "Explain"),function()
addGMMessage(_("msgGM", "This is where you determine the number of defense platforms surrounding the players' primary base. The left portion of the text on the button(s) indicates the current selection. The right portion of the text on the button(s) indicates the value after clicking the button."))
end)
end
-- Display player control codes
function showKraylorCodes()
showControlCodes("Kraylor")
end
function showExuariCodes()
showControlCodes("Exuari")
end
function showHumanCodes()
showControlCodes("Human Navy")
end
function showKtlitanCodes()
showControlCodes("Ktlitans")
end
function showControlCodes(faction_filter)
local code_list = {}
for pidx=1,32 do
local p = getPlayerShip(pidx)
if p ~= nil and p:isValid() then
if faction_filter == "Kraylor" then
if p:getFaction() == "Kraylor" then
code_list[p:getCallSign()] = {code = p.control_code, faction = p:getFaction()}
end
elseif faction_filter == "Human Navy" then
if p:getFaction() == "Human Navy" then
code_list[p:getCallSign()] = {code = p.control_code, faction = p:getFaction()}
end
elseif faction_filter == "Exuari" then
if p:getFaction() == "Exuari" then
code_list[p:getCallSign()] = {code = p.control_code, faction = p:getFaction()}
end
elseif faction_filter == "Ktlitans" then
if p:getFaction() == "Ktlitans" then
code_list[p:getCallSign()] = {code = p.control_code, faction = p:getFaction()}
end
else
code_list[p:getCallSign()] = {code = p.control_code, faction = p:getFaction()}
end
end
end
local sorted_names = {}
for name in pairs(code_list) do
table.insert(sorted_names,name)
end
table.sort(sorted_names)
local output = ""
for idx, name in ipairs(sorted_names) do
local faction = ""
if code_list[name].faction == "Kraylor" then
faction = " (Kraylor)"
elseif code_list[name].faction == "Ktlitans" then
faction = " (Ktlitan)"
elseif code_list[name].faction == "Exuari" then
faction = " (Exuari)"
end
output = output .. string.format(_("msgGM", "%s: %s %s\n"),name,code_list[name].code,faction)
end
addGMMessage(output)
end
function resetControlCodes()
for i,p in ipairs(getActivePlayerShips()) do
local stem = tableRemoveRandom(control_code_stem)
local branch = math.random(100,999)
p.control_code = stem .. branch
p:setControlCode(stem .. branch)
end
showControlCodes()
end
-- General configuration functions
function setGameTimeLimit()
clearGMFunctions()
addGMFunction(_("buttonGM", "-Main from Time"),mainGMButtons)
if game_time_limit < 6000 then
addGMFunction(string.format(_("buttonGM", "%i Add 5 -> %i"),game_time_limit/60,game_time_limit/60 + 5),function()
game_time_limit = game_time_limit + 300
max_game_time = game_time_limit
setGameTimeLimit()
end)
end
if game_time_limit > 300 then
addGMFunction(string.format(_("buttonGM", "%i Del 5 -> %i"),game_time_limit/60,game_time_limit/60 - 5),function()
game_time_limit = game_time_limit - 300
max_game_time = game_time_limit
setGameTimeLimit()
end)
end
addGMFunction(_("buttonGM", "Explain"),function()
addGMMessage(_("msgGM", "This is where you set the time limit for the game. The game ends at the end of the time limit and the faction with the highest score wins."))
end)
end
function setMissileAvailability()
clearGMFunctions()
addGMFunction(_("buttonGM", "-Main from Missiles"),mainGMButtons)
addGMFunction(_("buttonGM", "-Terrain"),setTerrainParameters)
local button_label = "unlimited"
if missile_availability == "unlimited" then
button_label = button_label .. _("buttonGM", "*")
end
addGMFunction(button_label,function()
missile_availability = "unlimited"
setMissileAvailability()
end)
button_label = "outer limited"
if missile_availability == "outer limited" then
button_label = button_label .. _("buttonGM", "*")
end
addGMFunction(button_label,function()
missile_availability = "outer limited"
setMissileAvailability()
end)
button_label = "limited"
if missile_availability == "limited" then
button_label = button_label .. _("buttonGM", "*")
end
addGMFunction(button_label,function()
missile_availability = "limited"
setMissileAvailability()
end)
addGMFunction(_("buttonGM", "Explain"),function()
addGMMessage(_("msgGM", "This is where you set the missile restock availability for the stations.\nThe 'unlimited' option is typical of most scenarios: you pay reputation to get missiles at stations that offer them.\nThe 'limited' option indicates that stations have a limited supply of missiles available for restock.\nThe 'outer limited' option indicates that all stations except the player's primary station have a limited supply of missiles.\nFor all the options that limit missile availability, the actual stockpiles of missiles is determined randomly for each game."))
end)
end
function setNPCShips()
clearGMFunctions()
addGMFunction(_("buttonGM", "-From NPC Strength"),mainGMButtons)
local button_label = _("buttonGM", "NPC Ships: No")
if npc_ships then
button_label = string.format(_("buttonGM", "NPC Ships: %i-%i"),npc_lower,npc_upper)
end
addGMFunction(button_label,function()
if npc_ships then
npc_ships = false
else
npc_ships = true
end
setNPCShips()
end)
if npc_ships then
if npc_lower < npc_upper - 5 then
addGMFunction(string.format(_("buttonGM", "%i From Add -> %i"),npc_lower,npc_lower + 5),function()
npc_lower = npc_lower + 5
setNPCShips()
end)
end
if npc_lower > 10 then
addGMFunction(string.format(_("buttonGM", "%i From Del -> %i"),npc_lower,npc_lower - 5),function()
npc_lower = npc_lower - 5
setNPCShips()
end)
end
if npc_upper < 200 then
addGMFunction(string.format(_("buttonGM", "%i To Add -> %i"),npc_upper,npc_upper + 5),function()
npc_upper = npc_upper + 5
setNPCShips()
end)
end
if npc_upper > npc_lower + 5 then
addGMFunction(string.format(_("buttonGM", "%i To Del -> %i"),npc_upper,npc_upper - 5),function()
npc_upper = npc_upper - 5
setNPCShips()
end)
end
end
addGMFunction(_("buttonGM", "Explain"),function()
addGMMessage(_("msgGM", "This is where you configure Non Player Character or NPC ships. Each team will be given NPC ships as configured here. If there should be no NPC ships, be sure the results show 'No'\n\nThe numbers being configured represent a range of relative strength values. For example, the Atlantis has a relative strength of 50. You may set the lower (From) and upper (To) values of this range. The scenario will add ships selected at random that have a total strength within the specified range. Each team will receive identcal NPC ships. These ships will start near the players' primary base and can be directed by the players via Relay or Operations."))
end)
end
-------------------------------------
-- Generate terrain and stations --
-------------------------------------
function generateTerrain()
-- Activities include:
-- Central terrain feature
-- Angle from center for each faction (used to place objects symmetrically)
-- Primary station and any defense platforms and/or defensive warp jammers
-- Positioning players around primary station
-- Placing other stations with varying capabilities and capacities
-- Wormholes, black holes, asteroids and nebulae
if terrain_generated then
return
end
terrain_generated = true
terrain_center_x = random(200000,300000)
terrain_center_y = random(100000,200000)
local ta = Asteroid():setPosition(terrain_center_x,terrain_center_y)
local terrain_center_sector = ta:getSectorName()
addGMMessage(string.format("The center of the universe is in sector\n%s",terrain_center_sector))
ta:destroy()
place_ref_list = {}
human_ref_list = {}
-- decide what lives at the center of the universe
local center_choice_list = {"Planet","Star","Black Hole"}
local center_choice = center_choice_list[math.random(1,#center_choice_list)]
if center_choice == "Planet" then
local center_planet, center_radius = choosePlanet(math.random(2,3),terrain_center_x,terrain_center_y)
table.insert(place_ref_list,center_planet)
if random(1,100) <= 50 then
local mx, my = vectorFromAngleNorth(random(0,360),center_radius + random(1000,2000))
local moon = choosePlanet(4,terrain_center_x + mx,terrain_center_y + my)
moon:setOrbit(center_planet,random(200,400))
table.insert(place_ref_list,moon)
end
elseif center_choice == "Star" then
local center_star, star_radius = choosePlanet(1,terrain_center_x,terrain_center_y)
table.insert(place_ref_list,center_star)
if random(1,100) <= 75 then
local plx, ply = vectorFromAngleNorth(random(0,360),star_radius + random(8000,15000))
local orbit_planet, orbit_radius = choosePlanet(math.random(2,3),terrain_center_x + plx,terrain_center_y + ply)
orbit_planet:setOrbit(center_star,random(800,2000))
table.insert(place_ref_list,orbit_planet)
if random(1,100) <= 50 then
local omx, omy = vectorFromAngleNorth(random(0,360),orbit_radius + random(1000,2000))
local orbit_moon = choosePlanet(4,terrain_center_x + plx + omx,terrain_center_y + ply + omy)
orbit_moon:setOrbit(orbit_planet,random(200,400))
table.insert(place_ref_list,orbit_moon)
end
end
elseif center_choice == "Black Hole" then
local black_hole_names = {
"Fornax A",
"Sagittarius A",
"Triangulum",
"Cygnus X-3",
"Messier 110",
"Virgo A",
"Andromeda",
"Sombrero",
"Great Annihilator",
}
table.insert(place_ref_list,BlackHole():setPosition(terrain_center_x,terrain_center_y):setCallSign(black_hole_names[math.random(1,#black_hole_names)]))
end
-- Set angles
faction_angle = {}
npc_fleet = {}
npc_fleet["Human Navy"] = {}
npc_fleet["Kraylor"] = {}
human_angle = random(0,360)
faction_angle["Human Navy"] = human_angle
local replicant_increment = 360/player_team_count
kraylor_angle = (human_angle + replicant_increment) % 360
faction_angle["Kraylor"] = kraylor_angle
if player_team_count > 2 then
exuari_angle = (kraylor_angle + replicant_increment) % 360
faction_angle["Exuari"] = exuari_angle
npc_fleet["Exuari"] = {}
end
if player_team_count > 3 then
ktlitan_angle = (exuari_angle + replicant_increment) % 360
faction_angle["Ktlitans"] = ktlitan_angle
npc_fleet["Ktlitans"] = {}
end
if respawn_type == "self" then
death_penalty = {}
death_penalty["Human Navy"] = 0
death_penalty["Kraylor"] = 0
if exuari_angle ~= nil then
death_penalty["Exuari"] = 0
end
if ktlitan_angle ~= nil then
death_penalty["Ktlitans"] = 0
end
end
-- Set primary stations
local primary_station_distance = random(50000,100000)
local primary_station_size = primary_station_size_options[primary_station_size_index]
if primary_station_size == "random" then
primary_station_size = szt()
end
base_station_value_list = {
["Huge Station"] = 10,
["Large Station"] = 5,
["Medium Station"] = 3,
["Small Station"] = 1,
}
faction_primary_station = {}
local psx, psy = vectorFromAngleNorth(human_angle,primary_station_distance)
station_primary_human = placeStation(terrain_center_x + psx, terrain_center_y + psy, "Random","Human Navy",primary_station_size)
faction_primary_station["Human Navy"] = {x = terrain_center_x + psx, y = terrain_center_y + psy, station = station_primary_human}
station_primary_human.score_value = base_station_value_list[primary_station_size] + 10
station_list["Human Navy"] = {}
table.insert(station_list["Human Navy"],station_primary_human)
table.insert(place_ref_list,station_primary_human)
table.insert(human_ref_list,station_primary_human)
local unlimited_missiles = true
if missile_availability == "limited" then
unlimited_missiles = false
end
station_primary_human.comms_data = {
friendlyness = random(75,100),
weapon_cost = {
Homing = math.random(1,6),
Nuke = math.random(10,30),
Mine = math.random(2,25),
EMP = math.random(8,20),
HVLI = math.random(1,4),
},
weapon_available = {
Homing = true,
Nuke = true,
Mine = true,
EMP = true,
HVLI = true,
},
weapon_inventory = {
Unlimited = unlimited_missiles,
Homing = math.floor(math.random(10,50)/difficulty),
Nuke = math.floor(math.random(5,30)/difficulty),
Mine = math.floor(math.random(8,40)/difficulty),
EMP = math.floor(math.random(6,34)/difficulty),
HVLI = math.floor(math.random(15,70)/difficulty),
},
services = {
supplydrop = "friend",
reinforcements = "friend",
jumpsupplydrop = "friend",
sensor_boost = "neutral",
preorder = "friend",
activatedefensefleet = "neutral",
jumpovercharge = "neutral",
jumpsupplydrop = "friend",
},
service_cost = {
supplydrop = math.random(80,120),
reinforcements = math.random(125,175),
hornetreinforcements = math.random(75,125),
phobosreinforcements = math.random(175,225),
jumpsupplydrop = math.random(110,140),
activatedefensefleet = math.random(15,40),
jumpovercharge = math.random(10,20),
jumpsupplydrop = math.random(110,150),
},
jump_overcharge = true,
probe_launch_repair = true,
hack_repair = true,
scan_repair = true,
combat_maneuver_repair= true,
self_destruct_repair = true,
tube_slow_down_repair = true,
sensor_boost = {value = primary_station_distance-35000, cost = 0},
reputation_cost_multipliers = {
friend = 1.0,
neutral = 3.0,
},
max_weapon_refill_amount = {friend = 1.0, neutral = 0.5 },
goods = { food = {quantity = 10, cost = 1},
medicine = {quantity = 10, cost = 5} },
trade = { food = false, medicine = false, luxury = false },
}
station_primary_human.comms_data.idle_defense_fleet = defense_fleet_list[primary_station_size][math.random(1,#defense_fleet_list[primary_station_size])]
psx, psy = vectorFromAngleNorth(kraylor_angle,primary_station_distance)
station_primary_kraylor = placeStation(terrain_center_x + psx, terrain_center_y + psy, "Random","Kraylor",primary_station_size)
faction_primary_station["Kraylor"] = {x = terrain_center_x + psx, y = terrain_center_y + psy, station = station_primary_kraylor}
station_primary_kraylor.score_value = base_station_value_list[primary_station_size] + 10
station_list["Kraylor"] = {}
table.insert(station_list["Kraylor"],station_primary_kraylor)
table.insert(place_ref_list,station_primary_kraylor)
station_primary_kraylor.comms_data = station_primary_human.comms_data
if exuari_angle ~= nil then
psx, psy = vectorFromAngleNorth(exuari_angle,primary_station_distance)
station_primary_exuari = placeStation(terrain_center_x + psx, terrain_center_y + psy, "Random","Exuari",primary_station_size)
faction_primary_station["Exuari"] = {x = terrain_center_x + psx, y = terrain_center_y + psy, station = station_primary_exuari}
station_primary_exuari.score_value = base_station_value_list[primary_station_size] + 10
station_list["Exuari"] = {}
table.insert(station_list["Exuari"],station_primary_exuari)
table.insert(place_ref_list,station_primary_exuari)
station_primary_exuari.comms_data = station_primary_human.comms_data
end
if ktlitan_angle ~= nil then
psx, psy = vectorFromAngleNorth(ktlitan_angle,primary_station_distance)
station_primary_ktlitan = placeStation(terrain_center_x + psx, terrain_center_y + psy, "Random","Ktlitans",primary_station_size)
faction_primary_station["Ktlitans"] = {x = terrain_center_x + psx, y = terrain_center_y + psy, station = station_primary_ktlitan}
station_primary_ktlitan.score_value = base_station_value_list[primary_station_size] + 10
station_list["Ktlitans"] = {}
table.insert(station_list["Ktlitans"],station_primary_ktlitan)
table.insert(place_ref_list,station_primary_ktlitan)
station_primary_ktlitan.comms_data = station_primary_human.comms_data
end
-- Set defense platforms and jammers (if applicable)
defense_platform_count = defense_platform_count_options[defense_platform_count_index].count
defense_platform_distance = defense_platform_count_options[defense_platform_count_index].distance
player_position_distance = defense_platform_count_options[defense_platform_count_index].player
if defense_platform_count == "random" then
local index = math.random(1,#defense_platform_count_options - 1)
defense_platform_count = defense_platform_count_options[index].count
defense_platform_distance = defense_platform_count_options[index].distance
player_position_distance = defense_platform_count_options[index].player
end
if primary_jammers == "random" then
primary_jammers = random(1,100) < 50
else
if primary_jammers == "on" then
primary_jammers = true
else
primary_jammers = false
end
end
local angle = human_angle
local vx = 0
local vy = 0
unlimited_missiles = false
if missile_availability == "unlimited" then
unlimited_missiles = true
end
if defense_platform_count > 0 then
local dp = nil
angle = human_angle
psx, psy = station_primary_human:getPosition()
local dp_list = {}
for i=1,defense_platform_count do
vx, vy = vectorFromAngleNorth(angle,defense_platform_distance)
dp = CpuShip():setTemplate("Defense platform"):setFaction("Human Navy"):setPosition(psx + vx,psy + vy):setScannedByFaction("Human Navy",true):setCallSign(string.format("HDP%i",i)):setDescription(string.format(_("scienceDescription-ship", "%s defense platform %i"),station_primary_human:getCallSign(),i)):orderRoaming()
dp.score_value = 50
table.insert(npc_fleet["Human Navy"],dp)
dp:setCommsScript(""):setCommsFunction(commsDefensePlatform)
dp.primary_station = station_primary_human
if primary_jammers then
vx, vy = vectorFromAngleNorth(angle,defense_platform_distance/2)
WarpJammer():setPosition(psx + vx, psy + vy):setRange(defense_platform_distance/2 + 4000):setFaction("Human Navy")
end
dp.comms_data = { --defense platform comms data
weapon_available = {
Homing = random(1,13)<=(3-difficulty),
HVLI = random(1,13)<=(6-difficulty),
Mine = false,
Nuke = false,
EMP = false,
},
weapon_inventory = {
Unlimited = unlimited_missiles,
Homing = math.floor(math.random(10,50)/difficulty),
Nuke = 0,
Mine = 0,
EMP = 0,
HVLI = math.floor(math.random(15,70)/difficulty),
},
services = {
supplydrop = "friend",
reinforcements = "friend",
jumpsupplydrop = "friend",
},
service_cost = {
supplydrop = math.random(80,120),
reinforcements = math.random(125,175),
jumpsupplydrop = math.random(110,140),
},
jump_overcharge = false,
probe_launch_repair = random(1,100) <= (20 - difficulty*2.5),
hack_repair = random(1,100) <= (22 - difficulty*2.5),
scan_repair = random(1,100) <= (30 - difficulty*2.5),
combat_maneuver_repair= random(1,100) <= (15 - difficulty*2.5),
self_destruct_repair = random(1,100) <= (25 - difficulty*2.5),
tube_slow_down_repair = random(1,100) <= (18 - difficulty*2.5),
reputation_cost_multipliers = {
friend = 1.0,
neutral = 3.0,
},
}
dp:setSharesEnergyWithDocked(random(1,100) <= (60 - difficulty*5))
dp:setRepairDocked(random(1,100) <= (50 - difficulty*5))
dp:setRestocksScanProbes(random(1,100) <= (40 - difficulty*5))
table.insert(dp_list,dp)
table.insert(place_ref_list,dp)
table.insert(human_ref_list,dp)
angle = (angle + 360/defense_platform_count) % 360
end
angle = kraylor_angle
psx, psy = station_primary_kraylor:getPosition()
for i=1,defense_platform_count do
vx, vy = vectorFromAngleNorth(angle,defense_platform_distance)
dp = CpuShip():setTemplate("Defense platform"):setFaction("Kraylor"):setPosition(psx + vx,psy + vy):setScannedByFaction("Kraylor",true):setCallSign(string.format("KDP%i",i)):setDescription(string.format(_("scienceDescription-ship", "%s defense platform %i"),station_primary_kraylor:getCallSign(),i)):orderRoaming()
dp.score_value = 50
table.insert(npc_fleet["Kraylor"],dp)
dp:setCommsScript(""):setCommsFunction(commsDefensePlatform)
dp.primary_station = station_primary_kraylor
if primary_jammers then
vx, vy = vectorFromAngleNorth(angle,defense_platform_distance/2)
WarpJammer():setPosition(psx + vx, psy + vy):setRange(defense_platform_distance/2 + 4000):setFaction("Kraylor")
end
dp.comms_data = dp_list[i].comms_data --replicate capabilities
dp:setSharesEnergyWithDocked(dp_list[i]:getSharesEnergyWithDocked())
dp:setRepairDocked(dp_list[i]:getRepairDocked())
dp:setRestocksScanProbes(dp_list[i]:getRestocksScanProbes())
table.insert(place_ref_list,dp)
angle = (angle + 360/defense_platform_count) % 360
end
if exuari_angle ~= nil then
angle = exuari_angle
psx, psy = station_primary_exuari:getPosition()
for i=1,defense_platform_count do
vx, vy = vectorFromAngleNorth(angle,defense_platform_distance)
dp = CpuShip():setTemplate("Defense platform"):setFaction("Exuari"):setPosition(psx + vx,psy + vy):setScannedByFaction("Exuari",true):setCallSign(string.format("EDP%i",i)):setDescription(string.format(_("scienceDescription-ship"), "%s defense platform %i",station_primary_exuari:getCallSign(),i)):orderRoaming()
dp.score_value = 50
table.insert(npc_fleet["Exuari"],dp)
dp:setCommsScript(""):setCommsFunction(commsDefensePlatform)
dp.primary_station = station_primary_exuari
if primary_jammers then
vx, vy = vectorFromAngleNorth(angle,defense_platform_distance/2)
WarpJammer():setPosition(psx + vx, psy + vy):setRange(defense_platform_distance/2 + 4000):setFaction("Exuari")
end
dp.comms_data = dp_list[i].comms_data --replicate capabilities
dp:setSharesEnergyWithDocked(dp_list[i]:getSharesEnergyWithDocked())
dp:setRepairDocked(dp_list[i]:getRepairDocked())
dp:setRestocksScanProbes(dp_list[i]:getRestocksScanProbes())
table.insert(place_ref_list,dp)
angle = (angle + 360/defense_platform_count) % 360
end
end
if ktlitan_angle ~= nil then
angle = ktlitan_angle
psx, psy = station_primary_ktlitan:getPosition()
for i=1,defense_platform_count do
vx, vy = vectorFromAngleNorth(angle,defense_platform_distance)
dp = CpuShip():setTemplate("Defense platform"):setFaction("Ktlitans"):setPosition(psx + vx,psy + vy):setScannedByFaction("Ktlitans",true):setCallSign(string.format("BDP%i",i)):setDescription(string.format(_("scienceDescription-ship", "%s defense platform %i"),station_primary_ktlitan:getCallSign(),i)):orderRoaming()
dp.score_value = 50
table.insert(npc_fleet["Ktlitans"],dp)
dp:setCommsScript(""):setCommsFunction(commsDefensePlatform)
dp.primary_station = station_primary_ktlitan
if primary_jammers then
vx, vy = vectorFromAngleNorth(angle,defense_platform_distance/2)
WarpJammer():setPosition(psx + vx, psy + vy):setRange(defense_platform_distance/2 + 4000):setFaction("Ktlitans")
end
dp.comms_data = dp_list[i].comms_data --replicate capabilities
dp:setSharesEnergyWithDocked(dp_list[i]:getSharesEnergyWithDocked())
dp:setRepairDocked(dp_list[i]:getRepairDocked())
dp:setRestocksScanProbes(dp_list[i]:getRestocksScanProbes())
table.insert(place_ref_list,dp)
angle = (angle + 360/defense_platform_count) % 360
end
end
else --no defense platforms
if primary_jammers then
local jammer_distance = 4000
local jammer_range = 8000
angle = human_angle
psx, psy = station_primary_human:getPosition()
for i=1,4 do
vx, vy = vectorFromAngleNorth(angle,jammer_distance)
local wj = WarpJammer():setPosition(psx + vx, psy + vy):setRange(jammer_range):setFaction("Human Navy")
table.insert(place_ref_list,wj)
table.insert(human_ref_list,wj)
angle = (angle + 90) % 360
end
angle = kraylor_angle
psx, psy = station_primary_kraylor:getPosition()
for i=1,4 do
vx, vy = vectorFromAngleNorth(angle,jammer_distance)
table.insert(place_ref_list,WarpJammer():setPosition(psx + vx, psy + vy):setRange(jammer_range):setFaction("Kraylor"))
angle = (angle + 90) % 360
end
if exuari_angle ~= nil then
angle = exuari_angle
psx, psy = station_primary_exuari:getPosition()
for i=1,4 do
vx, vy = vectorFromAngleNorth(angle,jammer_distance)
table.insert(place_ref_list,WarpJammer():setPosition(psx + vx, psy + vy):setRange(jammer_range):setFaction("Exuari"))
angle = (angle + 90) % 360
end
end
if ktlitan_angle ~= nil then
angle = ktlitan_angle
psx, psy = station_primary_ktlitan:getPosition()
for i=1,4 do
vx, vy = vectorFromAngleNorth(angle,jammer_distance)
table.insert(place_ref_list,WarpJammer():setPosition(psx + vx, psy + vy):setRange(jammer_range):setFaction("Ktlitans"))
angle = (angle + 90) % 360
end
end
end
end
-- Place players
player_restart = {}
if player_ship_types == "spawned" then
local player_count = 0
for pidx=1,32 do
local p = getPlayerShip(pidx)
if p ~= nil and p:isValid() then
player_count = player_count + 1
end
end
local out = ""
if player_count < ships_per_team then
if player_count == 0 then
out = string.format(_("msgGM", "No player ships spawned. %i are required.\n\nUsing default ship set."),ships_per_team)
elseif player_count == 1 then
out = string.format(_("msgGM", "Only one player ship spawned. %i are required.\n\nUsing default ship set."),ships_per_team)
else
out = string.format(_("msgGM", "Only %i player ships spawned. %i are required.\n\nUsing default ship set."),player_count,ships_per_team)
end
player_ship_types = "default"
addGMMessage(out)
placeDefaultPlayerShips()
elseif player_count > ships_per_team then
if ships_per_team == 1 then
out = string.format(_("msgGM", "%i player ships spawned. Only %i is required.\n\nUsing default ship set."),player_count,ships_per_team)
else
out = string.format(_("msgGM", "%i player ships spawned. Only %i are required.\n\nUsing default ship set."),player_count,ships_per_team)
end
player_ship_types = "default"
addGMMessage(out)
placeDefaultPlayerShips()
end
psx, psy = station_primary_human:getPosition()
angle = human_angle
for pidx=1,ships_per_team do
local p = getPlayerShip(pidx)
if p ~= nil and p:isValid() then
setPlayer(p)
startPlayerPosition(p,angle)
local respawn_x, respawn_y = p:getPosition()
p.respawn_x = respawn_x
p.respawn_y = respawn_y
player_restart[p:getCallSign()] = {self = p, template = p:getTypeName(), control_code = p.control_code, faction = p:getFaction(), respawn_x = respawn_x, respawn_y = respawn_y}
angle = (angle + 360/ships_per_team) % 360
else
addGMMessage(_("msgGM", "One of the player ships spawned is not valid, switching to default ship set"))
player_ship_types = "default"
break
end
end
if player_ship_types == "default" then
placeDefaultPlayerShips()
else
replicatePlayers("Kraylor")
if exuari_angle ~= nil then
replicatePlayers("Exuari")
end
if ktlitan_angle ~= nil then
replicatePlayers("Ktlitans")
end
end
elseif player_ship_types == "custom" then
placeCustomPlayerShips()
else --default
placeDefaultPlayerShips()
end
for pidx=1,32 do
local p = getPlayerShip(pidx)
if p ~= nil and p:isValid() then
table.insert(place_ref_list,p)
if p:getFaction() == "Human Navy" then
table.insert(human_ref_list,p)
end
end
end
-- Place NPC ships (if applicable)
local npc_fleet_count = 0
if npc_ships then
npc_fleet_count = math.random(1,ships_per_team)
local fleet_index = 1
local fleet_angle_increment = 360/npc_fleet_count
for n=1,npc_fleet_count do
local angle = (human_angle + n * fleet_angle_increment) % 360
local fleet_strength = random(npc_lower,npc_upper)
local pool_selectivity_choices = {"full","less/heavy","more/light"}
pool_selectivity = pool_selectivity_choices[math.random(1,#pool_selectivity_choices)]
local fleetComposition_choices = {"Random","Non-DB","Fighters","Chasers","Frigates","Beamers","Missilers","Adders","Drones"}
fleetComposition = fleetComposition_choices[math.random(1,#fleetComposition_choices)]
local fcx, fcy = vectorFromAngleNorth(angle,defense_platform_distance + 5000)
psx, psy = station_primary_human:getPosition()
local human_fleet = spawnRandomArmed(psx + fcx, psy + fcy, fleet_strength, fleet_index, nil, angle)
fleet_index = fleet_index + 1
for idx, ship in ipairs(human_fleet) do
ship.score_value = ship_template[ship:getTypeName()].strength
ship:setScannedByFaction("Human Navy",true)
table.insert(human_ref_list,ship)
table.insert(place_ref_list,ship)
table.insert(npc_fleet["Human Navy"],ship)
end
fleet_index = fleet_index + 1
local fleet_prefix = generateCallSignPrefix()
angle = (kraylor_angle + n * fleet_angle_increment) % 360
for idx, source_ship in ipairs(human_fleet) do
local sx, sy = source_ship:getPosition()
local obj_ref_angle = angleFromVectorNorth(sx, sy, terrain_center_x, terrain_center_y)
local obj_ref_distance = distance(terrain_center_x, terrain_center_y, sx, sy)
obj_ref_angle = (obj_ref_angle + replicant_increment) % 360
local rep_x, rep_y = vectorFromAngleNorth(obj_ref_angle,obj_ref_distance)
local selected_template = source_ship:getTypeName()
local ship = ship_template[selected_template].create("Kraylor",selected_template)
ship.score_value = ship_template[selected_template].strength
ship:setScannedByFaction("Kraylor",true)
ship:setPosition(terrain_center_x + rep_x, terrain_center_y + rep_y)
ship:setCallSign(generateCallSign(fleet_prefix))
ship:setCommsScript(""):setCommsFunction(commsShip)
ship:orderIdle()
ship:setHeading(angle)
ship:setRotation(angle + 270)
ship.fleetIndex = fleet_index
table.insert(place_ref_list,ship)
table.insert(npc_fleet["Kraylor"],ship)
end
if exuari_angle ~= nil then
fleet_index = fleet_index + 1
local fleet_prefix = generateCallSignPrefix()
angle = (exuari_angle + n * fleet_angle_increment) % 360
for idx, source_ship in ipairs(human_fleet) do
local sx, sy = source_ship:getPosition()
local obj_ref_angle = angleFromVectorNorth(sx, sy, terrain_center_x, terrain_center_y)
local obj_ref_distance = distance(terrain_center_x, terrain_center_y, sx, sy)
obj_ref_angle = (obj_ref_angle + replicant_increment * 2) % 360
local rep_x, rep_y = vectorFromAngleNorth(obj_ref_angle,obj_ref_distance)
local selected_template = source_ship:getTypeName()
local ship = ship_template[selected_template].create("Exuari",selected_template)
ship.score_value = ship_template[selected_template].strength
ship:setScannedByFaction("Exuari",true)
ship:setPosition(terrain_center_x + rep_x, terrain_center_y + rep_y)
ship:setCallSign(generateCallSign(fleet_prefix))
ship:setCommsScript(""):setCommsFunction(commsShip)
ship:orderIdle()
ship:setHeading(angle)
ship:setRotation(angle + 270)
ship.fleetIndex = fleet_index
table.insert(place_ref_list,ship)
table.insert(npc_fleet["Exuari"],ship)
end
end
if ktlitan_angle ~= nil then
fleet_index = fleet_index + 1
local fleet_prefix = generateCallSignPrefix()
angle = (ktlitan_angle + n * fleet_angle_increment) % 360
for idx, source_ship in ipairs(human_fleet) do
local sx, sy = source_ship:getPosition()
local obj_ref_angle = angleFromVectorNorth(sx, sy, terrain_center_x, terrain_center_y)
local obj_ref_distance = distance(terrain_center_x, terrain_center_y, sx, sy)
obj_ref_angle = (obj_ref_angle + replicant_increment * 3) % 360
local rep_x, rep_y = vectorFromAngleNorth(obj_ref_angle,obj_ref_distance)
local selected_template = source_ship:getTypeName()
local ship = ship_template[selected_template].create("Ktlitans",selected_template)
ship.score_value = ship_template[selected_template].strength
ship:setScannedByFaction("Ktlitans",true)
ship:setPosition(terrain_center_x + rep_x, terrain_center_y + rep_y)
ship:setCallSign(generateCallSign(fleet_prefix))
ship:setCommsScript(""):setCommsFunction(commsShip)
ship:orderIdle()
ship:setHeading(angle)
ship:setRotation(angle + 270)
ship.fleetIndex = fleet_index
table.insert(place_ref_list,ship)
table.insert(npc_fleet["Ktlitans"],ship)
end
end
end
end
-- Place stations
local candidate_x = 0
local candidate_y = 0
local center_x = 0
local center_y = 0
local perimeter = 0
local avg_dist = 0
local bubble = 2500
local team_station_count_list = {50,25,16,12}
local stretch_bound = 0
for i=1,team_station_count_list[player_team_count] do
center_x, center_y, perimeter, avg_dist = analyzeBlob(human_ref_list)
stretch_bound = 5000
repeat
candidate_x, candidate_y = vectorFromAngleNorth(random(0,360),random(math.min(avg_dist,5000),math.min(perimeter,50000) + stretch_bound))
candidate_x = center_x + candidate_x
candidate_y = center_y + candidate_y
stretch_bound = stretch_bound + 500
until(farEnough(place_ref_list,candidate_x,candidate_y,math.max(perimeter/i,15000)))
local sr_size = szt()
local pStation = placeStation(candidate_x, candidate_y, "Random","Human Navy",sr_size)
table.insert(station_list["Human Navy"],pStation)
pStation.score_value = base_station_value_list[sr_size]
table.insert(place_ref_list,pStation)
table.insert(human_ref_list,pStation)
pStation.comms_data = {
friendlyness = random(15,100),
weapon_cost = {
Homing = math.random(2,8),
Nuke = math.random(12,30),
Mine = math.random(3,28),
EMP = math.random(9,25),
HVLI = math.random(2,5),
},
weapon_available = {
Homing = random(1,13)<=(6-difficulty),
HVLI = random(1,13)<=(6-difficulty),
Mine = random(1,13)<=(5-difficulty),
Nuke = random(1,13)<=(4-difficulty),
EMP = random(1,13)<=(4-difficulty),
},
weapon_inventory = {
Unlimited = unlimited_missiles,
Homing = math.floor(math.random(10,40)/difficulty),
Nuke = math.floor(math.random(5,20)/difficulty),
Mine = math.floor(math.random(8,30)/difficulty),
EMP = math.floor(math.random(6,24)/difficulty),
HVLI = math.floor(math.random(15,50)/difficulty),
},
services = {
supplydrop = "friend",
reinforcements = "friend",
jumpsupplydrop = "friend",
sensor_boost = "neutral",
preorder = "friend",
activatedefensefleet = "neutral",
jumpovercharge = "neutral",
},
service_cost = {
supplydrop = math.random(80,120),
reinforcements = math.random(125,175),
hornetreinforcements = math.random(75,125),
phobosreinforcements = math.random(175,225),
activatedefensefleet = math.random(15,40),
jumpovercharge = math.random(10,20),
jumpsupplydrop = math.random(110,140),
},
jump_overcharge = random(1,100) <= (20 - difficulty*2.5),
probe_launch_repair = random(1,100) <= (33 - difficulty*2.5),
hack_repair = random(1,100) <= (42 - difficulty*2.5),
scan_repair = random(1,100) <= (50 - difficulty*2.5),
combat_maneuver_repair= random(1,100) <= (28 - difficulty*2.5),
self_destruct_repair = random(1,100) <= (25 - difficulty*2.5),
tube_slow_down_repair = random(1,100) <= (35 - difficulty*2.5),
reputation_cost_multipliers = {
friend = 1.0,
neutral = 3.0,
},
max_weapon_refill_amount = {friend = 1.0, neutral = 0.5 },
}
pStation.comms_data.idle_defense_fleet = defense_fleet_list[sr_size][math.random(1,#defense_fleet_list[sr_size])]
pStation:setSharesEnergyWithDocked(random(1,100) <= (50 - difficulty*5))
pStation:setRepairDocked(random(1,100) <= (40 - difficulty*5))
pStation:setRestocksScanProbes(random(1,100) <= (30 - difficulty*5))
if scientist_count < 5 then
if random(1,100) < 30 then
if scientist_list["Human Navy"] == nil then
scientist_list["Human Navy"] = {}
end
table.insert(
scientist_list["Human Navy"],
{
name = tableRemoveRandom(scientist_names),
topic = tableRemoveRandom(scientist_topics),
location = pStation,
location_name = pStation:getCallSign(),
score_value = scientist_score_value,
upgrade_requirement = upgrade_requirements[math.random(1,#upgrade_requirements)],
upgrade = tableRemoveRandom(upgrade_list),
upgrade_automated_application = upgrade_automated_applications[math.random(1,#upgrade_automated_applications)],
}
)
scientist_count = scientist_count + 1
end
end
local obj_ref_angle = angleFromVectorNorth(candidate_x, candidate_y, terrain_center_x, terrain_center_y)
local obj_ref_distance = distance(terrain_center_x, terrain_center_y, candidate_x, candidate_y)
obj_ref_angle = (obj_ref_angle + replicant_increment) % 360
local rep_x, rep_y = vectorFromAngleNorth(obj_ref_angle,obj_ref_distance)
pStation = placeStation(terrain_center_x + rep_x, terrain_center_y + rep_y, "Random","Kraylor",sr_size)
table.insert(station_list["Kraylor"],pStation)
pStation.score_value = base_station_value_list[sr_size]
pStation.comms_data = human_ref_list[#human_ref_list].comms_data
pStation:setSharesEnergyWithDocked(human_ref_list[#human_ref_list]:getSharesEnergyWithDocked())
pStation:setRepairDocked(human_ref_list[#human_ref_list]:getRepairDocked())
pStation:setRestocksScanProbes(human_ref_list[#human_ref_list]:getRestocksScanProbes())
table.insert(place_ref_list,pStation)
if scientist_list["Human Navy"] ~= nil then
if scientist_list["Kraylor"] == nil then
scientist_list["Kraylor"] = {}
end
if #scientist_list["Kraylor"] < #scientist_list["Human Navy"] then
table.insert(
scientist_list["Kraylor"],
{
name = tableRemoveRandom(scientist_names),
topic = scientist_list["Human Navy"][#scientist_list["Human Navy"]].topic,
location = pStation,
location_name = pStation:getCallSign(),
score_value = scientist_score_value,
upgrade_requirement = upgrade_requirements[math.random(1,#upgrade_requirements)],
upgrade = scientist_list["Human Navy"][#scientist_list["Human Navy"]].upgrade,
upgrade_automated_application = scientist_list["Human Navy"][#scientist_list["Human Navy"]].upgrade_automated_application,
}
)
end
end
if exuari_angle ~= nil then
obj_ref_angle = (obj_ref_angle + replicant_increment) % 360
rep_x, rep_y = vectorFromAngleNorth(obj_ref_angle,obj_ref_distance)
pStation = placeStation(terrain_center_x + rep_x, terrain_center_y + rep_y, "Random","Exuari",sr_size)
table.insert(station_list["Exuari"],pStation)
pStation.score_value = base_station_value_list[sr_size]
pStation.comms_data = human_ref_list[#human_ref_list].comms_data
pStation:setSharesEnergyWithDocked(human_ref_list[#human_ref_list]:getSharesEnergyWithDocked())
pStation:setRepairDocked(human_ref_list[#human_ref_list]:getRepairDocked())
pStation:setRestocksScanProbes(human_ref_list[#human_ref_list]:getRestocksScanProbes())
table.insert(place_ref_list,pStation)
if scientist_list["Human Navy"] ~= nil then
if scientist_list["Exuari"] == nil then
scientist_list["Exuari"] = {}
end
if #scientist_list["Exuari"] < #scientist_list["Human Navy"] then
table.insert(
scientist_list["Exuari"],
{
name = tableRemoveRandom(scientist_names),
topic = scientist_list["Human Navy"][#scientist_list["Human Navy"]].topic,
location = pStation,
location_name = pStation:getCallSign(),
score_value = scientist_score_value,
upgrade_requirement = upgrade_requirements[math.random(1,#upgrade_requirements)],
upgrade = scientist_list["Human Navy"][#scientist_list["Human Navy"]].upgrade,
upgrade_automated_application = scientist_list["Human Navy"][#scientist_list["Human Navy"]].upgrade_automated_application,
}
)
end
end
end
if ktlitan_angle ~= nil then
obj_ref_angle = (obj_ref_angle + replicant_increment) % 360
rep_x, rep_y = vectorFromAngleNorth(obj_ref_angle,obj_ref_distance)
pStation = placeStation(terrain_center_x + rep_x, terrain_center_y + rep_y, "Random","Ktlitans",sr_size)
table.insert(station_list["Ktlitans"],pStation)
pStation.score_value = base_station_value_list[sr_size]
pStation.comms_data = human_ref_list[#human_ref_list].comms_data
pStation:setSharesEnergyWithDocked(human_ref_list[#human_ref_list]:getSharesEnergyWithDocked())
pStation:setRepairDocked(human_ref_list[#human_ref_list]:getRepairDocked())
pStation:setRestocksScanProbes(human_ref_list[#human_ref_list]:getRestocksScanProbes())
table.insert(place_ref_list,pStation)
if scientist_list["Human Navy"] ~= nil then
if scientist_list["Ktlitans"] == nil then
scientist_list["Ktlitans"] = {}
end
if #scientist_list["Ktlitans"] < #scientist_list["Human Navy"] then
table.insert(
scientist_list["Ktlitans"],
{
name = tableRemoveRandom(scientist_names),
topic = scientist_list["Human Navy"][#scientist_list["Human Navy"]].topic,
location = pStation,
location_name = pStation:getCallSign(),
score_value = scientist_score_value,
upgrade_requirement = upgrade_requirements[math.random(1,#upgrade_requirements)],
upgrade = scientist_list["Human Navy"][#scientist_list["Human Navy"]].upgrade,
upgrade_automated_application = scientist_list["Human Navy"][#scientist_list["Human Navy"]].upgrade_automated_application,
}
)
end
end
end
end --station build loop
-- Build some wormholes if applicable
local hole_list = {}
local wormhole_count = math.random(0,3)
if wormhole_count > 0 then
for w=1,wormhole_count do
center_x, center_y, perimeter, avg_dist = analyzeBlob(human_ref_list)
stretch_bound = 5000
bubble = 6000
repeat
-- print("wormhole candidate numbers. average distance:",avg_dist,"perimeter:",perimeter)
candidate_x, candidate_y = vectorFromAngleNorth(random(0,360),random(math.min(avg_dist,20000),math.min(perimeter,100000) + stretch_bound))
candidate_x = center_x + candidate_x
candidate_y = center_y + candidate_y
stretch_bound = stretch_bound + 500
until(farEnough(place_ref_list,candidate_x,candidate_y,bubble))
local wormhole = WormHole():setPosition(candidate_x,candidate_y)
table.insert(place_ref_list,wormhole)
table.insert(human_ref_list,wormhole)
table.insert(hole_list,wormhole)
center_x, center_y, perimeter, avg_dist = analyzeBlob(human_ref_list)
stretch_bound = 5000
local target_candidate_x = 0
local target_candidate_y = 0
repeat
target_candidate_x, target_candidate_y = vectorFromAngleNorth(random(0,360),random(avg_dist,50000 + perimeter + stretch_bound))
target_candidate_x = center_x + target_candidate_x
target_candidate_y = center_y + target_candidate_y
stretch_bound = stretch_bound + 500
until(farEnough(place_ref_list,target_candidate_x,target_candidate_y,bubble))
local ta = VisualAsteroid():setPosition(target_candidate_x,target_candidate_y)
table.insert(place_ref_list,ta)
table.insert(human_ref_list,ta)
wormhole:setTargetPosition(target_candidate_x,target_candidate_y)
local obj_ref_angle = angleFromVectorNorth(candidate_x, candidate_y, terrain_center_x, terrain_center_y)
local obj_ref_distance = distance(terrain_center_x, terrain_center_y, candidate_x, candidate_y)
obj_ref_angle = (obj_ref_angle + replicant_increment) % 360
local rep_x, rep_y = vectorFromAngleNorth(obj_ref_angle,obj_ref_distance)
wormhole = WormHole():setPosition(terrain_center_x + rep_x, terrain_center_y + rep_y)
table.insert(place_ref_list,wormhole)
table.insert(hole_list,wormhole)
local target_ref_angle = angleFromVectorNorth(target_candidate_x, target_candidate_y, terrain_center_x, terrain_center_y)
local target_ref_distance = distance(terrain_center_x, terrain_center_y, target_candidate_x, target_candidate_y)
target_ref_angle = (target_ref_angle + replicant_increment) % 360
rep_x, rep_y = vectorFromAngleNorth(target_ref_angle,target_ref_distance)
wormhole:setTargetPosition(terrain_center_x + rep_x, terrain_center_y + rep_y)
if exuari_angle ~= nil then
obj_ref_angle = (obj_ref_angle + replicant_increment) % 360
rep_x, rep_y = vectorFromAngleNorth(obj_ref_angle,obj_ref_distance)
wormhole = WormHole():setPosition(terrain_center_x + rep_x, terrain_center_y + rep_y)
table.insert(place_ref_list,wormhole)
table.insert(hole_list,wormhole)
target_ref_angle = (target_ref_angle + replicant_increment) % 360
rep_x, rep_y = vectorFromAngleNorth(target_ref_angle,target_ref_distance)
wormhole:setTargetPosition(terrain_center_x + rep_x, terrain_center_y + rep_y)
end
if ktlitan_angle ~= nil then
obj_ref_angle = (obj_ref_angle + replicant_increment) % 360
rep_x, rep_y = vectorFromAngleNorth(obj_ref_angle,obj_ref_distance)
wormhole = WormHole():setPosition(terrain_center_x + rep_x, terrain_center_y + rep_y)
table.insert(place_ref_list,wormhole)
table.insert(hole_list,wormhole)
target_ref_angle = (target_ref_angle + replicant_increment) % 360
rep_x, rep_y = vectorFromAngleNorth(target_ref_angle,target_ref_distance)
wormhole:setTargetPosition(terrain_center_x + rep_x, terrain_center_y + rep_y)
end
end
end --wormhole build
-- Maybe sprinkle in some black holes
local blackhole_count = math.random(0,6)
if blackhole_count > 0 then
for b=1,blackhole_count do
center_x, center_y, perimeter, avg_dist = analyzeBlob(human_ref_list)
stretch_bound = 5000
bubble = 6000
repeat
candidate_x, candidate_y = vectorFromAngleNorth(random(0,360),random(math.min(avg_dist,20000),math.min(perimeter,100000) + stretch_bound))
candidate_x = center_x + candidate_x
candidate_y = center_y + candidate_y
stretch_bound = stretch_bound + 500
until(farEnough(place_ref_list,candidate_x,candidate_y,bubble))
local blackhole = BlackHole():setPosition(candidate_x,candidate_y)
table.insert(place_ref_list,blackhole)
table.insert(human_ref_list,blackhole)
table.insert(hole_list,blackhole)
local obj_ref_angle = angleFromVectorNorth(candidate_x, candidate_y, terrain_center_x, terrain_center_y)
local obj_ref_distance = distance(terrain_center_x, terrain_center_y, candidate_x, candidate_y)
obj_ref_angle = (obj_ref_angle + replicant_increment) % 360
local rep_x, rep_y = vectorFromAngleNorth(obj_ref_angle,obj_ref_distance)
blackhole = BlackHole():setPosition(terrain_center_x + rep_x, terrain_center_y + rep_y)
table.insert(place_ref_list,blackhole)
table.insert(hole_list,blackhole)
if exuari_angle ~= nil then
obj_ref_angle = (obj_ref_angle + replicant_increment) % 360
rep_x, rep_y = vectorFromAngleNorth(obj_ref_angle,obj_ref_distance)
blackhole = BlackHole():setPosition(terrain_center_x + rep_x, terrain_center_y + rep_y)
table.insert(place_ref_list,blackhole)
table.insert(hole_list,blackhole)
end
if ktlitan_angle ~= nil then
obj_ref_angle = (obj_ref_angle + replicant_increment) % 360
rep_x, rep_y = vectorFromAngleNorth(obj_ref_angle,obj_ref_distance)
blackhole = BlackHole():setPosition(terrain_center_x + rep_x, terrain_center_y + rep_y)
table.insert(place_ref_list,blackhole)
table.insert(hole_list,blackhole)
end
end
end --blackhole build
local mine_field_count = math.random(0,(6-player_team_count))
local mine_field_type_list = {"line","arc"}
if mine_field_count > 0 then
for m=1,mine_field_count do
center_x, center_y, perimeter, avg_dist = analyzeBlob(human_ref_list)
stretch_bound = 5000
bubble = 6000
repeat
candidate_x, candidate_y = vectorFromAngleNorth(random(0,360),random(math.min(avg_dist,20000),math.min(perimeter,100000) + stretch_bound))
candidate_x = center_x + candidate_x
candidate_y = center_y + candidate_y
stretch_bound = stretch_bound + 500
until(farEnough(place_ref_list,candidate_x,candidate_y,bubble))
local mine_field_type = mine_field_type_list[math.random(1,#mine_field_type_list)]
local mine_list = {}
local mine_ref_list = {}
if mine_field_type == "line" then
local mle_x, mle_y = vectorFromAngleNorth(random(0,360),random(8000,30000))
mine_list = createObjectsListOnLine(candidate_x + mle_x, candidate_y + mle_y, candidate_x, candidate_y, 1200, Mine, math.random(1,3))
for i=1,#mine_list do
local tm = mine_list[i]
local mx, my = tm:getPosition()
if farEnough(place_ref_list,mx,my,1000) and farEnough(mine_ref_list,mx,my,1000) then
table.insert(mine_ref_list,tm)
local obj_ref_angle = angleFromVectorNorth(mx, my, terrain_center_x, terrain_center_y)
local obj_ref_distance = distance(terrain_center_x, terrain_center_y, mx, my)
obj_ref_angle = (obj_ref_angle + replicant_increment) % 360
local rep_x, rep_y = vectorFromAngleNorth(obj_ref_angle,obj_ref_distance)
table.insert(mine_ref_list,Mine():setPosition(terrain_center_x + rep_x, terrain_center_y + rep_y))
if exuari_angle ~= nil then
obj_ref_angle = (obj_ref_angle + replicant_increment) % 360
rep_x, rep_y = vectorFromAngleNorth(obj_ref_angle,obj_ref_distance)
table.insert(mine_ref_list,Mine():setPosition(terrain_center_x + rep_x, terrain_center_y + rep_y))
end
if ktlitan_angle ~= nil then
obj_ref_angle = (obj_ref_angle + replicant_increment) % 360
rep_x, rep_y = vectorFromAngleNorth(obj_ref_angle,obj_ref_distance)
table.insert(mine_ref_list,Mine():setPosition(terrain_center_x + rep_x, terrain_center_y + rep_y))
end
else
tm:destroy()
end
end
for idx, tm in ipairs(mine_ref_list) do
table.insert(place_ref_list,tm)
end
elseif mine_field_type == "arc" then
local arc_radius = random(8000,25000)
local mid_angle = random(0,360)
local spread = random(10,30)
local angle = (mid_angle + (180 - spread) % 360)
local mar_x, mar_y = vectorFromAngleNorth(angle,arc_radius)
local mar_x = mar_x + candidate_x
local mar_y = mar_y + candidate_y
local final_angle = (mid_angle + (180 + spread)) % 360
local mine_count = 0
local mx, my = vectorFromAngleNorth(angle,arc_radius)
local tm = Mine():setPosition(mar_x + mx, mar_y + my)
table.insert(mine_list,tm)
local angle_increment = 0
repeat
angle_increment = angle_increment + 0.1
mx, my = vectorFromAngleNorth(angle + angle_increment,arc_radius)
until(distance(tm,mar_x + mx, mar_y + my) > 1200)
if final_angle <= angle then
final_angle = final_angle + 360
end
repeat
angle = angle + angle_increment
mx, my = vectorFromAngleNorth(angle,arc_radius)
tm = Mine():setPosition(mar_x + mx, mar_y + my)
table.insert(mine_list,tm)
until(angle > final_angle)
for i=1,#mine_list do
local tm = mine_list[i]
local mx, my = tm:getPosition()
if farEnough(place_ref_list,mx,my,1000) and farEnough(mine_ref_list,mx,my,1000) then
table.insert(mine_ref_list,tm)
local obj_ref_angle = angleFromVectorNorth(mx, my, terrain_center_x, terrain_center_y)
local obj_ref_distance = distance(terrain_center_x, terrain_center_y, mx, my)
obj_ref_angle = (obj_ref_angle + replicant_increment) % 360
local rep_x, rep_y = vectorFromAngleNorth(obj_ref_angle,obj_ref_distance)
table.insert(mine_ref_list,Mine():setPosition(terrain_center_x + rep_x, terrain_center_y + rep_y))
if exuari_angle ~= nil then
obj_ref_angle = (obj_ref_angle + replicant_increment) % 360
rep_x, rep_y = vectorFromAngleNorth(obj_ref_angle,obj_ref_distance)
table.insert(mine_ref_list,Mine():setPosition(terrain_center_x + rep_x, terrain_center_y + rep_y))
end
if ktlitan_angle ~= nil then
obj_ref_angle = (obj_ref_angle + replicant_increment) % 360
rep_x, rep_y = vectorFromAngleNorth(obj_ref_angle,obj_ref_distance)
table.insert(mine_ref_list,Mine():setPosition(terrain_center_x + rep_x, terrain_center_y + rep_y))
end
else
tm:destroy()
end
end
for idx, tm in ipairs(mine_ref_list) do
table.insert(place_ref_list,tm)
end
end
end
end
-- Asteroid build
local asteroid_field_count = math.random(2,(10-player_team_count))
local asteroid_field_type_list = {"blob","line","arc"}
for a=1,asteroid_field_count do
center_x, center_y, perimeter, avg_dist = analyzeBlob(human_ref_list)
stretch_bound = 5000
bubble = 6000
repeat
candidate_x, candidate_y = vectorFromAngleNorth(random(0,360),random(math.min(avg_dist,20000),math.min(perimeter,100000) + stretch_bound))
candidate_x = center_x + candidate_x
candidate_y = center_y + candidate_y
stretch_bound = stretch_bound + 500
until(farEnough(place_ref_list,candidate_x,candidate_y,bubble))
local asteroid_field_type = asteroid_field_type_list[math.random(1,#asteroid_field_type_list)]
local asteroid_list = {}
local asteroid_ref_list = {}
if asteroid_field_type == "blob" then
local blob_count = math.random(10,30)
-- print("blob count:",blob_count)
asteroid_list = placeRandomListAroundPoint(Asteroid,blob_count,100,15000,candidate_x,candidate_y)
for i=1,#asteroid_list do
local ta = asteroid_list[i]
local ax, ay = ta:getPosition()
local as = asteroidSize()
if farEnough(place_ref_list,ax,ay,as) and farEnough(asteroid_ref_list,ax,ay,as) then
ta:setSize(as)
table.insert(asteroid_ref_list,ta)
local obj_ref_angle = angleFromVectorNorth(ax, ay, terrain_center_x, terrain_center_y)
local obj_ref_distance = distance(terrain_center_x, terrain_center_y, ax, ay)
obj_ref_angle = (obj_ref_angle + replicant_increment) % 360
local rep_x, rep_y = vectorFromAngleNorth(obj_ref_angle,obj_ref_distance)
table.insert(asteroid_ref_list,Asteroid():setPosition(terrain_center_x + rep_x, terrain_center_y + rep_y):setSize(as))
if exuari_angle ~= nil then
obj_ref_angle = (obj_ref_angle + replicant_increment) % 360
rep_x, rep_y = vectorFromAngleNorth(obj_ref_angle,obj_ref_distance)
table.insert(asteroid_ref_list,Asteroid():setPosition(terrain_center_x + rep_x, terrain_center_y + rep_y):setSize(as))
end
if ktlitan_angle ~= nil then
obj_ref_angle = (obj_ref_angle + replicant_increment) % 360
rep_x, rep_y = vectorFromAngleNorth(obj_ref_angle,obj_ref_distance)
table.insert(asteroid_ref_list,Asteroid():setPosition(terrain_center_x + rep_x, terrain_center_y + rep_y):setSize(as))
end
else
ta:destroy()
end
end
for idx, ta in ipairs(asteroid_ref_list) do
table.insert(place_ref_list,ta)
end
elseif asteroid_field_type == "line" then
-- print("asteroid line")
local ale_x, ale_y = vectorFromAngleNorth(random(0,360),random(8000,30000))
asteroid_list = createObjectsListOnLine(candidate_x + ale_x, candidate_y + ale_y, candidate_x, candidate_y, random(500,900), Asteroid, 7, 25, 250)
for i=1,#asteroid_list do
local ta = asteroid_list[i]
local ax, ay = ta:getPosition()
local as = asteroidSize()
if farEnough(place_ref_list,ax,ay,as) and farEnough(asteroid_ref_list,ax,ay,as) then
ta:setSize(as)
table.insert(asteroid_ref_list,ta)
local obj_ref_angle = angleFromVectorNorth(ax, ay, terrain_center_x, terrain_center_y)
local obj_ref_distance = distance(terrain_center_x, terrain_center_y, ax, ay)
obj_ref_angle = (obj_ref_angle + replicant_increment) % 360
local rep_x, rep_y = vectorFromAngleNorth(obj_ref_angle,obj_ref_distance)
table.insert(asteroid_ref_list,Asteroid():setPosition(terrain_center_x + rep_x, terrain_center_y + rep_y):setSize(as))
if exuari_angle ~= nil then
obj_ref_angle = (obj_ref_angle + replicant_increment) % 360
rep_x, rep_y = vectorFromAngleNorth(obj_ref_angle,obj_ref_distance)
table.insert(asteroid_ref_list,Asteroid():setPosition(terrain_center_x + rep_x, terrain_center_y + rep_y):setSize(as))
end
if ktlitan_angle ~= nil then
obj_ref_angle = (obj_ref_angle + replicant_increment) % 360
rep_x, rep_y = vectorFromAngleNorth(obj_ref_angle,obj_ref_distance)
table.insert(asteroid_ref_list,Asteroid():setPosition(terrain_center_x + rep_x, terrain_center_y + rep_y):setSize(as))
end
else
ta:destroy()
end
end
for idx, ta in ipairs(asteroid_ref_list) do
table.insert(place_ref_list,ta)
end
elseif asteroid_field_type == "arc" then
local angle_to_radius = random(0,360)
local radius_to_arc = random(8000,25000)
local aar_x, aar_y = vectorFromAngleNorth(angle_to_radius,radius_to_arc)
local spread = random(10,30)
local number_in_arc = math.min(math.floor(spread * 2) + math.random(5,20),35)
-- print("asteroid arc number:",number_in_arc)
asteroid_list = createRandomListAlongArc(Asteroid, number_in_arc, candidate_x + aar_x, candidate_y + aar_y, radius_to_arc, (angle_to_radius + (180-spread)) % 360, (angle_to_radius + (180+spread)) % 360, 1000)
for i=1,#asteroid_list do
local ta = asteroid_list[i]
local ax, ay = ta:getPosition()
local as = asteroidSize()
if farEnough(place_ref_list,ax,ay,as) and farEnough(asteroid_ref_list,ax,ay,as) then
ta:setSize(as)
table.insert(asteroid_ref_list,ta)
local obj_ref_angle = angleFromVectorNorth(ax, ay, terrain_center_x, terrain_center_y)
local obj_ref_distance = distance(terrain_center_x, terrain_center_y, ax, ay)
obj_ref_angle = (obj_ref_angle + replicant_increment) % 360
local rep_x, rep_y = vectorFromAngleNorth(obj_ref_angle,obj_ref_distance)
table.insert(asteroid_ref_list,Asteroid():setPosition(terrain_center_x + rep_x, terrain_center_y + rep_y):setSize(as))
if exuari_angle ~= nil then
obj_ref_angle = (obj_ref_angle + replicant_increment) % 360
rep_x, rep_y = vectorFromAngleNorth(obj_ref_angle,obj_ref_distance)
table.insert(asteroid_ref_list,Asteroid():setPosition(terrain_center_x + rep_x, terrain_center_y + rep_y):setSize(as))
end
if ktlitan_angle ~= nil then
obj_ref_angle = (obj_ref_angle + replicant_increment) % 360
rep_x, rep_y = vectorFromAngleNorth(obj_ref_angle,obj_ref_distance)
table.insert(asteroid_ref_list,Asteroid():setPosition(terrain_center_x + rep_x, terrain_center_y + rep_y):setSize(as))
end
else
ta:destroy()
end
end
for idx, ta in ipairs(asteroid_ref_list) do
table.insert(place_ref_list,ta)
end
end
end -- asteroid fields build
-- Nebula build
local nebula_field_count = math.random(2,8)
center_x, center_y, perimeter, avg_dist = analyzeBlob(human_ref_list)
for n=1,nebula_field_count do
stretch_bound = 5000
bubble = 7000
repeat
candidate_x, candidate_y = vectorFromAngleNorth(random(0,360),random(math.min(avg_dist,20000),math.min(perimeter,100000) + stretch_bound))
candidate_x = center_x + candidate_x
candidate_y = center_y + candidate_y
stretch_bound = stretch_bound + 500
until(farEnough(hole_list,candidate_x,candidate_y,bubble))
local neb = Nebula():setPosition(candidate_x,candidate_y)
local nebula_field = {}
table.insert(nebula_field,neb)
local nebula_field_size = math.random(0,5)
if nebula_field_size > 0 then
for i=1,nebula_field_size do
local na_x = 0
local na_y = 0
local nx = 0
local ny = 0
local attempts = 0
repeat
na_x, na_y = vectorFromAngleNorth(random(0,360),random(8000,9500))
nx, ny = nebula_field[math.random(1,#nebula_field)]:getPosition()
attempts = attempts + 1
until(farEnough(hole_list, na_x + nx, na_y + ny, bubble) or attempts > 50)
if attempts <= 50 then
neb = Nebula():setPosition(na_x + nx, na_y + ny)
table.insert(nebula_field,neb)
else
break
end
end
end
for i=1,#nebula_field do
candidate_x, candidate_y = nebula_field[i]:getPosition()
local obj_ref_angle = angleFromVectorNorth(candidate_x, candidate_y, terrain_center_x, terrain_center_y)
local obj_ref_distance = distance(terrain_center_x, terrain_center_y, candidate_x, candidate_y)
obj_ref_angle = (obj_ref_angle + replicant_increment) % 360
local rep_x, rep_y = vectorFromAngleNorth(obj_ref_angle,obj_ref_distance)
Nebula():setPosition(terrain_center_x + rep_x, terrain_center_y + rep_y)
if exuari_angle ~= nil then
obj_ref_angle = (obj_ref_angle + replicant_increment) % 360
rep_x, rep_y = vectorFromAngleNorth(obj_ref_angle,obj_ref_distance)
Nebula():setPosition(terrain_center_x + rep_x, terrain_center_y + rep_y)
end
if ktlitan_angle ~= nil then
obj_ref_angle = (obj_ref_angle + replicant_increment) % 360
rep_x, rep_y = vectorFromAngleNorth(obj_ref_angle,obj_ref_distance)
Nebula():setPosition(terrain_center_x + rep_x, terrain_center_y + rep_y)
end
end
end -- nebula field build
game_state = "terrain generated"
-- Store (then print) original values for later comparison
local stat_list = gatherStats()
original_score = {}
local out = "Original scores:"
original_score["Human Navy"] = stat_list.human.weighted_score
out = out .. string.format("\nHuman Navy: %.2f",stat_list.human.weighted_score)
original_score["Kraylor"] = stat_list.kraylor.weighted_score
out = out .. string.format("\nKraylor: %.2f",stat_list.kraylor.weighted_score)
if exuari_angle ~= nil then
original_score["Exuari"] = stat_list.exuari.weighted_score
out = out .. string.format("\nExuari: %.2f",stat_list.exuari.weighted_score)
end
if ktlitan_angle ~= nil then
original_score["Ktlitans"] = stat_list.ktlitan.weighted_score
out = out .. string.format("\nKtlitans: %.2f",stat_list.ktlitan.weighted_score)
end
allowNewPlayerShips(false)
print(out)
-- Provide summary terrain details in console log
print("----- Terrain Info -----")
print("Center:",terrain_center_sector,"featuring:",center_choice)
print("Primary stations:",primary_station_size,"Jammers:",primary_jammers,"defense platforms:",defense_platform_count)
local output_player_types = player_ship_types
if player_ship_types == "custom" then
output_player_types = output_player_types .. " (" .. custom_player_ship_type .. ")"
end
print("Teams:",player_team_count,"Player ships:",ships_per_team .. "(" .. ships_per_team*player_team_count .. ")","Player ship types:",output_player_types)
print("NPC Fleets:",npc_fleet_count .. "(" .. npc_fleet_count*player_team_count .. ")")
print("Wormholes:",wormhole_count .. "(" .. wormhole_count*player_team_count .. ")","Black holes:",blackhole_count .. "(" .. blackhole_count*player_team_count .. ")")
print("Asteroid fields:",asteroid_field_count .. "(" .. asteroid_field_count*player_team_count .. ")","Nebula groups:",nebula_field_count .. "(" .. nebula_field_count*player_team_count .. ")")
end
function spawnRandomArmed(x, y, enemyStrength, fleetIndex, shape, angle)
--x and y are central spawn coordinates
--fleetIndex is the number of the fleet to be spawned
--sl (was) the score list, nl is the name list, bl is the boolean list
--spawn_distance optional - used for ambush or pyramid
--spawn_angle optional - used for ambush or pyramid
--px and py are the player coordinates or the pyramid fly towards point coordinates
local sp = 1000 --spacing of spawned group
if shape == nil then
local shape_choices = {"square","hexagonal"}
shape = shape_choices[math.random(1,#shape_choices)]
end
local enemy_position = 0
local enemyList = {}
local template_pool = getTemplatePool(enemyStrength)
if #template_pool < 1 then
addGMMessage(_("msgGM", "Empty Template pool: fix excludes or other criteria"))
return enemyList
end
local fleet_prefix = generateCallSignPrefix()
while enemyStrength > 0 do
local selected_template = template_pool[math.random(1,#template_pool)]
-- print("selected template:",selected_template)
-- print("base:",ship_template[selected_template].base)
local ship = ship_template[selected_template].create("Human Navy",selected_template)
ship:setCallSign(generateCallSign(fleet_prefix))
ship:setCommsScript(""):setCommsFunction(commsShip)
ship:orderIdle()
ship:setHeading(angle)
ship:setRotation(angle + 270)
enemy_position = enemy_position + 1
ship:setPosition(x + formation_delta[shape].x[enemy_position] * sp, y + formation_delta[shape].y[enemy_position] * sp)
ship.fleetIndex = fleetIndex
table.insert(enemyList, ship)
enemyStrength = enemyStrength - ship_template[selected_template].strength
end
return enemyList
end
function getTemplatePool(max_strength)
local function getStrengthSort(tbl, sortFunction)
local keys = {}
for key in pairs(tbl) do
table.insert(keys,key)
end
table.sort(keys, function(a,b)
return sortFunction(tbl[a], tbl[b])
end)
return keys
end
local ship_template_by_strength = getStrengthSort(ship_template, function(a,b)
return a.strength > b.strength
end)
local template_pool = {}
-- print("fleet composition:",fleetComposition,"fleet group sub fleet composition:",fleet_group[fleetComposition])
if pool_selectivity == "less/heavy" then
for idx, current_ship_template in ipairs(ship_template_by_strength) do
-- print("currrent ship template:",current_ship_template,"strength:",ship_template[current_ship_template].strength,"max strength:",max_strength)
if ship_template[current_ship_template].strength <= max_strength then
if fleetComposition == "Non-DB" then
if ship_template[current_ship_template].create ~= stockTemplate then
table.insert(template_pool,current_ship_template)
end
elseif fleetComposition == "Random" then
table.insert(template_pool,current_ship_template)
else
if ship_template[current_ship_template][fleet_group[fleetComposition]] then
table.insert(template_pool,current_ship_template)
end
end
end
if #template_pool >= 5 then
break
end
end
elseif pool_selectivity == "more/light" then
for i=#ship_template_by_strength,1,-1 do
local current_ship_template = ship_template_by_strength[i]
-- print("currrent ship template:",current_ship_template,"strength:",ship_template[current_ship_template].strength,"max strength:",max_strength)
if ship_template[current_ship_template].strength <= max_strength then
if fleetComposition == "Non-DB" then
if ship_template[current_ship_template].create ~= stockTemplate then
table.insert(template_pool,current_ship_template)
end
elseif fleetComposition == "Random" then
table.insert(template_pool,current_ship_template)
else
if ship_template[current_ship_template][fleet_group[fleetComposition]] then
table.insert(template_pool,current_ship_template)
end
end
end
if #template_pool >= 20 then
break
end
end
else --full
for current_ship_template, details in pairs(ship_template) do
if details.strength <= max_strength then
if fleetComposition == "Non-DB" then
if ship_template[current_ship_template].create ~= stockTemplate then
table.insert(template_pool,current_ship_template)
end
elseif fleetComposition == "Random" then
table.insert(template_pool,current_ship_template)
else
if ship_template[current_ship_template][fleet_group[fleetComposition]] then
table.insert(template_pool,current_ship_template)
end
end
end
end
end
--print("returning template pool containing these templates:")
--for idx, template in ipairs(template_pool) do
-- print(template)
--end
return template_pool
end
function stockTemplate(enemyFaction,template)
local ship = CpuShip():setFaction(enemyFaction):setTemplate(template):orderRoaming()
ship:onTakingDamage(function(self,instigator)
string.format("") --serious proton needs a global context
if instigator ~= nil then
self.damage_instigator = instigator
end
end)
return ship
end
function tableRemoveRandom(array)
-- Remove random element from array and return it.
-- Returns nil if the array is empty,
-- analogous to `table.remove`.
local array_item_count = #array
if array_item_count == 0 then
return nil
end
local selected_item = math.random(array_item_count)
array[selected_item], array[array_item_count] = array[array_item_count], array[selected_item]
return table.remove(array)
end
function asteroidSize()
return random(1,160)+random(1,120)+random(1,80)+random(1,40)+random(1,20)+random(1,10)
end
function createRandomListAlongArc(object_type, amount, x, y, distance, startArc, endArcClockwise, randomize)
-- Create amount of objects of type object_type along arc
-- Center defined by x and y
-- Radius defined by distance
-- Start of arc between 0 and 360 (startArc), end arc: endArcClockwise
-- Use randomize to vary the distance from the center point. Omit to keep distance constant
-- Example:
-- createRandomAlongArc(Asteroid, 100, 500, 3000, 65, 120, 450)
local list = {}
if randomize == nil then randomize = 0 end
if amount == nil then amount = 1 end
local arcLen = endArcClockwise - startArc
if startArc > endArcClockwise then
endArcClockwise = endArcClockwise + 360
arcLen = arcLen + 360
end
if amount > arcLen then
for ndex=1,arcLen do
local radialPoint = startArc+ndex
local pointDist = distance + random(-randomize,randomize)
table.insert(list,object_type():setPosition(x + math.cos(radialPoint / 180 * math.pi) * pointDist, y + math.sin(radialPoint / 180 * math.pi) * pointDist))
end
for ndex=1,amount-arcLen do
radialPoint = random(startArc,endArcClockwise)
pointDist = distance + random(-randomize,randomize)
table.insert(list,object_type():setPosition(x + math.cos(radialPoint / 180 * math.pi) * pointDist, y + math.sin(radialPoint / 180 * math.pi) * pointDist))
end
else
for ndex=1,amount do
radialPoint = random(startArc,endArcClockwise)
pointDist = distance + random(-randomize,randomize)
table.insert(list,object_type():setPosition(x + math.cos(radialPoint / 180 * math.pi) * pointDist, y + math.sin(radialPoint / 180 * math.pi) * pointDist))
end
end
return list
end
function createObjectsListOnLine(x1, y1, x2, y2, spacing, object_type, rows, chance, randomize)
-- Create objects along a line between two vectors, optionally with grid
-- placement and randomization.
--
-- createObjectsOnLine(x1, y1, x2, y2, spacing, object_type, rows, chance, randomize)
-- x1, y1: Starting coordinates
-- x2, y2: Ending coordinates
-- spacing: The distance between each object.
-- object_type: The object type. Calls `object_type():setPosition()`.
-- rows (optional): The number of rows, minimum 1. Defaults to 1.
-- chance (optional): The percentile chance an object will be created,
-- minimum 1. Defaults to 100 (always).
-- randomize (optional): If present, randomize object placement by this
-- amount. Defaults to 0 (grid).
--
-- Examples: To create a mine field, run:
-- createObjectsOnLine(0, 0, 10000, 0, 1000, Mine, 4)
-- This creates 4 rows of mines from 0,0 to 10000,0, with mines spaced 1U
-- apart.
--
-- The `randomize` parameter adds chaos to the pattern. This works well for
-- asteroid fields:
-- createObjectsOnLine(0, 0, 10000, 0, 300, Asteroid, 4, 100, 800)
local list = {}
if rows == nil then rows = 1 end
if chance == nil then chance = 100 end
if randomize == nil then randomize = 0 end
local d = distance(x1, y1, x2, y2)
local xd = (x2 - x1) / d
local yd = (y2 - y1) / d
for cnt_x=0,d,spacing do
for cnt_y=0,(rows-1)*spacing,spacing do
local px = x1 + xd * cnt_x + yd * (cnt_y - (rows - 1) * spacing * 0.5) + random(-randomize, randomize)
local py = y1 + yd * cnt_x - xd * (cnt_y - (rows - 1) * spacing * 0.5) + random(-randomize, randomize)
if random(0, 100) < chance then
table.insert(list,object_type():setPosition(px, py))
end
end
end
return list
end
function placeRandomListAroundPoint(object_type, amount, dist_min, dist_max, x0, y0)
-- create amount of object_type, at a distance between dist_min and dist_max around the point (x0, y0)
-- save in a list that is returned to caller
local object_list = {}
for n=1,amount do
local r = random(0, 360)
local distance = random(dist_min, dist_max)
x = x0 + math.cos(r / 180 * math.pi) * distance
y = y0 + math.sin(r / 180 * math.pi) * distance
table.insert(object_list,object_type():setPosition(x, y))
end
return object_list
end
function placeRandomAsteroidsAroundPoint(amount, dist_min, dist_max, x0, y0)
-- create amount of asteroid, at a distance between dist_min and dist_max around the point (x0, y0)
for n=1,amount do
local r = random(0, 360)
local distance = random(dist_min, dist_max)
x = x0 + math.cos(r / 180 * math.pi) * distance
y = y0 + math.sin(r / 180 * math.pi) * distance
local asteroid_size = random(1,100) + random(1,75) + random(1,75) + random(1,20) + random(1,20) + random(1,20) + random(1,20) + random(1,20) + random(1,20) + random(1,20)
Asteroid():setPosition(x, y):setSize(asteroid_size)
end
end
function choosePlanet(index,x,y)
local planet_list = {
{
radius = random(500,1500), distance = -2000,
name = {"Gamma Piscium","Beta Lyporis","Sigma Draconis","Iota Carinae","Theta Arietis","Epsilon Indi","Beta Hydri"},
color = {
red = random(0.9,1), green = random(0.85,1), blue = random(0.9,1)
},
texture = {
atmosphere = "planets/star-1.png"
},
},
{
radius = random(2500,4000), distance = -2000, rotation = random(250,350),
name = {"Bespin","Aldea","Bersallis","Alpha Omicron","Farius Prime","Deneb","Mordan","Nelvana"},
texture = {
surface = "planets/gas-1.png"
},
},
{
radius = random(2000,3500), distance = -2000, rotation = random(350,450),
name = {"Alderaan","Dagobah","Dantooine","Rigel","Pahvo","Penthara","Scalos","Tanuga","Vacca","Terlina","Timor"},
color = {
red = random(0.1,0.3), green = random(0.1,0.3), blue = random(0.9,1)
},
texture = {
surface = "planets/planet-1.png", cloud = "planets/clouds-1.png", atmosphere = "planets/atmosphere.png"
},
},
{
radius = random(200,400), distance = -150, rotation = random(60,100),
name = {"Adrastea","Belior","Cressida","Europa","Kyrrdis","Oberon","Pallas","Telesto","Vesta"},
texture = {
surface = "planets/moon-1.png"
}
},
}
local planet = Planet():setPosition(x,y):setPlanetRadius(planet_list[index].radius):setDistanceFromMovementPlane(planet_list[index].distance):setCallSign(planet_list[index].name[math.random(1,#planet_list[index].name)])
if planet_list[index].texture.surface ~= nil then
planet:setPlanetSurfaceTexture(planet_list[index].texture.surface)
end
if planet_list[index].texture.atmosphere ~= nil then
planet:setPlanetAtmosphereTexture(planet_list[index].texture.atmosphere)
end
if planet_list[index].texture.cloud ~= nil then
planet:setPlanetCloudTexture(planet_list[index].texture.cloud)
end
if planet_list[index].color ~= nil then
planet:setPlanetAtmosphereColor(planet_list[index].color.red,planet_list[index].color.green,planet_list[index].color.blue)
end
if planet_list[index].rotation ~= nil then
planet:setAxialRotationTime(planet_list[index].rotation)
end
return planet, planet_list[index].radius
end
function vectorFromAngleNorth(angle,distance)
angle = (angle + 270) % 360
local x, y = vectorFromAngle(angle,distance)
return x, y
end
function angleFromVectorNorth(p1x,p1y,p2x,p2y)
TWOPI = 6.2831853071795865
RAD2DEG = 57.2957795130823209
atan2parm1 = p2x - p1x
atan2parm2 = p2y - p1y
theta = math.atan2(atan2parm1, atan2parm2)
if theta < 0 then
theta = theta + TWOPI
end
return (360 - (RAD2DEG * theta)) % 360
end
function analyzeBlob(object_list)
--given a blob (list) of objects, find the center and the max perimeter and avg dist values
local center_x = 0
local center_y = 0
local max_perimeter = 0
local total_distance = 0
local average_distance = 0
if object_list ~= nil and #object_list > 0 then
for i=1,#object_list do
local obj_x, obj_y = object_list[i]:getPosition()
center_x = center_x + obj_x
center_y = center_y + obj_y
end
center_x = center_x/#object_list
center_y = center_y/#object_list
for i=1,#object_list do
--[[
if distance_diagnostic then
print("function analyzeBlob")
if object_list[i] == nil then
print(" object_list[i] is nil")
print(" " .. i)
print(" " .. object_list)
else
print(" " .. i,object_list[i])
end
if center_x == nil then
print(" center_x is nil")
else
print(" center_x: " .. center_x)
end
end
--]]
local current_distance = distance(object_list[i],center_x,center_y)
total_distance = total_distance + current_distance
if current_distance >= max_perimeter then
max_perimeter = current_distance
end
end
average_distance = total_distance/#object_list
end
return center_x, center_y, max_perimeter, average_distance
end
function farEnough(list,pos_x,pos_y,bubble)
local far_enough = true
for i=1,#list do
local list_item = list[i]
--[[
if distance_diagnostic then
print("function farEnough")
if list_item == nil then
print(" list_item is nil")
print(" " .. i)
print(" " .. list)
else
print(" " .. i)
print(list_item)
end
if pos_x == nil then
print(" pos_x is nil")
else
print(" pos_x: " .. pos_x)
end
end
--]]
local distance_away = distance(list_item,pos_x,pos_y)
if distance_away < bubble then
far_enough = false
break
end
if isObjectType(list_item,"BlackHole") or isObjectType(list_item,"WormHole") then
if distance_away < 6000 then
far_enough = false
break
end
end
if isObjectType(list_item,"Planet") then
if distance_away < 4000 then
far_enough = false
break
end
end
end
return far_enough
end
-- Player ship types, placement and naming functions
function placeCustomPlayerShips()
print("place custom player ships")
player_restart = {}
for pidx=1,32 do
local p = getPlayerShip(pidx)
if p ~= nil and p:isValid() then
p:destroy()
end
end
local angle = human_angle
for idx, template in ipairs(custom_player_ship_sets[custom_player_ship_type][ships_per_team]) do
-- print("Human ships per team template:",template)
local p = nil
if player_ship_stats[template].stock then
p = PlayerSpaceship():setTemplate(template):setFaction("Human Navy")
else
p = customPlayerShip(template)
p:setFaction("Human Navy")
end
setPlayer(p)
startPlayerPosition(p,angle)
local respawn_x, respawn_y = p:getPosition()
p.respawn_x = respawn_x
p.respawn_y = respawn_y
player_restart[p:getCallSign()] = {self = p, template = p:getTypeName(), control_code = p.control_code, faction = p:getFaction(), respawn_x = respawn_x, respawn_y = respawn_y}
angle = (angle + 360/ships_per_team) % 360
end
replicatePlayers("Kraylor")
if exuari_angle ~= nil then
replicatePlayers("Exuari")
end
if ktlitan_angle ~= nil then
replicatePlayers("Ktlitans")
end
end
function customPlayerShip(custom_template,p)
if player_ship_stats[custom_template] == nil then
print("Invalid custom player ship template")
return nil
end
if p == nil then
p = PlayerSpaceship()
end
if custom_template == "Striker LX" then
p:setTemplate("Striker")
p:setTypeName("Striker LX")
p:setRepairCrewCount(3) --more (vs 2)
p:setShieldsMax(100,100) --stronger shields (vs 50, 30)
p:setShields(100,100)
p:setHullMax(100) --weaker hull (vs 120)
p:setHull(100)
p:setMaxEnergy(600) --more maximum energy (vs 500)
p:setEnergy(600)
p:setImpulseMaxSpeed(65) --faster impulse max (vs 45)
-- Arc, Dir, Range, CycleTime, Damage
p:setBeamWeapon(0, 10, -15, 1100, 6.0, 6.5) --shorter (vs 1200) more damage (vs 6.0)
p:setBeamWeapon(1, 10, 15, 1100, 6.0, 6.5)
-- Arc, Dir, Rotate speed
p:setBeamWeaponTurret(0, 100, -15, .2) --slower turret speed (vs 6)
p:setBeamWeaponTurret(1, 100, 15, .2)
p:setWeaponTubeCount(2) --more tubes (vs 0)
p:setWeaponTubeDirection(0,180)
p:setWeaponTubeDirection(1,180)
p:setWeaponStorageMax("Homing",4)
p:setWeaponStorage("Homing", 4)
p:setWeaponStorageMax("Nuke",2)
p:setWeaponStorage("Nuke", 2)
p:setWeaponStorageMax("EMP",3)
p:setWeaponStorage("EMP", 3)
p:setWeaponStorageMax("Mine",3)
p:setWeaponStorage("Mine", 3)
p:setWeaponStorageMax("HVLI",6)
p:setWeaponStorage("HVLI", 6)
elseif custom_template == "Focus" then
p:setTemplate("Crucible")
p:setTypeName("Focus")
p:setImpulseMaxSpeed(70) --slower (vs 80)
p:setRotationMaxSpeed(20) --faster spin (vs 15)
p:setWarpDrive(false) --no warp
p:setHullMax(100) --weaker hull (vs 160)
p:setHull(100)
p:setShieldsMax(100, 100) --weaker shields (vs 160, 160)
p:setShields(100, 100)
-- Arc, Dir, Range, CycleTime, Damage
p:setBeamWeapon(0, 60, -20, 1000.0, 6.0, 5) --narrower (vs 70)
p:setBeamWeapon(1, 60, 20, 1000.0, 6.0, 5)
p:setWeaponTubeCount(4) --fewer (vs 6)
p:weaponTubeAllowMissle(2,"Homing") --big tube shoots more stuff (vs HVLI)
p:weaponTubeAllowMissle(2,"EMP")
p:weaponTubeAllowMissle(2,"Nuke")
p:setWeaponTubeExclusiveFor(3,"Mine") --rear (vs left)
p:setWeaponTubeDirection(3, 180)
p:setWeaponStorageMax("EMP",2) --fewer (vs 6)
p:setWeaponStorage("EMP", 2)
p:setWeaponStorageMax("Nuke",1) --fewer (vs 4)
p:setWeaponStorage("Nuke", 1)
elseif custom_template == "Holmes" then
p:setTemplate("Crucible")
p:setTypeName("Holmes")
p:setImpulseMaxSpeed(70) --slower (vs 80)
-- Arc, Dir, Range, CycleTime, Dmg
p:setBeamWeapon(0, 50, -85, 900.0, 6.0, 5) --broadside beams, narrower (vs 70)
p:setBeamWeapon(1, 50, -95, 900.0, 6.0, 5)
p:setBeamWeapon(2, 50, 85, 900.0, 6.0, 5)
p:setBeamWeapon(3, 50, 95, 900.0, 6.0, 5)
p:setWeaponTubeCount(4) --fewer (vs 6)
p:setWeaponTubeExclusiveFor(0,"Homing") --tubes only shoot homing missiles (vs more options)
p:setWeaponTubeExclusiveFor(1,"Homing")
p:setWeaponTubeExclusiveFor(2,"Homing")
p:setWeaponTubeExclusiveFor(3,"Mine")
p:setWeaponTubeDirection(3, 180)
p:setWeaponStorageMax("Homing",10) --more (vs 8)
p:setWeaponStorage("Homing", 10)
p:setWeaponStorageMax("HVLI",0) --fewer
p:setWeaponStorage("HVLI", 0)
p:setWeaponStorageMax("EMP",0) --fewer
p:setWeaponStorage("EMP", 0)
p:setWeaponStorageMax("Nuke",0) --fewer
p:setWeaponStorage("Nuke", 0)
elseif custom_template == "Maverick XP" then
p:setTemplate("Maverick")
p:setTypeName("Maverick XP")
p:setImpulseMaxSpeed(65) --slower impulse max (vs 80)
p:setWarpDrive(false) --no warp
-- Arc, Dir, Range, CycleTime, Dmg
p:setBeamWeapon(0, 10, 0, 1000.0, 20.0, 20)
-- Arc, Dir, Rotate speed
p:setBeamWeaponTurret(0, 270, 0, .4)
p:setBeamWeaponEnergyPerFire(0,p:getBeamWeaponEnergyPerFire(0)*6)
p:setBeamWeaponHeatPerFire(0,p:getBeamWeaponHeatPerFire(0)*5)
p:setBeamWeapon(1, 0, 0, 0, 0, 0) --eliminate 5 beams
p:setBeamWeapon(2, 0, 0, 0, 0, 0)
p:setBeamWeapon(3, 0, 0, 0, 0, 0)
p:setBeamWeapon(4, 0, 0, 0, 0, 0)
p:setBeamWeapon(5, 0, 0, 0, 0, 0)
elseif custom_template == "Phobos T2" then
p:setTemplate("Phobos M3P")
p:setTypeName("Phobos T2")
p:setRepairCrewCount(4) --more repair crew (vs 3)
p:setRotationMaxSpeed(20) --faster spin (vs 10)
p:setShieldsMax(120,80) --stronger front, weaker rear (vs 100,100)
p:setShields(120,80)
p:setMaxEnergy(800) --less maximum energy (vs 1000)
p:setEnergy(800)
-- Arc, Dir, Range, CycleTime, Dmg
p:setBeamWeapon(0, 10, -30, 1200, 4, 6) --split direction (30 vs 15)
p:setBeamWeapon(1, 10, 30, 1200, 4, 6) --reduced cycle time (4 vs 8)
-- Arc, Dir, Rotate speed
p:setBeamWeaponTurret(0, 60, -30, .3) --slow turret beams
p:setBeamWeaponTurret(1, 60, 30, .3)
p:setWeaponTubeCount(2) --one fewer tube (1 forward, 1 rear vs 2 forward, 1 rear)
p:setWeaponTubeDirection(0,0) --first tube points straight forward
p:setWeaponTubeDirection(1,180) --second tube points straight back
p:setWeaponTubeExclusiveFor(1,"Mine")
p:setWeaponStorageMax("Homing",8) --reduce homing storage (vs 10)
p:setWeaponStorage("Homing",8)
p:setWeaponStorageMax("HVLI",16) --reduce HVLI storage (vs 20)
p:setWeaponStorage("HVLI",16)
end
return p
end
function placeDefaultPlayerShips()
player_restart = {}
for pidx=1,32 do
local p = getPlayerShip(pidx)
if p ~= nil and p:isValid() then
p:destroy()
end
end
angle = faction_angle["Human Navy"]
for idx, template in ipairs(default_player_ship_sets[ships_per_team]) do
local p = PlayerSpaceship():setTemplate(template):setFaction("Human Navy")
setPlayer(p)
startPlayerPosition(p,angle)
local respawn_x, respawn_y = p:getPosition()
p.respawn_x = respawn_x
p.respawn_y = respawn_y
player_restart[p:getCallSign()] = {self = p, template = p:getTypeName(), control_code = p.control_code, faction = p:getFaction(), respawn_x = respawn_x, respawn_y = respawn_y}
angle = (angle + 360/ships_per_team) % 360
end
replicatePlayers("Kraylor")
if exuari_angle ~= nil then
replicatePlayers("Exuari")
end
if ktlitan_angle ~= nil then
replicatePlayers("Ktlitans")
end
end
function startPlayerPosition(p,angle)
-- print("start player position angle:",angle)
vx, vy = vectorFromAngleNorth(angle,player_position_distance)
p:setPosition(faction_primary_station[p:getFaction()].x + vx, faction_primary_station[p:getFaction()].y + vy):setHeading(angle):commandTargetRotation((angle + 270) % 360)
end
function replicatePlayers(faction)
-- Replicate the Human Navy player ships to the designated faction
-- print("replicate players faction:",faction)
local angle = faction_angle[faction]
local temp_player_restart = {}
for name, details in pairs(player_restart) do
-- print("player restart item faction:",details.faction)
if details.faction == "Human Navy" then
-- print("name:",name,"details:",details,"details.template:",details.template,"faction:",faction)
local p = PlayerSpaceship()
if p ~= nil and p:isValid() then
if player_ship_stats[details.template].stock then
p:setTemplate(details.template)
else
customPlayerShip(details.template,p)
end
p:setFaction(faction)
setPlayer(p)
startPlayerPosition(p,angle)
local respawn_x, respawn_y = p:getPosition()
p.respawn_x = respawn_x
p.respawn_y = respawn_y
temp_player_restart[p:getCallSign()] = {self = p, template = p:getTypeName(), control_code = p.control_code, faction = p:getFaction(), respawn_x = respawn_x, respawn_y = respawn_y}
angle = (angle + 360/ships_per_team) % 360
else
addGMMessage(_("msgGM", "Player creation failed"))
end
end
end
for name, details in pairs(temp_player_restart) do
player_restart[name] = {self = details.self, template = details.template, control_code = details.control_code, faction = details.faction, respawn_x = details.respawn_x, respawn_y = details.respawn_y}
end
end
function namePlayerShip(p)
if p.name == nil then
local use_fixed = false
if predefined_player_ships ~= nil then
if pps_index == nil then
pps_index = 0
end
pps_index = pps_index + 1
if predefined_player_ships[pps_index] ~= nil then
use_fixed = true
else
predefined_player_ships = nil
end
end
if use_fixed then
p:setCallSign(predefined_player_ships[pps_index].name)
else
if rwc_player_ship_names[template_player_type] ~= nil and #rwc_player_ship_names[template_player_type] > 0 then
local selected_name_index = math.random(1,#rwc_player_ship_names[template_player_type])
p:setCallSign(rwc_player_ship_names[template_player_type][selected_name_index])
table.remove(rwc_player_ship_names[template_player_type],selected_name_index)
else
if rwc_player_ship_names["Unknown"] ~= nil and #rwc_player_ship_names["Unknown"] > 0 then
selected_name_index = math.random(1,#rwc_player_ship_names["Unknown"])
p:setCallSign(rwc_player_ship_names["Unknown"][selected_name_index])
table.remove(rwc_player_ship_names["Unknown"],selected_name_index)
end
end
end
end
p.name = "set"
end
function playerDestroyed(self,instigator)
respawn_count = respawn_count + 1
if respawn_count > 300 then
print("Hit respawn limit")
return
end
local name = self:getCallSign()
local faction = self:getFaction()
local old_template = self:getTypeName()
local p = PlayerSpaceship()
if p ~= nil and p:isValid() then
if respawn_type == "lindworm" then
p:setTemplate("ZX-Lindworm")
elseif respawn_type == "self" then
p:setTemplate(old_template)
death_penalty[faction] = death_penalty[faction] + self.shipScore
end
p:setFaction(faction)
p.control_code = self.control_code
p:setControlCode(p.control_code)
local name_19 = string.lpad(p:getCallSign(),19)
local cc_19 = string.lpad(p.control_code,19)
-- print(p:getCallSign(),"Control code:",p.control_code,"Faction:",faction)
print(name_19,"Control code:",cc_19,"Faction:",faction)
if respawn_type == "lindworm" then
if old_template == "ZX-Lindworm" then
resetPlayer(p,name)
else
resetPlayer(p)
end
elseif respawn_type == "self" then
resetPlayer(p,name)
end
p:setPosition(self.respawn_x, self.respawn_y)
p.respawn_x = self.respawn_x
p.respawn_y = self.respawn_y
if respawn_type == "lindworm" then
player_restart[name] = {self = p, template = "ZX-Lindworm", control_code = p.control_code, faction = faction, respawn_x = self.respawn_x, respawn_y = self.respawn_y}
elseif respawn_type == "self" then
player_restart[name] = {self = p, template = old_template, control_code = p.control_code, faction = faction, respawn_x = self.respawn_x, respawn_y = self.respawn_y}
end
else
respawn_countdown = 2
if restart_queue == nil then
restart_queue = {}
end
table.insert(restart_queue,name)
end
end
function string.lpad(str, len, char)
if char == nil then
char = " "
end
return str .. string.rep(char, len - string.len(str))
end
function delayedRespawn(name)
if name == nil then
if restart_queue ~= nil then
if #restart_queue > 0 then
name = restart_queue[1]
else
respawn_countdown = nil
return
end
else
respawn_countdown = nil
return
end
end
if player_restart[name] ~= nil then
local faction = player_restart[name].faction
local old_template = player_restart[name].template
local p = PlayerSpaceship()
if p~= nil and p:isValid() then
if respawn_type == "lindworm" then
p:setTemplate("ZX-Lindworm")
elseif respawn_type == "self" then
p:setTemplate(old_template)
death_penalty[faction] = death_penalty[faction] + self.shipScore
end
p:setFaction(faction)
p.control_code = player_restart[name].control_code
p:setControlCode(p.control_code)
local name_19 = string.lpad(p:getCallSign(),19)
local cc_19 = string.lpad(p.control_code,19)
print(name_19,"Control code:",cc_19,"Faction:",faction)
-- print(p:getCallSign(),"Control code:",p.control_code,"Faction:",faction)
if respawn_type == "lindworm" then
if old_template == "ZX-Lindworm" then
resetPlayer(p,name)
else
resetPlayer(p)
end
elseif respawn_type == "self" then
resetPlayer(p,name)
end
p:setPosition(player_restart[name].respawn_x,player_restart[name].respawn_y)
p.respawn_x = player_restart[name].respawn_x
p.respawn_y = player_restart[name].respawn_y
if respawn_type == "lindworm" then
player_restart[name] = {self = p, template = "ZX-Lindworm", control_code = p.control_code, faction = faction, respawn_x = player_restart[name].respawn_x, respawn_y = player_restart[name].respawn_y}
elseif respawn_type == "self" then
player_restart[name] = {self = p, template = old_template, control_code = p.control_code, faction = faction, respawn_x = player_restart[name].respawn_x, respawn_y = player_restart[name].respawn_y}
end
if restart_queue ~= nil and #restart_queue > 0 then
for i=1,#restart_queue do
if restart_queue[i] == name then
table.remove(restart_queue,i)
respawn_countdown = nil
break
end
end
end
else
if restart_queue ~= nil and #restart_queue > 0 then
respawn_countdown = 2
end
end
else
if restart_queue ~= nil then
if #restart_queue > 0 then
for i=1,#restart_queue do
if restart_queue[i] == name then
table.remove(restart_queue,i)
print("problem with " .. name)
break
end
end
end
end
end
end
function resetPlayer(p,name)
local faction = p:getFaction()
if name == nil then
namePlayerShip(p)
else
p:setCallSign(name)
p.name = "set"
end
commonPlayerSet(p)
end
function commonPlayerSet(p)
local template_player_type = p:getTypeName()
if template_player_type == "Player Fighter" then
-- Arc, Dir, Range, CycleTime, Dmg
p:setBeamWeapon(0, 40, 0, 500, 6, 4)
p:setBeamWeapon(2, 40, -10, 1000, 6, 8)
end
p.shipScore = player_ship_stats[template_player_type].strength
p.maxCargo = player_ship_stats[template_player_type].cargo
p.cargo = p.maxCargo
p.maxRepairCrew = p:getRepairCrewCount()
p.healthyShield = 1.0
p.prevShield = 1.0
p.healthyReactor = 1.0
p.prevReactor = 1.0
p.healthyManeuver = 1.0
p.prevManeuver = 1.0
p.healthyImpulse = 1.0
p.prevImpulse = 1.0
if p:getBeamWeaponRange(0) > 0 then
p.healthyBeam = 1.0
p.prevBeam = 1.0
end
if p:getWeaponTubeCount() > 0 then
p.healthyMissile = 1.0
p.prevMissile = 1.0
end
if p:hasWarpDrive() then
p.healthyWarp = 1.0
p.prevWarp = 1.0
end
if p:hasJumpDrive() then
p.healthyJump = 1.0
p.prevJump = 1.0
end
p.initialCoolant = p:getMaxCoolant()
p:setLongRangeRadarRange(player_ship_stats[template_player_type].long_range_radar)
p:setShortRangeRadarRange(player_ship_stats[template_player_type].short_range_radar)
p.normal_long_range_radar = p:getLongRangeRadarRange()
p:setMaxScanProbeCount(player_ship_stats[template_player_type].probes)
p:setScanProbeCount(p:getMaxScanProbeCount())
if (not p:hasSystem("jumpdrive") and player_ship_stats[template_player_type].long_jump > 0) or
(p:hasSystem("jumpdrive") and player_ship_stats[template_player_type].long_jump ~= 50) then
p:setJumpDrive(true)
p.max_jump_range = player_ship_stats[template_player_type].long_jump*1000
p.min_jump_range = player_ship_stats[template_player_type].short_jump*1000
p:setJumpDriveRange(p.min_jump_range,p.max_jump_range)
p:setJumpDriveCharge(p.max_jump_range)
end
if not p:hasSystem("warp") and player_ship_stats[template_player_type].warp > 0 then
p:setWarpDrive(true)
p:setWarpSpeed(player_ship_stats[template_player_type].warp)
end
p:onDestruction(playerDestroyed)
end
function setPlayer(p)
local faction = p:getFaction()
namePlayerShip(p) --always name it before giving it the control code
-- p:addReputationPoints(1000) --testing only
p:addReputationPoints(base_reputation)
if predefined_player_ships ~= nil and predefined_player_ships[pps_index] ~= nil and predefined_player_ships[pps_index].control_code ~= nil then
p.control_code = predefined_player_ships[pps_index].control_code
p:setControlCode(predefined_player_ships[pps_index].control_code)
else
local stem = tableRemoveRandom(control_code_stem)
local branch = math.random(100,999)
p.control_code = stem .. branch
p:setControlCode(stem .. branch)
end
-- local name_19 = string.lpad(p:getCallSign(),19)
-- local cc_19 = string.lpad(p.control_code,19)
-- print(name_19,"Control code:",cc_19,"Faction:",faction)
-- print(p:getCallSign(),"Control code:",p.control_code,"Faction:",faction)
commonPlayerSet(p)
end
------------------------------
-- Station communications --
------------------------------
function commsStation()
if comms_target.comms_data == nil then
comms_target.comms_data = {}
end
mergeTables(comms_target.comms_data, {
friendlyness = random(0.0, 100.0),
weapons = {
Homing = "neutral",
HVLI = "neutral",
Mine = "neutral",
Nuke = "friend",
EMP = "friend",
},
weapon_cost = {
Homing = math.random(1,4),
HVLI = math.random(1,3),
Mine = math.random(2,5),
Nuke = math.random(12,18),
EMP = math.random(7,13),
},
services = {
supplydrop = "friend",
reinforcements = "friend",
sensor_boost = "neutral",
preorder = "friend",
activatedefensefleet = "neutral",
},
service_cost = {
supplydrop = math.random(80,120),
reinforcements = math.random(125,175),
phobosReinforcements = math.random(200,250),
stalkerReinforcements = math.random(275,325),
activatedefensefleet = 20,
},
reputation_cost_multipliers = {
friend = 1.0,
neutral = 3.0,
},
max_weapon_refill_amount = {
friend = 1.0,
neutral = 0.5,
}
})
comms_data = comms_target.comms_data
if comms_source:isEnemy(comms_target) then
return false
end
if not comms_source:isDocked(comms_target) then
handleUndockedState()
else
handleDockedState()
end
return true
end
function commsDefensePlatform()
if comms_target.comms_data == nil then
comms_target.comms_data = {}
end
mergeTables(comms_target.comms_data, {
friendlyness = random(0.0, 100.0),
weapons = {
Homing = "neutral",
HVLI = "neutral",
Mine = "neutral",
Nuke = "friend",
EMP = "friend"
},
weapon_cost = {
Homing = math.random(1,4),
HVLI = math.random(1,3),
Mine = math.random(2,5),
Nuke = math.random(12,18),
EMP = math.random(7,13)
},
services = {
supplydrop = "friend",
reinforcements = "friend",
},
service_cost = {
supplydrop = math.random(80,120),
reinforcements = math.random(125,175),
phobosReinforcements = math.random(200,250),
stalkerReinforcements = math.random(275,325)
},
reputation_cost_multipliers = {
friend = 1.0,
neutral = 3.0
},
max_weapon_refill_amount = {
friend = 1.0,
neutral = 0.5
}
})
comms_data = comms_target.comms_data
if comms_source:isEnemy(comms_target) then
return false
end
if comms_source:isDocked(comms_target) then
-- handleDockedState()
setCommsMessage(string.format(_("defensePlatform-comms","Hi %s"),comms_source:getCallSign()))
restockOrdnance(commsDefensePlatform)
completionConditions(commsDefensePlatform)
dockingServicesStatus(commsDefensePlatform)
repairSubsystems(commsDefensePlatform)
stationDefenseReport(commsDefensePlatform)
if primary_jammers then
if comms_source:isFriendly(comms_target) then
addCommsReply(string.format(_("defensePlatform-comms","Transfer to %s"),comms_target.primary_station:getCallSign()),function()
comms_source:commandUndock()
local psx, psy = comms_target.primary_station:getPosition()
local angle = comms_source:getHeading()
local station_dock_radius = {
["Small Station"] = 300,
["Medium Station"] = 1000,
["Large Station"] = 1300,
["Huge Station"] = 1500,
}
local dock_distance = station_dock_radius[comms_target.primary_station:getTypeName()]
local vx, vy = vectorFromAngleNorth(angle,dock_distance)
comms_source:setPosition(psx + vx, psy + vy)
comms_source:commandDock(comms_target.primary_station)
setCommsMessage(string.format(_("defensePlatform-comms","Don't let %s forget their friends on duty at %s"),comms_target.primary_station:getCallSign(),comms_target:getCallSign()))
end)
end
end
else --undocked
local dock_messages = {
_("defensePlatform-comms","Dock if you want anything"),
_("defensePlatform-comms","You must dock before we can do anything"),
_("defensePlatform-comms","Gotta dock first"),
_("defensePlatform-comms","Can't do anything for you unless you dock"),
_("defensePlatform-comms","Docking crew is standing by"),
_("defensePlatform-comms","Dock first, then talk"),
}
setCommsMessage(dock_messages[math.random(1,#dock_messages)])
ordnanceAvailability(commsDefensePlatform)
completionConditions(commsDefensePlatform)
dockingServicesStatus(commsDefensePlatform)
stationDefenseReport(commsDefensePlatform)
end
return true
end
function handleDockedState()
if comms_source:isFriendly(comms_target) then
oMsg = _("station-comms", "Good day, officer!\nWhat can we do for you today?")
else
oMsg = _("station-comms", "Welcome to our lovely station.")
end
if comms_target:areEnemiesInRange(20000) then
oMsg = oMsg .. _("station-comms", "\nForgive us if we seem a little distracted. We are carefully monitoring the enemies nearby.")
end
setCommsMessage(oMsg)
restockOrdnance(commsStation)
completionConditions(commsStation)
if advanced_intel then
advanceIntel(commsStation)
end
dockingServicesStatus(commsStation)
repairSubsystems(commsStation)
boostSensorsWhileDocked(commsStation)
overchargeJump(commsStation)
activateDefenseFleet(commsStation)
if scientist_list[comms_target:getFaction()] ~= nil then
for idx, scientist in ipairs(scientist_list[comms_target:getFaction()]) do
if scientist.location == comms_target then
addCommsReply(string.format(_("station-comms","Speak with scientist %s"),scientist.name),function()
setCommsMessage(string.format(_("station-comms","Greetings, %s\nI've got great ideas for the war effort.\nWhat can I do for you?"),comms_source:getCallSign()))
addCommsReply(_("station-comms","Please come aboard our ship"),function()
setCommsMessage(string.format(_("station-comms","Certainly, %s\n\n%s boards your ship"),comms_source:getCallSign(),scientist.name))
scientist.location = comms_source
scientist.location_name = comms_source:getCallSign()
addCommsReply(_("Back"), commsStation)
end)
addCommsReply(_("station-comms","Can you tell me some more about your ideas?"),function()
local rc = false
local msg = ""
local completed_message = ""
local npc_message = ""
setCommsMessage(string.format(_("station-comms","I'd need to visit %s to proceed further"),faction_primary_station[comms_target:getFaction()].station:getCallSign()))
if string.find(scientist.upgrade_requirement,"talk") or string.find(scientist.upgrade_requirement,"meet") then
if string.find(scientist.upgrade_requirement,"primary") then
if faction_primary_station[comms_target:getFaction()].station ~= nil and faction_primary_station[comms_target:getFaction()].station:isValid() then
if faction_primary_station[comms_target:getFaction()].station.available_upgrades == nil then
faction_primary_station[comms_target:getFaction()].station.available_upgrades = {}
end
faction_primary_station[comms_target:getFaction()].station.available_upgrades[scientist.upgrade.name] = scientist.upgrade.action
setCommsMessage(string.format(_("station-comms","I just sent details on a %s to %s. With their facilities, you should be able to apply the upgrade the next time you dock there."),scientist.upgrade.name,faction_primary_station[comms_target:getFaction()].station:getCallSign()))
else
setCommsMessage(_("station-comms","Without your primary station to apply my research, I'm afraid my information is useless"))
end
else
rc, msg = scientist.upgrade.action(comms_source)
if rc then
completed_message = string.format(_("station-comms","After an extended conversation with %s and the exchange of technical information with various crew members, you apply the insight into %s gained by %s.\n\n%s"),scientist.name,scientist.topic,scientist.name,msg)
if scientist.upgrade_automated_application == "single" then
setCommsMessage(completed_message)
elseif scientist.upgrade_automated_application == "players" then
for pidx=1,32 do
local p = getPlayerShip(pidx)
if p ~= nil and p:isValid() and p ~= comms_source and p:getFaction() == comms_source:getFaction() then
rc, msg = scientist.upgrade.action(p)
if rc then
p:addToShipLog(string.format(_("shipLog","%s provided details from %s for an upgrade. %s"),comms_source:getCallSign(),scientist.name,msg),"Magenta")
end
end
end
setCommsMessage(string.format(_("station-comms","%s\nThe upgrade details were also provided to the other players in your faction."),completed_message))
elseif scientist.upgrade_automated_application == "all" then
if scientist.upgrade.action ~= longerSensorsUpgrade and scientist.upgrade.action ~= batteryEfficiencyUpgrade then
if npc_fleet ~= nil and npc_fleet[comms_source:getFaction()] ~= nil and #npc_fleet[comms_source:getFaction()] > 0 then
for i=1,#npc_fleet[comms_source:getFaction()] do
local npc = npc_fleet[comms_source:getFaction()][i]
if npc ~= nil and npc:isValid() then
rc, msg = scientist.upgrade.action(npc)
end
end
npc_message = _("station-comms","and npc ships ")
end
end
for pidx=1,32 do
local p = getPlayerShip(pidx)
if p ~= nil and p:isValid() and p ~= comms_source and p:getFaction() == comms_source:getFaction() then
rc, msg = scientist.upgrade.action(p)
if rc then
p:addToShipLog(string.format(_("shipLog","%s provided details from %s for an upgrade. %s"),comms_source:getCallSign(),scientist.name,msg),"Magenta")
end
end
end
setCommsMessage(string.format(_("station-comms","%s\nThe upgrade details were also provided to the other players %sin your faction."),completed_message,npc_message))
end
else
setCommsMessage(string.format(_("station-comms","Your conversation with %s about %s was interesting, but not directly applicable.\n\n%s"),scientist.name,scientist.topic,msg))
end
end
elseif scientist.upgrade_requirement == "transport" then
if comms_target == faction_primary_station[comms_target:getFaction()].station then
rc, msg = scientist.upgrade.action(comms_source)
if rc then
completed_message = string.format(_("station-comms","After an extended conversation with %s, various crew members and %s facilities managers, you apply the insight into %s gained by %s.\n\n%s"),scientist.name,comms_target:getCallSign(),scientist.topic,scientist.name,msg)
if faction_primary_station[comms_target:getFaction()].station.available_upgrades == nil then
faction_primary_station[comms_target:getFaction()].station.available_upgrades = {}
end
faction_primary_station[comms_target:getFaction()].station.available_upgrades[scientist.upgrade.name] = scientist.upgrade.action
setCommsMessage(completed_message)
if scientist.upgrade_automated_application == "all" then
if scientist.upgrade.action ~= longerSensorsUpgrade and scientist.upgrade.action ~= batteryEfficiencyUpgrade then
if npc_fleet ~= nil and npc_fleet[comms_source:getFaction()] ~= nil and #npc_fleet[comms_source:getFaction()] > 0 then
for i=1,#npc_fleet[comms_source:getFaction()] do
local npc = npc_fleet[comms_source:getFaction()][i]
if npc ~= nil and npc:isValid() then
rc, msg = scientist.upgrade.action(npc)
end
end
npc_message = _("station-comms","and npc ships ")
end
end
setCommsMessage(string.format(_("station-comms","%s\nNPC ships received the upgrade as well"),completed_message))
end
else
setCommsMessage(string.format(_("station-comms","Your conversation with %s about %s was interesting, but not directly applicable.\n\n%s"),scientist.name,scientist.topic,msg))
if faction_primary_station[comms_target:getFaction()].station.available_upgrades == nil then
faction_primary_station[comms_target:getFaction()].station.available_upgrades = {}
end
faction_primary_station[comms_target:getFaction()].station.available_upgrades[scientist.upgrade.name] = scientist.upgrade.action
end
end
elseif scientist.upgrade_requirement == "confer" then
if comms_target == faction_primary_station[comms_target:getFaction()].station then
local colleage_count = 0
local conferee = nil
for idx, colleague in ipairs(scientist_list[comms_target:getFaction()]) do
if colleague.location == comms_target and colleague ~= scientist then
colleage_count = colleage_count + 1
conferee = colleague
end
end
if colleage_count > 0 then
rc, msg = scientist.upgrade.action(comms_source)
if rc then
completed_message = string.format(_("station-comms","After an extended conversation with %s, %s, various crew members and %s facilities managers, you apply the insight into %s and %s gained by %s.\n\n%s"),scientist.name,conferee.name,comms_target:getCallSign(),scientist.topic,conferee.topic,scientist.name,msg)
if faction_primary_station[comms_target:getFaction()].station.available_upgrades == nil then
faction_primary_station[comms_target:getFaction()].station.available_upgrades = {}
end
faction_primary_station[comms_target:getFaction()].station.available_upgrades[scientist.upgrade.name] = scientist.upgrade.action
if scientist.upgrade_automated_application == "single" then
setCommsMessage(completed_message)
elseif scientist.upgrade_automated_application == "players" then
for pidx=1,32 do
local p = getPlayerShip(pidx)
if p ~= nil and p:isValid() and p ~= comms_source and p:getFaction() == comms_source:getFaction() then
rc, msg = scientist.upgrade.action(p)
if rc then
p:addToShipLog(string.format(_("shipLog","%s provided details from %s for an upgrade. %s"),comms_source:getCallSign(),scientist.name,msg),"Magenta")
end
end
end
setCommsMessage(string.format(_("station-comms","%s\nThe upgrade details were also provided to the other players in your faction."),completed_message))
elseif scientist.upgrade_automated_application == "all" then
if scientist.upgrade.action ~= longerSensorsUpgrade and scientist.upgrade.action ~= batteryEfficiencyUpgrade then
if npc_fleet ~= nil and npc_fleet[comms_source:getFaction()] ~= nil and #npc_fleet[comms_source:getFaction()] > 0 then
for i=1,#npc_fleet[comms_source:getFaction()] do
local npc = npc_fleet[comms_source:getFaction()][i]
if npc ~= nil and npc:isValid() then
rc, msg = scientist.upgrade.action(npc)
end
end
npc_message = _("station-comms","and npc ships ")
end
end
for pidx=1,32 do
local p = getPlayerShip(pidx)
if p ~= nil and p:isValid() and p ~= comms_source and p:getFaction() == comms_source:getFaction() then
rc, msg = scientist.upgrade.action(p)
if rc then
p:addToShipLog(string.format(_("shipLog","%s provided details from %s for an upgrade. %s"),comms_source:getCallSign(),scientist.name,msg),"Magenta")
end
end
end
setCommsMessage(string.format(_("station-comms","%s\nThe upgrade details were also provided to the other players %sin your faction."),completed_message,npc_message))
end
else
setCommsMessage(string.format(_("station-comms","Your conversation with %s and %s about %s and %s was interesting, but not directly applicable.\n\n%s"),scientist.name,conferee.name,scientist.topic,conferee.topic,msg))
if faction_primary_station[comms_target:getFaction()].station.available_upgrades == nil then
faction_primary_station[comms_target:getFaction()].station.available_upgrades = {}
end
faction_primary_station[comms_target:getFaction()].station.available_upgrades[scientist.upgrade.name] = scientist.upgrade.action
end
else
setCommsMessage(string.format(_("station-comms","I've got this idea for a %s, but I just can't quite get it to crystalize. If I had another scientist here to collaborate with, I might get further along"),scientist.upgrade.name))
end
end
end
end)
addCommsReply(_("Back"), commsStation)
end)
end
if scientist.location == comms_source then
addCommsReply(string.format(_("station-comms","Escort %s on to %s"),scientist.name,comms_target:getCallSign()),function()
setCommsMessage(string.format(_("station-comms","%s thanks you for your hospitality and disembarks to %s"),scientist.name,comms_target:getCallSign()))
scientist.location = comms_target
scientist.location_name = comms_target:getCallSign()
addCommsReply(_("Back"), commsStation)
end)
end
end
end
if comms_target.available_upgrades ~= nil then
for name, action in pairs(comms_target.available_upgrades) do
addCommsReply(name,function()
string.format("") --Serious Proton needs global reference/context
local rc, msg = action(comms_source)
if rc then
setCommsMessage(string.format(_("station-comms","Congratulations!\n%s"),msg))
else
setCommsMessage(string.format(_("station-comms","Sorry.\n%s"),msg))
end
end)
end
end
stationFlavorInformation(commsStation)
if comms_source:isFriendly(comms_target) then
if random(1,100) <= (20 - difficulty*2) then
if comms_source:getRepairCrewCount() < comms_source.maxRepairCrew then
hireCost = math.random(30,60)
else
hireCost = math.random(45,90)
end
addCommsReply(string.format(_("trade-comms", "Recruit repair crew member for %i reputation"),hireCost), function()
if not comms_source:takeReputationPoints(hireCost) then
setCommsMessage(_("needRep-comms", "Insufficient reputation"))
else
comms_source:setRepairCrewCount(comms_source:getRepairCrewCount() + 1)
resetPreviousSystemHealth(comms_source)
setCommsMessage(_("trade-comms", "Repair crew member hired"))
end
addCommsReply(_("Back"), commsStation)
end)
end
if comms_source.initialCoolant ~= nil then
if math.random(1,100) <= (20 - difficulty*2) then
local coolantCost = math.random(45,90)
if comms_source:getMaxCoolant() < comms_source.initialCoolant then
coolantCost = math.random(30,60)
end
addCommsReply(string.format(_("trade-comms", "Purchase coolant for %i reputation"),coolantCost), function()
if not comms_source:takeReputationPoints(coolantCost) then
setCommsMessage(_("needRep-comms", "Insufficient reputation"))
else
comms_source:setMaxCoolant(comms_source:getMaxCoolant() + 2)
setCommsMessage(_("trade-comms", "Additional coolant purchased"))
end
addCommsReply(_("Back"), commsStation)
end)
end
end
end
if primary_jammers then
if comms_source:isFriendly(comms_target) then
if defense_platform_count > 0 and comms_target == faction_primary_station[comms_source:getFaction()].station then
addCommsReply("Exit Jammer",function()
comms_source:commandUndock()
local psx, psy = comms_target:getPosition()
local angle = (faction_angle[comms_source:getFaction()] + 180) % 360
local vx, vy = vectorFromAngleNorth(angle,defense_platform_distance + 4000)
comms_source:setPosition(psx + vx, psy + vy):setHeading(angle):commandTargetRotation((angle + 270) % 360)
setCommsMessage("Have fun storming the castle")
end)
end
end
end
buySellTrade(commsStation)
end --end of handleDockedState function
function handleUndockedState()
--Handle communications when we are not docked with the station.
if comms_source:isFriendly(comms_target) then
oMsg = _("station-comms", "Good day, officer.\nIf you need supplies, please dock with us first.")
else
oMsg = _("station-comms", "Greetings.\nIf you want to do business, please dock with us first.")
end
if comms_target:areEnemiesInRange(20000) then
oMsg = oMsg .. _("station-comms", "\nBe aware that if enemies in the area get much closer, we will be too busy to conduct business with you.")
end
setCommsMessage(oMsg)
-- expediteDock(commsStation) --may reinstate if time permits. Needs code in update function, player loop
addCommsReply(_("station-comms", "I need information"), function()
setCommsMessage(_("station-comms", "What kind of information do you need?"))
ordnanceAvailability(commsStation)
goodsAvailabilityOnStation(commsStation)
completionConditions(commsStation)
if advanced_intel then
advanceIntel(commsStation)
end
dockingServicesStatus(commsStation)
stationFlavorInformation(commsStation)
stationDefenseReport(commsStation)
end)
requestSupplyDrop(commsStation)
requestJumpSupplyDrop(commsStation)
requestReinforcements(commsStation)
activateDefenseFleet(commsStation)
if scientist_list[comms_target:getFaction()] ~= nil then
for idx, scientist in ipairs(scientist_list[comms_target:getFaction()]) do
if scientist.location == comms_target then
addCommsReply(string.format(_("station-comms","Speak with scientist %s"),scientist.name),function()
setCommsMessage(string.format(_("station-comms","Greetings, %s\nI've got great ideas for the war effort.\nWhat can I do for you?"),comms_source:getCallSign()))
addCommsReply(_("station-comms","Can you tell me some more about your ideas?"),function()
local rc = false
local msg = ""
local completed_message = ""
local npc_message = ""
if string.find(scientist.upgrade_requirement,"talk") then
if string.find(scientist.upgrade_requirement,"primary") then
if faction_primary_station[comms_target:getFaction()].station ~= nil and faction_primary_station[comms_target:getFaction()].station:isValid() then
if faction_primary_station[comms_target:getFaction()].station.available_upgrades == nil then
faction_primary_station[comms_target:getFaction()].station.available_upgrades = {}
end
faction_primary_station[comms_target:getFaction()].station.available_upgrades[scientist.upgrade.name] = scientist.upgrade.action
setCommsMessage(string.format(_("station-comms","I just sent details on a %s to %s. With their facilities, you should be able to apply the upgrade the next time you dock there."),scientist.upgrade.name,faction_primary_station[comms_target:getFaction()].station:getCallSign()))
else
setCommsMessage(_("station-comms","Without your primary station to apply my research, I'm afraid my information is useless"))
end
else
local rc, msg = scientist.upgrade.action(comms_source)
if rc then
completed_message = string.format(_("station-comms","After an extended conversation with %s and the exchange of technical information with various crew members, you apply the insight into %s gained by %s.\n\n%s"),scientist.name,scientist.topic,scientist.name,msg)
if scientist.upgrade_automated_application == "single" then
setCommsMessage(completed_message)
elseif scientist.upgrade_automated_application == "players" then
for pidx=1,32 do
local p = getPlayerShip(pidx)
if p ~= nil and p:isValid() and p ~= comms_source and p:getFaction() == comms_source:getFaction() then
rc, msg = scientist.upgrade.action(p)
if rc then
p:addToShipLog(string.format(_("shipLog","%s provided details from %s for an upgrade. %s"),comms_source:getCallSign(),scientist.name,msg),"Magenta")
end
end
end
setCommsMessage(string.format(_("station-comms","\nThe upgrade details were also provided to the other players in your faction."),completed_message))
elseif scientist.upgrade_automated_application == "all" then
if scientist.upgrade.action ~= longerSensorsUpgrade and scientist.upgrade.action ~= batteryEfficiencyUpgrade then
if npc_fleet ~= nil and npc_fleet[comms_source:getFaction()] ~= nil and #npc_fleet[comms_source:getFaction()] > 0 then
for i=1,#npc_fleet[comms_source:getFaction()] do
local npc = npc_fleet[comms_source:getFaction()][i]
if npc ~= nil and npc:isValid() then
rc, msg = scientist.upgrade.action(npc)
end
end
npc_message = _("station-comms","and npc ships ")
end
end
for pidx=1,32 do
local p = getPlayerShip(pidx)
if p ~= nil and p:isValid() and p ~= comms_source and p:getFaction() == comms_source:getFaction() then
rc, msg = scientist.upgrade.action(p)
if rc then
p:addToShipLog(string.format(_("station-comms","%s provided details from %s for an upgrade. %s"),comms_source:getCallSign(),scientist.name,msg),"Magenta")
end
end
end
setCommsMessage(string.format(_("station-comms","%s\nThe upgrade details were also provided to the other players %sin your faction."),completed_message,npc_message))
end
else
setCommsMessage(string.format(_("station-comms","Your conversation with %s about %s was interesting, but not directly applicable.\n\n%s"),scientist.name,scientist.topic,msg))
end
local overhear_chance = 16
if scientist.upgrade_automated_application == "players" then
overhear_chance = 28
end
if scientist.upgrade_automated_application == "all" then
overhear_chance = 39
end
if random(1,100) <= overhear_chance then
for pidx=1,32 do
local p = getPlayerShip(pidx)
if p ~= nil and p:isValid() then
if p:getFaction() == comms_source:getFaction() then
p:addToShipLog(string.format(_("station-comms","Communication between %s and %s intercepted by enemy faction"),comms_source:getCallSign(),comms_target:getCallSign()),"Magenta")
else
p:addToShipLog(string.format(_("station-comms","%s conversation intercepted regarding %s. Probable military application. Suggest you contact our own scientist in the same field"),comms_source:getFaction(),scientist.topic),"Magenta")
end
end
end
end
end
else
setCommsMessage(_("station-comms","I should not discuss it over an open communication line. Perhaps you should visit and we can talk"))
end
end)
addCommsReply(_("Back"), commsStation)
end)
end
end
end
end
function isAllowedTo(state)
if state == "friend" and comms_source:isFriendly(comms_target) then
return true
end
if state == "neutral" and not comms_source:isEnemy(comms_target) then
return true
end
return false
end
function getWeaponCost(weapon)
return math.ceil(comms_data.weapon_cost[weapon] * comms_data.reputation_cost_multipliers[getFriendStatus()])
end
function getFriendStatus()
if comms_source:isFriendly(comms_target) then
return "friend"
else
return "neutral"
end
end
function dockingServicesStatus(return_function)
addCommsReply(_("stationServices-comms", "Docking services status"), function()
local service_status = string.format(_("stationServices-comms", "Station %s docking services status:"),comms_target:getCallSign())
if comms_target:getRestocksScanProbes() then
service_status = string.format(_("stationServices-comms", "%s\nReplenish scan probes."),service_status)
else
if comms_target.probe_fail_reason == nil then
local reason_list = {
_("stationServices-comms", "Cannot replenish scan probes due to fabrication unit failure."),
_("stationServices-comms", "Parts shortage prevents scan probe replenishment."),
_("stationServices-comms", "Management has curtailed scan probe replenishment for cost cutting reasons."),
}
comms_target.probe_fail_reason = reason_list[math.random(1,#reason_list)]
end
service_status = string.format(_("stationServices-comms", "%s\n%s"),service_status,comms_target.probe_fail_reason)
end
if comms_target:getRepairDocked() then
service_status = string.format(_("stationServices-comms", "%s\nShip hull repair."),service_status)
else
if comms_target.repair_fail_reason == nil then
reason_list = {
_("stationServices-comms", "We're out of the necessary materials and supplies for hull repair."),
_("stationServices-comms", "Hull repair automation unavailable while it is undergoing maintenance."),
_("stationServices-comms", "All hull repair technicians quarantined to quarters due to illness."),
}
comms_target.repair_fail_reason = reason_list[math.random(1,#reason_list)]
end
service_status = string.format(_("stationServices-comms", "%s\n%s"),service_status,comms_target.repair_fail_reason)
end
if comms_target:getSharesEnergyWithDocked() then
service_status = string.format(_("stationServices-comms", "%s\nRecharge ship energy stores."),service_status)
else
if comms_target.energy_fail_reason == nil then
reason_list = {
_("stationServices-comms", "A recent reactor failure has put us on auxiliary power, so we cannot recharge ships."),
_("stationServices-comms", "A damaged power coupling makes it too dangerous to recharge ships."),
_("stationServices-comms", "An asteroid strike damaged our solar cells and we are short on power, so we can't recharge ships right now."),
}
comms_target.energy_fail_reason = reason_list[math.random(1,#reason_list)]
end
service_status = string.format(_("stationServices-comms", "%s\n%s"),service_status,comms_target.energy_fail_reason)
end
if comms_target.comms_data.jump_overcharge then
service_status = string.format(_("stationServices-comms", "%s\nMay overcharge jump drive"),service_status)
end
if comms_target.comms_data.probe_launch_repair then
service_status = string.format(_("stationServices-comms", "%s\nMay repair probe launch system"),service_status)
end
if comms_target.comms_data.hack_repair then
service_status = string.format(_("stationServices-comms", "%s\nMay repair hacking system"),service_status)
end
if comms_target.comms_data.scan_repair then
service_status = string.format(_("stationServices-comms", "%s\nMay repair scanners"),service_status)
end
if comms_target.comms_data.combat_maneuver_repair then
service_status = string.format(_("stationServices-comms", "%s\nMay repair combat maneuver"),service_status)
end
if comms_target.comms_data.self_destruct_repair then
service_status = string.format(_("stationServices-comms", "%s\nMay repair self destruct system"),service_status)
end
if comms_target.comms_data.tube_slow_down_repair then
service_status = string.format(_("stationServices-comms", "%s\nMay repair slow loading tubes"),service_status)
end
setCommsMessage(service_status)
addCommsReply(_("Back"), return_function)
end)
end
function stationFlavorInformation(return_function)
if (comms_target.comms_data.general ~= nil and comms_target.comms_data.general ~= "") or (comms_target.comms_data.history ~= nil and comms_target.comms_data.history ~= "") then
addCommsReply(_("station-comms", "Tell me more about your station"), function()
setCommsMessage(_("station-comms", "What would you like to know?"))
if comms_target.comms_data.general ~= nil and comms_target.comms_data.general ~= "" then
addCommsReply(_("stationGeneralInfo-comms", "General information"), function()
setCommsMessage(comms_target.comms_data.general)
addCommsReply(_("Back"), return_function)
end)
end
if comms_target.comms_data.history ~= nil and comms_target.comms_data.history ~= "" then
addCommsReply(_("stationStory-comms", "Station history"), function()
setCommsMessage(comms_target.comms_data.history)
addCommsReply(_("Back"), return_function)
end)
end
end)
end
end
function stationDefenseReport(return_function)
addCommsReply(_("stationAssist-comms", "Report status"), function()
msg = string.format(_("stationAssist-comms", "Hull: %d%%\n"), math.floor(comms_target:getHull() / comms_target:getHullMax() * 100))
local shields = comms_target:getShieldCount()
if shields == 1 then
msg = string.format(_("stationAssist-comms", "%sShield: %d%%\n"),msg,math.floor(comms_target:getShieldLevel(0) / comms_target:getShieldMax(0) * 100))
msg = string.format(_("stationAssist-comms", "%sShield: %d%%\n"),msg,math.floor(comms_target:getShieldLevel(0) / comms_target:getShieldMax(0) * 100))
else
for n=0,shields-1 do
msg = string.format(_("stationAssist-comms", "%sShield %s: %d%%\n"),msg,n,math.floor(comms_target:getShieldLevel(n) / comms_target:getShieldMax(n) * 100))
end
end
setCommsMessage(msg);
addCommsReply(_("Back"), return_function)
end)
end
function completionConditions(return_function)
addCommsReply(_("stationStats-comms","What ends the war?"),function()
local out = string.format(_("stationStats-comms","The war ends in one of three ways:\n1) Time runs out\n2) A faction drops below half of original score\n3) A faction either leads or trails the other factions by %i%%\n"),thresh*100)
local stat_list = gatherStats()
out = string.format(_("stationStats-comms","%s\nHuman Navy Current:%.1f Original:%.1f (%.2f%%)"),out,stat_list.human.weighted_score,original_score["Human Navy"],(stat_list.human.weighted_score/original_score["Human Navy"])*100)
if stat_list.human.death_penalty ~= nil then
out = string.format(_("stationStats-comms","%s\nHuman Navy loss of player ship penalty: %.1f"),out,stat_list.human.death_penalty * stat_list.weight.ship)
end
out = string.format(_("stationStats-comms","%s\nKraylor Current:%.1f Original:%.1f (%.2f%%)"),out,stat_list.kraylor.weighted_score,original_score["Kraylor"],(stat_list.kraylor.weighted_score/original_score["Kraylor"])*100)
if stat_list.kraylor.death_penalty ~= nil then
out = string.format(_("stationStats-comms","%s\nKraylor loss of player ship penalty: %.1f"),out,stat_list.kraylor.death_penalty * stat_list.weight.ship)
end
if exuari_angle ~= nil then
out = string.format(_("stationStats-comms","%s\nExuari Current:%.1f Original:%.1f (%.2f%%)"),out,stat_list.exuari.weighted_score,original_score["Exuari"],(stat_list.exuari.weighted_score/original_score["Exuari"])*100)
if stat_list.exuari.death_penalty ~= nil then
out = string.format(_("stationStats-comms","%s\nExuari loss of player ship penalty: %.1f"),out,stat_list.exuari.death_penalty * stat_list.weight.ship)
end
end
if ktlitan_angle ~= nil then
out = string.format(_("stationStats-comms","%s\nKtlitan Current:%.1f Original:%.1f (%.2f%%)"),out,stat_list.ktlitan.weighted_score,original_score["Ktlitans"],(stat_list.ktlitan.weighted_score/original_score["Ktlitans"])*100)
if stat_list.ktlitan.death_penalty ~= nil then
out = string.format(_("stationStats-comms","%s\nKtlitan loss of player ship penalty: %.1f"),out,stat_list.ktlitan.death_penalty * stat_list.weight.ship)
end
end
out = string.format(_("stationStats-comms","%s\n\nStation weight:%i%% Player ship weight:%i%% NPC weight:%i%%"),out,stat_list.weight.station*100,stat_list.weight.ship*100,stat_list.weight.npc*100)
local tie_breaker = {}
for i,p in ipairs(getActivePlayerShips()) do
tie_breaker[p:getFaction()] = p:getReputationPoints()
end
out = string.format(_("stationStats-comms","%s\nTie breaker points:"),out)
local faction_points_list = ""
for faction,points in pairs(tie_breaker) do
faction_points_list = string.format(_("stationStats-comms","%s %s:%f"),faction_points_list,faction,points/10000)
end
out = string.format(_("stationStats-comms","%s %s"),out,faction_points_list)
setCommsMessage(out)
addCommsReply(string.format(_("stationStats-comms","Station values (Total:%i)"),stat_list[f2s[comms_source:getFaction()]].station_score_total),function()
local out = _("stationStats-comms","Stations: (value, type, name)")
for name, details in pairs(stat_list[f2s[comms_source:getFaction()]].station) do
out = string.format(_("stationStats-comms","%s\n %i, %s, %s"),out,details.score_value,details.template_type,name)
end
out = string.format(_("stationStats-comms","%s\nTotal:%i multiplied by weight (%i%%) = weighted total:%.1f"),out,stat_list[f2s[comms_source:getFaction()]].station_score_total,stat_list.weight.station*100,stat_list[f2s[comms_source:getFaction()]].station_score_total*stat_list.weight.station)
setCommsMessage(out)
addCommsReply(_("Back"), return_function)
end)
addCommsReply(string.format(_("stationStats-comms","Player ship values (Total:%i)"),stat_list[f2s[comms_source:getFaction()]].ship_score_total),function()
local out = _("stationStats-comms","Player ships: (value, type, name)")
for name, details in pairs(stat_list[f2s[comms_source:getFaction()]].ship) do
out = string.format(_("stationStats-comms","%s\n %i, %s, %s"),out,details.score_value,details.template_type,name)
end
out = string.format(_("stationStats-comms","%s\nTotal:%i multiplied by weight (%i%%) = weighted total:%.1f"),out,stat_list[f2s[comms_source:getFaction()]].ship_score_total,stat_list.weight.ship*100,stat_list[f2s[comms_source:getFaction()]].ship_score_total*stat_list.weight.ship)
setCommsMessage(out)
addCommsReply(_("Back"), return_function)
end)
addCommsReply(string.format(_("stationStats-comms","NPC ship values (Total:%i)"),stat_list[f2s[comms_source:getFaction()]].npc_score_total),function()
local out = _("stationStats-comms","NPC assets: value, type, name (location)")
for name, details in pairs(stat_list[f2s[comms_source:getFaction()]].npc) do
if details.template_type ~= nil then
out = string.format(_("stationStats-comms","%s\n %i, %s, %s"),out,details.score_value,details.template_type,name)
elseif details.topic ~= nil then
out = string.format(_("stationStats-comms","%s\n %i, %s, %s (%s)"),out,details.score_value,details.topic,name,details.location_name)
end
end
out = string.format(_("stationStats-comms","%s\nTotal:%i multiplied by weight (%i%%) = weighted total:%.1f"),out,stat_list[f2s[comms_source:getFaction()]].npc_score_total,stat_list.weight.npc*100,stat_list[f2s[comms_source:getFaction()]].npc_score_total*stat_list.weight.npc)
setCommsMessage(out)
addCommsReply(_("Back"), return_function)
end)
addCommsReply(_("Back"), return_function)
end)
end
function advanceIntel(return_function)
addCommsReply(_("stationIntel-comms","Where are the enemy headquarters?"),function()
local out = ""
for faction, p_s_info in pairs(faction_primary_station) do
if faction ~= comms_source:getFaction() then
if p_s_info.station:isValid() then
if out == "" then
out = string.format(_("stationIntel-comms","%s primary station %s is located in sector %s."),faction,p_s_info.station:getCallSign(),p_s_info.station:getSectorName())
else
out = string.format(_("stationIntel-comms","%s\n%s primary station %s is located in sector %s."),out,faction,p_s_info.station:getCallSign(),p_s_info.station:getSectorName())
end
else
if out == "" then
out = string.format(_("stationIntel-comms","%s primary station is off the grid."),faction)
else
out = string.format(_("stationIntel-comms","%s\n%s primary station is off the grid."),out,faction)
end
end
end
end
setCommsMessage(string.format(_("stationIntel-comms","The intelligence department has provided this information:\n%s"),out))
addCommsReply(_("Back"), return_function)
end)
end
-- Undocked actions
function getServiceCost(service)
return math.ceil(comms_data.service_cost[service])
end
function requestSupplyDrop(return_function)
if isAllowedTo(comms_target.comms_data.services.supplydrop) then
addCommsReply(string.format(_("stationAssist-comms", "Can you send a supply drop? (%d rep)"), getServiceCost("supplydrop")), function()
if comms_source:getWaypointCount() < 1 then
setCommsMessage(_("stationAssist-comms", "You need to set a waypoint before you can request backup."));
else
setCommsMessage(_("stationAssist-comms", "To which waypoint should we deliver your supplies?"));
for n=1,comms_source:getWaypointCount() do
addCommsReply(string.format(_("stationAssist-comms", "WP %d"),n), function()
if comms_source:takeReputationPoints(getServiceCost("supplydrop")) then
local position_x, position_y = comms_target:getPosition()
local target_x, target_y = comms_source:getWaypoint(n)
local script = Script()
script:setVariable("position_x", position_x):setVariable("position_y", position_y)
script:setVariable("target_x", target_x):setVariable("target_y", target_y)
script:setVariable("faction_id", comms_target:getFactionId()):run("supply_drop.lua")
setCommsMessage(string.format(_("stationAssist-comms", "We have dispatched a supply ship toward WP %d"), n));
else
setCommsMessage(_("needRep-comms", "Not enough reputation!"));
end
addCommsReply(_("Back"), return_function)
end)
end
end
addCommsReply(_("Back"), return_function)
end)
end
end
function requestJumpSupplyDrop(return_function)
if isAllowedTo(comms_target.comms_data.services.jumpsupplydrop) then
addCommsReply(string.format(_("stationAssist-comms", "Can you send a supply drop via jump ship? (%d rep)"), getServiceCost("jumpsupplydrop")), function()
if comms_source:getWaypointCount() < 1 then
setCommsMessage(_("stationAssist-comms", "You need to set a waypoint before you can request backup."));
else
setCommsMessage(_("stationAssist-comms", "To which waypoint should we deliver your supplies?"));
for n=1,comms_source:getWaypointCount() do
addCommsReply(string.format(_("stationAssist-comms", "WP %d"),n), function()
if comms_source:takeReputationPoints(getServiceCost("jumpsupplydrop")) then
local position_x, position_y = comms_target:getPosition()
local target_x, target_y = comms_source:getWaypoint(n)
local script = Script()
script:setVariable("position_x", position_x):setVariable("position_y", position_y)
script:setVariable("target_x", target_x):setVariable("target_y", target_y)
script:setVariable("jump_freighter","Yes")
script:setVariable("faction_id", comms_target:getFactionId()):run("supply_drop.lua")
setCommsMessage(string.format(_("stationAssist-comms", "We have dispatched a supply ship with a jump drive toward WP %d"), n));
else
setCommsMessage(_("needRep-comms", "Not enough reputation!"));
end
addCommsReply(_("Back"), return_function)
end)
end
end
addCommsReply(_("Back"), return_function)
end)
end
end
function requestReinforcements(return_function)
if isAllowedTo(comms_target.comms_data.services.reinforcements) then
addCommsReply(_("stationAssist-comms", "Please send reinforcements"),function()
if comms_source:getWaypointCount() < 1 then
setCommsMessage(_("stationAssist-comms", "You need to set a waypoint before you can request reinforcements"))
else
setCommsMessage(_("stationAssist-comms", "What kind of reinforcements would you like?"))
addCommsReply(string.format(_("stationAssist-comms", "Standard Adder MK5 (%d Rep)"),getServiceCost("reinforcements")),function()
if comms_source:getWaypointCount() < 1 then
setCommsMessage(_("stationAssist-comms", "You need to set a waypoint before you can request reinforcements"))
else
setCommsMessage(_("stationAssist-comms", "To which waypoint should we dispatch the Adder MK5?"));
for n=1,comms_source:getWaypointCount() do
addCommsReply(string.format(_("stationAssist-comms", "Waypoint %d"),n), function()
if comms_source:takeReputationPoints(getServiceCost("reinforcements")) then
ship = CpuShip():setFactionId(comms_target:getFactionId()):setPosition(comms_target:getPosition()):setTemplate("Adder MK5"):setScanned(true):orderDefendLocation(comms_source:getWaypoint(n))
ship:setCommsScript(""):setCommsFunction(commsShip)
ship.score_value = ship_template["Adder MK5"].strength
table.insert(npc_fleet[comms_target:getFaction()],ship)
setCommsMessage(string.format(_("stationAssist-comms", "We have dispatched %s to assist at waypoint %d"),ship:getCallSign(),n))
else
setCommsMessage(_("needRep-comms", "Not enough reputation!"));
end
addCommsReply(_("Back"), return_function)
end)
end
end
addCommsReply(_("Back"), return_function)
end)
if comms_data.service_cost.hornetreinforcements ~= nil then
addCommsReply(string.format(_("stationAssist-comms", "MU52 Hornet (%d Rep)"),getServiceCost("hornetreinforcements")),function()
if comms_source:getWaypointCount() < 1 then
setCommsMessage(_("stationAssist-comms", "You need to set a waypoint before you can request reinforcements"))
else
setCommsMessage(_("stationAssist-comms", "To which waypoint should we dispatch the MU52 Hornet?"));
for n=1,comms_source:getWaypointCount() do
addCommsReply(string.format(_("stationAssist-comms", "Waypoint %d"),n), function()
if comms_source:takeReputationPoints(getServiceCost("hornetreinforcements")) then
ship = CpuShip():setFactionId(comms_target:getFactionId()):setPosition(comms_target:getPosition()):setTemplate("MU52 Hornet"):setScanned(true):orderDefendLocation(comms_source:getWaypoint(n))
ship:setCommsScript(""):setCommsFunction(commsShip)
ship.score_value = ship_template["MU52 Hornet"].strength
table.insert(npc_fleet[comms_target:getFaction()],ship)
setCommsMessage(string.format(_("stationAssist-comms", "We have dispatched %s to assist at waypoint %d"),ship:getCallSign(),n))
else
setCommsMessage(_("needRep-comms", "Not enough reputation!"));
end
addCommsReply(_("Back"), return_function)
end)
end
end
addCommsReply(_("Back"), return_function)
end)
end
if comms_data.service_cost.phobosreinforcements ~= nil then
addCommsReply(string.format(_("stationAssist-comms", "Phobos T3 (%d Rep)"),getServiceCost("phobosreinforcements")),function()
if comms_source:getWaypointCount() < 1 then
setCommsMessage(_("stationAssist-comms", "You need to set a waypoint before you can request reinforcements"))
else
setCommsMessage(_("stationAssist-comms", "To which waypoint should we dispatch the Phobos T3?"));
for n=1,comms_source:getWaypointCount() do
addCommsReply(string.format(_("stationAssist-comms", "Waypoint %d"),n), function()
if comms_source:takeReputationPoints(getServiceCost("phobosreinforcements")) then
ship = CpuShip():setFactionId(comms_target:getFactionId()):setPosition(comms_target:getPosition()):setTemplate("Phobos T3"):setScanned(true):orderDefendLocation(comms_source:getWaypoint(n))
ship:setCommsScript(""):setCommsFunction(commsShip)
ship.score_value = ship_template["Phobos T3"].strength
table.insert(npc_fleet[comms_target:getFaction()],ship)
setCommsMessage(string.format(_("stationAssist-comms", "We have dispatched %s to assist at waypoint %d"),ship:getCallSign(),n))
else
setCommsMessage(_("needRep-comms", "Not enough reputation!"));
end
addCommsReply(_("Back"), return_function)
end)
end
end
addCommsReply(_("Back"), return_function)
end)
end
end
addCommsReply(_("Back"), return_function)
end)
end
end
function ordnanceAvailability(return_function)
addCommsReply(_("ammo-comms", "What ordnance do you have available for restock?"), function()
local missileTypeAvailableCount = 0
local ordnanceListMsg = ""
if comms_target.comms_data.weapon_available.Homing and (comms_target.comms_data.weapon_inventory.Unlimited or comms_target.comms_data.weapon_inventory.Homing > 0) then
missileTypeAvailableCount = missileTypeAvailableCount + 1
ordnanceListMsg = ordnanceListMsg .. _("ammo-comms", "\n Homing")
if not comms_target.comms_data.weapon_inventory.Unlimited then
ordnanceListMsg = ordnanceListMsg .. string.format(_("ammo-comms", "(%i)"),math.floor(comms_target.comms_data.weapon_inventory.Homing))
end
end
if comms_target.comms_data.weapon_available.Nuke and (comms_target.comms_data.weapon_inventory.Unlimited or comms_target.comms_data.weapon_inventory.Nuke > 0) then
missileTypeAvailableCount = missileTypeAvailableCount + 1
ordnanceListMsg = ordnanceListMsg .. _("ammo-comms", "\n Nuke")
if not comms_target.comms_data.weapon_inventory.Unlimited then
ordnanceListMsg = ordnanceListMsg .. string.format(_("ammo-comms", "(%i)"),math.floor(comms_target.comms_data.weapon_inventory.Nuke))
end
end
if comms_target.comms_data.weapon_available.Mine and (comms_target.comms_data.weapon_inventory.Unlimited or comms_target.comms_data.weapon_inventory.Mine > 0) then
missileTypeAvailableCount = missileTypeAvailableCount + 1
ordnanceListMsg = ordnanceListMsg .. _("ammo-comms", "\n Mine")
if not comms_target.comms_data.weapon_inventory.Unlimited then
ordnanceListMsg = ordnanceListMsg .. string.format(_("ammo-comms", "(%i)"),math.floor(comms_target.comms_data.weapon_inventory.Mine))
end
end
if comms_target.comms_data.weapon_available.EMP and (comms_target.comms_data.weapon_inventory.Unlimited or comms_target.comms_data.weapon_inventory.EMP > 0) then
missileTypeAvailableCount = missileTypeAvailableCount + 1
ordnanceListMsg = ordnanceListMsg .. _("ammo-comms", "\n EMP")
if not comms_target.comms_data.weapon_inventory.Unlimited then
ordnanceListMsg = ordnanceListMsg .. string.format(_("ammo-comms", "(%i)"),math.floor(comms_target.comms_data.weapon_inventory.EMP))
end
end
if comms_target.comms_data.weapon_available.HVLI and (comms_target.comms_data.weapon_inventory.Unlimited or comms_target.comms_data.weapon_inventory.HVLI > 0) then
missileTypeAvailableCount = missileTypeAvailableCount + 1
ordnanceListMsg = ordnanceListMsg .. _("ammo-comms", "\n HVLI")
if not comms_target.comms_data.weapon_inventory.Unlimited then
ordnanceListMsg = ordnanceListMsg .. string.format(_("ammo-comms", "(%i)"),math.floor(comms_target.comms_data.weapon_inventory.HVLI))
end
end
if missileTypeAvailableCount == 0 then
ordnanceListMsg = _("ammo-comms", "We have no ordnance available for restock")
elseif missileTypeAvailableCount == 1 then
ordnanceListMsg = string.format(_("ammo-comms", "We have the following type of ordnance available for restock:%s"), ordnanceListMsg)
else
ordnanceListMsg = string.format(_("ammo-comms", "We have the following types of ordnance available for restock:%s"), ordnanceListMsg)
end
setCommsMessage(ordnanceListMsg)
addCommsReply(_("Back"), return_function)
end)
end
function goodsAvailabilityOnStation(return_function)
local goodsAvailable = false
if comms_target.comms_data.goods ~= nil then
for good, goodData in pairs(comms_target.comms_data.goods) do
if goodData["quantity"] > 0 then
goodsAvailable = true
end
end
end
if goodsAvailable then
addCommsReply(_("trade-comms", "What goods do you have available for sale or trade?"), function()
local goodsAvailableMsg = string.format(_("trade-comms", "Station %s:\nGoods or components available: quantity, cost in reputation"),comms_target:getCallSign())
for good, goodData in pairs(comms_target.comms_data.goods) do
goodsAvailableMsg = goodsAvailableMsg .. string.format(_("trade-comms", "\n %14s: %2i, %3i"),good_desc[good],goodData["quantity"],goodData["cost"])
end
setCommsMessage(goodsAvailableMsg)
addCommsReply(_("Back"), return_function)
end)
end
end
--[[
function expediteDock(return_function)
if isAllowedTo(comms_target.comms_data.services.preorder) then
addCommsReply("Expedite Dock",function()
if comms_source.expedite_dock == nil then
comms_source.expedite_dock = false
end
if comms_source.expedite_dock then
--handle expedite request already present
local existing_expedite = "Docking crew is standing by"
if comms_target == comms_source.expedite_dock_station then
existing_expedite = existing_expedite .. ". Current preorders:"
local preorders_identified = false
if comms_source.preorder_hvli ~= nil then
preorders_identified = true
existing_expedite = existing_expedite .. string.format("\n HVLIs: %i",comms_source.preorder_hvli)
end
if comms_source.preorder_homing ~= nil then
preorders_identified = true
existing_expedite = existing_expedite .. string.format("\n Homings: %i",comms_source.preorder_homing)
end
if comms_source.preorder_mine ~= nil then
preorders_identified = true
existing_expedite = existing_expedite .. string.format("\n Mines: %i",comms_source.preorder_mine)
end
if comms_source.preorder_emp ~= nil then
preorders_identified = true
existing_expedite = existing_expedite .. string.format("\n EMPs: %i",comms_source.preorder_emp)
end
if comms_source.preorder_nuke ~= nil then
preorders_identified = true
existing_expedite = existing_expedite .. string.format("\n Nukes: %i",comms_source.preorder_nuke)
end
if comms_source.preorder_repair_crew ~= nil then
preorders_identified = true
existing_expedite = existing_expedite .. "\n One repair crew"
end
if comms_source.preorder_coolant ~= nil then
preorders_identified = true
existing_expedite = existing_expedite .. "\n Coolant"
end
if preorders_identified then
existing_expedite = existing_expedite .. "\nWould you like to preorder anything else?"
else
existing_expedite = existing_expedite .. " none.\nWould you like to preorder anything?"
end
preorder_message = existing_expedite
preOrderOrdnance(return_function)
else
existing_expedite = existing_expedite .. string.format(" on station %s (not this station, %s).",comms_source.expedite_dock_station:getCallSign(),comms_target:getCallSign())
setCommsMessage(existing_expedite)
end
addCommsReply(_("Back"),return_function)
else
setCommsMessage("If you would like to speed up the addition of resources such as energy, ordnance, etc., please provide a time frame for your arrival. A docking crew will stand by until that time, after which they will return to their normal duties")
preorder_message = "Docking crew is standing by. Would you like to pre-order anything?"
addCommsReply("One minute (5 rep)", function()
if comms_source:takeReputationPoints(5) then
comms_source.expedite_dock = true
comms_source.expedite_dock_station = comms_target
comms_source.expedite_dock_timer_max = 60
preOrderOrdnance(return_function)
else
setCommsMessage(_("needRep-comms", "Insufficient reputation"))
end
addCommsReply(_("Back"), return_function)
end)
addCommsReply("Two minutes (10 Rep)", function()
if comms_source:takeReputationPoints(10) then
comms_source.expedite_dock = true
comms_source.expedite_dock_station = comms_target
comms_source.expedite_dock_timer_max = 120
preOrderOrdnance(return_function)
else
setCommsMessage(_("needRep-comms", "Insufficient reputation"))
end
addCommsReply(_("Back"), return_function)
end)
addCommsReply("Three minutes (15 Rep)", function()
if comms_source:takeReputationPoints(15) then
comms_source.expedite_dock = true
comms_source.expedite_dock_station = comms_target
comms_source.expedite_dock_timer_max = 180
preOrderOrdnance(return_function)
else
setCommsMessage(_("needRep-comms", "Insufficient reputation"))
end
addCommsReply(_("Back"), return_function)
end)
end
addCommsReply(_("Back"), return_function)
end)
end
end
function preOrderOrdnance(return_function)
setCommsMessage(preorder_message)
local hvli_count = math.floor(comms_source:getWeaponStorageMax("HVLI") * comms_target.comms_data.max_weapon_refill_amount[getFriendStatus()]) - comms_source:getWeaponStorage("HVLI")
if comms_target.comms_data.weapon_available.HVLI and isAllowedTo(comms_target.comms_data.weapons["HVLI"]) and hvli_count > 0 then
local hvli_prompt = ""
local hvli_cost = getWeaponCost("HVLI")
if hvli_count > 1 then
hvli_prompt = string.format("%i HVLIs * %i Rep = %i Rep",hvli_count,hvli_cost,hvli_count*hvli_cost)
else
hvli_prompt = string.format("%i HVLI * %i Rep = %i Rep",hvli_count,hvli_cost,hvli_count*hvli_cost)
end
addCommsReply(hvli_prompt,function()
if comms_source:takeReputationPoints(hvli_count*hvli_cost) then
comms_source.preorder_hvli = hvli_count
if hvli_count > 1 then
setCommsMessage(string.format("%i HVLIs preordered",hvli_count))
else
setCommsMessage(string.format("%i HVLI preordered",hvli_count))
end
else
setCommsMessage(_("needRep-comms", "Insufficient reputation"))
end
preorder_message = "Docking crew is standing by. Would you like to pre-order anything?"
addCommsReply(_("Back"),return_function)
end)
end
local homing_count = math.floor(comms_source:getWeaponStorageMax("Homing") * comms_target.comms_data.max_weapon_refill_amount[getFriendStatus()]) - comms_source:getWeaponStorage("Homing")
if comms_target.comms_data.weapon_available.Homing and isAllowedTo(comms_target.comms_data.weapons["Homing"]) and homing_count > 0 then
local homing_prompt = ""
local homing_cost = getWeaponCost("Homing")
if homing_count > 1 then
homing_prompt = string.format("%i Homings * %i Rep = %i Rep",homing_count,homing_cost,homing_count*homing_cost)
else
homing_prompt = string.format("%i Homing * %i Rep = %i Rep",homing_count,homing_cost,homing_count*homing_cost)
end
addCommsReply(homing_prompt,function()
if comms_source:takeReputationPoints(homing_count*homing_cost) then
comms_source.preorder_homing = homing_count
if homing_count > 1 then
setCommsMessage(string.format("%i Homings preordered",homing_count))
else
setCommsMessage(string.format("%i Homing preordered",homing_count))
end
else
setCommsMessage(_("needRep-comms", "Insufficient reputation"))
end
preorder_message = "Docking crew is standing by. Would you like to pre-order anything?"
addCommsReply(_("Back"),return_function)
end)
end
local mine_count = math.floor(comms_source:getWeaponStorageMax("Mine") * comms_target.comms_data.max_weapon_refill_amount[getFriendStatus()]) - comms_source:getWeaponStorage("Mine")
if comms_target.comms_data.weapon_available.Mine and isAllowedTo(comms_target.comms_data.weapons["Mine"]) and mine_count > 0 then
local mine_prompt = ""
local mine_cost = getWeaponCost("Mine")
if mine_count > 1 then
mine_prompt = string.format("%i Mines * %i Rep = %i Rep",mine_count,mine_cost,mine_count*mine_cost)
else
mine_prompt = string.format("%i Mine * %i Rep = %i Rep",mine_count,mine_cost,mine_count*mine_cost)
end
addCommsReply(mine_prompt,function()
if comms_source:takeReputationPoints(mine_count*mine_cost) then
comms_source.preorder_mine = mine_count
if mine_count > 1 then
setCommsMessage(string.format("%i Mines preordered",mine_count))
else
setCommsMessage(string.format("%i Mine preordered",mine_count))
end
else
setCommsMessage(_("needRep-comms", "Insufficient reputation"))
end
preorder_message = "Docking crew is standing by. Would you like to pre-order anything?"
addCommsReply(_("Back"),return_function)
end)
end
local emp_count = math.floor(comms_source:getWeaponStorageMax("EMP") * comms_target.comms_data.max_weapon_refill_amount[getFriendStatus()]) - comms_source:getWeaponStorage("EMP")
if comms_target.comms_data.weapon_available.EMP and isAllowedTo(comms_target.comms_data.weapons["EMP"]) and emp_count > 0 then
local emp_prompt = ""
local emp_cost = getWeaponCost("EMP")
if emp_count > 1 then
emp_prompt = string.format("%i EMPs * %i Rep = %i Rep",emp_count,emp_cost,emp_count*emp_cost)
else
emp_prompt = string.format("%i EMP * %i Rep = %i Rep",emp_count,emp_cost,emp_count*emp_cost)
end
addCommsReply(emp_prompt,function()
if comms_source:takeReputationPoints(emp_count*emp_cost) then
comms_source.preorder_emp = emp_count
if emp_count > 1 then
setCommsMessage(string.format("%i EMPs preordered",emp_count))
else
setCommsMessage(string.format("%i EMP preordered",emp_count))
end
else
setCommsMessage(_("needRep-comms", "Insufficient reputation"))
end
preorder_message = "Docking crew is standing by. Would you like to pre-order anything?"
addCommsReply(_("Back"),return_function)
end)
end
local nuke_count = math.floor(comms_source:getWeaponStorageMax("Nuke") * comms_target.comms_data.max_weapon_refill_amount[getFriendStatus()]) - comms_source:getWeaponStorage("Nuke")
if comms_target.comms_data.weapon_available.Nuke and isAllowedTo(comms_target.comms_data.weapons["Nuke"]) and nuke_count > 0 then
local nuke_prompt = ""
local nuke_cost = getWeaponCost("Nuke")
if nuke_count > 1 then
nuke_prompt = string.format("%i Nukes * %i Rep = %i Rep",nuke_count,nuke_cost,nuke_count*nuke_cost)
else
nuke_prompt = string.format("%i Nuke * %i Rep = %i Rep",nuke_count,nuke_cost,nuke_count*nuke_cost)
end
addCommsReply(nuke_prompt,function()
if comms_source:takeReputationPoints(nuke_count*nuke_cost) then
comms_source.preorder_nuke = nuke_count
if nuke_count > 1 then
setCommsMessage(string.format("%i Nukes preordered",nuke_count))
else
setCommsMessage(string.format("%i Nuke preordered",nuke_count))
end
else
setCommsMessage(_("needRep-comms", "Insufficient reputation"))
end
preorder_message = "Docking crew is standing by. Would you like to pre-order anything?"
addCommsReply(_("Back"),return_function)
end)
end
if comms_source.preorder_repair_crew == nil then
if random(1,100) <= 20 then
if comms_source:isFriendly(comms_target) then
if comms_source:getRepairCrewCount() < comms_source.maxRepairCrew then
hireCost = math.random(30,60)
else
hireCost = math.random(45,90)
end
addCommsReply(string.format(_("trade-comms", "Recruit repair crew member for %i reputation"),hireCost), function()
if not comms_source:takeReputationPoints(hireCost) then
setCommsMessage(_("needRep-comms", "Insufficient reputation"))
else
comms_source.preorder_repair_crew = 1
setCommsMessage("Repair crew hired on your behalf. They will board when you dock")
end
preorder_message = "Docking crew is standing by. Would you like to pre-order anything?"
addCommsReply(_("Back"),return_function)
end)
end
end
end
if comms_source.preorder_coolant == nil then
if random(1,100) <= 20 then
if comms_source:isFriendly(comms_target) then
if comms_source.initialCoolant ~= nil then
local coolant_cost = math.random(45,90)
if comms_source:getMaxCoolant() < comms_source.initialCoolant then
coolant_cost = math.random(30,60)
end
addCommsReply(string.format("Set aside coolant for %i reputation",coolant_cost), function()
if comms_source:takeReputationPoints(coolant_cost) then
comms_source.preorder_coolant = 2
setCommsMessage("Coolant set aside for you. It will be loaded when you dock")
else
setCommsMessage(_("needRep-comms", "Insufficient reputation"))
end
preorder_message = "Docking crew is standing by. Would you like to pre-order anything?"
addCommsReply(_("Back"),return_function)
end)
end
end
end
end
end
--]]
function activateDefenseFleet(return_function)
if isAllowedTo(comms_target.comms_data.services.activatedefensefleet) and
comms_target.comms_data.idle_defense_fleet ~= nil then
local defense_fleet_count = 0
for name, template in pairs(comms_target.comms_data.idle_defense_fleet) do
defense_fleet_count = defense_fleet_count + 1
end
if defense_fleet_count > 0 then
addCommsReply(string.format(_("station-comms","Activate station defense fleet (%s rep)"),getServiceCost("activatedefensefleet")),function()
if comms_source:takeReputationPoints(getServiceCost("activatedefensefleet")) then
local out = string.format(_("station-comms","%s defense fleet\n"),comms_target:getCallSign())
for name, template in pairs(comms_target.comms_data.idle_defense_fleet) do
local script = Script()
local position_x, position_y = comms_target:getPosition()
local station_name = comms_target:getCallSign()
script:setVariable("position_x", position_x):setVariable("position_y", position_y)
script:setVariable("station_name",station_name)
script:setVariable("name",name)
script:setVariable("template",template)
script:setVariable("faction_id",comms_target:getFactionId())
script:run("border_defend_station.lua")
out = out .. " " .. name
comms_target.comms_data.idle_defense_fleet[name] = nil
end
out = string.format(_("station-comms","%s\nactivated"),out)
setCommsMessage(out)
else
setCommsMessage(_("needRep-comms", "Insufficient reputation"))
end
addCommsReply(_("Back"), return_function)
end)
end
end
end
-- Docked actions
function restockOrdnance(return_function)
local missilePresence = 0
local missile_types = {'Homing', 'Nuke', 'Mine', 'EMP', 'HVLI'}
for idx, missile_type in ipairs(missile_types) do
missilePresence = missilePresence + comms_source:getWeaponStorageMax(missile_type)
end
if missilePresence > 0 then
if (comms_target.comms_data.weapon_available.Nuke and comms_source:getWeaponStorageMax("Nuke") > 0) and (comms_target.comms_data.weapon_inventory.Unlimited or comms_target.comms_data.weapon_inventory.Nuke > 0) or
(comms_target.comms_data.weapon_available.EMP and comms_source:getWeaponStorageMax("EMP") > 0) and (comms_target.comms_data.weapon_inventory.Unlimited or comms_target.comms_data.weapon_inventory.EMP > 0) or
(comms_target.comms_data.weapon_available.Homing and comms_source:getWeaponStorageMax("Homing") > 0) and (comms_target.comms_data.weapon_inventory.Unlimited or comms_target.comms_data.weapon_inventory.Homing > 0) or
(comms_target.comms_data.weapon_available.Mine and comms_source:getWeaponStorageMax("Mine") > 0) and (comms_target.comms_data.weapon_inventory.Unlimited or comms_target.comms_data.weapon_inventory.Mine > 0) or
(comms_target.comms_data.weapon_available.HVLI and comms_source:getWeaponStorageMax("HVLI") > 0) and (comms_target.comms_data.weapon_inventory.Unlimited or comms_target.comms_data.weapon_inventory.HVLI > 0) then
addCommsReply(_("ammo-comms", "I need ordnance restocked"), function()
setCommsMessage(_("ammo-comms", "What type of ordnance?"))
if comms_source:getWeaponStorageMax("Nuke") > 0 and (comms_target.comms_data.weapon_inventory.Unlimited or comms_target.comms_data.weapon_inventory.Nuke > 0) then
if comms_target.comms_data.weapon_available.Nuke then
local ask = {_("ammo-comms", "Can you supply us with some nukes?"),_("ammo-comms", "We really need some nukes.")}
local avail = ""
if not comms_target.comms_data.weapon_inventory.Unlimited then
avail = string.format(_("ammo-comms", ", %i avail"),math.floor(comms_target.comms_data.weapon_inventory.Nuke))
end
local nuke_prompt = string.format(_("ammo-comms", "%s (%i rep each%s)"),ask[math.random(1,#ask)],getWeaponCost("Nuke"),avail)
addCommsReply(nuke_prompt, function()
handleWeaponRestock("Nuke",return_function)
end)
end --end station has nuke available if branch
end --end player can accept nuke if branch
if comms_source:getWeaponStorageMax("EMP") > 0 and (comms_target.comms_data.weapon_inventory.Unlimited or comms_target.comms_data.weapon_inventory.EMP > 0) then
if comms_target.comms_data.weapon_available.EMP then
local ask = {_("ammo-comms", "Please re-stock our EMP missiles."),_("ammo-comms", "Got any EMPs?")}
local avail = ""
if not comms_target.comms_data.weapon_inventory.Unlimited then
avail = string.format(_("ammo-comms", ", %i avail"),math.floor(comms_target.comms_data.weapon_inventory.EMP))
end
local emp_prompt = string.format(_("ammo-comms", "%s (%i rep each%s)"),ask[math.random(1,#ask)],getWeaponCost("EMP"),avail)
addCommsReply(emp_prompt, function()
handleWeaponRestock("EMP",return_function)
end)
end --end station has EMP available if branch
end --end player can accept EMP if branch
if comms_source:getWeaponStorageMax("Homing") > 0 and (comms_target.comms_data.weapon_inventory.Unlimited or comms_target.comms_data.weapon_inventory.Homing > 0) then
if comms_target.comms_data.weapon_available.Homing then
local ask = {_("ammo-comms", "Do you have spare homing missiles for us?"),_("ammo-comms", "Do you have extra homing missiles?")}
local avail = ""
if not comms_target.comms_data.weapon_inventory.Unlimited then
avail = string.format(_("ammo-comms", ", %i avail"),math.floor(comms_target.comms_data.weapon_inventory.Homing))
end
local homing_prompt = string.format(_("ammo-comms", "%s (%i rep each%s)"),ask[math.random(1,#ask)],getWeaponCost("Homing"),avail)
addCommsReply(homing_prompt, function()
handleWeaponRestock("Homing",return_function)
end)
end --end station has homing for player if branch
end --end player can accept homing if branch
if comms_source:getWeaponStorageMax("Mine") > 0 and (comms_target.comms_data.weapon_inventory.Unlimited or comms_target.comms_data.weapon_inventory.Mine > 0) then
if comms_target.comms_data.weapon_available.Mine then
local ask = {_("ammo-comms", "We could use some mines."),_("ammo-comms", "How about mines?")}
local avail = ""
if not comms_target.comms_data.weapon_inventory.Unlimited then
avail = string.format(_("ammo-comms", ", %i avail"),math.floor(comms_target.comms_data.weapon_inventory.Mine))
end
local mine_prompt = string.format(_("ammo-comms", "%s (%i rep each%s)"),ask[math.random(1,#ask)],getWeaponCost("Mine"),avail)
addCommsReply(mine_prompt, function()
handleWeaponRestock("Mine",return_function)
end)
end --end station has mine for player if branch
end --end player can accept mine if branch
if comms_source:getWeaponStorageMax("HVLI") > 0 and (comms_target.comms_data.weapon_inventory.Unlimited or comms_target.comms_data.weapon_inventory.HVLI > 0) then
if comms_target.comms_data.weapon_available.HVLI then
local ask = {_("ammo-comms", "What about HVLI?"),_("ammo-comms", "Could you provide HVLI?")}
local avail = ""
if not comms_target.comms_data.weapon_inventory.Unlimited then
avail = string.format(_("ammo-comms", ", %i avail"),math.floor(comms_target.comms_data.weapon_inventory.HVLI))
end
local hvli_prompt = string.format(_("ammo-comms", "%s (%i rep each%s)"),ask[math.random(1,#ask)],getWeaponCost("HVLI"),avail)
addCommsReply(hvli_prompt, function()
handleWeaponRestock("HVLI",return_function)
end)
end --end station has HVLI for player if branch
end --end player can accept HVLI if branch
end) --end player requests secondary ordnance comms reply branch
end --end secondary ordnance available from station if branch
end --end missles used on player ship if branch
end
function repairSubsystems(return_function)
local offer_repair = false
if comms_target.comms_data.probe_launch_repair and not comms_source:getCanLaunchProbe() then
offer_repair = true
end
if not offer_repair and comms_target.comms_data.hack_repair and not comms_source:getCanHack() then
offer_repair = true
end
if not offer_repair and comms_target.comms_data.scan_repair and not comms_source:getCanScan() then
offer_repair = true
end
if not offer_repair and comms_target.comms_data.combat_maneuver_repair and not comms_source:getCanCombatManeuver() then
offer_repair = true
end
if not offer_repair and comms_target.comms_data.self_destruct_repair and not comms_source:getCanSelfDestruct() then
offer_repair = true
end
if not offer_repair and comms_target.comms_data.tube_slow_down_repair then
local tube_load_time_slowed = false
if comms_source.normal_tube_load_time ~= nil then
local tube_count = comms_source:getWeaponTubeCount()
if tube_count > 0 then
local tube_index = 0
repeat
if comms_source.normal_tube_load_time[tube_index] ~= comms_source:getTubeLoadTime(tube_index) then
tube_load_time_slowed = true
break
end
tube_index = tube_index + 1
until(tube_index >= tube_count)
end
end
if tube_load_time_slowed then
offer_repair = true
end
end
if offer_repair then
addCommsReply(_("stationServices-comms", "Repair ship system"),function()
setCommsMessage(_("stationServices-comms", "What system would you like repaired?"))
if comms_target.comms_data.probe_launch_repair then
if not comms_source:getCanLaunchProbe() then
addCommsReply(_("stationServices-comms", "Repair probe launch system (5 Rep)"),function()
if comms_source:takeReputationPoints(5) then
comms_source:setCanLaunchProbe(true)
setCommsMessage(_("stationServices-comms", "Your probe launch system has been repaired"))
else
setCommsMessage(_("needRep-comms", "Insufficient reputation"))
end
addCommsReply(_("Back"), return_function)
end)
end
end
if comms_target.comms_data.hack_repair then
if not comms_source:getCanHack() then
addCommsReply(_("stationServices-comms", "Repair hacking system (5 Rep)"),function()
if comms_source:takeReputationPoints(5) then
comms_source:setCanHack(true)
setCommsMessage(_("stationServices-comms", "Your hack system has been repaired"))
else
setCommsMessage(_("needRep-comms", "Insufficient reputation"))
end
addCommsReply(_("Back"), return_function)
end)
end
end
if comms_target.comms_data.scan_repair then
if not comms_source:getCanScan() then
addCommsReply(_("stationServices-comms", "Repair scanners (5 Rep)"),function()
if comms_source:takeReputationPoints(5) then
comms_source:setCanScan(true)
setCommsMessage(_("stationServices-comms", "Your scanners have been repaired"))
else
setCommsMessage(_("needRep-comms", "Insufficient reputation"))
end
addCommsReply(_("Back"), return_function)
end)
end
end
if comms_target.comms_data.combat_maneuver_repair then
if not comms_source:getCanCombatManeuver() then
addCommsReply(_("stationServices-comms", "Repair combat maneuver (5 Rep)"),function()
if comms_source:takeReputationPoints(5) then
comms_source:setCanCombatManeuver(true)
setCommsMessage(_("stationServices-comms", "Your combat maneuver has been repaired"))
else
setCommsMessage(_("needRep-comms", "Insufficient reputation"))
end
addCommsReply(_("Back"), return_function)
end)
end
end
if comms_target.comms_data.self_destruct_repair then
if not comms_source:getCanSelfDestruct() then
addCommsReply(_("stationServices-comms", "Repair self destruct system (5 Rep)"),function()
if comms_source:takeReputationPoints(5) then
comms_source:setCanSelfDestruct(true)
setCommsMessage(_("stationServices-comms", "Your self destruct system has been repaired"))
else
setCommsMessage(_("needRep-comms", "Insufficient reputation"))
end
addCommsReply(_("Back"), return_function)
end)
end
end
if comms_target.comms_data.tube_slow_down_repair then
local tube_load_time_slowed = false
if comms_source.normal_tube_load_time ~= nil then
local tube_count = comms_source:getWeaponTubeCount()
if tube_count > 0 then
local tube_index = 0
repeat
if comms_source.normal_tube_load_time[tube_index] < comms_source:getTubeLoadTime(tube_index) then
tube_load_time_slowed = true
break
end
tube_index = tube_index + 1
until(tube_index >= tube_count)
end
end
if tube_load_time_slowed then
addCommsReply(_("stationServices-comms", "Repair slow tube loading (5 Rep)"),function()
if comms_source:takeReputationPoints(5) then
local tube_count = comms_source:getWeaponTubeCount()
local tube_index = 0
repeat
comms_source:setTubeLoadTime(tube_index,comms_source.normal_tube_load_time[tube_index])
tube_index = tube_index + 1
until(tube_index >= tube_count)
setCommsMessage(_("stationServices-comms", "Your tube load times have been returned to normal"))
else
setCommsMessage(_("needRep-comms", "Insufficient reputation"))
end
addCommsReply(_("Back"), return_function)
end)
end
end
addCommsReply(_("Back"), return_function)
end)
end
end
function handleWeaponRestock(weapon, return_function)
if not comms_source:isDocked(comms_target) then
setCommsMessage(_("station-comms", "You need to stay docked for that action."))
return
end
if not isAllowedTo(comms_target.comms_data.weapons[weapon]) then
if weapon == "Nuke" then setCommsMessage(_("ammo-comms", "We do not deal in weapons of mass destruction."))
elseif weapon == "EMP" then setCommsMessage(_("ammo-comms", "We do not deal in weapons of mass disruption."))
else setCommsMessage(_("ammo-comms", "We do not deal in those weapons.")) end
return
end
local points_per_item = getWeaponCost(weapon)
local item_amount = math.floor(comms_source:getWeaponStorageMax(weapon) * comms_target.comms_data.max_weapon_refill_amount[getFriendStatus()]) - comms_source:getWeaponStorage(weapon)
if item_amount <= 0 then
if weapon == "Nuke" then
setCommsMessage(_("ammo-comms", "All nukes are charged and primed for destruction."));
else
setCommsMessage(_("ammo-comms", "Sorry, sir, but you are as fully stocked as I can allow."));
end
addCommsReply(_("Back"), return_function)
else
local inventory_status = ""
if comms_source:getReputationPoints() > points_per_item * item_amount and (comms_target.comms_data.weapon_inventory.Unlimited or comms_target.comms_data.weapon_inventory[weapon] >= item_amount) then
if comms_source:takeReputationPoints(points_per_item * item_amount) then
comms_source:setWeaponStorage(weapon, comms_source:getWeaponStorage(weapon) + item_amount)
if not comms_target.comms_data.weapon_inventory.Unlimited then
comms_target.comms_data.weapon_inventory[weapon] = comms_target.comms_data.weapon_inventory[weapon] - item_amount
inventory_status = string.format(_("ammo-comms", "\nStation inventory of %s type weapons reduced to %i"),weapon,math.floor(comms_target.comms_data.weapon_inventory[weapon]))
end
if comms_source:getWeaponStorage(weapon) == comms_source:getWeaponStorageMax(weapon) then
setCommsMessage(_("ammo-comms", "You are fully loaded and ready to explode things.") .. inventory_status)
else
setCommsMessage(_("ammo-comms", "We generously resupplied you with some weapon charges.\nPut them to good use.") .. inventory_status)
end
else
setCommsMessage(_("needRep-comms", "Not enough reputation."))
return
end
else
if comms_source:getReputationPoints() > points_per_item then
setCommsMessage(_("ammo-comms", "Either you can't afford as much as I'd like to give you, or I don't have enough to fully restock you."))
addCommsReply(_("ammo-comms", "Get just one"), function()
if comms_source:takeReputationPoints(points_per_item) then
comms_source:setWeaponStorage(weapon, comms_source:getWeaponStorage(weapon) + 1)
if not comms_target.comms_data.weapon_inventory.Unlimited then
comms_target.comms_data.weapon_inventory[weapon] = comms_target.comms_data.weapon_inventory[weapon] - 1
inventory_status = string.format(_("ammo-comms", "\nStation inventory of %s type weapons reduced to %i"),weapon,math.floor(comms_target.comms_data.weapon_inventory[weapon]))
end
if comms_source:getWeaponStorage(weapon) == comms_source:getWeaponStorageMax(weapon) then
setCommsMessage(_("ammo-comms", "You are fully loaded and ready to explode things.") .. inventory_status)
else
setCommsMessage(_("ammo-comms", "We generously resupplied you with one weapon charge.\nPut it to good use.") .. inventory_status)
end
else
setCommsMessage(_("needRep-comms", "Not enough reputation."))
end
return
end)
else
setCommsMessage(_("needRep-comms", "Not enough reputation."))
return
end
end
addCommsReply(_("Back"), return_function)
end
end
function buySellTrade(return_function)
local goodCount = 0
if comms_target.comms_data.goods == nil then
return
end
for good, goodData in pairs(comms_target.comms_data.goods) do
if goodData.quantity > 0 then
goodCount = goodCount + 1
end
end
if goodCount > 0 then
addCommsReply(_("trade-comms", "Buy, sell, trade"), function()
local goodsReport = string.format(_("trade-comms", "Station %s:\nGoods or components available for sale: quantity, cost in reputation\n"),comms_target:getCallSign())
for good, goodData in pairs(comms_target.comms_data.goods) do
goodsReport = goodsReport .. string.format(_("trade-comms", " %s: %i, %i\n"),good_desc[good],goodData["quantity"],goodData["cost"])
end
if comms_target.comms_data.buy ~= nil then
goodsReport = goodsReport .. _("trade-comms", "Goods or components station will buy: price in reputation\n")
for good, price in pairs(comms_target.comms_data.buy) do
goodsReport = goodsReport .. string.format(_("trade-comms", " %s: %i\n"),good_desc[good],price)
end
end
goodsReport = goodsReport .. string.format(_("trade-comms", "Current cargo aboard %s:\n"),comms_source:getCallSign())
local cargoHoldEmpty = true
local goodCount = 0
if comms_source.goods ~= nil then
for good, goodQuantity in pairs(comms_source.goods) do
goodCount = goodCount + 1
goodsReport = goodsReport .. string.format(_("trade-comms", " %s: %i\n"),good_desc[good],goodQuantity)
end
end
if goodCount < 1 then
goodsReport = goodsReport .. _("trade-comms", " Empty\n")
end
goodsReport = goodsReport .. string.format(_("trade-comms", "Available Space: %i, Available Reputation: %i\n"),comms_source.cargo,math.floor(comms_source:getReputationPoints()))
setCommsMessage(goodsReport)
for good, goodData in pairs(comms_target.comms_data.goods) do
addCommsReply(string.format(_("trade-comms", "Buy one %s for %i reputation"),good_desc[good],goodData["cost"]), function()
local goodTransactionMessage = string.format(_("trade-comms", "Type: %s, Quantity: %i, Rep: %i"),good_desc[good],goodData["quantity"],goodData["cost"])
if comms_source.cargo < 1 then
goodTransactionMessage = goodTransactionMessage .. _("trade-comms", "\nInsufficient cargo space for purchase")
elseif goodData["cost"] > math.floor(comms_source:getReputationPoints()) then
goodTransactionMessage = goodTransactionMessage .. _("needRep-comms", "\nInsufficient reputation for purchase")
elseif goodData["quantity"] < 1 then
goodTransactionMessage = goodTransactionMessage .. _("trade-comms", "\nInsufficient station inventory")
else
if comms_source:takeReputationPoints(goodData["cost"]) then
comms_source.cargo = comms_source.cargo - 1
goodData["quantity"] = goodData["quantity"] - 1
if comms_source.goods == nil then
comms_source.goods = {}
end
if comms_source.goods[good] == nil then
comms_source.goods[good] = 0
end
comms_source.goods[good] = comms_source.goods[good] + 1
goodTransactionMessage = goodTransactionMessage .. _("trade-comms", "\npurchased")
else
goodTransactionMessage = goodTransactionMessage .. _("needRep-comms", "\nInsufficient reputation for purchase")
end
end
setCommsMessage(goodTransactionMessage)
addCommsReply(_("Back"), return_function)
end)
end
if comms_target.comms_data.buy ~= nil then
for good, price in pairs(comms_target.comms_data.buy) do
if comms_source.goods ~= nil then
if comms_source.goods[good] ~= nil and comms_source.goods[good] > 0 then
addCommsReply(string.format(_("trade-comms", "Sell one %s for %i reputation"),good_desc[good],price), function()
local goodTransactionMessage = string.format(_("trade-comms", "Type: %s, Reputation price: %i"),good,price)
comms_source.goods[good] = comms_source.goods[good] - 1
comms_source:addReputationPoints(price)
goodTransactionMessage = goodTransactionMessage .. _("trade-comms", "\nOne sold")
comms_source.cargo = comms_source.cargo + 1
setCommsMessage(goodTransactionMessage)
addCommsReply(_("Back"), return_function)
end)
end
end
end
end
if comms_target.comms_data.trade.food and comms_source.goods["food"] > 0 then
for good, goodData in pairs(comms_target.comms_data.goods) do
addCommsReply(string.format(_("trade-comms", "Trade food for %s"),good_desc[good]), function()
local goodTransactionMessage = string.format(_("trade-comms", "Type: %s, Quantity: %i"),good_desc[good],goodData["quantity"])
if goodData["quantity"] < 1 then
goodTransactionMessage = goodTransactionMessage .. _("trade-comms", "\nInsufficient station inventory")
else
goodData["quantity"] = goodData["quantity"] - 1
if comms_source.goods == nil then
comms_source.goods = {}
end
if comms_source.goods[good] == nil then
comms_source.goods[good] = 0
end
comms_source.goods[good] = comms_source.goods[good] + 1
comms_source.goods["food"] = comms_source.goods["food"] - 1
goodTransactionMessage = goodTransactionMessage .. _("trade-comms", "\nTraded")
end
setCommsMessage(goodTransactionMessage)
addCommsReply(_("Back"), return_function)
end)
end
end
if comms_target.comms_data.trade.medicine and comms_source.goods["medicine"] > 0 then
for good, goodData in pairs(comms_target.comms_data.goods) do
addCommsReply(string.format(_("trade-comms", "Trade medicine for %s"),good_desc[good]), function()
local goodTransactionMessage = string.format(_("trade-comms", "Type: %s, Quantity: %i"),good_desc[good],goodData["quantity"])
if goodData["quantity"] < 1 then
goodTransactionMessage = goodTransactionMessage .. _("trade-comms", "\nInsufficient station inventory")
else
goodData["quantity"] = goodData["quantity"] - 1
if comms_source.goods == nil then
comms_source.goods = {}
end
if comms_source.goods[good] == nil then
comms_source.goods[good] = 0
end
comms_source.goods[good] = comms_source.goods[good] + 1
comms_source.goods["medicine"] = comms_source.goods["medicine"] - 1
goodTransactionMessage = goodTransactionMessage .. _("trade-comms", "\nTraded")
end
setCommsMessage(goodTransactionMessage)
addCommsReply(_("Back"), return_function)
end)
end
end
if comms_target.comms_data.trade.luxury and comms_source.goods["luxury"] > 0 then
for good, goodData in pairs(comms_target.comms_data.goods) do
addCommsReply(string.format(_("trade-comms", "Trade luxury for %s"),good_desc[good]), function()
local goodTransactionMessage = string.format(_("trade-comms", "Type: %s, Quantity: %i"),good_desc[good],goodData["quantity"])
if goodData[quantity] < 1 then
goodTransactionMessage = goodTransactionMessage .. _("trade-comms", "\nInsufficient station inventory")
else
goodData["quantity"] = goodData["quantity"] - 1
if comms_source.goods == nil then
comms_source.goods = {}
end
if comms_source.goods[good] == nil then
comms_source.goods[good] = 0
end
comms_source.goods[good] = comms_source.goods[good] + 1
comms_source.goods["luxury"] = comms_source.goods["luxury"] - 1
goodTransactionMessage = goodTransactionMessage .. _("trade-comms", "\nTraded")
end
setCommsMessage(goodTransactionMessage)
addCommsReply(_("Back"), return_function)
end)
end
end
addCommsReply(_("Back"), return_function)
end)
end
end
function boostSensorsWhileDocked(return_function)
if comms_target.comms_data.sensor_boost ~= nil then
if comms_target.comms_data.sensor_boost.cost > 0 then
addCommsReply(string.format(_("upgrade-comms","Augment scan range with station sensors while docked (%i rep)"),comms_target.comms_data.sensor_boost.cost),function()
if comms_source:takeReputationPoints(comms_target.comms_data.sensor_boost.cost) then
if comms_source.normal_long_range_radar == nil then
comms_source.normal_long_range_radar = comms_source:getLongRangeRadarRange()
end
comms_source:setLongRangeRadarRange(comms_source.normal_long_range_radar + comms_target.comms_data.sensor_boost.value)
setCommsMessage(string.format(_("upgrade-comms","sensors increased by %i units"),comms_target.comms_data.sensor_boost.value/1000))
else
setCommsMessage(_("needRep-comms", "Insufficient reputation"))
end
addCommsReply(_("Back"), return_function)
end)
end
end
end
function overchargeJump(return_function)
if comms_target.comms_data.jump_overcharge and isAllowedTo(comms_target.comms_data.services.jumpovercharge) then
if comms_source:hasJumpDrive() then
local max_charge = comms_source.max_jump_range
if max_charge == nil then
max_charge = 50000
end
if comms_source:getJumpDriveCharge() >= max_charge then
addCommsReply(string.format(_("upgrade-comms","Overcharge Jump Drive (%s rep)"),getServiceCost("jumpovercharge")),function()
if comms_source:takeReputationPoints(getServiceCost("jumpovercharge")) then
comms_source:setJumpDriveCharge(comms_source:getJumpDriveCharge() + max_charge)
setCommsMessage(string.format(_("upgrade-comms","Your jump drive has been overcharged to %ik"),math.floor(comms_source:getJumpDriveCharge()/1000)))
else
setCommsMessage(_("needRep-comms", "Insufficient reputation"))
end
addCommsReply(_("Back"), return_function)
end)
end
end
end
end
-- Upgrades
function hullStrengthUpgrade(p)
if p.hull_strength_upgrade == nil then
p.hull_strength_upgrade = "done"
p:setHullMax(p:getHullMax()*1.2)
p:setHull(p:getHullMax())
p:setImpulseMaxSpeed(p:getImpulseMaxSpeed()*.9)
return true, _("upgrade-comms","Your hull strength has been increased by 20%")
else
return false, _("upgrade-comms","You already have the hull strength upgrade")
end
end
function missileLoadSpeedUpgrade(p)
if p.missile_load_speed_upgrade == nil then
local tube_count = p:getWeaponTubeCount()
if tube_count > 0 then
local tube_index = 0
if p.normal_tube_load_time == nil then
p.normal_tube_load_time = {}
repeat
p.normal_tube_load_time[tube_index] = p:getTubeLoadTime(tube_index)
tube_index = tube_index + 1
until(tube_index >= tube_count)
tube_index = 0
end
repeat
p:setTubeLoadTime(tube_index,p.normal_tube_load_time[tube_index]*.8)
p.normal_tube_load_time[tube_index] = p.normal_tube_load_time[tube_index]*.8
tube_index = tube_index + 1
until(tube_index >= tube_count)
return true, _("upgrade-comms","Your missile tube load time has been reduced by 20%")
else
return false, _("upgrade-comms","Your ship has no missile systems and thus cannot be upgraded")
end
else
return false, _("upgrade-comms","You already have the missile load speed upgrade")
end
end
function shieldStrengthUpgrade(p)
if p.shield_strength_upgrade == nil then
if p:getShieldCount() > 0 then
p.shield_strength_upgrade = "done"
if p:getShieldCount() == 1 then
p:setShieldsMax(p:getShieldMax(0)*1.2)
else
p:setShieldsMax(p:getShieldMax(0)*1.2,p:getShieldMax(1)*1.2)
end
return true, _("upgrade-comms","Your ship shields are now 20% stronger. They'll need to charge to their new higher capacity")
else
return false, _("upgrade-comms","Your ship has no shields and thus cannot be upgraded")
end
else
return false, _("upgrade-comms","You already have the shield upgrade")
end
end
function beamDamageUpgrade(p)
if p.beam_damage_upgrade == nil then
if p:getBeamWeaponRange(0) > 0 then
p.beam_damage_upgrade = "done"
local bi = 0
repeat
local tempArc = p:getBeamWeaponArc(bi)
local tempDir = p:getBeamWeaponDirection(bi)
local tempRng = p:getBeamWeaponRange(bi)
local tempCyc = p:getBeamWeaponCycleTime(bi)
local tempDmg = p:getBeamWeaponDamage(bi)
p:setBeamWeapon(bi,tempArc,tempDir,tempRng,tempCyc,tempDmg*1.2)
p:setBeamWeaponHeatPerFire(bi,p:getBeamWeaponHeatPerFire(bi)*1.2)
p:setBeamWeaponEnergyPerFire(bi,p:getBeamWeaponEnergyPerFire(bi)*1.2)
bi = bi + 1
until(p:getBeamWeaponRange(bi) < 1)
return true, _("upgrade-comms","Your ship beam weapons damage has been increased by 20%")
else
return false, _("upgrade-comms","Your ship has no beam weapons and thus cannot be upgraded")
end
else
return false, _("upgrade-comms","You already have the beam damage upgrade")
end
end
function beamRangeUpgrade(p)
if p.beam_range_upgrade == nil then
if p:getBeamWeaponRange(0) > 0 then
p.beam_range_upgrade = "done"
local bi = 0
repeat
local tempArc = p:getBeamWeaponArc(bi)
local tempDir = p:getBeamWeaponDirection(bi)
local tempRng = p:getBeamWeaponRange(bi)
local tempCyc = p:getBeamWeaponCycleTime(bi)
local tempDmg = p:getBeamWeaponDamage(bi)
p:setBeamWeapon(bi,tempArc,tempDir,tempRng*1.2,tempCyc,tempDmg)
p:setBeamWeaponHeatPerFire(bi,p:getBeamWeaponHeatPerFire(bi)*1.2)
p:setBeamWeaponEnergyPerFire(bi,p:getBeamWeaponEnergyPerFire(bi)*1.2)
bi = bi + 1
until(p:getBeamWeaponRange(bi) < 1)
return true, _("upgrade-comms","Your ship beam weapons range has been increased by 20%")
else
return false, _("upgrade-comms","Your ship has no beam weapons and thus cannot be upgraded")
end
else
return false, _("upgrade-comms","You already have the beam range upgrade")
end
end
function batteryEfficiencyUpgrade(p)
if p.battery_efficiency_upgrade == nil then
p.battery_efficiency_upgrade = "done"
p:setMaxEnergy(p:getMaxEnergy()*1.2)
p:setImpulseMaxSpeed(p:getImpulseMaxSpeed()*.95)
return true, _("upgrade-comms","Your ship batteries can now store 20% more energy. You'll need to charge them longer to use their full capacity")
else
return false, _("upgrade-comms","You already have the battery efficiency upgrade")
end
end
function fasterImpulseUpgrade(p)
if p.faster_impulse_upgrade == nil then
p.faster_impulse_upgrade = "done"
p:setImpulseMaxSpeed(p:getImpulseMaxSpeed()*1.2)
p:setRotationMaxSpeed(p:getRotationMaxSpeed()*.95)
return true, _("upgrade-comms","Your maximum impulse top speed has been increased by 20%")
else
return false, _("upgrade-comms","You already have an upgraded impulse engine")
end
end
function longerSensorsUpgrade(p)
if p.longer_sensors_upgrade == nil then
p.longer_sensors_upgrade = "done"
if p.normal_long_range_radar == nil then
p.normal_long_range_radar = p:getLongRangeRadarRange()
end
p:setLongRangeRadarRange(p:getLongRangeRadarRange() + 10000)
p.normal_long_range_radar = p.normal_long_range_radar + 10000
return true, _("upgrade-comms","Your ship's long range sensors have had their reach increased by 10 units")
else
return false, _("upgrade-comms","You already have upgraded long range sensors")
end
end
function fasterSpinUpgrade(p)
if p.faster_spin_upgrade == nil then
p.faster_spin_upgrade = "done"
p:setRotationMaxSpeed(p:getRotationMaxSpeed()*1.2)
return true, _("upgrade-comms","Your maneuvering speed has been increased by 20%")
else
return false, _("upgrade-comms","You already have upgraded maneuvering speed")
end
end
---------------------------
-- Ship Communications --
---------------------------
function commsShip()
if comms_target.comms_data == nil then
comms_target.comms_data = {friendlyness = random(0.0, 100.0)}
end
if comms_target.comms_data.goods == nil then
comms_target.comms_data.goods = {}
comms_target.comms_data.goods[commonGoods[math.random(1,#commonGoods)]] = {quantity = 1, cost = random(20,80)}
local shipType = comms_target:getTypeName()
if shipType:find("Freighter") ~= nil then
if shipType:find("Goods") ~= nil or shipType:find("Equipment") ~= nil then
repeat
comms_target.comms_data.goods[commonGoods[math.random(1,#commonGoods)]] = {quantity = 1, cost = random(20,80)}
local goodCount = 0
for good, goodData in pairs(comms_target.comms_data.goods) do
goodCount = goodCount + 1
end
until(goodCount >= 3)
end
end
end
if comms_source:isFriendly(comms_target) then
return friendlyComms()
end
if comms_source:isEnemy(comms_target) and comms_target:isFriendOrFoeIdentifiedBy(comms_source) then
return enemyComms()
end
return neutralComms()
end
function friendlyComms()
if comms_target.comms_data.friendlyness < 20 then
setCommsMessage(_("shipAssist-comms", "What do you want?"));
else
setCommsMessage(_("shipAssist-comms", "Sir, how can we assist?"));
end
shipDefendWaypoint(commsShip)
shipFlyBlind(commsShip)
shipAssistPlayer(commsShip)
shipStatusReport(commsShip)
shipDockNearby(commsShip)
shipRoaming(commsShip)
shipStandGround(commsShip)
shipIdle(commsShip)
fleetCommunication(commsShip)
friendlyFreighterCommunication(commsShip)
return true
end
function enemyComms()
local faction = comms_target:getFaction()
local tauntable = false
local amenable = false
if comms_target.comms_data.friendlyness >= 33 then --final: 33
--taunt logic
local taunt_option = _("shipEnemy-comms", "We will see to your destruction!")
local taunt_success_reply = _("shipEnemy-comms", "Your bloodline will end here!")
local taunt_failed_reply = _("shipEnemy-comms", "Your feeble threats are meaningless.")
local taunt_threshold = 30 --base chance of being taunted
if faction == "Kraylor" then
taunt_threshold = 35
setCommsMessage(_("shipEnemy-comms", "Ktzzzsss.\nYou will DIEEee weaklingsss!"));
local kraylorTauntChoice = math.random(1,3)
if kraylorTauntChoice == 1 then
taunt_option = _("shipEnemy-comms", "We will destroy you")
taunt_success_reply = _("shipEnemy-comms", "We think not. It is you who will experience destruction!")
elseif kraylorTauntChoice == 2 then
taunt_option = _("shipEnemy-comms", "You have no honor")
taunt_success_reply = _("shipEnemy-comms", "Your insult has brought our wrath upon you. Prepare to die.")
taunt_failed_reply = _("shipEnemy-comms", "Your comments about honor have no meaning to us")
else
taunt_option = _("shipEnemy-comms", "We pity your pathetic race")
taunt_success_reply = _("shipEnemy-comms", "Pathetic? You will regret your disparagement!")
taunt_failed_reply = _("shipEnemy-comms", "We don't care what you think of us")
end
elseif faction == "Arlenians" then
taunt_threshold = 25
setCommsMessage(_("shipEnemy-comms", "We wish you no harm, but will harm you if we must.\nEnd of transmission."));
elseif faction == "Exuari" then
taunt_threshold = 40
setCommsMessage(_("shipEnemy-comms", "Stay out of our way, or your death will amuse us extremely!"));
elseif faction == "Ghosts" then
taunt_threshold = 20
setCommsMessage(_("shipEnemy-comms", "One zero one.\nNo binary communication detected.\nSwitching to universal speech.\nGenerating appropriate response for target from human language archives.\n:Do not cross us:\nCommunication halted."));
taunt_option = _("shipEnemy-comms", "EXECUTE: SELFDESTRUCT")
taunt_success_reply = _("shipEnemy-comms", "Rogue command received. Targeting source.")
taunt_failed_reply = _("shipEnemy-comms", "External command ignored.")
elseif faction == "Ktlitans" then
setCommsMessage(_("shipEnemy-comms", "The hive suffers no threats. Opposition to any of us is opposition to us all.\nStand down or prepare to donate your corpses toward our nutrition."));
taunt_option = _("shipEnemy-comms", "<Transmit 'The Itsy-Bitsy Spider' on all wavelengths>")
taunt_success_reply = _("shipEnemy-comms", "We do not need permission to pluck apart such an insignificant threat.")
taunt_failed_reply = _("shipEnemy-comms", "The hive has greater priorities than exterminating pests.")
elseif faction == "TSN" then
taunt_threshold = 15
setCommsMessage(_("shipEnemy-comms", "State your business"))
elseif faction == "USN" then
taunt_threshold = 15
setCommsMessage(_("shipEnemy-comms", "What do you want? (not that we care)"))
elseif faction == "CUF" then
taunt_threshold = 15
setCommsMessage(_("shipEnemy-comms", "Don't waste our time"))
else
setCommsMessage(_("shipEnemy-comms", "Mind your own business!"));
end
comms_target.comms_data.friendlyness = comms_target.comms_data.friendlyness - random(0, 10) --reduce friendlyness after each interaction
addCommsReply(taunt_option, function()
if random(0, 100) <= taunt_threshold then --final: 30
local current_order = comms_target:getOrder()
print("order: " .. current_order)
--Possible order strings returned:
--Roaming
--Fly towards
--Attack
--Stand Ground
--Idle
--Defend Location
--Defend Target
--Fly Formation (?)
--Fly towards (ignore all)
--Dock
if comms_target.original_order == nil then
comms_target.original_faction = faction
comms_target.original_order = current_order
if current_order == "Fly towards" or current_order == "Defend Location" or current_order == "Fly towards (ignore all)" then
comms_target.original_target_x, comms_target.original_target_y = comms_target:getOrderTargetLocation()
--print(string.format("Target_x: %f, Target_y: %f",comms_target.original_target_x,comms_target.original_target_y))
end
if current_order == "Attack" or current_order == "Dock" or current_order == "Defend Target" then
local original_target = comms_target:getOrderTarget()
--print("target:")
--print(original_target)
--print(original_target:getCallSign())
comms_target.original_target = original_target
end
comms_target.taunt_may_expire = true --change to conditional in future refactoring
table.insert(enemy_reverts,comms_target)
end
comms_target:orderAttack(comms_source) --consider alternative options besides attack in future refactoring
setCommsMessage(taunt_success_reply);
else
setCommsMessage(taunt_failed_reply);
end
end)
tauntable = true
end
local enemy_health = getEnemyHealth(comms_target)
if change_enemy_order_diagnostic then print(string.format(" enemy health: %.2f",enemy_health)) end
if change_enemy_order_diagnostic then print(string.format(" friendliness: %.1f",comms_target.comms_data.friendlyness)) end
if comms_target.comms_data.friendlyness >= 66 or enemy_health < .5 then --final: 66, .5
--amenable logic
local amenable_chance = comms_target.comms_data.friendlyness/3 + (1 - enemy_health)*30
if change_enemy_order_diagnostic then print(string.format(" amenability: %.1f",amenable_chance)) end
addCommsReply("Stop your actions",function()
local amenable_roll = random(0,100)
if change_enemy_order_diagnostic then print(string.format(" amenable roll: %.1f",amenable_roll)) end
if amenable_roll < amenable_chance then
local current_order = comms_target:getOrder()
if comms_target.original_order == nil then
comms_target.original_order = current_order
comms_target.original_faction = faction
if current_order == "Fly towards" or current_order == "Defend Location" or current_order == "Fly towards (ignore all)" then
comms_target.original_target_x, comms_target.original_target_y = comms_target:getOrderTargetLocation()
--print(string.format("Target_x: %f, Target_y: %f",comms_target.original_target_x,comms_target.original_target_y))
end
if current_order == "Attack" or current_order == "Dock" or current_order == "Defend Target" then
local original_target = comms_target:getOrderTarget()
--print("target:")
--print(original_target)
--print(original_target:getCallSign())
comms_target.original_target = original_target
end
table.insert(enemy_reverts,comms_target)
end
comms_target.amenability_may_expire = true
comms_target:orderIdle()
comms_target:setFaction("Independent")
setCommsMessage("Just this once, we'll take your advice")
else
setCommsMessage("No")
end
end)
comms_target.comms_data.friendlyness = comms_target.comms_data.friendlyness - random(0, 10) --reduce friendlyness after each interaction
amenable = true
end
if tauntable or amenable then
return true
else
return false
end
end
function neutralComms()
local shipType = comms_target:getTypeName()
if shipType:find("Freighter") ~= nil or shipType:find("Transport") ~= nil or shipType:find("Cargo") ~= nil then
setCommsMessage(_("trade-comms", "Yes?"))
shipCargoSellReport(commsShip)
if distance(comms_source,comms_target) < 5000 then
if comms_source.cargo > 0 then
if comms_target.comms_data.friendlyness > 66 then
if shipType:find("Goods") ~= nil or shipType:find("Equipment") ~= nil then
shipBuyGoods(commsShip,1)
else
shipBuyGoods(commsShip,2)
end
elseif comms_target.comms_data.friendlyness > 33 then
if shipType:find("Goods") ~= nil or shipType:find("Equipment") ~= nil then
shipBuyGoods(commsShip,2)
else
shipBuyGoods(commsShip,3)
end
else --least friendly
if shipType:find("Goods") ~= nil or shipType:find("Equipment") ~= nil then
shipBuyGoods(commsShip,3)
end
end --end friendly branches
end --player has room for cargo
end --close enough to sell
else --not a freighter
if comms_target.comms_data.friendlyness > 50 then
setCommsMessage(_("ship-comms", "Sorry, we have no time to chat with you.\nWe are on an important mission."));
else
setCommsMessage(_("ship-comms", "We have nothing for you.\nGood day."));
end
end --end non-freighter communications else branch
return true
end --end neutral communications function
function shipStatusReport(return_function)
addCommsReply(_("shipAssist-comms", "Report status"), function()
msg = string.format(_("shipAssist-comms", "Hull: %d%%\n"), math.floor(comms_target:getHull() / comms_target:getHullMax() * 100))
local shields = comms_target:getShieldCount()
if shields == 1 then
msg = string.format(_("shipAssist-comms", "%sShield: %d%%\n"),msg, math.floor(comms_target:getShieldLevel(0) / comms_target:getShieldMax(0) * 100))
elseif shields == 2 then
msg = string.format(_("shipAssist-comms", "%sFront Shield: %d%%\n"),msg, math.floor(comms_target:getShieldLevel(0) / comms_target:getShieldMax(0) * 100))
msg = string.format(_("shipAssist-comms", "%sRear Shield: %d%%\n"),msg, math.floor(comms_target:getShieldLevel(1) / comms_target:getShieldMax(1) * 100))
else
for n=0,shields-1 do
msg = string.format(_("shipAssist-comms", "%sShield %s: %d%%\n"),msg, n, math.floor(comms_target:getShieldLevel(n) / comms_target:getShieldMax(n) * 100))
end
end
local missile_types = {'Homing', 'Nuke', 'Mine', 'EMP', 'HVLI'}
for i, missile_type in ipairs(missile_types) do
if comms_target:getWeaponStorageMax(missile_type) > 0 then
msg = string.format(_("shipAssist-comms", "%s%s Missiles: %d/%d\n"),msg, missile_type, math.floor(comms_target:getWeaponStorage(missile_type)), math.floor(comms_target:getWeaponStorageMax(missile_type)))
end
end
if comms_target:hasJumpDrive() then
msg = string.format(_("shipAssist-comms","%sJump drive charge: %s"),msg,comms_target:getJumpDriveCharge())
end
setCommsMessage(msg)
addCommsReply(_("Back"), return_function)
end)
end
function shipIdle(return_function)
addCommsReply(_("shipAssist-comms", "Stop. Do nothing."), function()
comms_target:orderIdle()
local idle_comment = {
_("shipAssist-comms","routine system maintenance"),
_("shipAssist-comms","for idle ship gossip"),
_("shipAssist-comms","exterior paint touch-up"),
_("shipAssist-comms","exercise for continued fitness"),
_("shipAssist-comms","meditation therapy"),
_("shipAssist-comms","internal simulated flight routines"),
_("shipAssist-comms","digital dreamscape construction"),
_("shipAssist-comms","catching up on reading the latest war drama novel"),
_("shipAssist-comms","writing up results of bifurcated personality research"),
_("shipAssist-comms","categorizing nearby miniscule space particles"),
_("shipAssist-comms","continuing the count of visible stars from this region"),
_("shipAssist-comms","internal systems diagnostics"),
}
setCommsMessage(string.format(_("shipAssist-comms", "Stopping. Doing nothing except %s."),idle_comment[math.random(1,#idle_comment)]))
addCommsReply(_("Back"), return_function)
end)
end
function shipRoaming(return_function)
addCommsReply(_("shipAssist-comms", "Attack all enemies. Start with the nearest."), function()
comms_target:orderRoaming()
setCommsMessage(_("shipAssist-comms", "Searching and destroying"))
addCommsReply(_("Back"), return_function)
end)
end
function shipStandGround(return_function)
addCommsReply(_("shipAssist-comms", "Stop and defend your current location"), function()
comms_target:orderStandGround()
setCommsMessage(_("shipAssist-comms", "Stopping. Shooting any enemy that approaches"))
addCommsReply(_("Back"), return_function)
end)
end
function shipDefendWaypoint(return_function)
addCommsReply(_("shipAssist-comms", "Defend a waypoint"), function()
if comms_source:getWaypointCount() == 0 then
setCommsMessage(_("shipAssist-comms", "No waypoints set. Please set a waypoint first."));
addCommsReply(_("Back"), return_function)
else
setCommsMessage(_("shipAssist-comms", "Which waypoint should we defend?"));
for n=1,comms_source:getWaypointCount() do
addCommsReply(string.format(_("shipAssist-comms", "Defend WP %d"), n), function()
comms_target:orderDefendLocation(comms_source:getWaypoint(n))
setCommsMessage(string.format(_("shipAssist-comms", "We are heading to assist at WP %d."), n));
addCommsReply(_("Back"), return_function)
end)
end
end
end)
end
function shipFlyBlind(return_function)
addCommsReply(_("shipAssist-comms", "Go to waypoint, ignore enemies"), function()
if comms_source:getWaypointCount() == 0 then
setCommsMessage(_("shipAssist-comms", "No waypoints set. Please set a waypoint first."));
addCommsReply(_("Back"), return_function)
else
setCommsMessage(_("shipAssist-comms", "Which waypoint should we approach?"));
for n=1,comms_source:getWaypointCount() do
addCommsReply(string.format(_("shipAssist-comms", "Defend WP %d"), n), function()
comms_target:orderFlyTowardsBlind(comms_source:getWaypoint(n))
setCommsMessage(string.format(_("shipAssist-comms", "We are heading to WP%d ignoring enemies."), n));
addCommsReply(_("Back"), return_function)
end)
end
end
end)
end
function shipAssistPlayer(return_function)
if comms_target.comms_data.friendlyness > 0.2 then
addCommsReply(_("shipAssist-comms", "Assist me"), function()
setCommsMessage(_("shipAssist-comms", "Heading toward you to assist."));
comms_target:orderDefendTarget(comms_source)
addCommsReply(_("Back"), return_function)
end)
end
end
function shipDockNearby(return_function)
for idx, obj in ipairs(comms_target:getObjectsInRange(5000)) do
local player_carrier = false
local template_name = ""
if isObjectType(obj,"PlayerSpaceship") then
template_name = obj:getTypeName()
if template_name == "Benedict" or template_name == "Kiriya" or template_name == "Saipan" then
player_carrier = true
end
end
local defense_platform = false
if isObjectType(obj,"CpuShip") then
template_name = obj:getTypeName()
if template_name == "Defense platform" then
defense_platform = true
end
end
if (isObjectType(obj,"SpaceStation") and not comms_target:isEnemy(obj)) or player_carrier or defense_platform then
addCommsReply(string.format(_("shipAssist-comms", "Dock at %s"), obj:getCallSign()), function()
setCommsMessage(string.format(_("shipAssist-comms", "Docking at %s."), obj:getCallSign()));
comms_target:orderDock(obj)
addCommsReply(_("Back"), return_function)
end)
end
end
end
function fleetCommunication(return_function)
if comms_target.fleetIndex ~= nil then
addCommsReply(string.format(_("shipAssist-comms", "Direct fleet %i"),comms_target.fleetIndex), function()
local fleet_state = string.format(_("shipAssist-comms", "Fleet %i consists of:\n"),comms_target.fleetIndex)
for idx, ship in ipairs(npc_fleet[comms_target:getFaction()]) do
if ship ~= nil and ship:isValid() then
if ship.fleetIndex == comms_target.fleetIndex then
fleet_state = fleet_state .. ship:getCallSign() .. " "
end
end
end
setCommsMessage(string.format(_("shipAssist-comms", "%s\n\nWhat command should be given to fleet %i?"),fleet_state,comms_target.fleetIndex))
addCommsReply(_("shipAssist-comms", "Report hull and shield status"), function()
msg = string.format(_("shipAssist-comms", "Fleet %i status:"),comms_target.fleetIndex)
for idx, fleetShip in ipairs(npc_fleet[comms_target:getFaction()]) do
if fleetShip.fleetIndex == comms_target.fleetIndex then
if fleetShip ~= nil and fleetShip:isValid() then
msg = string.format(_("shipAssist-comms", "%s\n %s:"),msg, fleetShip:getCallSign())
msg = string.format(_("shipAssist-comms", "%s\n Hull: %d%%"),msg, math.floor(fleetShip:getHull() / fleetShip:getHullMax() * 100))
local shields = fleetShip:getShieldCount()
if shields == 1 then
msg = string.format(_("shipAssist-comms", "%s\n Shield: %d%%"),msg, math.floor(fleetShip:getShieldLevel(0) / fleetShip:getShieldMax(0) * 100))
else
msg = string.format(_("shipAssist-comms", "%s\n Shields: "),msg)
if shields == 2 then
msg = string.format(_("shipAssist-comms", "%sFront: %d%% Rear: %d%%"),msg, math.floor(fleetShip:getShieldLevel(0) / fleetShip:getShieldMax(0) * 100), math.floor(fleetShip:getShieldLevel(1) / fleetShip:getShieldMax(1) * 100))
else
for n=0,shields-1 do
msg = string.format(_("shipAssist-comms", "%s %d:%d%%"),msg, n, math.floor(fleetShip:getShieldLevel(n) / fleetShip:getShieldMax(n) * 100))
end
end
end
end
end
end
setCommsMessage(msg)
addCommsReply(_("Back"), return_function)
end)
addCommsReply(_("shipAssist-comms", "Report missile status"), function()
msg = string.format(_("shipAssist-comms", "Fleet %i missile status:"),comms_target.fleetIndex)
for idx, fleetShip in ipairs(npc_fleet[comms_target:getFaction()]) do
if fleetShip.fleetIndex == comms_target.fleetIndex then
if fleetShip ~= nil and fleetShip:isValid() then
msg = string.format(_("shipAssist-comms", "%s\n %s:"),msg, fleetShip:getCallSign())
local missile_types = {'Homing', 'Nuke', 'Mine', 'EMP', 'HVLI'}
missileMsg = ""
for idx2, missile_type in ipairs(missile_types) do
if fleetShip:getWeaponStorageMax(missile_type) > 0 then
missileMsg = string.format(_("shipAssist-comms", "%s\n %s: %d/%d"),missileMsg, missile_type, math.floor(fleetShip:getWeaponStorage(missile_type)), math.floor(fleetShip:getWeaponStorageMax(missile_type)))
end
end
if missileMsg ~= "" then
msg = string.format(_("shipAssist-comms", "%s\n Missiles: %s"),msg, missileMsg)
end
end
end
end
setCommsMessage(msg)
addCommsReply(_("Back"), return_function)
end)
addCommsReply(_("shipAssist-comms", "Assist me"), function()
for idx, fleetShip in ipairs(npc_fleet[comms_target:getFaction()]) do
if fleetShip.fleetIndex == comms_target.fleetIndex then
if fleetShip ~= nil and fleetShip:isValid() then
fleetShip:orderDefendTarget(comms_source)
end
end
end
setCommsMessage(string.format(_("shipAssist-comms", "Fleet %s heading toward you to assist"),comms_target.fleetIndex))
addCommsReply(_("Back"), return_function)
end)
addCommsReply(_("shipAssist-comms", "Defend a waypoint"), function()
if comms_source:getWaypointCount() == 0 then
setCommsMessage(_("shipAssist-comms", "No waypoints set. Please set a waypoint first."));
addCommsReply(_("Back"), return_function)
else
setCommsMessage(_("shipAssist-comms", "Which waypoint should we defend?"));
for n=1,comms_source:getWaypointCount() do
addCommsReply(string.format(_("shipAssist-comms", "Defend WP %d"), n), function()
for idx, fleetShip in ipairs(npc_fleet[comms_target:getFaction()]) do
if fleetShip.fleetIndex == comms_target.fleetIndex then
if fleetShip ~= nil and fleetShip:isValid() then
fleetShip:orderDefendLocation(comms_source:getWaypoint(n))
end
end
end
setCommsMessage(string.format(_("shipAssist-comms", "We are heading to assist at WP %d."), n));
addCommsReply(_("Back"), return_function)
end)
end
end
end)
addCommsReply(_("shipAssist-comms", "Go to waypoint. Attack enemies en route"), function()
if comms_source:getWaypointCount() == 0 then
setCommsMessage(_("shipAssist-comms", "No waypoints set. Please set a waypoint first."));
addCommsReply(_("Back"), return_function)
else
setCommsMessage(_("shipAssist-comms", "Which waypoint?"));
for n=1,comms_source:getWaypointCount() do
addCommsReply(string.format(_("shipAssist-comms", "Go to WP%d"),n), function()
for idx, fleetShip in ipairs(npc_fleet[comms_target:getFaction()]) do
if fleetShip.fleetIndex == comms_target.fleetIndex then
if fleetShip ~= nil and fleetShip:isValid() then
fleetShip:orderFlyTowards(comms_source:getWaypoint(n))
end
end
end
setCommsMessage(string.format(_("shipAssist-comms", "Going to WP%d, watching for enemies en route"), n));
addCommsReply(_("Back"), return_function)
end)
end
end
end)
addCommsReply(_("shipAssist-comms", "Go to waypoint. Ignore enemies"), function()
if comms_source:getWaypointCount() == 0 then
setCommsMessage(_("shipAssist-comms", "No waypoints set. Please set a waypoint first."));
addCommsReply(_("Back"), return_function)
else
setCommsMessage(_("shipAssist-comms", "Which waypoint?"));
for n=1,comms_source:getWaypointCount() do
addCommsReply(string.format(_("shipAssist-comms", "Go to WP%d"),n), function()
for idx, fleetShip in ipairs(npc_fleet[comms_target:getFaction()]) do
if fleetShip.fleetIndex == comms_target.fleetIndex then
if fleetShip ~= nil and fleetShip:isValid() then
fleetShip:orderFlyTowardsBlind(comms_source:getWaypoint(n))
end
end
end
setCommsMessage(string.format(_("shipAssist-comms", "Going to WP%d, ignoring enemies"), n));
addCommsReply(_("Back"), return_function)
end)
end
end
end)
addCommsReply(_("shipAssist-comms", "Go offensive, attack all enemy targets"), function()
for idx, fleetShip in ipairs(npc_fleet[comms_target:getFaction()]) do
if fleetShip.fleetIndex == comms_target.fleetIndex then
if fleetShip ~= nil and fleetShip:isValid() then
fleetShip:orderRoaming()
end
end
end
setCommsMessage(string.format(_("shipAssist-comms", "Fleet %s is on an offensive rampage"),comms_target.fleetIndex))
addCommsReply(_("Back"), return_function)
end)
addCommsReply(_("shipAssist-comms", "Stop and defend your current position"), function()
for idx, fleetShip in ipairs(npc_fleet[comms_target:getFaction()]) do
if fleetShip.fleetIndex == comms_target.fleetIndex then
fleetShip:orderStandGround()
end
end
setCommsMessage(_("shipAssist-comms", "Stopping and defending"))
addCommsReply(_("Back"), return_function)
end)
addCommsReply(_("shipAssist-comms", "Stop and do nothing"), function()
for idx, fleetShip in ipairs(npc_fleet[comms_target:getFaction()]) do
if fleetShip.fleetIndex == comms_target.fleetIndex then
fleetShip:orderIdle()
end
end
setCommsMessage(_("shipAssist-comms", "Stopping and doing nothing"))
addCommsReply(_("Back"), return_function)
end)
end)
end
end
function friendlyFreighterCommunication(return_function)
local shipType = comms_target:getTypeName()
if shipType:find("Freighter") ~= nil then
if distance(comms_source, comms_target) < 5000 then
if comms_target.comms_data.friendlyness > 66 then
if shipType:find("Goods") ~= nil or shipType:find("Equipment") ~= nil then
shipTradeGoods(return_function)
end --goods or equipment freighter
if comms_source.cargo > 0 then
shipBuyGoods(return_function,1)
end --player has cargo space branch
elseif comms_target.comms_data.friendlyness > 33 then
if comms_source.cargo > 0 then
if shipType:find("Goods") ~= nil or shipType:find("Equipment") ~= nil then
shipBuyGoods(return_function,1)
else --not goods or equipment freighter
shipBuyGoods(return_function,2)
end
end --player has room for cargo branch
else --least friendly
if comms_source.cargo > 0 then
if shipType:find("Goods") ~= nil or shipType:find("Equipment") ~= nil then
shipBuyGoods(return_function,2)
end --goods or equipment freighter
end --player has room to get goods
end --various friendliness choices
else --not close enough to sell
shipCargoSellReport(return_function)
end
end
end
function shipCargoSellReport(return_function)
addCommsReply(_("trade-comms", "Do you have cargo you might sell?"), function()
local goodCount = 0
local cargoMsg = _("trade-comms", "We've got ")
for good, goodData in pairs(comms_target.comms_data.goods) do
if goodData.quantity > 0 then
if goodCount > 0 then
cargoMsg = cargoMsg .. _("trade-comms",", ") .. good_desc[good]
else
cargoMsg = cargoMsg .. good_desc[good]
end
end
goodCount = goodCount + goodData.quantity
end
if goodCount == 0 then
cargoMsg = cargoMsg .. _("trade-comms", "nothing")
end
setCommsMessage(cargoMsg)
addCommsReply(_("Back"), return_function)
end)
end
function shipTradeGoods(return_function)
if comms_source.goods ~= nil and comms_source.goods.luxury ~= nil and comms_source.goods.luxury > 0 then
for good, goodData in pairs(comms_target.comms_data.goods) do
if goodData.quantity > 0 and good ~= "luxury" then
addCommsReply(string.format(_("trade-comms", "Trade luxury for %s"),good_desc[good]), function()
goodData.quantity = goodData.quantity - 1
if comms_source.goods == nil then
comms_source.goods = {}
end
if comms_source.goods[good] == nil then
comms_source.goods[good] = 0
end
comms_source.goods[good] = comms_source.goods[good] + 1
comms_source.goods.luxury = comms_source.goods.luxury - 1
setCommsMessage(string.format(_("trade-comms", "Traded your luxury for %s from %s"),good_desc[good],comms_target:getCallSign()))
addCommsReply(_("Back"), return_function)
end)
end
end --freighter goods loop
end --player has luxury branch
end
function shipBuyGoods(return_function,price_multiplier)
for good, goodData in pairs(comms_target.comms_data.goods) do
if goodData.quantity > 0 then
addCommsReply(string.format(_("trade-comms", "Buy one %s for %i reputation"),good_desc[good],math.floor(goodData.cost*price_multiplier)), function()
if comms_source:takeReputationPoints(goodData.cost*price_multiplier) then
goodData.quantity = goodData.quantity - 1
if comms_source.goods == nil then
comms_source.goods = {}
end
if comms_source.goods[good] == nil then
comms_source.goods[good] = 0
end
comms_source.goods[good] = comms_source.goods[good] + 1
comms_source.cargo = comms_source.cargo - 1
setCommsMessage(string.format(_("trade-comms", "Purchased %s from %s"),good_desc[good],comms_target:getCallSign()))
else
setCommsMessage(_("needRep-comms", "Insufficient reputation for purchase"))
end
addCommsReply(_("Back"), return_function)
end)
end
end --freighter goods loop
end
-------------------------------
-- Defend ship communication --
-------------------------------
function commsDefendShip()
if comms_target.comms_data == nil then
comms_target.comms_data = {friendlyness = random(0.0, 100.0)}
end
comms_data = comms_target.comms_data
if comms_source:isFriendly(comms_target) then
return friendlyDefendComms(comms_data)
end
if comms_source:isEnemy(comms_target) and comms_target:isFriendOrFoeIdentifiedBy(comms_source) then
return enemyDefendComms(comms_data)
end
return neutralDefendComms(comms_data)
end
function friendlyDefendComms(comms_data)
if comms_data.friendlyness < 20 then
setCommsMessage(_("shipAssist-comms", "What do you want?"));
else
setCommsMessage(_("shipAssist-comms", "Sir, how can we assist?"));
end
shipStatusReport(commsDefendShip)
return true
end
function enemyDefendComms(comms_data)
if comms_data.friendlyness > 50 then
local faction = comms_target:getFaction()
local taunt_option = _("shipEnemy-comms", "We will see to your destruction!")
local taunt_success_reply = _("shipEnemy-comms", "Your bloodline will end here!")
local taunt_failed_reply = _("shipEnemy-comms", "Your feeble threats are meaningless.")
if faction == "Kraylor" then
setCommsMessage(_("shipEnemy-comms", "Ktzzzsss.\nYou will DIEEee weaklingsss!"));
elseif faction == "Arlenians" then
setCommsMessage(_("shipEnemy-comms", "We wish you no harm, but will harm you if we must.\nEnd of transmission."));
elseif faction == "Exuari" then
setCommsMessage(_("shipEnemy-comms", "Stay out of our way, or your death will amuse us extremely!"));
elseif faction == "Ghosts" then
setCommsMessage(_("shipEnemy-comms", "One zero one.\nNo binary communication detected.\nSwitching to universal speech.\nGenerating appropriate response for target from human language archives.\n:Do not cross us:\nCommunication halted."));
taunt_option = _("shipEnemy-comms", "EXECUTE: SELFDESTRUCT")
taunt_success_reply = _("shipEnemy-comms", "Rogue command received. Targeting source.")
taunt_failed_reply = _("shipEnemy-comms", "External command ignored.")
elseif faction == "Ktlitans" then
setCommsMessage(_("shipEnemy-comms", "The hive suffers no threats. Opposition to any of us is opposition to us all.\nStand down or prepare to donate your corpses toward our nutrition."));
taunt_option = _("shipEnemy-comms", "<Transmit 'The Itsy-Bitsy Spider' on all wavelengths>")
taunt_success_reply = _("shipEnemy-comms", "We do not need permission to pluck apart such an insignificant threat.")
taunt_failed_reply = _("shipEnemy-comms", "The hive has greater priorities than exterminating pests.")
else
setCommsMessage(_("shipEnemy-comms", "Mind your own business!"));
end
comms_data.friendlyness = comms_data.friendlyness - random(0, 10)
addCommsReply(taunt_option, function()
if random(0, 100) < 30 then
comms_target:orderAttack(player)
setCommsMessage(taunt_success_reply);
else
setCommsMessage(taunt_failed_reply);
end
end)
return true
end
return false
end
function neutralDefendComms(comms_data)
if comms_data.friendlyness > 50 then
setCommsMessage(_("ship-comms", "Sorry, we have no time to chat with you.\nWe are on an important mission."));
else
setCommsMessage(_("ship-comms", "We have nothing for you.\nGood day."));
end
return true
end
function playerShipCargoInventory(p)
p:addToShipLog(string.format(_("inventory-shipLog", "%s Current cargo:"),p:getCallSign()),"Yellow")
local goodCount = 0
if p.goods ~= nil then
for good, goodQuantity in pairs(p.goods) do
goodCount = goodCount + 1
p:addToShipLog(string.format(_("inventory-shipLog", " %s: %i"),good_desc[good],goodQuantity),"Yellow")
end
end
if goodCount < 1 then
p:addToShipLog(_("inventory-shipLog", " Empty"),"Yellow")
end
p:addToShipLog(string.format(_("inventory-shipLog", "Available space: %i"),p.cargo),"Yellow")
end
function resetPreviousSystemHealth(p)
string.format("") --may need global context
if p == nil then
p = comms_source
end
local currentShield = 0
if p:getShieldCount() > 1 then
currentShield = (p:getSystemHealth("frontshield") + p:getSystemHealth("rearshield"))/2
else
currentShield = p:getSystemHealth("frontshield")
end
p.prevShield = currentShield
p.prevReactor = p:getSystemHealth("reactor")
p.prevManeuver = p:getSystemHealth("maneuver")
p.prevImpulse = p:getSystemHealth("impulse")
if p:getBeamWeaponRange(0) > 0 then
if p.healthyBeam == nil then
p.healthyBeam = 1.0
p.prevBeam = 1.0
end
p.prevBeam = p:getSystemHealth("beamweapons")
end
if p:getWeaponTubeCount() > 0 then
if p.healthyMissile == nil then
p.healthyMissile = 1.0
p.prevMissile = 1.0
end
p.prevMissile = p:getSystemHealth("missilesystem")
end
if p:hasWarpDrive() then
if p.healthyWarp == nil then
p.healthyWarp = 1.0
p.prevWarp = 1.0
end
p.prevWarp = p:getSystemHealth("warp")
end
if p:hasJumpDrive() then
if p.healthyJump == nil then
p.healthyJump = 1.0
p.prevJump = 1.0
end
p.prevJump = p:getSystemHealth("jumpdrive")
end
end
function gatherStats()
local stat_list = {}
stat_list.scenario = {name = "Chaos of War", version = scenario_version}
stat_list.times = {}
stat_list.times.game = {}
stat_list.times.stage = game_state
stat_list.times.game.max = max_game_time
stat_list.times.game.total_seconds_left = game_time_limit
stat_list.times.game.minutes_left = math.floor(game_time_limit / 60)
stat_list.times.game.seconds_left = math.floor(game_time_limit % 60)
stat_list.human = {}
stat_list.human.ship = {}
stat_list.human.ship_score_total = 0
stat_list.human.npc = {}
stat_list.human.npc_score_total = 0
stat_list.human.station_score_total = 0
stat_list.human.station = {}
stat_list.kraylor = {}
stat_list.kraylor.ship = {}
stat_list.kraylor.ship_score_total = 0
stat_list.kraylor.npc = {}
stat_list.kraylor.npc_score_total = 0
stat_list.kraylor.station_score_total = 0
stat_list.kraylor.station = {}
if exuari_angle ~= nil then
stat_list.exuari = {}
stat_list.exuari.ship = {}
stat_list.exuari.ship_score_total = 0
stat_list.exuari.npc = {}
stat_list.exuari.npc_score_total = 0
stat_list.exuari.station_score_total = 0
stat_list.exuari.station = {}
end
if ktlitan_angle ~= nil then
stat_list.ktlitan = {}
stat_list.ktlitan.ship = {}
stat_list.ktlitan.ship_score_total = 0
stat_list.ktlitan.npc = {}
stat_list.ktlitan.npc_score_total = 0
stat_list.ktlitan.station_score_total = 0
stat_list.ktlitan.station = {}
end
for pidx=1,32 do
p = getPlayerShip(pidx)
if p ~= nil then
if p:isValid() then
local faction = p:getFaction()
if p.shipScore ~= nil then
stat_list[f2s[faction]].ship_score_total = stat_list[f2s[faction]].ship_score_total + p.shipScore
stat_list[f2s[faction]].ship[p:getCallSign()] = {template_type = p:getTypeName(), is_alive = true, score_value = p.shipScore}
else
print("ship score for " .. p:getCallSign() .. " has not been set")
end
end
end
end
if npc_fleet ~= nil then
for faction, list in pairs(npc_fleet) do
for idx, ship in ipairs(list) do
if ship:isValid() then
stat_list[f2s[faction]].npc_score_total = stat_list[f2s[faction]].npc_score_total + ship.score_value
stat_list[f2s[faction]].npc[ship:getCallSign()] = {template_type = ship:getTypeName(), is_alive = true, score_value = ship.score_value}
end
end
end
end
if scientist_list ~= nil then
for faction, list in pairs(scientist_list) do
for idx, scientist in ipairs(list) do
if scientist.location:isValid() then
stat_list[f2s[faction]].npc_score_total = stat_list[f2s[faction]].npc_score_total + scientist.score_value
stat_list[f2s[faction]].npc[scientist.name] = {topic = scientist.topic, is_alive = true, score_value = scientist.score_value, location_name = scientist.location_name}
end
end
end
end
for faction, list in pairs(station_list) do
for idx, station in ipairs(list) do
if station:isValid() then
stat_list[f2s[faction]].station_score_total = stat_list[f2s[faction]].station_score_total + station.score_value
stat_list[f2s[faction]].station[station:getCallSign()] = {template_type = station:getTypeName(), is_alive = true, score_value = station.score_value}
end
end
end
local station_weight = .6
local player_ship_weight = .3
local npc_ship_weight = .1
stat_list.weight = {}
stat_list.weight.station = station_weight
stat_list.weight.ship = player_ship_weight
stat_list.weight.npc = npc_ship_weight
local human_death_penalty = 0
local kraylor_death_penalty = 0
local exuari_death_penalty = 0
local ktlitan_death_penalty = 0
if respawn_type == "self" then
human_death_penalty = death_penalty["Human Navy"]
stat_list.human.death_penalty = death_penalty["Human Navy"]
kraylor_death_penalty = death_penalty["Kraylor"]
stat_list.kraylor.death_penalty = death_penalty["Kraylor"]
if exuari_angle ~= nil then
exuari_death_penalty = death_penalty["Exuari"]
stat_list.exuari.death_penalty = death_penalty["Exuari"]
end
if ktlitan_angle ~= nil then
ktlitan_death_penalty = death_penalty["Ktlitans"]
stat_list.ktlitan.death_penalty = death_penalty["Ktlitans"]
end
end
stat_list.human.tie_breaker = 0
stat_list.kraylor.tie_breaker = 0
if exuari_angle ~= nil then
stat_list.exuari.tie_breaker = 0
end
if ktlitan_angle ~= nil then
stat_list.ktlitan.tie_breaker = 0
end
for i,p in ipairs(getActivePlayerShips()) do
if p:getFaction() == "Human Navy" then
stat_list.human.tie_breaker = p:getReputationPoints()/10000
stat_list.human.reputation = p:getReputationPoints()
end
if p:getFaction() == "Kraylor" then
stat_list.kraylor.tie_breaker = p:getReputationPoints()/10000
stat_list.kraylor.reputation = p:getReputationPoints()
end
if exuari_angle ~= nil then
if p:getFaction() == "Exuari" then
stat_list.exuari.tie_breaker = p:getReputationPoints()/10000
stat_list.exuari.reputation = p:getReputationPoints()
end
end
if ktlitan_angle ~= nil then
if p:getFaction() == "Ktlitans" then
stat_list.ktlitan.tie_breaker = p:getReputationPoints()/10000
stat_list.ktlitan.reputation = p:getReputationPoints()
end
end
end
stat_list.human.weighted_score =
stat_list.human.station_score_total*station_weight +
stat_list.human.ship_score_total*player_ship_weight +
stat_list.human.npc_score_total*npc_ship_weight -
human_death_penalty*player_ship_weight
stat_list.human.comprehensive_weighted_score =
stat_list.human.weighted_score +
stat_list.human.tie_breaker
stat_list.kraylor.weighted_score =
stat_list.kraylor.station_score_total*station_weight +
stat_list.kraylor.ship_score_total*player_ship_weight +
stat_list.kraylor.npc_score_total*npc_ship_weight -
kraylor_death_penalty*player_ship_weight
stat_list.kraylor.comprehensive_weighted_score =
stat_list.kraylor.weighted_score +
stat_list.kraylor.tie_breaker
if exuari_angle ~= nil then
stat_list.exuari.weighted_score =
stat_list.exuari.station_score_total*station_weight +
stat_list.exuari.ship_score_total*player_ship_weight +
stat_list.exuari.npc_score_total*npc_ship_weight -
exuari_death_penalty*player_ship_weight
stat_list.exuari.comprehensive_weighted_score =
stat_list.exuari.weighted_score +
stat_list.exuari.tie_breaker
end
if ktlitan_angle ~= nil then
stat_list.ktlitan.weighted_score =
stat_list.ktlitan.station_score_total*station_weight +
stat_list.ktlitan.ship_score_total*player_ship_weight +
stat_list.ktlitan.npc_score_total*npc_ship_weight -
ktlitan_death_penalty*player_ship_weight
stat_list.ktlitan.comprehensive_weighted_score =
stat_list.ktlitan.weighted_score +
stat_list.ktlitan.tie_breaker
end
if original_score ~= nil then
stat_list.human.original_weighted_score = original_score["Human Navy"]
stat_list.kraylor.original_weighted_score = original_score["Kraylor"]
if exuari_angle ~= nil then
stat_list.exuari.original_weighted_score = original_score["Exuari"]
end
if ktlitan_angle ~= nil then
stat_list.ktlitan.original_weighted_score = original_score["Ktlitans"]
end
end
return stat_list
end
function pickWinner(reason)
local stat_list = gatherStats()
local sorted_faction = {}
local tie_breaker = {}
for pidx=1,32 do
local p = getPlayerShip(pidx)
if p ~= nil and p:isValid() then
tie_breaker[p:getFaction()] = p:getReputationPoints()/10000
end
end
stat_list.human.comprehensive_weighted_score = stat_list.human.weighted_score + tie_breaker["Human Navy"]
table.insert(sorted_faction,{name="Human Navy",score=stat_list.human.comprehensive_weighted_score})
stat_list.kraylor.comprehensive_weighted_score = stat_list.kraylor.weighted_score + tie_breaker["Kraylor"]
table.insert(sorted_faction,{name="Kraylor",score=stat_list.kraylor.comprehensive_weighted_score})
if exuari_angle ~= nil then
stat_list.exuari.comprehensive_weighted_score = stat_list.exuari.weighted_score + tie_breaker["Exuari"]
table.insert(sorted_faction,{name="Exuari",score=stat_list.exuari.comprehensive_weighted_score})
end
if ktlitan_angle ~= nil then
stat_list.ktlitan.comprehensive_weighted_score = stat_list.ktlitan.weighted_score + tie_breaker["Ktlitans"]
table.insert(sorted_faction,{name="Ktlitans",score=stat_list.ktlitan.comprehensive_weighted_score})
end
table.sort(sorted_faction,function(a,b)
return a.score > b.score
end)
local out = string.format(_("msgMainscreen", "%s wins with a score of %f!\n"),sorted_faction[1].name,sorted_faction[1].score)
for i=2,#sorted_faction do
out = out .. string.format(_("msgMainscreen", "%s:%f "),sorted_faction[i].name,sorted_faction[i].score)
end
out = out .. "\n" .. reason
print(out)
print("Humans:",stat_list.human.comprehensive_weighted_score,string.format("%s + %s",stat_list.human.weighted_score,tie_breaker["Human Navy"]))
print("Kraylor:",stat_list.kraylor.comprehensive_weighted_score,string.format("%s + %s",stat_list.kraylor.weighted_score,tie_breaker["Kraylor"]))
if exuari_angle then
print("Exuari:",stat_list.exuari.comprehensive_weighted_score,string.format("%s + %s",stat_list.exuari.weighted_score,tie_breaker["Exuari"]))
end
if ktlitan_angle then
print("Ktlitans:",stat_list.ktlitan.comprehensive_weighted_score,string.format("%s + %s",stat_list.ktlitan.weighted_score,tie_breaker["Ktlitans"]))
end
addGMMessage(out)
globalMessage(out)
game_state = string.format("victory-%s",f2s[sorted_faction[1].name])
victory(sorted_faction[1].name)
end
function update(delta)
if delta == 0 then
--game paused
return
end
if respawn_countdown ~= nil then
respawn_countdown = respawn_countdown - delta
if respawn_countdown < 0 then
delayedRespawn()
end
end
if mainGMButtons == mainGMButtonsDuringPause then
mainGMButtons = mainGMButtonsAfterPause
mainGMButtons()
end
if not terrain_generated then
generateTerrain()
end
game_state = "running"
local stat_list = gatherStats()
if stat_list.human.weighted_score < original_score["Human Navy"]/2 then
pickWinner("End cause: Human Navy fell below 50% of original strength")
end
if stat_list.kraylor.weighted_score < original_score["Kraylor"]/2 then
pickWinner("End cause: Kraylor fell below 50% of original strength")
end
if exuari_angle ~= nil then
if stat_list.exuari.weighted_score < original_score["Exuari"]/2 then
pickWinner("End cause: Exuari fell below 50% of original strength")
end
end
if ktlitan_angle ~= nil then
if stat_list.ktlitan.weighted_score < original_score["Ktlitans"]/2 then
pickWinner("End cause: Ktlitans fell below 50% of original strength")
end
end
game_time_limit = game_time_limit - delta
if game_time_limit < 0 then
pickWinner("End cause: Time ran out")
end
local hrs = stat_list.human.weighted_score/original_score["Human Navy"]
local krs = stat_list.kraylor.weighted_score/original_score["Kraylor"]
local rel_dif = math.abs(hrs-krs)
if rel_dif > thresh then
if exuari_angle ~= nil then
ers = stat_list.exuari.weighted_score/original_score["Exuari"]
rel_dif = math.abs(hrs-ers)
local ref_dif_2 = math.abs(ers-krs)
if rel_dif > thresh or ref_dif_2 > thresh then
if ktlitan_angle ~= nil then
brs = stat_list.ktlitan.weighted_score/original_score["Ktlitans"]
rel_dif = math.abs(brs-ers)
ref_dif_2 = math.abs(brs-krs)
local rel_dif_3 = math.abs(hrs-brs)
if rel_dif > thresh or ref_dif_2 > thresh or rel_dif_3 > thresh then
pickWinner(string.format("End cause: score difference exceeded %i%%",thresh*100))
end
else
pickWinner(string.format("End cause: score difference exceeded %i%%",thresh*100))
end
end
else
pickWinner(string.format("End cause: score difference exceeded %i%%",thresh*100))
end
end
local score_banner = string.format(_("-tabRelay&Operations", "H:%i K:%i"),math.floor(stat_list.human.weighted_score),math.floor(stat_list.kraylor.weighted_score))
if exuari_angle ~= nil then
score_banner = string.format(_("-tabRelay&Operations", "%s E:%i"),score_banner,math.floor(stat_list.exuari.weighted_score))
end
if ktlitan_angle ~= nil then
score_banner = string.format(_("-tabRelay&Operations", "%s B:%i"),score_banner,math.floor(stat_list.ktlitan.weighted_score))
end
if game_time_limit > 60 then
score_banner = string.format(_("-tabRelay&Operations", "%s %i:%.2i"),score_banner,stat_list.times.game.minutes_left,stat_list.times.game.seconds_left)
else
score_banner = string.format(_("-tabRelay&Operations", "%s %i"),score_banner,stat_list.times.game.seconds_left)
end
if scientist_asset_message == nil then
scientist_asset_message = "sent"
if scientist_list ~= nil then
for pidx=1,32 do
local p = getPlayerShip(pidx)
if p ~= nil and p:isValid() then
if scientist_list[p:getFaction()] ~= nil then
if #scientist_list[p:getFaction()] > 1 then
p:addToShipLog("In addition to the stations and fleet assets, Command has deemed certain scientists as critical to the war effort. Loss of these scientists will count against you like the loss of stations and fleet assets will. Scientist list:","Magenta")
else
p:addToShipLog("In addition to the stations and fleet assets, Command has deemed this scientist as critical to the war effort. Loss of this scientist will count against you like the loss of stations and fleet assets will. Scientist:","Magenta")
end
for idx, scientist in ipairs(scientist_list[p:getFaction()]) do
p:addToShipLog(string.format("Value: %i, Name: %s, Specialization: %s, Location: %s",scientist.score_value,scientist.name,scientist.topic,scientist.location_name),"Magenta")
end
if #scientist_list[p:getFaction()] > 1 then
p:addToShipLog("These scientists will be weighted with the other NPC assets","Magenta")
else
p:addToShipLog("This scientist will be weighted with the other NPC assets","Magenta")
end
end
end
end
end
end
healthCheckTimer = healthCheckTimer - delta
local warning_message = nil
local warning_station = nil
local warning_message = {}
local warning_station = {}
for stn_faction, stn_list in pairs(station_list) do
for station_index=1,#stn_list do
local current_station = stn_list[station_index]
if current_station ~= nil and current_station:isValid() then
if current_station.proximity_warning == nil then
for idx, obj in ipairs(current_station:getObjectsInRange(station_sensor_range)) do
if obj ~= nil and obj:isValid() then
if obj:isEnemy(current_station) then
if isObjectType(obj,"PlayerSpaceship") then
warning_station[stn_faction] = current_station
warning_message[stn_faction] = string.format(_("helpfullWarning-shipLog", "[%s in %s] We detect one or more enemies nearby. At least one is of type %s"),current_station:getCallSign(),current_station:getSectorName(),obj:getTypeName())
current_station.proximity_warning = warning_message[stn_faction]
current_station.proximity_warning_timer = delta + 300
break
end
end
end
end
if warning_station[stn_faction] ~= nil then --was originally warning message
break
end
else
current_station.proximity_warning_timer = current_station.proximity_warning_timer - delta
if current_station.proximity_warning_timer < 0 then
current_station.proximity_warning = nil
end
end
if warning_station[stn_faction] == nil then
--shield damage warning
if current_station.shield_damage_warning == nil then
for i=1,current_station:getShieldCount() do
if current_station:getShieldLevel(i-1) < current_station:getShieldMax(i-1) then
warning_station[stn_faction] = current_station
warning_message[stn_faction] = string.format("[%s in %s] Our shields have taken damage",current_station:getCallSign(),current_station:getSectorName())
current_station.shield_damage_warning = warning_message[stn_faction]
current_station.shield_damage_warning_timer = delta + 300
break
end
end
if warning_station[stn_faction] ~= nil then
break
end
else
current_station.shield_damage_warning_timer = current_station.shield_damage_warning_timer - delta
if current_station.shield_damage_warning_timer < 0 then
current_station.shield_damage_warning = nil
end
end
end
if warning_station[stn_faction] == nil then
--severe shield damage warning
if current_station.severe_shield_warning == nil then
local current_station_shield_count = current_station:getShieldCount()
for i=1,current_station_shield_count do
if current_station:getShieldLevel(i-1) < current_station:getShieldMax(i-1)*.1 then
warning_station[stn_faction] = current_station
if current_station_shield_count == 1 then
warning_message[stn_faction] = string.format("[%s in %s] Our shields are nearly gone",current_station:getCallSign(),current_station:getSectorName())
else
warning_message[stn_faction] = string.format("[%s in %s] One or more of our shields are nearly gone",current_station:getCallSign(),current_station:getSectorName())
end
current_station.severe_shield_warning = warning_message[stn_faction]
current_station.severe_shield_warning_timer = delta + 300
break
end
end
if warning_station[stn_faction] ~= nil then
break
end
else
current_station.severe_shield_warning_timer = current_station.severe_shield_warning_timer - delta
if current_station.severe_shield_warning_timer < 0 then
current_station.severe_shield_warning = nil
end
end
end
if warning_station[stn_faction] == nil then
--hull damage warning
if current_station.hull_warning == nil then
if current_station:getHull() < current_station:getHullMax() then
warning_station[stn_faction] = current_station
warning_message[stn_faction] = string.format("[%s in %s] Our hull has been damaged",current_station:getCallSign(),current_station:getSectorName())
current_station.hull_warning = warning_message[stn_faction]
break
end
end
end
if warning_station[stn_faction] == nil then
--severe hull damage warning
if current_station.severe_hull_warning == nil then
if current_station:getHull() < current_station:getHullMax()*.1 then
warning_station[stn_faction] = current_station
warning_message[stn_faction] = string.format("[%s in %s] We are on the brink of destruction",current_station:getCallSign(),current_station:getSectorName())
current_station.severe_hull_warning = warning_message[stn_faction]
end
end
end
end -- current station not nil and is valid
end
end
for pidx=1,32 do
local p = getPlayerShip(pidx)
if p ~= nil and p:isValid() then
local player_name = p:getCallSign()
if advanced_intel then
if p.advance_intel_msg == nil then
local p_faction = p:getFaction()
local p_station = faction_primary_station[p_faction].station
for faction, p_s_info in pairs(faction_primary_station) do
if p_faction ~= faction then
p:addToShipLog(string.format("%s primary station %s is located in %s",faction,p_s_info.station:getCallSign(),p_s_info.station:getSectorName()),"Magenta")
end
end
p.advance_intel_msg = "sent"
end
end
if warning_station["Human Navy"] ~= nil and p:getFaction() == "Human Navy" then
p:addToShipLog(warning_message["Human Navy"],"Red")
end
if warning_station["Kraylor"] ~= nil and p:getFaction() == "Kraylor" then
p:addToShipLog(warning_message["Kraylor"],"Red")
end
if exuari_angle ~= nil then
if warning_station["Exuari"] ~= nil and p:getFaction() == "Exuari" then
p:addToShipLog(warning_message["Exuari"],"Red")
end
end
if ktlitan_angle ~= nil then
if warning_station["Ktlitans"] ~= nil and p:getFaction() == "Ktlitans" then
p:addToShipLog(warning_message["Ktlitans"],"Red")
end
end
local name_tag_text = string.format(_("-tabRelay&Ops&Helms&Tactical", "%s in %s"),player_name,p:getSectorName())
if p:hasPlayerAtPosition("Relay") then
p.name_tag = "name_tag"
p:addCustomInfo("Relay",p.name_tag,name_tag_text)
p.score_banner = "score_banner"
p:addCustomInfo("Relay",p.score_banner,score_banner)
end
if p:hasPlayerAtPosition("Operations") then
p.name_tag_ops = "name_tag_ops"
p:addCustomInfo("Operations",p.name_tag_ops,name_tag_text)
p.score_banner_ops = "score_banner_ops"
p:addCustomInfo("Operations",p.score_banner_ops,score_banner)
end
if p:hasPlayerAtPosition("ShipLog") then
p.name_tag_log = "name_tag_log"
p:addCustomInfo("ShipLog",p.name_tag_log,name_tag_text)
p.score_banner_log = "score_banner_log"
p:addCustomInfo("ShipLog",p.score_banner_log,score_banner)
end
if p:hasPlayerAtPosition("Helms") then
p.name_tag_helm = "name_tag_helm"
p:addCustomInfo("Helms",p.name_tag_helm,name_tag_text)
end
if p:hasPlayerAtPosition("Tactical") then
p.name_tag_tac = "name_tag_tac"
p:addCustomInfo("Tactical",p.name_tag_tac,name_tag_text)
end
if p.inventoryButton == nil then
local goodCount = 0
if p.goods ~= nil then
for good, goodQuantity in pairs(p.goods) do
goodCount = goodCount + 1
end
end
if goodCount > 0 then --add inventory button when cargo acquired
if p:hasPlayerAtPosition("Relay") then
if p.inventoryButton == nil then
local tbi = "inventory" .. player_name
p:addCustomButton("Relay",tbi,_("inventory-buttonRelay", "Inventory"),function () playerShipCargoInventory(p) end)
p.inventoryButton = true
end
end
if p:hasPlayerAtPosition("Operations") then
if p.inventoryButton == nil then
local tbi = "inventoryOp" .. player_name
p:addCustomButton("Operations",tbi,_("inventory-buttonOperations", "Inventory"), function () playerShipCargoInventory(p) end)
p.inventoryButton = true
end
end
end
end
if healthCheckTimer < 0 then --check to see if any crew perish (or other consequences) due to excessive damage
if p:getRepairCrewCount() > 0 then
local fatalityChance = 0
local currentShield = 0
if p:getShieldCount() > 1 then
currentShield = (p:getSystemHealth("frontshield") + p:getSystemHealth("rearshield"))/2
else
currentShield = p:getSystemHealth("frontshield")
end
fatalityChance = fatalityChance + (p.prevShield - currentShield)
p.prevShield = currentShield
local currentReactor = p:getSystemHealth("reactor")
fatalityChance = fatalityChance + (p.prevReactor - currentReactor)
p.prevReactor = currentReactor
local currentManeuver = p:getSystemHealth("maneuver")
fatalityChance = fatalityChance + (p.prevManeuver - currentManeuver)
p.prevManeuver = currentManeuver
local currentImpulse = p:getSystemHealth("impulse")
fatalityChance = fatalityChance + (p.prevImpulse - currentImpulse)
p.prevImpulse = currentImpulse
if p:getBeamWeaponRange(0) > 0 then
if p.healthyBeam == nil then
p.healthyBeam = 1.0
p.prevBeam = 1.0
end
local currentBeam = p:getSystemHealth("beamweapons")
fatalityChance = fatalityChance + (p.prevBeam - currentBeam)
p.prevBeam = currentBeam
end
if p:getWeaponTubeCount() > 0 then
if p.healthyMissile == nil then
p.healthyMissile = 1.0
p.prevMissile = 1.0
end
local currentMissile = p:getSystemHealth("missilesystem")
fatalityChance = fatalityChance + (p.prevMissile - currentMissile)
p.prevMissile = currentMissile
end
if p:hasWarpDrive() then
if p.healthyWarp == nil then
p.healthyWarp = 1.0
p.prevWarp = 1.0
end
local currentWarp = p:getSystemHealth("warp")
fatalityChance = fatalityChance + (p.prevWarp - currentWarp)
p.prevWarp = currentWarp
end
if p:hasJumpDrive() then
if p.healthyJump == nil then
p.healthyJump = 1.0
p.prevJump = 1.0
end
local currentJump = p:getSystemHealth("jumpdrive")
fatalityChance = fatalityChance + (p.prevJump - currentJump)
p.prevJump = currentJump
end
if p:getRepairCrewCount() == 1 then
fatalityChance = fatalityChance/2 -- increase survival chances of last repair crew standing
end
if fatalityChance > 0 then
if math.random() < (fatalityChance) then
if p.initialCoolant == nil then
p:setRepairCrewCount(p:getRepairCrewCount() - 1)
if p:hasPlayerAtPosition("Engineering") then
local repairCrewFatality = "repairCrewFatality"
p:addCustomMessage("Engineering",repairCrewFatality,_("repairCrew-msgEngineer", "One of your repair crew has perished"))
end
if p:hasPlayerAtPosition("Engineering+") then
local repairCrewFatalityPlus = "repairCrewFatalityPlus"
p:addCustomMessage("Engineering+",repairCrewFatalityPlus,_("repairCrew-msgEngineer+", "One of your repair crew has perished"))
end
else
local consequence = 0
local upper_consequence = 2
local consequence_list = {}
if p:getCanLaunchProbe() then
upper_consequence = upper_consequence + 1
table.insert(consequence_list,"probe")
end
if p:getCanHack() then
upper_consequence = upper_consequence + 1
table.insert(consequence_list,"hack")
end
if p:getCanScan() then
upper_consequence = upper_consequence + 1
table.insert(consequence_list,"scan")
end
if p:getCanCombatManeuver() then
upper_consequence = upper_consequence + 1
table.insert(consequence_list,"combat_maneuver")
end
if p:getCanSelfDestruct() then
upper_consequence = upper_consequence + 1
table.insert(consequence_list,"self_destruct")
end
if p:getWeaponTubeCount() > 0 then
upper_consequence = upper_consequence + 1
table.insert(consequence_list,"tube_time")
end
consequence = math.random(1,upper_consequence)
if consequence == 1 then
p:setRepairCrewCount(p:getRepairCrewCount() - 1)
if p:hasPlayerAtPosition("Engineering") then
local repairCrewFatality = "repairCrewFatality"
p:addCustomMessage("Engineering",repairCrewFatality,_("repairCrew-msgEngineer", "One of your repair crew has perished"))
end
if p:hasPlayerAtPosition("Engineering+") then
local repairCrewFatalityPlus = "repairCrewFatalityPlus"
p:addCustomMessage("Engineering+",repairCrewFatalityPlus,_("repairCrew-msgEngineer+", "One of your repair crew has perished"))
end
elseif consequence == 2 then
local current_coolant = p:getMaxCoolant()
local lost_coolant = 0
if current_coolant >= 10 then
lost_coolant = current_coolant*random(.25,.5) --lose between 25 and 50 percent
else
lost_coolant = current_coolant*random(.15,.35) --lose between 15 and 35 percent
end
p:setMaxCoolant(current_coolant - lost_coolant)
if p.reclaimable_coolant == nil then
p.reclaimable_coolant = 0
end
p.reclaimable_coolant = math.min(20,p.reclaimable_coolant + lost_coolant*random(.8,1))
if p:hasPlayerAtPosition("Engineering") then
local coolantLoss = "coolantLoss"
p:addCustomMessage("Engineering",coolantLoss,_("coolant-msgEngineer", "Damage has caused a loss of coolant"))
end
if p:hasPlayerAtPosition("Engineering+") then
local coolantLossPlus = "coolantLossPlus"
p:addCustomMessage("Engineering+",coolantLossPlus,_("coolant-msgEngineer+", "Damage has caused a loss of coolant"))
end
else
local named_consequence = consequence_list[consequence-2]
if named_consequence == "probe" then
p:setCanLaunchProbe(false)
if p:hasPlayerAtPosition("Engineering") then
p:addCustomMessage("Engineering","probe_launch_damage_message",_("damage-msgEngineer", "The probe launch system has been damaged"))
end
if p:hasPlayerAtPosition("Engineering+") then
p:addCustomMessage("Engineering+","probe_launch_damage_message_plus",_("damage-msgEngineer+", "The probe launch system has been damaged"))
end
elseif named_consequence == "hack" then
p:setCanHack(false)
if p:hasPlayerAtPosition("Engineering") then
p:addCustomMessage("Engineering","hack_damage_message",_("damage-msgEngineer", "The hacking system has been damaged"))
end
if p:hasPlayerAtPosition("Engineering+") then
p:addCustomMessage("Engineering+","hack_damage_message_plus",_("damage-msgEngineer+", "The hacking system has been damaged"))
end
elseif named_consequence == "scan" then
p:setCanScan(false)
if p:hasPlayerAtPosition("Engineering") then
p:addCustomMessage("Engineering","scan_damage_message",_("damage-msgEngineer", "The scanners have been damaged"))
end
if p:hasPlayerAtPosition("Engineering+") then
p:addCustomMessage("Engineering+","scan_damage_message_plus",_("damage-msgEngineer+", "The scanners have been damaged"))
end
elseif named_consequence == "combat_maneuver" then
p:setCanCombatManeuver(false)
if p:hasPlayerAtPosition("Engineering") then
p:addCustomMessage("Engineering","combat_maneuver_damage_message",_("damage-msgEngineer", "Combat maneuver has been damaged"))
end
if p:hasPlayerAtPosition("Engineering+") then
p:addCustomMessage("Engineering+","combat_maneuver_damage_message_plus",_("damage-msgEngineer+", "Combat maneuver has been damaged"))
end
elseif named_consequence == "self_destruct" then
p:setCanSelfDestruct(false)
if p:hasPlayerAtPosition("Engineering") then
p:addCustomMessage("Engineering","self_destruct_damage_message",_("damage-msgEngineer", "Self destruct system has been damaged"))
end
if p:hasPlayerAtPosition("Engineering+") then
p:addCustomMessage("Engineering+","self_destruct_damage_message_plus",_("damage-msgEngineer+", "Self destruct system has been damaged"))
end
elseif named_consequence == "tube_time" then
local tube_count = p:getWeaponTubeCount()
local tube_index = 0
if p.normal_tube_load_time == nil then
p.normal_tube_load_time = {}
repeat
p.normal_tube_load_time[tube_index] = p:getTubeLoadTime(tube_index)
tube_index = tube_index + 1
until(tube_index >= tube_count)
tube_index = 0
end
repeat
p:setTubeLoadTime(tube_index,p:getTubeLoadTime(tube_index) + 2)
tube_index = tube_index + 1
until(tube_index >= tube_count)
if p:hasPlayerAtPosition("Engineering") then
p:addCustomMessage("Engineering","tube_slow_down_message",_("damage-msgEngineer", "Tube damage has caused tube load time to increase"))
end
if p:hasPlayerAtPosition("Engineering+") then
p:addCustomMessage("Engineering+","tube_slow_down_message_plus",_("damage-msgEngineer+", "Tube damage has caused tube load time to increase"))
end
end
end --coolant loss branch
end --could lose coolant branch
end --bad consequences of damage branch
end --possible chance of bad consequences branch
else --no repair crew left
if random(1,100) <= 4 then
p:setRepairCrewCount(1)
if p:hasPlayerAtPosition("Engineering") then
local repairCrewRecovery = "repairCrewRecovery"
p:addCustomMessage("Engineering",repairCrewRecovery,_("repairCrew-msgEngineer", "Medical team has revived one of your repair crew"))
end
if p:hasPlayerAtPosition("Engineering+") then
local repairCrewRecoveryPlus = "repairCrewRecoveryPlus"
p:addCustomMessage("Engineering+",repairCrewRecoveryPlus,_("repairCrew-msgEngineer+", "Medical team has revived one of your repair crew"))
end
resetPreviousSystemHealth(p)
end --medical science triumph branch
end --no repair crew left
if p.initialCoolant ~= nil then
current_coolant = p:getMaxCoolant()
if current_coolant < 20 then
if random(1,100) <= 4 then
local reclaimed_coolant = 0
if p.reclaimable_coolant ~= nil and p.reclaimable_coolant > 0 then
reclaimed_coolant = p.reclaimable_coolant*random(.1,.5) --get back 10 to 50 percent of reclaimable coolant
p:setMaxCoolant(math.min(20,current_coolant + reclaimed_coolant))
p.reclaimable_coolant = p.reclaimable_coolant - reclaimed_coolant
end
local noticable_reclaimed_coolant = math.floor(reclaimed_coolant)
if noticable_reclaimed_coolant > 0 then
if p:hasPlayerAtPosition("Engineering") then
local coolant_recovery = "coolant_recovery"
p:addCustomMessage("Engineering",coolant_recovery,_("coolant-msgEngineer", "Automated systems have recovered some coolant"))
end
if p:hasPlayerAtPosition("Engineering+") then
local coolant_recovery_plus = "coolant_recovery_plus"
p:addCustomMessage("Engineering+",coolant_recovery_plus,_("coolant-msgEngineer+", "Automated systems have recovered some coolant"))
end
end
resetPreviousSystemHealth(p)
end
end
end
end --health check branch
local secondary_systems_optimal = true
if not p:getCanLaunchProbe() then
secondary_systems_optimal = false
end
if secondary_systems_optimal and not p:getCanHack() then
secondary_systems_optimal = false
end
if secondary_systems_optimal and not p:getCanScan() then
secondary_systems_optimal = false
end
if secondary_systems_optimal and not p:getCanCombatManeuver() then
secondary_systems_optimal = false
end
if secondary_systems_optimal and not p:getCanSelfDestruct() then
secondary_systems_optimal = false
end
if secondary_systems_optimal then
local tube_count = p:getWeaponTubeCount()
if tube_count > 0 and p.normal_tube_load_time ~= nil then
local tube_index = 0
repeat
if p.normal_tube_load_time[tube_index] < p:getTubeLoadTime(tube_index) then
secondary_systems_optimal = false
break
end
tube_index = tube_index + 1
until(tube_index >= tube_count)
end
end
if secondary_systems_optimal then --remove damage report button
if p.damage_report ~= nil then
p:removeCustom(p.damage_report)
p.damage_report = nil
end
if p.damage_report_plus ~= nil then
p:removeCustom(p.damage_report_plus)
p.damage_report_plus = nil
end
else --add damage report button
if p:hasPlayerAtPosition("Engineering") then
p.damage_report = "damage_report"
p:addCustomButton("Engineering",p.damage_report,_("-buttonEngineer", "Damage Report"),function()
local dmg_msg = "In addition to the primary systems constantly monitored in engineering, the following secondary systems have also been damaged requiring docking repair facilities:"
if not p:getCanLaunchProbe() then
dmg_msg = dmg_msg .. "\nProbe launch system"
end
if not p:getCanHack() then
dmg_msg = dmg_msg .. "\nHacking system"
end
if not p:getCanScan() then
dmg_msg = dmg_msg .. "\nScanning system"
end
if not p:getCanCombatManeuver() then
dmg_msg = dmg_msg .. "\nCombat maneuvering system"
end
if not p:getCanSelfDestruct() then
dmg_msg = dmg_msg .. "\nSelf destruct system"
end
local tube_count = p:getWeaponTubeCount()
if tube_count > 0 then
if tube_count > 0 and p.normal_tube_load_time ~= nil then
local tube_index = 0
repeat
if p.normal_tube_load_time[tube_index] < p:getTubeLoadTime(tube_index) then
dmg_msg = dmg_msg .. _("damage-msgEngineer", "\nWeapon tube load time degraded")
break
end
tube_index = tube_index + 1
until(tube_index >= tube_count)
end
end
p.dmg_msg = "dmg_msg"
p:addCustomMessage("Engineering",p.dmg_msg,dmg_msg)
end)
end --engineering damage report button
if p:hasPlayerAtPosition("Engineering+") then
p.damage_report_plus = "damage_report_plus"
p:addCustomButton("Engineering",p.damage_report_plus,_("damage-buttonEngineer", "Damage Report"),function()
local dmg_msg = "In addition to the primary systems constantly monitored in engineering, the following secondary systems have also been damaged requiring docking repair facilities:"
if not p:getCanLaunchProbe() then
dmg_msg = dmg_msg .. "\nProbe launch system"
end
if not p:getCanHack() then
dmg_msg = dmg_msg .. "\nHacking system"
end
if not p:getCanScan() then
dmg_msg = dmg_msg .. "\nScanning system"
end
if not p:getCanCombatManeuver() then
dmg_msg = dmg_msg .. "\nCombat maneuvering system"
end
if not p:getCanSelfDestruct() then
dmg_msg = dmg_msg .. "\nSelf destruct system"
end
local tube_count = p:getWeaponTubeCount()
if tube_count > 0 then
if tube_count > 0 and p.normal_tube_load_time ~= nil then
local tube_index = 0
repeat
if p.normal_tube_load_time[tube_index] < p:getTubeLoadTime(tube_index) then
dmg_msg = dmg_msg .. _("damage-msgEngineer+", "\nWeapon tube load time degraded")
break
end
tube_index = tube_index + 1
until(tube_index >= tube_count)
end
end
p.dmg_msg = "dmg_msg"
p:addCustomMessage("Engineering+",p.dmg_msg,dmg_msg)
end)
end --engineering plus damage report button
end --damage report button necessary
if p.normal_long_range_radar == nil then
p.normal_long_range_radar = p:getLongRangeRadarRange()
end
local sensor_boost_amount = 0
local sensor_boost_present = false
if station_primary_human:isValid() then
if p:isDocked(station_primary_human) then
sensor_boost_present = true
sensor_boost_amount = station_primary_human.comms_data.sensor_boost.value
end
end
if station_primary_kraylor:isValid() then
if p:isDocked(station_primary_kraylor) then
sensor_boost_present = true
sensor_boost_amount = station_primary_kraylor.comms_data.sensor_boost.value
end
end
if exuari_angle ~= nil then
if station_primary_exuari:isValid() then
if p:isDocked(station_primary_exuari) then
sensor_boost_present = true
sensor_boost_amount = station_primary_exuari.comms_data.sensor_boost.value
end
end
end
if ktlitan_angle ~= nil then
if station_primary_ktlitan:isValid() then
if p:isDocked(station_primary_ktlitan) then
sensor_boost_present = true
sensor_boost_amount = station_primary_ktlitan.comms_data.sensor_boost.value
end
end
end
local boosted_range = p.normal_long_range_radar + sensor_boost_amount
if sensor_boost_present then
if p:getLongRangeRadarRange() < boosted_range then
p:setLongRangeRadarRange(boosted_range)
end
else
if p:getLongRangeRadarRange() > p.normal_long_range_radar then
p:setLongRangeRadarRange(p.normal_long_range_radar)
end
end
end --p is not nil and is valid
end --loop through players
end
| 0 | 0.69492 | 1 | 0.69492 | game-dev | MEDIA | 0.94339 | game-dev | 0.689594 | 1 | 0.689594 |
evido/wotreplay-parser | 2,209 | data/maps/definitions/95_lost_city_ctf.xml | <95_lost_city_ctf.xml><name>#arenas:95_lost_city_ctf/name</name><description>#arenas:95_lost_city_ctf/description</description><geometry>spaces/95_lost_city_ctf</geometry><estimatedLoad>0.3</estimatedLoad><roundLength>900</roundLength><boundingBox><bottomLeft>-500.000000 -500.000000</bottomLeft><upperRight>500.000000 500.000000</upperRight></boundingBox><minimap>spaces/95_lost_city_ctf/mmap.dds</minimap><vehicleCamouflageKind>desert</vehicleCamouflageKind><umbraEnabled>1</umbraEnabled><wwmusicSetup><wwmusicLoading>music_lost_city_loading_screen</wwmusicLoading><wwmusicIntensive>music_lost_city_dron_intensive</wwmusicIntensive><wwmusicRelaxed>music_lost_city_dron_relaxed</wwmusicRelaxed><wwmusicStop>music_dron_stop</wwmusicStop><wwmusicEndbattleStop>music_dron_endbattle_stop</wwmusicEndbattleStop><wwmusicResultWin>music_lost_city_result_win</wwmusicResultWin><wwmusicResultDrawn>music_lost_city_result_drawn</wwmusicResultDrawn><wwmusicResultDefeat>music_lost_city_result_defeat</wwmusicResultDefeat></wwmusicSetup><wwambientSound>amb_map_95_wind</wwambientSound><water><texScale>0</texScale><freqX>0</freqX><freqZ>0</freqZ></water><gameplayTypes><ctf><teamBasePositions><team1><position1>0.000000 -350.000000</position1></team1><team2><position1>-0.000023 350.000000</position1></team2></teamBasePositions></ctf><domination><teamSpawnPoints><team1><position>350 -450</position></team1><team2><position>350 450</position></team2></teamSpawnPoints><controlPoint>-0.000069 0.000015</controlPoint></domination><assault><winnerIfTimeout>1</winnerIfTimeout><teamSpawnPoints><team1><position>380 0</position></team1><team2><position>-410 0</position></team2></teamSpawnPoints><teamBasePositions><team1><position1>191.677200 0.737327</position1></team1></teamBasePositions></assault><assault2><winnerIfTimeout>1</winnerIfTimeout><winnerIfExtermination>1</winnerIfExtermination><teamSpawnPoints><team1><position>-315.682 121.161</position></team1><team2><position>315.682 -121.161</position></team2></teamSpawnPoints><teamBasePositions><team1><position1>53.463390 292.177000</position1><position2>-0.000015 0.000000</position2></team1></teamBasePositions></assault2></gameplayTypes></95_lost_city_ctf.xml>
| 0 | 0.597153 | 1 | 0.597153 | game-dev | MEDIA | 0.986577 | game-dev | 0.585192 | 1 | 0.585192 |
pawn-lang/YSI-Includes | 9,700 | YSI_Players/y_text/y_text_entry.inc | #if defined _INC_y_text
#endinput
#endif
#define _INC_y_text
/*
Legal:
Version: MPL 1.1
The contents of this file are subject to the Mozilla Public License Version
1.1 the "License"; you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the
License.
The Original Code is the YSI framework.
The Initial Developer of the Original Code is Alex "Y_Less" Cole.
Portions created by the Initial Developer are Copyright (c) 2022
the Initial Developer. All Rights Reserved.
Contributors:
Y_Less
koolk
JoeBullet/Google63
g_aSlice/Slice
Misiur
samphunter
tianmeta
maddinat0r
spacemud
Crayder
Dayvison
Ahmad45123
Zeex
irinel1996
Yiin-
Chaprnks
Konstantinos
Masterchen09
Southclaws
PatchwerkQWER
m0k1
paulommu
udan111
Cheaterman
Thanks:
JoeBullet/Google63 - Handy arbitrary ASM jump code using SCTRL.
ZeeX - Very productive conversations.
koolk - IsPlayerinAreaEx code.
TheAlpha - Danish translation.
breadfish - German translation.
Fireburn - Dutch translation.
yom - French translation.
50p - Polish translation.
Zamaroht - Spanish translation.
Los - Portuguese translation.
Dracoblue, sintax, mabako, Xtreme, other coders - Producing other modes for
me to strive to better.
Pixels^ - Running XScripters where the idea was born.
Matite - Pestering me to release it and using it.
Very special thanks to:
Thiadmer - PAWN, whose limits continue to amaze me!
Kye/Kalcor - SA:MP.
SA:MP Team past, present and future - SA:MP.
Optional plugins:
Gamer_Z - GPS.
Incognito - Streamer.
Me - sscanf2, fixes2, Whirlpool.
*/
#if defined YSI_TESTS
// Fake `IsPlayerConnected`.
#define _YSI_SPECIAL_DEBUG
#endif
#include "..\..\YSI_Core\y_utils"
// Make sure this is included early.
#include "..\..\YSI_Data\y_playerset"
// Apparently I'd already written the internal code to support this and forgot!
#define Y_TEXT_UNIQUE
#if !defined Y_TEXT_MAX_SETS
#define Y_TEXT_MAX_SETS (16)
#endif
#if !defined Y_TEXT_PER_SET
#define Y_TEXT_PER_SET (64)
#endif
#if !defined MAX_TEXT_ENTRIES
#define MAX_TEXT_ENTRIES (Y_TEXT_PER_SET * Y_TEXT_MAX_SETS)
#endif
#if defined YSI_TESTS
#define MAX_Y_TEXT_TEST_LINES (10)
#define MAX_Y_TEXT_TEST_LENGTH (1024)
// These mocks DO NOT use ALS or stock, so that we get compile-time warnings
// about anything that may interfere. Tests shouldn't really be run on a
// full mode with all other things (unless you are doing integration tests),
// so the warnings are appropriate.
new
YSI_gTextTestPlayer[MAX_Y_TEXT_TEST_LINES],
YSI_gTextTestStyle[MAX_Y_TEXT_TEST_LINES],
YSI_gTextTestTime[MAX_Y_TEXT_TEST_LINES],
YSI_gTextTestOutput[MAX_Y_TEXT_TEST_LINES][MAX_Y_TEXT_TEST_LENGTH],
YSI_gTextTest;
// Hook SA:MP natives, so that calls to print functions are routed to us
// instead. "TxT" = "TextTest".
TxT_SendClientMessage(playerid, color, const message[])
{
YSI_gTextTestPlayer[YSI_gTextTest] = playerid,
YSI_gTextTestStyle[YSI_gTextTest] = color,
StrCpy(YSI_gTextTestOutput[YSI_gTextTest], message),
++YSI_gTextTest;
}
#define SendClientMessage TxT_SendClientMessage
TxT_SendPlayerMessageToPlayer(playerid, senderid, const message[])
{
YSI_gTextTestPlayer[YSI_gTextTest] = playerid,
YSI_gTextTestStyle[YSI_gTextTest] = senderid,
StrCpy(YSI_gTextTestOutput[YSI_gTextTest], message),
++YSI_gTextTest;
}
#define SendPlayerMessageToPlayer TxT_SendPlayerMessageToPlayer
TxT_GameTextForPlayer(playerid, const string[], time, style)
{
YSI_gTextTestPlayer[YSI_gTextTest] = playerid,
YSI_gTextTestStyle[YSI_gTextTest] = style,
YSI_gTextTestTime[YSI_gTextTest] = time,
StrCpy(YSI_gTextTestOutput[YSI_gTextTest], string),
++YSI_gTextTest;
}
#define GameTextForPlayer TxT_GameTextForPlayer
TextTest_Reset()
{
for (new i = 0; i != MAX_Y_TEXT_TEST_LINES; ++i)
{
YSI_gTextTestPlayer[i] = cellmin,
YSI_gTextTestStyle[i] = cellmin,
YSI_gTextTestTime[i] = cellmin,
YSI_gTextTestOutput[i][0] = '\0';
}
YSI_gTextTest = 0;
}
// TODO: TextDraw hooks.
#endif
#include "..\..\YSI_Storage\y_xml"
#include "..\..\YSI_Server\y_td"
#include "..\..\YSI_Server\y_colours"
#include "y_text_styles"
// This is a horribly eclectic collection of libraries from all over the place
// and written at different times with different aims - frankly I'll be AMAZED
// if it all comes together and works.
//
// 2017: I'm still amazed it works!
//
// 2018: Collating core includes, hopefully will still work.
#if !defined MAX_PLAYER_NAME
#define MAX_PLAYER_NAME 24
#elseif MAX_PLAYER_NAME != (24)
#error Unknown MAX_PLAYER_NAME size.
#else
// Strip the brackets off.
#undef MAX_PLAYER_NAME
#define MAX_PLAYER_NAME 24
#endif
//#include <a_samp>
#include "..\..\YSI_Server\y_colours"
#include "..\..\YSI_Data\y_hashmap"
#include "..\..\YSI_Data\y_jaggedarray"
#include "y_text_load"
#include "..\..\YSI_Coding\y_va"
#include "y_text_render"
#include "..\..\YSI_Storage\y_ini"
#include "..\..\YSI_Data\y_iterate"
#include "..\..\YSI_Players\y_languages"
#include "..\..\YSI_Visual\y_dialog"
#include "..\..\YSI_Coding\y_inline"
#include "..\..\YSI_Coding\y_hooks"
#include "y_text_impl"
#define UNDO_MOVE|||
#define DO_MOVE|||%0``` %0DO_MOVE|||
#define Text_Send(%0,%1) PSF:_Text_Send(%0,DO_TEXT_SET:%1 UNDO_MOVE|||)
#define Text_Render(%0,%1) _Text_Render(%0,DO_TEXT_SET:%1 UNDO_MOVE|||)
#define Text_Format(%0,%1,%2,%3,%4) _Text_Format(%0,%1,%2,%3,DO_TEXT_SET:%4 UNDO_MOVE|||)
#define Text_Format_GT_0(%0,%1,%2,%3) Text_Format(%0,%1,%2, e_STYLE_TYPE_GT_0,%3)
#define Text_Format_GT_1(%0,%1,%2,%3) Text_Format(%0,%1,%2, e_STYLE_TYPE_GT_1,%3)
#define Text_Format_GT_2(%0,%1,%2,%3) Text_Format(%0,%1,%2, e_STYLE_TYPE_GT_2,%3)
#define Text_Format_GT_3(%0,%1,%2,%3) Text_Format(%0,%1,%2, e_STYLE_TYPE_GT_3,%3)
#define Text_Format_GT_4(%0,%1,%2,%3) Text_Format(%0,%1,%2, e_STYLE_TYPE_GT_4,%3)
#define Text_Format_GT_5(%0,%1,%2,%3) Text_Format(%0,%1,%2, e_STYLE_TYPE_GT_5,%3)
#define Text_Format_GT_6(%0,%1,%2,%3) Text_Format(%0,%1,%2, e_STYLE_TYPE_GT_6,%3)
#define Text_Format_TD(%0,%1,%2,%3) Text_Format(%0,%1,%2, e_STYLE_TYPE_TD,%3)
#define Text_Format_3D(%0,%1,%2,%3 Text_Format(%0,%1,%2, e_STYLE_TYPE_3D,%3)
#define Text_Format_Client(%0,%1,%2,%3) Text_Format(%0,%1,%2, e_STYLE_TYPE_CLIENT,%3)
#define Text_Format_Player(%0,%1,%2,%3) Text_Format(%0,%1,%2, e_STYLE_TYPE_PLAYER,%3)
#define Text_Format_Other(%0,%1,%2,%3) Text_Format(%0,%1,%2, e_STYLE_TYPE_OTHER,%3)
#define Text_Format_Dialog(%0,%1,%2,%3) Text_Format(%0,%1,%2, e_STYLE_TYPE_DIALOG,%3)
//#define _Text_Send(%0YCMD:%1) _Text_Send(%0_:YCMD_REP_0:YCMD_REP_1:%1)
//#define YCMD_REP_0:YCMD_REP_1:%0, Command_GetID(%0),
//#define YCMD_REP_1:%0) Command_GetID(%0))
// This code allows "DEFAULT_TEXT_SET" to propogate through the text one section
// at a time without detecting later matches too early. The design of "DO_MOVE"
// and "UNDO_MOVE" means that the compiler will correctly detect the end of the
// code, regardless of the length, and end.
#define Text_MessageBox(%0,%1,%2,%3,%4,%5) PSF:_Text_DialogBox(%0,DIALOG_STYLE_MSGBOX,%1,DO_TEXT_SET:%2 DO_MOVE|||,DO_TEXT_SET:%3 ```,DO_TEXT_SET:%4 ```,DO_TEXT_SET:%5 UN```)
#define Text_InputBox(%0,%1,%2,%3,%4,%5) PSF:_Text_DialogBox(%0,DIALOG_STYLE_INPUT,%1,DO_TEXT_SET:%2 DO_MOVE|||,DO_TEXT_SET:%3 ```,DO_TEXT_SET:%4 ```,DO_TEXT_SET:%5 UN```)
#define Text_ListBox(%0,%1,%2,%3,%4,%5) PSF:_Text_DialogBox(%0,DIALOG_STYLE_LIST,%1,DO_TEXT_SET:%2 DO_MOVE|||,DO_TEXT_SET:%3 ```,DO_TEXT_SET:%4 ```,DO_TEXT_SET:%5 UN```)
#define Text_PasswordBox(%0,%1,%2,%3,%4,%5) PSF:_Text_DialogBox(%0,DIALOG_STYLE_PASSWORD,%1,DO_TEXT_SET:%2 DO_MOVE|||,DO_TEXT_SET:%3 ```,DO_TEXT_SET:%4 ```,DO_TEXT_SET:%5 UN```)
#define Text_DialogBox(%0,%9,%1,%2,%3,%4,%5) PSF:_Text_DialogBox(%0,%9,%1,DO_TEXT_SET:%2 DO_MOVE|||,DO_TEXT_SET:%3 ```,DO_TEXT_SET:%4 ```,DO_TEXT_SET:%5 UN```)
//#define Text_MessageBox(%0,%1,%2,%3) PSF:_Text_MessageBox(%0,%1,DEFAULT_TEXT_SET,#%2 DO_MOVE|||,DEFAULT_TEXT_SET,#%3 $$$,DEFAULT_TEXT_SET,#%4 $$$,DEFAULT_TEXT_SET,#%5 UN$$$)
//#define _Text_MessageBox(%0YCMD:%1) _Text_MessageBox(%0_:YCMD_REP_0:YCMD_REP_1:%1)
//stock Text_GetAllIDs(
static stock
YSI_g_sFormat[1024],
YSI_g_sTemp[1024];
stock Text_FormatEx(output[], len, const format[], GLOBAL_TAG_TYPES:...)
{
// "Format_Standardise" modifies "input" repeatedly.
StrCpy(YSI_g_sFormat, format);
Format_Standardise(YSI_g_sFormat, YSI_g_sTemp);
Format_Render(INVALID_PLAYER_ID, NO_LANGUAGE, output, len - 1, 0, e_FORMAT_FLAGS_NONE, YSI_g_sTemp, ___(3));
}
stock Text_PrintFEx(const format[], GLOBAL_TAG_TYPES:...)
{
// "Format_Standardise" modifies "input" repeatedly.
StrCpy(YSI_g_sFormat, format);
Format_Standardise(YSI_g_sFormat, YSI_g_sTemp);
Format_Render(INVALID_PLAYER_ID, NO_LANGUAGE, YSI_g_sFormat, sizeof (YSI_g_sFormat) - 1, 0, e_FORMAT_FLAGS_NONE, YSI_g_sTemp, ___(1));
print(sFormat);
}
#if defined YSI_TESTS
#if defined YSI_NO_TEST_WARNINGS
#pragma warning push
#pragma warning disable 203
#pragma warning disable 204
#pragma warning disable 213
#pragma warning disable 214
#pragma warning disable 219
#pragma warning disable 234
#pragma warning disable 239
#pragma warning disable 240
#endif
#include "y_text_tests"
#if defined YSI_NO_TEST_WARNINGS
#pragma warning pop
#endif
#endif
#if !defined formatex
#define formatex Text_FormatEx
#endif
#if !defined printfex
#define printfex Text_PrintFEx
#endif
| 0 | 0.505506 | 1 | 0.505506 | game-dev | MEDIA | 0.33574 | game-dev | 0.572468 | 1 | 0.572468 |
dingzhen-vape/WurstCN | 3,875 | src/main/java/net/wurstclient/options/ZoomManagerScreen.java | /*
* Copyright (c) 2014-2024 Wurst-Imperium and contributors.
*
* This source code is subject to the terms of the GNU General Public
* License, version 3. If a copy of the GPL was not distributed with this
* file, You can obtain one at: https://www.gnu.org/licenses/gpl-3.0.txt
*/
package net.wurstclient.options;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.gui.Drawable;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.widget.ButtonWidget;
import net.minecraft.client.option.KeyBinding;
import net.minecraft.client.util.InputUtil;
import net.minecraft.text.Text;
import net.wurstclient.WurstClient;
import net.wurstclient.other_features.ZoomOtf;
import net.wurstclient.settings.CheckboxSetting;
import net.wurstclient.settings.SliderSetting;
public class ZoomManagerScreen extends Screen implements PressAKeyCallback
{
private Screen prevScreen;
private ButtonWidget keyButton;
private ButtonWidget scrollButton;
public ZoomManagerScreen(Screen par1GuiScreen)
{
super(Text.literal(""));
prevScreen = par1GuiScreen;
}
@Override
public void init()
{
WurstClient wurst = WurstClient.INSTANCE;
ZoomOtf zoom = wurst.getOtfs().zoomOtf;
SliderSetting level = zoom.getLevelSetting();
CheckboxSetting scroll = zoom.getScrollSetting();
Text zoomKeyName = wurst.getZoomKey().getBoundKeyLocalizedText();
addDrawableChild(ButtonWidget
.builder(Text.literal("Back"), b -> client.setScreen(prevScreen))
.dimensions(width / 2 - 100, height / 4 + 144 - 16, 200, 20)
.build());
addDrawableChild(keyButton = ButtonWidget
.builder(Text.literal("Zoom Key: ").append(zoomKeyName),
b -> client.setScreen(new PressAKeyScreen(this)))
.dimensions(width / 2 - 79, height / 4 + 24 - 16, 158, 20).build());
addDrawableChild(ButtonWidget
.builder(Text.literal("More"), b -> level.increaseValue())
.dimensions(width / 2 - 79, height / 4 + 72 - 16, 50, 20).build());
addDrawableChild(ButtonWidget
.builder(Text.literal("Less"), b -> level.decreaseValue())
.dimensions(width / 2 - 25, height / 4 + 72 - 16, 50, 20).build());
addDrawableChild(ButtonWidget
.builder(Text.literal("Default"),
b -> level.setValue(level.getDefaultValue()))
.dimensions(width / 2 + 29, height / 4 + 72 - 16, 50, 20).build());
addDrawableChild(
scrollButton = ButtonWidget
.builder(
Text.literal(
"Use Mouse Wheel: " + onOrOff(scroll.isChecked())),
b -> toggleScroll())
.dimensions(width / 2 - 79, height / 4 + 96 - 16, 158, 20)
.build());
}
private void toggleScroll()
{
ZoomOtf zoom = WurstClient.INSTANCE.getOtfs().zoomOtf;
CheckboxSetting scroll = zoom.getScrollSetting();
scroll.setChecked(!scroll.isChecked());
scrollButton.setMessage(
Text.literal("Use Mouse Wheel: " + onOrOff(scroll.isChecked())));
}
private String onOrOff(boolean on)
{
return on ? "ON" : "OFF";
}
@Override
public void close()
{
client.setScreen(prevScreen);
}
@Override
public void render(DrawContext context, int mouseX, int mouseY,
float partialTicks)
{
ZoomOtf zoom = WurstClient.INSTANCE.getOtfs().zoomOtf;
SliderSetting level = zoom.getLevelSetting();
renderBackground(context, mouseX, mouseY, partialTicks);
context.drawCenteredTextWithShadow(textRenderer, "Zoom Manager",
width / 2, 40, 0xffffff);
context.drawTextWithShadow(textRenderer,
"Zoom Level: " + level.getValueString(), width / 2 - 75,
height / 4 + 44, 0xcccccc);
for(Drawable drawable : drawables)
drawable.render(context, mouseX, mouseY, partialTicks);
}
@Override
public void setKey(String key)
{
WurstClient.INSTANCE.getZoomKey()
.setBoundKey(InputUtil.fromTranslationKey(key));
client.options.write();
KeyBinding.updateKeysByCode();
keyButton.setMessage(Text.literal("Zoom Key: " + key));
}
}
| 0 | 0.84691 | 1 | 0.84691 | game-dev | MEDIA | 0.513198 | game-dev,desktop-app | 0.941862 | 1 | 0.941862 |
mcclure/bitbucket-backup | 4,207 | repos/jumpcore/contents/desktop/input_ent.cpp | /*
* input_ent.cpp
* Jumpcore
*
* Created by Andi McClure on 11/16/13.
* Copyright 2013 Run Hello. All rights reserved.
*
*/
#include "input_ent.h"
#include "input.h"
#include "inputcodes.h"
#include "internalfile.h"
input_vacuum_ent::input_vacuum_ent(InputKind _kind) : ent(), spec(_kind, I_VACUUM) {}
void input_vacuum_ent::insert(ent *_parent, int _prio) {
ent::insert(_parent, _prio);
InputRules::rules()->load(spec);
}
void input_vacuum_ent::die() {
InputRules::rules()->unload(spec);
ent::die();
}
void input_vacuum_ent::input(InputData *data) {
#ifdef SELF_EDIT
const string &debugString = data->debugString();
ERR("Input: %s\n", debugString.c_str());
#endif
}
void sticker::input(InputData *d) {
if (d->inputcode == inputcode) {
strength = d->strength;
update(d);
}
}
float sticker::stick(float gate) {
return fabs(strength) > gate ? strength : 0;
}
void switcher::input(InputData *d) {
if (d->inputcode == inputcode) {
if (toggle)
down = !down;
else
down = d->axiscode & AXISCODE_RISE_MASK;
update(d);
}
}
input_mapper::input_mapper() : ent(), found_controllers(false) {
static bool __ever_loaded = false;
if (!__ever_loaded) {
char bindingsfile[FILENAMESIZE];
internalPath(bindingsfile, "gamecontrollerdb.txt");
SDL_GameControllerAddMappingsFromFile(bindingsfile);
__ever_loaded = true;
}
}
void input_mapper::clear() {
for(int c = 0; c < currentRules.size(); c++) {
InputRuleSpec &spec = currentRules[c];
InputRules::rules()->unload(spec);
}
currentRules.clear();
}
void input_mapper::assign() {
clear();
for(int j = 0; j < SDL_NumJoysticks(); j++) {
SDL_GameController *controller = SDL_GameControllerOpen(j);
string name = nameForJoystick(j);
if (controller) {
found_controllers = true;
for(int c = 0; c < currentWishes.size(); c++) {
InputWishSpec &wish = currentWishes[c];
InputRuleSpec spec;
spec.inputcode = wish.inputcode;
spec.axiscode = wish.axiscode;
SDL_GameControllerButtonBind result;
result.bindType = SDL_CONTROLLER_BINDTYPE_NONE;
{
SDL_GameControllerAxis axis = SDL_GameControllerGetAxisFromString(wish.value.c_str());
if (axis != SDL_CONTROLLER_AXIS_INVALID)
result = SDL_GameControllerGetBindForAxis(controller, axis);
}
if (result.bindType == SDL_CONTROLLER_BINDTYPE_NONE) {
SDL_GameControllerButton button = SDL_GameControllerGetButtonFromString(wish.value.c_str());
if (button != SDL_CONTROLLER_BUTTON_INVALID)
result = SDL_GameControllerGetBindForButton(controller, button);
}
if (result.bindType != SDL_CONTROLLER_BINDTYPE_NONE) {
switch (result.bindType) {
case SDL_CONTROLLER_BINDTYPE_BUTTON:
spec = InputRuleSpec(InputKindButton, wish.inputcode, wish.axiscode|result.value.button, name);
break;
case SDL_CONTROLLER_BINDTYPE_AXIS:
spec = InputRuleSpec(InputKindAxis, wish.inputcode, wish.axiscode|result.value.axis, name);
break;
case SDL_CONTROLLER_BINDTYPE_HAT:
uint32_t hat = wish.axiscode|result.value.hat.hat;
if (result.value.hat.hat_mask & (1|4)) hat |= AXISCODE_YHAT_MASK;
else hat |= AXISCODE_XHAT_MASK;
if ((result.value.hat.hat_mask & (4|8)) && (hat & (AXISCODE_HIGH_MASK|AXISCODE_RAW_MASK))) {
hat &= ~AXISCODE_HIGH_MASK; // Blank high if it's present
hat |= AXISCODE_LOW_MASK;
}
spec = InputRuleSpec(InputKindHat, wish.inputcode, hat, name);
break;
}
// TODO: Names?
if (spec.kind != InputKindInvalid)
InputRules::rules()->load(spec);
ERR("LOADED FOR %s BIND %d,%d VALUE %s\n", wish.value.c_str(), (int)result.bindType, (int)result.value.button, spec.debugString().c_str());
}
}
SDL_GameControllerClose(controller);
}
}
}
void input_mapper::addKeyboard(SDL_Scancode value, uint32_t inputcode, uint32_t axiscode) {
}
void input_mapper::addJoystick(const string &value, uint32_t inputcode, uint32_t axiscode) {
currentWishes.push_back(InputWishSpec(value, inputcode, axiscode));
}
void input_mapper::inserting() { assign(); }
void input_mapper::input(InputData *) {
}
| 0 | 0.891379 | 1 | 0.891379 | game-dev | MEDIA | 0.80846 | game-dev | 0.850863 | 1 | 0.850863 |
needle-mirror/com.unity.entities | 3,469 | Unity.Entities/RetainBlobAssetSystem.cs | using Unity.Burst;
using Unity.Collections;
namespace Unity.Entities
{
[RequireMatchingQueriesForUpdate]
[WorldSystemFilter(WorldSystemFilterFlags.Default | WorldSystemFilterFlags.Editor | WorldSystemFilterFlags.ThinClientSimulation)]
[UpdateInGroup(typeof(InitializationSystemGroup))]
partial class RetainBlobAssetSystem : SystemBase
{
protected unsafe override void OnUpdate()
{
foreach (var (blobOwner, entity) in
SystemAPI.Query<BlobAssetOwner>()
.WithAll<RetainBlobAssets>()
.WithNone<RetainBlobAssetBatchPtr>().WithEntityAccess())
{
BlobAssetBatch.Retain(blobOwner.BlobAssetBatchPtr);
EntityManager.AddComponentData(entity, new RetainBlobAssetBatchPtr { BlobAssetBatchPtr = blobOwner.BlobAssetBatchPtr});
}
var retainBlobAssetBatchQuery = SystemAPI.QueryBuilder().WithNone<BlobAssetOwner>().WithAll<RetainBlobAssets>()
.WithAll<RetainBlobAssetBatchPtr>().Build();
var retainBlobAssetBatchEntities = retainBlobAssetBatchQuery.ToEntityArray(Allocator.Temp);
foreach (var entity in retainBlobAssetBatchEntities)
{
var retainBlobAssets = EntityManager.GetComponentData<RetainBlobAssets>(entity);
if (retainBlobAssets.FramesToRetainBlobAssets-- <= 0)
{
EntityManager.RemoveComponent<RetainBlobAssets>(entity);
EntityManager.RemoveComponent<RetainBlobAssetBatchPtr>(entity);
}
else
EntityManager.SetComponentData(entity, retainBlobAssets);
}
var retainBlobAssetsQuery = SystemAPI.QueryBuilder().WithNone<BlobAssetOwner>().WithAll<RetainBlobAssets>()
.WithAll<RetainBlobAssetPtr>().Build();
var retainBlobAssetsEntities = retainBlobAssetsQuery.ToEntityArray(Allocator.Temp);
foreach (var entity in retainBlobAssetsEntities)
{
var retainBlobAssets = EntityManager.GetComponentData<RetainBlobAssets>(entity);
var retainBlobAssetPtr = EntityManager.GetComponentData<RetainBlobAssetPtr>(entity);
if (retainBlobAssets.FramesToRetainBlobAssets-- <= 0)
{
retainBlobAssetPtr.BlobAsset->Invalidate();
Memory.Unmanaged.Free(retainBlobAssetPtr.BlobAsset, Allocator.Persistent);
EntityManager.RemoveComponent<RetainBlobAssets>(entity);
EntityManager.RemoveComponent<RetainBlobAssetPtr>(entity);
}
else
EntityManager.SetComponentData(entity, retainBlobAssets);
}
}
protected override unsafe void OnDestroy()
{
foreach (var retainPtr in SystemAPI.Query<RefRO<RetainBlobAssetBatchPtr>>()
.WithAll<RetainBlobAssets>())
{
BlobAssetBatch.Release(retainPtr.ValueRO.BlobAssetBatchPtr);
}
foreach (var retainPtr in SystemAPI.Query<RefRO<RetainBlobAssetPtr>>()
.WithAll<RetainBlobAssets>())
{
retainPtr.ValueRO.BlobAsset->Invalidate();
Memory.Unmanaged.Free(retainPtr.ValueRO.BlobAsset, Allocator.Persistent);
}
}
}
}
| 0 | 0.897671 | 1 | 0.897671 | game-dev | MEDIA | 0.912017 | game-dev | 0.883367 | 1 | 0.883367 |
OpenXRay/xray-16 | 2,070 | src/xrGame/alife_monster_patrol_path_manager.h | ////////////////////////////////////////////////////////////////////////////
// Module : alife_monster_patrol_path_manager.h
// Created : 01.11.2005
// Modified : 22.11.2005
// Author : Dmitriy Iassenev
// Description : ALife monster patrol path manager class
////////////////////////////////////////////////////////////////////////////
#pragma once
#include "xrAICore/Navigation/game_graph_space.h"
#include "xrAICore/Navigation/PatrolPath/patrol_path.h"
class CMovementManagerHolder;
class CPatrolPath;
class CALifeMonsterPatrolPathManager
{
public:
typedef CMovementManagerHolder object_type;
typedef GameGraph::_GRAPH_ID _GRAPH_ID;
private:
object_type* m_object;
private:
const CPatrolPath* m_path;
EPatrolStartType m_start_type;
EPatrolRouteType m_route_type;
bool m_use_randomness;
u32 m_start_vertex_index;
private:
bool m_actual;
bool m_completed;
u32 m_current_vertex_index;
u32 m_previous_vertex_index;
private:
void select_nearest();
void actualize();
bool location_reached() const;
void navigate();
public:
CALifeMonsterPatrolPathManager(object_type* object);
void update();
void path(const shared_str& path_name);
public:
IC object_type& object() const;
IC void path(const CPatrolPath* path);
IC void path(LPCSTR path_name);
IC void start_type(const EPatrolStartType& start_type);
IC void route_type(const EPatrolRouteType& route_type);
IC const EPatrolStartType& start_type() const;
IC const EPatrolRouteType& route_type() const;
IC bool actual() const;
IC bool completed() const;
IC const CPatrolPath& path() const;
IC void start_vertex_index(const u32& start_vertex_index);
IC bool use_randomness() const;
IC void use_randomness(const bool& use_randomness);
const _GRAPH_ID& target_game_vertex_id() const;
const u32& target_level_vertex_id() const;
const Fvector& target_position() const;
private:
DECLARE_SCRIPT_REGISTER_FUNCTION();
};
#include "alife_monster_patrol_path_manager_inline.h"
| 0 | 0.973381 | 1 | 0.973381 | game-dev | MEDIA | 0.82876 | game-dev | 0.89451 | 1 | 0.89451 |
ActiveNick/HoloBot | 3,095 | Assets/MixedRealityToolkit/Extensions/EditorClassExtensions/ScriptableObjectExtensions.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.IO;
using UnityEditor;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Editor
{
/// <summary>
/// Extensions for <see href="https://docs.unity3d.com/ScriptReference/ScriptableObject.html">ScriptableObject</see>s
/// </summary>
public static class ScriptableObjectExtensions
{
/// <summary>
/// Creates, saves, and then opens a new asset for the target <see href="https://docs.unity3d.com/ScriptReference/ScriptableObject.html">ScriptableObject</see>.
/// </summary>
/// <param name="scriptableObject"><see href="https://docs.unity3d.com/ScriptReference/ScriptableObject.html">ScriptableObject</see> you want to create an asset file for.</param>
/// <param name="path">Optional path for the new asset.</param>
/// <param name="fileName">Optional filename for the new asset.</param>
public static ScriptableObject CreateAsset(this ScriptableObject scriptableObject, string path = null, string fileName = null)
{
var name = string.IsNullOrEmpty(fileName) ? $"{scriptableObject.GetType().Name}" : fileName;
if (string.IsNullOrEmpty(path))
{
path = "Assets";
}
if (Path.GetExtension(path) != string.Empty)
{
var subtractedPath = path.Substring(path.LastIndexOf("/", StringComparison.Ordinal));
path = path.Replace(subtractedPath, string.Empty);
}
if (!Directory.Exists(Path.GetFullPath(path)))
{
Directory.CreateDirectory(Path.GetFullPath(path));
}
string assetPathAndName = AssetDatabase.GenerateUniqueAssetPath($"{path}/{name}.asset");
AssetDatabase.CreateAsset(scriptableObject, assetPathAndName);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
EditorGUIUtility.PingObject(scriptableObject);
return scriptableObject;
}
/// <summary>
/// Gets all the scriptable object instances in the project.
/// </summary>
/// <typeparam name="T">The Type of <see href="https://docs.unity3d.com/ScriptReference/ScriptableObject.html">ScriptableObject</see> you're wanting to find instances of.</typeparam>
/// <returns>An Array of instances for the type.</returns>
public static T[] GetAllInstances<T>() where T : ScriptableObject
{
// FindAssets uses tags check documentation for more info
string[] guids = AssetDatabase.FindAssets($"t:{typeof(T).Name}");
var instances = new T[guids.Length];
for (int i = 0; i < guids.Length; i++)
{
string path = AssetDatabase.GUIDToAssetPath(guids[i]);
instances[i] = AssetDatabase.LoadAssetAtPath<T>(path);
}
return instances;
}
}
} | 0 | 0.804425 | 1 | 0.804425 | game-dev | MEDIA | 0.933698 | game-dev | 0.882306 | 1 | 0.882306 |
Xiao-MoMi/Custom-Fishing | 2,572 | core/src/main/resources/contents/bait/default.yml | # Note: These are the default configurations of the plugin
# and do not necessarily mean that players can have a good
# gaming experience. We hope that you will create
# customized configurations based on your own ideas,
# allowing players to experience the uniqueness of your server.
# use Vanilla items as bait
BOOK:
tag: false
material: book
requirements:
requirement_1:
type: rod
value:
- magical_rod
not-met-actions:
action_message:
type: message
value:
- 'This bait can only be used on <#7B68EE>Magical Fishing Rod'
simple_bait:
material: paper
display:
name: '<b><#00BFFF>Simple lures'
lore:
- ''
- '<#7FFFD4>Desciption:'
- '<gray>Made from natural ingredients, it attracts'
- '<gray>fish in a calm and steady manner. It''s the'
- '<gray>go-to choice for those who prefer a '
- '<gray>straightforward and reliable fishing experience.'
- ''
- '<#FFD700>Effects:'
- '<gray> - Reduce fishing difficulty'
- ''
custom-model-data: 50001
effects:
effect_1:
type: difficulty
value: -10
magnetic_bait:
material: paper
display:
name: '<b><red>Magn<blue>etic <gray>lures'
lore:
- ''
- '<#7FFFD4>Desciption:'
- '<gray>Its radiant shimmer and unique energy pulse'
- '<gray>prove irresistible to curious fish, drawing'
- '<gray>them in with unprecedented speed. This is '
- '<gray>not just a bait, it''s a spectacle that fish'
- '<gray>can''t help but investigate.'
- ''
- '<#FFD700>Effects:'
- '<gray> - Reduce wait time'
- '<gray> - More time for fishing'
- ''
custom-model-data: 50002
effects:
effect_1:
type: wait-time-multiplier
value: 0.9
effect_2:
type: game-time
value: 2
wild_bait:
material: paper
display:
name: '<b><#2E8B57>Wild lures'
lore:
- ''
- '<#7FFFD4>Desciption:'
- '<gray>Crafted for the fearless angler, the Wild '
- '<gray>Attraction Bait is an infusion of potent '
- '<gray>natural ingredients, exuding an irresistible'
- '<gray>aroma for large aquatic beasts.'
- ''
- '<#FFD700>Effects:'
- '<gray> - Increase fishing difficulty'
- '<gray> - Increase the size of fish caught'
- ''
custom-model-data: 50003
effects:
effect_1:
type: difficulty
value: +20
effect_2:
type: size-multiplier
value: 1.5
effect_3:
type: game-time
value: -2 | 0 | 0.750233 | 1 | 0.750233 | game-dev | MEDIA | 0.972499 | game-dev | 0.821473 | 1 | 0.821473 |
LordOfDragons/dragengine | 8,238 | src/dragengine/src/resources/animator/deAnimator.cpp | /*
* MIT License
*
* Copyright (C) 2024, DragonDreams GmbH (info@dragondreams.ch)
*
* 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "deAnimator.h"
#include "deAnimatorManager.h"
#include "deAnimatorLink.h"
#include "controller/deAnimatorController.h"
#include "rule/deAnimatorRule.h"
#include "../animation/deAnimation.h"
#include "../rig/deRig.h"
#include "../../systems/modules/animator/deBaseAnimatorAnimator.h"
#include "../../deEngine.h"
#include "../../common/exceptions.h"
// Class deAnimator
/////////////////////
// Constructor, destructor
////////////////////////////
deAnimator::deAnimator( deAnimatorManager *manager ) :
deResource( manager ),
pControllers( NULL ),
pControllerCount( 0 ),
pControllerSize( 0 ),
pLinks( NULL ),
pLinkCount( 0 ),
pLinkSize( 0 ),
pPeerAnimator( NULL ){
}
deAnimator::~deAnimator(){
pCleanUp();
}
// Management
///////////////
void deAnimator::SetRig( deRig *rig ){
if( rig == pRig ){
return;
}
pRig = rig;
if( pPeerAnimator ){
pPeerAnimator->RigChanged();
}
}
void deAnimator::SetAnimation( deAnimation *animation ){
if( pAnimation == animation ){
return;
}
pAnimation = animation;
if( pPeerAnimator ){
pPeerAnimator->AnimationChanged();
}
}
void deAnimator::NotifyBonesChanged(){
if( pPeerAnimator ){
pPeerAnimator->BonesChanged();
}
}
void deAnimator::NotifyVertexPositionSetsChanged(){
if( pPeerAnimator ){
pPeerAnimator->VertexPositionSetsChanged();
}
}
// Controller Management
//////////////////////////
deAnimatorController *deAnimator::GetControllerAt( int index ) const{
if( index < 0 || index >= pControllerCount ){
DETHROW( deeInvalidParam );
}
return pControllers[ index ];
}
int deAnimator::IndexOfController( deAnimatorController *controller ) const{
if( ! controller ){
DETHROW( deeInvalidParam );
}
int i;
for( i=0; i<pControllerCount; i++ ){
if( pControllers[ i ] == controller ){
return i;
}
}
return -1;
}
int deAnimator::IndexOfControllerNamed( const char *name ) const{
int i;
for( i=0; i<pControllerCount; i++ ){
if( pControllers[ i ]->GetName() == name ){
return i;
}
}
return -1;
}
bool deAnimator::HasController( deAnimatorController *controller ) const{
if( ! controller ) DETHROW( deeInvalidParam );
int i;
for( i=0; i<pControllerCount; i++ ){
if( pControllers[ i ] == controller ){
return true;
}
}
return false;
}
void deAnimator::AddController( deAnimatorController *controller ){
if( ! controller ) DETHROW( deeInvalidParam );
if( pControllerCount == pControllerSize ){
int i, newSize = pControllerSize * 3 / 2 + 1;
deAnimatorController **newArray = new deAnimatorController*[ newSize ];
if( ! newArray ) DETHROW( deeOutOfMemory );
if( pControllers ){
for( i=0; i<pControllerSize; i++ ) newArray[ i ] = pControllers[ i ];
delete [] pControllers;
}
pControllers = newArray;
pControllerSize = newSize;
}
pControllers[ pControllerCount ] = controller;
pControllerCount++;
if( pPeerAnimator ){
pPeerAnimator->ControllerCountChanged();
}
}
void deAnimator::RemoveController( deAnimatorController *controller ){
int index = IndexOfController( controller );
if( index == -1 ) DETHROW( deeInvalidParam );
int i;
for( i=index+1; i<pControllerCount; i++ ){
pControllers[ i - 1 ] = pControllers[ i ];
}
pControllerCount--;
delete controller;
if( pPeerAnimator ){
pPeerAnimator->ControllerCountChanged();
}
}
void deAnimator::RemoveAllControllers(){
while( pControllerCount > 0 ){
delete pControllers[ pControllerCount - 1 ];
pControllerCount--;
}
if( pPeerAnimator ){
pPeerAnimator->ControllerCountChanged();
}
}
void deAnimator::NotifyControllerChangedAt( int index ){
if( index < 0 || index >= pControllerCount ) DETHROW( deeInvalidParam );
if( pPeerAnimator ){
pPeerAnimator->ControllerChanged( index, pControllers[ index ] );
}
}
// Link Management
////////////////////
deAnimatorLink *deAnimator::GetLinkAt( int index ) const{
if( index < 0 || index >= pLinkCount ) DETHROW( deeInvalidParam );
return pLinks[ index ];
}
int deAnimator::IndexOfLink( deAnimatorLink *link ) const{
if( ! link ) DETHROW( deeInvalidParam );
int i;
for( i=0; i<pLinkCount; i++ ){
if( pLinks[ i ] == link ) return i;
}
return -1;
}
bool deAnimator::HasLink( deAnimatorLink *link ) const{
if( ! link ) DETHROW( deeInvalidParam );
int i;
for( i=0; i<pLinkCount; i++ ){
if( pLinks[ i ] == link ) return true;
}
return false;
}
void deAnimator::AddLink( deAnimatorLink *link ){
if( ! link ) DETHROW( deeInvalidParam );
if( pLinkCount == pLinkSize ){
int i, newSize = pLinkSize * 3 / 2 + 1;
deAnimatorLink **newArray = new deAnimatorLink*[ newSize ];
if( ! newArray ) DETHROW( deeOutOfMemory );
if( pLinks ){
for( i=0; i<pLinkSize; i++ ) newArray[ i ] = pLinks[ i ];
delete [] pLinks;
}
pLinks = newArray;
pLinkSize = newSize;
}
pLinks[ pLinkCount ] = link;
pLinkCount++;
if( pPeerAnimator ) pPeerAnimator->LinksChanged();
}
void deAnimator::RemoveLink( deAnimatorLink *link ){
int i, index = IndexOfLink( link );
if( index == -1 ) DETHROW( deeInvalidParam );
for( i=index+1; i<pLinkCount; i++ ){
pLinks[ i - 1 ] = pLinks[ i ];
}
pLinkCount--;
if( pPeerAnimator ) pPeerAnimator->LinksChanged();
delete link;
}
void deAnimator::RemoveAllLinks(){
while( pLinkCount > 0 ){
delete pLinks[ pLinkCount - 1 ];
pLinkCount--;
}
if( pPeerAnimator ) pPeerAnimator->LinksChanged();
}
void deAnimator::NotifyLinkChangedAt( int index ){
if( index < 0 || index >= pLinkCount ) DETHROW( deeInvalidParam );
if( pPeerAnimator ) pPeerAnimator->LinksChanged();
}
// Rule Management
////////////////////
int deAnimator::GetRuleCount() const{
return pRules.GetCount();
}
deAnimatorRule *deAnimator::GetRuleAt( int index ) const{
return ( deAnimatorRule* )pRules.GetAt( index );
}
int deAnimator::IndexOfRule( deAnimatorRule *rule ) const{
return pRules.IndexOf( rule );
}
bool deAnimator::HasRule( deAnimatorRule *rule ) const{
return pRules.Has( rule );
}
void deAnimator::AddRule( deAnimatorRule *rule ){
if( ! rule ){
DETHROW( deeInvalidParam );
}
pRules.Add( rule );
if( pPeerAnimator ){
pPeerAnimator->RulesChanged();
}
}
void deAnimator::RemoveRule( deAnimatorRule *rule ){
pRules.Remove( rule );
if( pPeerAnimator ){
pPeerAnimator->RulesChanged();
}
}
void deAnimator::RemoveAllRules(){
pRules.RemoveAll();
if( pPeerAnimator ){
pPeerAnimator->RulesChanged();
}
}
void deAnimator::NotifyRulesChanged(){
if( pPeerAnimator ){
pPeerAnimator->RulesChanged();
}
}
// System Peers
/////////////////
void deAnimator::SetPeerAnimator( deBaseAnimatorAnimator *peer ){
if( peer == pPeerAnimator ){
return;
}
if( pPeerAnimator ){
delete pPeerAnimator;
}
pPeerAnimator = peer;
}
// Private function
/////////////////////
void deAnimator::pCleanUp(){
if( pPeerAnimator ){
delete pPeerAnimator;
pPeerAnimator = NULL;
}
RemoveAllRules();
RemoveAllLinks();
if( pLinks ) delete [] pLinks;
RemoveAllControllers();
if( pControllers ){
delete [] pControllers;
}
}
| 0 | 0.939019 | 1 | 0.939019 | game-dev | MEDIA | 0.551408 | game-dev | 0.983204 | 1 | 0.983204 |
ClimateGlobalChange/tempestextremes | 5,326 | src/util/GenerateConnectivityFile.cpp | ///////////////////////////////////////////////////////////////////////////////
///
/// \file GenerateConnectivityFile.cpp
/// \author Paul Ullrich
/// \version January 28, 2019
///
/// <remarks>
/// Copyright 2000-2018 Paul Ullrich
///
/// This file is distributed as part of the Tempest source code package.
/// Permission is granted to use, copy, modify and distribute this
/// source code and its documentation under the terms of the GNU General
/// Public License. This software is provided "as is" without express
/// or implied warranty.
/// </remarks>
#include "CommandLine.h"
#include "Exception.h"
#include "Announce.h"
#include "STLStringHelper.h"
#include "GridElements.h"
#include "SimpleGrid.h"
///////////////////////////////////////////////////////////////////////////////
int main(int argc, char** argv) {
// Turn off fatal errors in NetCDF
NcError error(NcError::silent_nonfatal);
try {
// Input mesh file
std::string strMeshFile;
// Input data file
std::string strDataFile;
// True if the input mesh contains concave elements
bool fConcave;
// Polynomial degree
int nP;
// Connectivity file type
std::string strConnectType;
// Output data file
std::string strConnectFile;
// Latitude name
std::string strLatitudeName;
// Longitude name
std::string strLongitudeName;
// Parse the command line
BeginCommandLine()
CommandLineString(strMeshFile, "in_mesh", "");
CommandLineString(strDataFile, "in_data", "");
CommandLineBool(fConcave, "in_concave");
CommandLineStringD(strConnectType, "out_type", "FV", "[FV|CGLL|DGLL]");
CommandLineInt(nP, "out_np", 4);
CommandLineString(strConnectFile, "out_connect", "");
CommandLineString(strLatitudeName, "latname", "lat");
CommandLineString(strLongitudeName, "lonname", "lon");
ParseCommandLine(argc, argv);
EndCommandLine(argv)
AnnounceBanner();
// Convert connectivity type to lowercase
STLStringHelper::ToLower(strConnectType);
// Check arguments
if ((strConnectType != "fv") &&
(strConnectType != "cgll") &&
(strConnectType != "dgll")
) {
_EXCEPTIONT("Invalid --out_type. Expected \"FV|CGLL|DGLL\"");
}
if ((nP < 2) && (strConnectType == "cgll")) {
_EXCEPTIONT("Invalid --out_np for --out_type CGLL. Expected np > 1.");
}
if ((nP < 1) && (strConnectType == "dgll")) {
_EXCEPTIONT("Invalid --out_np for --out_type DGLL. Expected np > 0.");
}
// Input mesh file
if (strMeshFile != "") {
// Load in the mesh
AnnounceStartBlock("Loading mesh");
Mesh mesh(strMeshFile);
AnnounceEndBlock("Done");
// Calculate connectivity information
AnnounceStartBlock("Calculating connectivity information");
mesh.RemoveZeroEdges();
mesh.CalculateFaceAreas(fConcave);
mesh.ConstructEdgeMap();
AnnounceEndBlock("Done");
// Generate SimpleGrid
AnnounceStartBlock("Converting mesh to connectivity format");
SimpleGrid grid;
if (strConnectType == "fv") {
grid.FromMeshFV(mesh);
} else {
grid.FromMeshFE(mesh, (strConnectType == "cgll"), nP);
}
AnnounceEndBlock("Done");
// Writing data to file
AnnounceStartBlock("Writing connectivity file");
grid.ToFile(strConnectFile);
AnnounceEndBlock("Done");
}
// Input data file
if (strDataFile != "") {
NcFile ncfilein(strDataFile.c_str());
if (!ncfilein.is_valid()) {
_EXCEPTION1("Unable to open data file \"%s\"", strDataFile.c_str());
}
NcVar * varLat = ncfilein.get_var(strLatitudeName.c_str());
if (varLat == NULL) {
_EXCEPTION2("Data file \"%s\" does not contain variable \"%s\"", strDataFile.c_str(), strLatitudeName.c_str());
}
NcVar * varLon = ncfilein.get_var(strLongitudeName.c_str());
if (varLon == NULL) {
_EXCEPTION2("Data file \"%s\" does not contain variable \"%s\"", strDataFile.c_str(), strLongitudeName.c_str());
}
if (varLat->get_dim(0)->size() != varLon->get_dim(0)->size()) {
_EXCEPTIONT("Data file latitude and longitude must have same length");
}
// Load data
std::vector<double> dLat(varLat->get_dim(0)->size());
varLat->get(&(dLat[0]), dLat.size());
std::vector<double> dLon(varLon->get_dim(0)->size());
varLon->get(&(dLon[0]), dLon.size());
bool fRadians = false;
NcAtt * attUnits = varLat->get_att("units");
if (attUnits != NULL) {
std::string strUnits = attUnits->as_string(0);
if ((strUnits == "radians") || (strUnits == "radian")) {
fRadians = true;
}
}
if (fRadians) {
for (size_t s = 0; s < dLon.size(); s++) {
dLon[s] = RadToDeg(dLon[s]);
dLat[s] = RadToDeg(dLat[s]);
}
}
// Generate the grid
SimpleGrid grid;
grid.m_nGridDim.resize(1);
grid.m_nGridDim[0] = dLon.size();
grid.m_dLon.Allocate(dLon.size());
memcpy(&(grid.m_dLon[0]), &(dLon[0]), dLon.size() * sizeof(double));
grid.m_dLat.Allocate(dLon.size());
memcpy(&(grid.m_dLat[0]), &(dLat[0]), dLat.size() * sizeof(double));
grid.m_dArea.Allocate(dLon.size());
for (size_t s = 0; s < dLon.size(); s++) {
grid.m_dArea[s] = 1.0;
}
grid.m_vecConnectivity.resize(dLon.size());
// Writing data to file
AnnounceStartBlock("Writing connectivity file");
grid.ToFile(strConnectFile);
AnnounceEndBlock("Done");
}
AnnounceBanner();
} catch(Exception & e) {
Announce(e.ToString().c_str());
}
}
///////////////////////////////////////////////////////////////////////////////
| 0 | 0.980087 | 1 | 0.980087 | game-dev | MEDIA | 0.340217 | game-dev | 0.986813 | 1 | 0.986813 |
oiuv/mud | 3,431 | kungfu/skill/huashan-jian/xian.c | // feilong.c 华山剑法「夺命连环三仙剑」
#include <ansi.h>
#include <combat.h>
#define XIAN "「" HIM "夺命连环三仙剑" NOR "」"
inherit F_SSERVER;
int perform(object me, object target)
{
int damage;
string msg;
object weapon;
int ap, dp, fp, pp;
if (userp(me) && ! me->query("can_perform/huashan-jian/xian"))
return notify_fail("你所使用的外功中没有这种功能。\n");
if (! target) target = offensive_target(me);
if (! target || ! me->is_fighting(target))
return notify_fail(XIAN "只能在战斗中对对手使用。\n");
if (! objectp(weapon = me->query_temp("weapon")) ||
(string)weapon->query("skill_type") != "sword")
return notify_fail("你使用的武器不对!\n");
if ((int)me->query_skill("huashan-jian", 1) < 160)
return notify_fail("你华山剑法不够娴熟,无法施展" XIAN "。\n");
if ((int)me->query_skill("dodge", 1) < 160)
return notify_fail("你轻功修为不够,无法施展" XIAN "。\n");
if ((int)me->query("neili") < 300)
return notify_fail("你现在真气不够,无法施展" XIAN "!\n");
if (me->query_skill_mapped("sword") != "huashan-jian")
return notify_fail("你没有激发华山剑法,无法使用" XIAN "。\n");
if (! living(target))
return notify_fail("对方都已经这样了,用不着这么费力吧?\n");
me->add("neili", -280);
ap = me->query_skill("sword");
dp = target->query_skill("dodge");
fp = target->query_skill("force");
pp = target->query_skill("parry");
message_sort(HIW "\n$N" HIW "长啸一声,手中" + weapon->name() + HIW "随即不停转动,汹涌而"
"出,正是华山剑宗绝技「" HIM "夺命连环三仙剑" HIW "」,但是" + weapon->name() + HIW
"剑锋突变,一剑顿时化为三剑,袭向$n" HIW "……\n" NOR, me, target);
msg = HIM "$N" HIM "将内力全都运到了剑上,呼的一剑,当头直劈。\n" NOR;
if (ap / 2 + random(ap) < dp)
msg += CYN "$n" CYN "斜身闪开。\n" NOR;
else
{
damage = ap + random(ap / 3);
msg += COMBAT_D->do_damage(me, target, WEAPON_ATTACK, damage, 40 + random(10),
HIR "$n" HIR "急忙后退,竟然躲避不及,被$N"
HIR "这一剑震得口吐鲜血,接连后退。\n" NOR);
}
msg += HIM "\n$N" HIM "圈转" + weapon->name() + HIM ",拦腰横削,剑势恢弘,剑气纵横,令人匪夷所思。\n" NOR;
if (ap / 2 + random(ap) < fp)
msg += CYN "$n" CYN "纵身从剑上越过。\n" NOR;
else
{
damage = ap + random(ap / 3);
msg += COMBAT_D->do_damage(me, target, WEAPON_ATTACK, damage, 50 + random(10),
HIR "此招来势当真快极,$n" HIR "哪里来得及闪"
"避招架?只见$N" HIR "剑光闪过,$n"
HIR "腰间霎时鲜血淋漓!\n" NOR);
}
msg += HIM "\n$N" HIM "长剑反撩,疾刺$p" HIM "后心,剑法之快,部位之准,当真闻所未闻。\n" NOR;
if (ap / 2 + random(ap) < pp)
msg += CYN "$n" CYN "身在空中,不及变招,只能挥出一招,正击中$N"
CYN "剑上,略一借力,飘然避去。\n" NOR;
else
{
damage = ap + random(ap / 2);
msg += COMBAT_D->do_damage(me, target, WEAPON_ATTACK, damage, 60 + random(10),
HIR "$n" HIR "身在空中,哪里来得及变招?只见$N"
HIR "此剑掠过,$n" HIR "大声惨呼,鲜血四下飞溅!\n" NOR);
}
me->start_busy(3);
message_combatd(msg, me, target);
return 1;
}
| 0 | 0.830763 | 1 | 0.830763 | game-dev | MEDIA | 0.977982 | game-dev | 0.865539 | 1 | 0.865539 |
imengyu/Ballance | 1,783 | Assets/System/Scripts/Editor/Tools/ExportRenderTexture.cs | using UnityEngine;
using UnityEditor;
using System.IO;
public class ExportRenderTexture : EditorWindow
{
public ExportRenderTexture()
{
titleContent = new GUIContent("Export RenderTexture");
}
private SerializedObject serializedObject;
private SerializedProperty pTexture = null;
[SerializeField]
private RenderTexture Texture = null;
private GUIStyle groupBox = null;
private void OnEnable()
{
serializedObject = new SerializedObject(this);
pTexture = serializedObject.FindProperty("Texture");
}
private void OnDisable()
{
EditorUtility.ClearProgressBar();
}
private void OnGUI()
{
bool close = false;
serializedObject.Update();
if (groupBox == null)
groupBox = GUI.skin.FindStyle("GroupBox");
EditorGUI.BeginChangeCheck();
EditorGUILayout.BeginVertical(groupBox);
EditorGUILayout.PropertyField(pTexture, new GUIContent("Texture"));
GUILayout.Space(50);
if (GUILayout.Button("OK")) {
close = true;
}
EditorGUILayout.EndVertical();
if (EditorGUI.EndChangeCheck())
serializedObject.ApplyModifiedProperties();
if(close) {
RenderTexture prev = RenderTexture.active;
RenderTexture.active = Texture;
Texture2D png = new Texture2D(Texture.width, Texture.height, TextureFormat.ARGB32, false);
png.ReadPixels(new Rect(0, 0, Texture.width, Texture.height), 0, 0);
byte[] bytes = png.EncodeToPNG();
string path = string.Format("Dump/raw {0}.png", Random.Range(0, 65536).ToString("X"));
FileStream file = File.Open(path, FileMode.Create);
BinaryWriter writer = new BinaryWriter(file);
writer.Write(bytes);
file.Close();
Texture2D.Destroy(png);
RenderTexture.active = prev;
}
}
} | 0 | 0.732726 | 1 | 0.732726 | game-dev | MEDIA | 0.784732 | game-dev,graphics-rendering | 0.788656 | 1 | 0.788656 |
AngeloTadeucci/Maple2 | 4,446 | Maple2.File.Ingest/Mapper/ScriptMapper.cs | using Maple2.File.IO;
using Maple2.File.Parser;
using Maple2.File.Parser.Xml.Script;
using Maple2.Model.Enum;
using Maple2.Model.Metadata;
using CinematicContent = Maple2.Model.Metadata.CinematicContent;
using CinematicDistractor = Maple2.Model.Metadata.CinematicDistractor;
using CinematicEventScript = Maple2.Model.Metadata.CinematicEventScript;
using ScriptContent = Maple2.Model.Metadata.ScriptContent;
namespace Maple2.File.Ingest.Mapper;
public class ScriptMapper : TypeMapper<ScriptMetadata> {
private readonly ScriptParser parser;
public ScriptMapper(M2dReader xmlReader, string language) {
parser = new ScriptParser(xmlReader, language);
}
protected override IEnumerable<ScriptMetadata> Map() {
foreach ((int id, NpcScript script) in parser.ParseNpc()) {
var states = new Dictionary<int, ScriptState>();
if (script.job != null) {
states.Add(script.job.id, new ScriptState(
Id: script.job.id,
Type: ScriptStateType.Job,
Pick: script.job.randomPick,
JobCondition: null,
Contents: ParseCinematicContents(script.job.content)));
}
foreach (TalkScript select in script.select) {
states.Add(select.id, new ScriptState(
Id: select.id,
Type: ScriptStateType.Select,
Pick: select.randomPick,
JobCondition: null,
Contents: ParseCinematicContents(select.content)));
}
foreach (ConditionTalkScript select in script.script) {
int[] conditions = select.gotoConditionTalkID; // TODO:
states.Add(select.id, new ScriptState(
Id: select.id,
Type: ScriptStateType.Script,
Pick: select.randomPick,
JobCondition: null,
Contents: ParseCinematicContents(select.content)));
}
if (states.Count == 0) {
continue;
}
yield return new ScriptMetadata(Id: id, Type: ScriptType.Npc, States: states);
}
foreach ((int id, QuestScript script) in parser.ParseQuest()) {
var states = new Dictionary<int, ScriptState>();
foreach (QuestTalkScript talk in script.script) {
states.Add(talk.id, new ScriptState(
Id: talk.id,
Type: ScriptStateType.Quest,
Pick: talk.randomPick,
JobCondition: (JobCode) talk.jobCondition,
Contents: ParseCinematicContents(talk.content)));
}
if (states.Count == 0) {
continue;
}
yield return new ScriptMetadata(Id: id, Type: ScriptType.Quest, States: states);
}
}
private static CinematicContent[] ParseCinematicContents(IList<Parser.Xml.Script.CinematicContent> contents) {
var result = new List<CinematicContent>();
foreach (Parser.Xml.Script.CinematicContent content in contents) {
var distractors = new List<CinematicDistractor>();
foreach (Parser.Xml.Script.CinematicDistractor distractor in content.distractor) {
distractors.Add(new CinematicDistractor(Goto: distractor.@goto, GotoFail: distractor.gotoFail));
}
var events = new List<CinematicEventScript>();
foreach (Parser.Xml.Script.CinematicEventScript @event in content.@event) {
var eventContents = new List<ScriptContent>();
foreach (Parser.Xml.Script.ScriptContent eventContent in @event.content) {
eventContents.Add(new ScriptContent(
Text: eventContent.text,
VoiceId: eventContent.voiceID,
Illustration: eventContent.illust));
}
events.Add(new CinematicEventScript(@event.id, eventContents.ToArray()));
}
result.Add(new CinematicContent(
Text: content.text,
ButtonType: (NpcTalkButton) content.buttonSet,
FunctionId: content.functionID,
Distractors: distractors.ToArray(),
Events: events.ToArray()));
}
return result.ToArray();
}
}
| 0 | 0.824788 | 1 | 0.824788 | game-dev | MEDIA | 0.605995 | game-dev | 0.763526 | 1 | 0.763526 |
doldecomp/melee | 4,744 | src/melee/ft/chara/ftPopo/ftPp_SpecialN.c | #include "ftPp_SpecialN.h"
#include "ftPp_Init.h"
#include <placeholder.h>
#include <platform.h>
#include "ft/fighter.h"
#include "ft/ft_081B.h"
#include "ft/ft_0877.h"
#include "ft/ft_0881.h"
#include "ft/ft_0892.h"
#include "ftCommon/ftCo_Attack100.h"
#include "ft/ftanim.h"
#include "ft/types.h"
#include "ftCommon/ftCo_Fall.h"
#include "ftCommon/ftCo_Landing.h"
#include "ftPopo/types.h"
#include "it/forward.h"
#include "it/items/it_27CF.h"
#include "it/items/itclimbersice.h"
#include "lb/lb_00B0.h"
#include <common_structs.h>
#include <dolphin/mtx.h>
#include <baselib/gobj.h>
/* 11F500 */ static void ftPp_SpecialN_8011F500(Fighter_GObj* gobj);
void ftPp_SpecialN_Enter(HSD_GObj* gobj)
{
Fighter* fp = (Fighter*) HSD_GObjGetUserData(gobj);
fp->throw_flags = 0;
fp->cmd_vars[0] = 0;
fp->fv.nn.x222C = 0;
Fighter_ChangeMotionState(gobj, 341, 0, 0.0f, 1.0f, 0.0f, NULL);
ftAnim_8006EBA4(gobj);
fp->accessory4_cb = &ftPp_SpecialN_8011F500;
}
void ftPp_SpecialAirN_Enter(HSD_GObj* gobj)
{
u8 _[4];
Fighter* fp = (Fighter*) HSD_GObjGetUserData(gobj);
ftIceClimberAttributes* icattr = fp->dat_attrs;
fp->throw_flags = 0;
fp->cmd_vars[0] = 0;
fp->fv.nn.x222C = 0;
if ((s32) fp->fv.nn.x224C == false) {
fp->self_vel.y = icattr->x4;
fp->fv.nn.x224C = true;
fp->fv.nn.x2250 = 0.0f;
} else {
fp->fv.nn.x2250 = -10.0;
}
Fighter_ChangeMotionState(gobj, 342, 0, 0.0f, 1.0f, 0.0f, NULL);
ftAnim_8006EBA4(gobj);
fp->accessory4_cb = &ftPp_SpecialN_8011F500;
}
void ftPp_SpecialN_Anim(HSD_GObj* gobj)
{
if (!ftAnim_IsFramesRemaining(gobj)) {
ft_8008A2BC(gobj);
}
}
void ftPp_SpecialAirN_Anim(HSD_GObj* gobj)
{
if (!ftAnim_IsFramesRemaining(gobj)) {
ftCo_Fall_Enter(gobj);
}
}
void ftPp_SpecialN_IASA(HSD_GObj* arg0) {}
void ftPp_SpecialAirN_IASA(HSD_GObj* arg0) {}
void ftPp_SpecialN_Phys(HSD_GObj* gobj)
{
ft_80084F3C(gobj);
}
void ftPp_SpecialAirN_Phys(HSD_GObj* gobj)
{
ft_80084EEC(gobj);
}
void ftPp_SpecialN_Coll(HSD_GObj* gobj)
{
if (!ft_80082708(gobj)) {
Fighter* fp1;
fp1 = GET_FIGHTER(gobj);
if (fp1->fv.nn.x222C != 0U) {
Fighter* fp2;
it_802C17DC(fp1->fv.nn.x222C);
fp2 = GET_FIGHTER(gobj);
if ((u32) fp1->fv.nn.x222C == (u32) fp2->fv.nn.x222C) {
fp2->fv.nn.x222C = 0U;
fp2->death2_cb = 0U;
fp2->take_dmg_cb = 0U;
}
}
ftCo_Fall_Enter(gobj);
}
}
void ftPp_SpecialAirN_Coll(Fighter_GObj* gobj)
{
Fighter *fp, *fp1, *fp2;
ftIceClimberAttributes* da;
PAD_STACK(16);
fp = gobj->user_data;
da = fp->dat_attrs;
if (ft_80081D0C(gobj) != GA_Ground) {
fp1 = gobj->user_data;
if (fp1->fv.pp.x222C != 0) {
it_802C17DC(fp1->fv.pp.x222C);
fp2 = gobj->user_data;
if (fp1->fv.pp.x222C == fp2->fv.pp.x222C) {
fp2->fv.pp.x222C = 0U;
fp2->death2_cb = NULL;
fp2->take_dmg_cb = NULL;
}
}
fp->fv.pp.x224C = 0;
fp->fv.pp.x2250 = 0.0f;
ftCo_LandingFallSpecial_Enter(gobj, false, da->x8);
}
}
static inline void inlineA0(Fighter_GObj* gobj, Fighter* other_fp)
{
Fighter* fp = GET_FIGHTER(gobj);
if (other_fp->fv.pp.x222C == fp->fv.pp.x222C) {
fp->fv.pp.x222C = NULL;
fp->death2_cb = NULL;
fp->take_dmg_cb = NULL;
}
}
static inline void inlineA1(Item_GObj* item_gobj, Fighter* fp) {}
void ftPp_SpecialN_8011F500(Fighter_GObj* gobj)
{
Fighter* fp = GET_FIGHTER(gobj);
u32 cmd_var0 = fp->cmd_vars[0];
if (cmd_var0 == 0) {
return;
}
if (cmd_var0 == 1) {
ftIceClimberAttributes* da = fp->dat_attrs;
Vec3 pos;
PAD_STACK(4 * 2);
lb_8000B1CC(fp->parts[0].joint, NULL, &pos);
pos.x = da->xC * fp->facing_dir + pos.x;
pos.y += da->x10 + fp->fv.pp.x2250;
fp->fv.pp.x222C = it_802C1590(gobj, &pos, 106, fp->facing_dir);
ft_PlaySFX(fp, 130021, 127, 64);
if (fp->fv.pp.x222C != NULL) {
fp->death2_cb = ftPp_Init_8011F060;
fp->take_dmg_cb = ftPp_Init_8011F060;
}
fp->cmd_vars[0] = 0;
} else if (cmd_var0 == 2) {
if (fp->fv.pp.x222C != NULL) {
it_802C16F8(fp->fv.pp.x222C);
fp->cmd_vars[0] = 0;
if (fp->kind == FTKIND_POPO) {
ft_800881D8(fp, 130141, 127, 64);
} else {
ft_800881D8(fp, 130090, 127, 64);
}
ft_PlaySFX(fp, 130024, 127, 64);
inlineA0(gobj, fp);
}
}
}
| 0 | 0.838025 | 1 | 0.838025 | game-dev | MEDIA | 0.35831 | game-dev | 0.9289 | 1 | 0.9289 |
katboi01/UmaViewer | 8,290 | Assets/Plugins/RootMotion/FinalIK/Tools/Recoil.cs | using UnityEngine;
using System.Collections;
namespace RootMotion.FinalIK {
/// <summary>
/// Procedural recoil using FBBIK.
/// </summary>
public class Recoil : OffsetModifier {
[System.Serializable]
public class RecoilOffset {
[Tooltip("Offset vector for the associated effector when doing recoil.")]
public Vector3 offset;
[Tooltip("When firing before the last recoil has faded, how much of the current recoil offset will be maintained?")]
[Range(0f, 1f)] public float additivity = 1f;
[Tooltip("Max additive recoil for automatic fire.")]
public float maxAdditiveOffsetMag = 0.2f;
// Linking this to an effector
[System.Serializable]
public class EffectorLink {
[Tooltip("Type of the FBBIK effector to use")]
public FullBodyBipedEffector effector;
[Tooltip("Weight of using this effector")]
public float weight;
}
[Tooltip("Linking this recoil offset to FBBIK effectors.")]
public EffectorLink[] effectorLinks;
private Vector3 additiveOffset;
private Vector3 lastOffset;
// Start recoil
public void Start() {
if (additivity <= 0f) return;
additiveOffset = Vector3.ClampMagnitude(lastOffset * additivity, maxAdditiveOffsetMag);
}
// Apply offset to FBBIK effectors
public void Apply(IKSolverFullBodyBiped solver, Quaternion rotation, float masterWeight, float length, float timeLeft) {
additiveOffset = Vector3.Lerp(Vector3.zero, additiveOffset, timeLeft / length);
lastOffset = (rotation * (offset * masterWeight)) + (rotation * additiveOffset);
foreach (EffectorLink e in effectorLinks) {
solver.GetEffector(e.effector).positionOffset += lastOffset * e.weight;
}
}
}
[System.Serializable]
public enum Handedness {
Right,
Left
}
[Tooltip("Reference to the AimIK component. Optional, only used to getting the aiming direction.")]
public AimIK aimIK;
[Tooltip("Set this true if you are using IKExecutionOrder.cs or a custom script to force AimIK solve after FBBIK.")]
public bool aimIKSolvedLast;
[Tooltip("Which hand is holding the weapon?")]
public Handedness handedness;
[Tooltip("Check for 2-handed weapons.")]
public bool twoHanded = true;
[Tooltip("Weight curve for the recoil offsets. Recoil procedure is as long as this curve.")]
public AnimationCurve recoilWeight;
[Tooltip("How much is the magnitude randomized each time Recoil is called?")]
public float magnitudeRandom = 0.1f;
[Tooltip("How much is the rotation randomized each time Recoil is called?")]
public Vector3 rotationRandom;
[Tooltip("Rotating the primary hand bone for the recoil (in local space).")]
public Vector3 handRotationOffset;
[Tooltip("Time of blending in another recoil when doing automatic fire.")]
public float blendTime;
[Space(10)]
[Tooltip("FBBIK effector position offsets for the recoil (in aiming direction space).")]
public RecoilOffset[] offsets;
[HideInInspector] public Quaternion rotationOffset = Quaternion.identity;
private float magnitudeMlp = 1f;
private float endTime = -1f;
private Quaternion handRotation, secondaryHandRelativeRotation, randomRotation;
private float length = 1f;
private bool initiated;
private float blendWeight;
private float w;
private Quaternion primaryHandRotation = Quaternion.identity;
//private Quaternion secondaryHandRotation = Quaternion.identity;
private bool handRotationsSet;
private Vector3 aimIKAxis;
/// <summary>
/// Returns true if recoil has finished or has not been called at all.
/// </summary>
public bool isFinished {
get {
return Time.time > endTime;
}
}
/// <summary>
/// Sets the starting rotations for the hands for 1 frame. Use this if the final rotation of the hands will not be the same as before FBBIK solves.
/// </summary>
public void SetHandRotations(Quaternion leftHandRotation, Quaternion rightHandRotation) {
if (handedness == Handedness.Left) {
primaryHandRotation = leftHandRotation;
//secondaryHandRotation = rightHandRotation;
} else {
primaryHandRotation = rightHandRotation;
//secondaryHandRotation = leftHandRotation;
}
handRotationsSet = true;
}
/// <summary>
/// Starts the recoil procedure.
/// </summary>
public void Fire(float magnitude) {
float rnd = magnitude * UnityEngine.Random.value * magnitudeRandom;
magnitudeMlp = magnitude + rnd;
randomRotation = Quaternion.Euler(rotationRandom * UnityEngine.Random.value);
foreach (RecoilOffset offset in offsets) {
offset.Start();
}
if (Time.time < endTime) blendWeight = 0f;
else blendWeight = 1f;
Keyframe[] keys = recoilWeight.keys;
length = keys[keys.Length - 1].time;
endTime = Time.time + length;
}
protected override void OnModifyOffset() {
if (aimIK != null) aimIKAxis = aimIK.solver.axis;
if (Time.time >= endTime) {
rotationOffset = Quaternion.identity;
return;
}
if (!initiated && ik != null) {
initiated = true;
ik.solver.OnPostUpdate += AfterFBBIK;
if (aimIK != null) aimIK.solver.OnPostUpdate += AfterAimIK;
}
blendTime = Mathf.Max(blendTime, 0f);
if (blendTime > 0f) blendWeight = Mathf.Min(blendWeight + Time.deltaTime * (1f / blendTime), 1f);
else blendWeight = 1f;
// Current weight of offset
float wTarget = recoilWeight.Evaluate(length - (endTime - Time.time)) * magnitudeMlp;
w = Mathf.Lerp(w, wTarget, blendWeight);
// Find the rotation space of the recoil
Quaternion lookRotation = aimIK != null && aimIK.solver.transform != null && !aimIKSolvedLast? Quaternion.LookRotation(aimIK.solver.IKPosition - aimIK.solver.transform.position, ik.references.root.up): ik.references.root.rotation;
lookRotation = randomRotation * lookRotation;
// Apply FBBIK effector positionOffsets
foreach (RecoilOffset offset in offsets) {
offset.Apply(ik.solver, lookRotation, w, length, endTime - Time.time);
}
if (!handRotationsSet) {
primaryHandRotation = primaryHand.rotation;
//if (twoHanded) secondaryHandRotation = secondaryHand.rotation;
}
handRotationsSet = false;
// Rotation offset of the primary hand
rotationOffset = Quaternion.Lerp(Quaternion.identity, Quaternion.Euler(randomRotation * primaryHandRotation * handRotationOffset), w);
handRotation = rotationOffset * primaryHandRotation;
// Fix the secondary hand relative to the primary hand
if (twoHanded) {
Vector3 secondaryHandRelativePosition = Quaternion.Inverse(primaryHand.rotation) * (secondaryHand.position - primaryHand.position);
secondaryHandRelativeRotation = Quaternion.Inverse(primaryHand.rotation) * secondaryHand.rotation;
Vector3 primaryHandPosition = primaryHand.position + primaryHandEffector.positionOffset;
Vector3 secondaryHandPosition = primaryHandPosition + handRotation * secondaryHandRelativePosition;
secondaryHandEffector.positionOffset += secondaryHandPosition - (secondaryHand.position + secondaryHandEffector.positionOffset);
}
if (aimIK != null && aimIKSolvedLast) aimIK.solver.axis = Quaternion.Inverse(ik.references.root.rotation) * Quaternion.Inverse(rotationOffset) * aimIKAxis;
}
private void AfterFBBIK() {
if (Time.time >= endTime) return;
// Rotate the hand bones
primaryHand.rotation = handRotation;
if (twoHanded) secondaryHand.rotation = primaryHand.rotation * secondaryHandRelativeRotation;
}
private void AfterAimIK() {
if (aimIKSolvedLast) aimIK.solver.axis = aimIKAxis;
}
// Shortcuts
private IKEffector primaryHandEffector {
get {
if (handedness == Handedness.Right) return ik.solver.rightHandEffector;
return ik.solver.leftHandEffector;
}
}
private IKEffector secondaryHandEffector {
get {
if (handedness == Handedness.Right) return ik.solver.leftHandEffector;
return ik.solver.rightHandEffector;
}
}
private Transform primaryHand {
get {
return primaryHandEffector.bone;
}
}
private Transform secondaryHand {
get {
return secondaryHandEffector.bone;
}
}
protected override void OnDestroy() {
base.OnDestroy();
if (ik != null && initiated) {
ik.solver.OnPostUpdate -= AfterFBBIK;
if (aimIK != null) aimIK.solver.OnPostUpdate -= AfterAimIK;
}
}
}
}
| 0 | 0.969352 | 1 | 0.969352 | game-dev | MEDIA | 0.857695 | game-dev | 0.982242 | 1 | 0.982242 |
onitama/OpenHSP | 186,551 | src/hsp3dish/gameplay/src/lua/lua_RadioButton.cpp | // Autogenerated by gameplay-luagen
#include "Base.h"
#include "ScriptController.h"
#include "lua_RadioButton.h"
#include "Animation.h"
#include "AnimationTarget.h"
#include "Base.h"
#include "Button.h"
#include "Control.h"
#include "Form.h"
#include "Game.h"
#include "Gamepad.h"
#include "Label.h"
#include "MaterialParameter.h"
#include "Node.h"
#include "RadioButton.h"
#include "Ref.h"
#include "ScriptController.h"
#include "ScriptTarget.h"
#include "Theme.h"
namespace gameplay
{
void luaRegister_RadioButton()
{
const luaL_Reg lua_members[] =
{
{"addListener", lua_RadioButton_addListener},
{"addRef", lua_RadioButton_addRef},
{"addScript", lua_RadioButton_addScript},
{"addScriptCallback", lua_RadioButton_addScriptCallback},
{"canFocus", lua_RadioButton_canFocus},
{"clearScripts", lua_RadioButton_clearScripts},
{"createAnimation", lua_RadioButton_createAnimation},
{"createAnimationFromBy", lua_RadioButton_createAnimationFromBy},
{"createAnimationFromTo", lua_RadioButton_createAnimationFromTo},
{"destroyAnimation", lua_RadioButton_destroyAnimation},
{"getAbsoluteBounds", lua_RadioButton_getAbsoluteBounds},
{"getAlignment", lua_RadioButton_getAlignment},
{"getAnimation", lua_RadioButton_getAnimation},
{"getAnimationPropertyComponentCount", lua_RadioButton_getAnimationPropertyComponentCount},
{"getAnimationPropertyValue", lua_RadioButton_getAnimationPropertyValue},
{"getAutoSize", lua_RadioButton_getAutoSize},
{"getBorder", lua_RadioButton_getBorder},
{"getBounds", lua_RadioButton_getBounds},
{"getClip", lua_RadioButton_getClip},
{"getClipBounds", lua_RadioButton_getClipBounds},
{"getConsumeInputEvents", lua_RadioButton_getConsumeInputEvents},
{"getCursorColor", lua_RadioButton_getCursorColor},
{"getCursorRegion", lua_RadioButton_getCursorRegion},
{"getCursorUVs", lua_RadioButton_getCursorUVs},
{"getFocusIndex", lua_RadioButton_getFocusIndex},
{"getFont", lua_RadioButton_getFont},
{"getFontSize", lua_RadioButton_getFontSize},
{"getGroupId", lua_RadioButton_getGroupId},
{"getHeight", lua_RadioButton_getHeight},
{"getId", lua_RadioButton_getId},
{"getImageColor", lua_RadioButton_getImageColor},
{"getImageRegion", lua_RadioButton_getImageRegion},
{"getImageUVs", lua_RadioButton_getImageUVs},
{"getMargin", lua_RadioButton_getMargin},
{"getOpacity", lua_RadioButton_getOpacity},
{"getPadding", lua_RadioButton_getPadding},
{"getParent", lua_RadioButton_getParent},
{"getRefCount", lua_RadioButton_getRefCount},
{"getScriptEvent", lua_RadioButton_getScriptEvent},
{"getSkinColor", lua_RadioButton_getSkinColor},
{"getSkinRegion", lua_RadioButton_getSkinRegion},
{"getState", lua_RadioButton_getState},
{"getStyle", lua_RadioButton_getStyle},
{"getText", lua_RadioButton_getText},
{"getTextAlignment", lua_RadioButton_getTextAlignment},
{"getTextColor", lua_RadioButton_getTextColor},
{"getTextRightToLeft", lua_RadioButton_getTextRightToLeft},
{"getTheme", lua_RadioButton_getTheme},
{"getTopLevelForm", lua_RadioButton_getTopLevelForm},
{"getTypeName", lua_RadioButton_getTypeName},
{"getWidth", lua_RadioButton_getWidth},
{"getX", lua_RadioButton_getX},
{"getY", lua_RadioButton_getY},
{"getZIndex", lua_RadioButton_getZIndex},
{"hasFocus", lua_RadioButton_hasFocus},
{"hasScriptListener", lua_RadioButton_hasScriptListener},
{"isChild", lua_RadioButton_isChild},
{"isContainer", lua_RadioButton_isContainer},
{"isEnabled", lua_RadioButton_isEnabled},
{"isEnabledInHierarchy", lua_RadioButton_isEnabledInHierarchy},
{"isHeightPercentage", lua_RadioButton_isHeightPercentage},
{"isSelected", lua_RadioButton_isSelected},
{"isVisible", lua_RadioButton_isVisible},
{"isVisibleInHierarchy", lua_RadioButton_isVisibleInHierarchy},
{"isWidthPercentage", lua_RadioButton_isWidthPercentage},
{"isXPercentage", lua_RadioButton_isXPercentage},
{"isYPercentage", lua_RadioButton_isYPercentage},
{"release", lua_RadioButton_release},
{"removeListener", lua_RadioButton_removeListener},
{"removeScript", lua_RadioButton_removeScript},
{"removeScriptCallback", lua_RadioButton_removeScriptCallback},
{"setAlignment", lua_RadioButton_setAlignment},
{"setAnimationPropertyValue", lua_RadioButton_setAnimationPropertyValue},
{"setAutoSize", lua_RadioButton_setAutoSize},
{"setBorder", lua_RadioButton_setBorder},
{"setBounds", lua_RadioButton_setBounds},
{"setCanFocus", lua_RadioButton_setCanFocus},
{"setConsumeInputEvents", lua_RadioButton_setConsumeInputEvents},
{"setCursorColor", lua_RadioButton_setCursorColor},
{"setCursorRegion", lua_RadioButton_setCursorRegion},
{"setEnabled", lua_RadioButton_setEnabled},
{"setFocus", lua_RadioButton_setFocus},
{"setFocusIndex", lua_RadioButton_setFocusIndex},
{"setFont", lua_RadioButton_setFont},
{"setFontSize", lua_RadioButton_setFontSize},
{"setGroupId", lua_RadioButton_setGroupId},
{"setHeight", lua_RadioButton_setHeight},
{"setId", lua_RadioButton_setId},
{"setImageColor", lua_RadioButton_setImageColor},
{"setImageRegion", lua_RadioButton_setImageRegion},
{"setMargin", lua_RadioButton_setMargin},
{"setOpacity", lua_RadioButton_setOpacity},
{"setPadding", lua_RadioButton_setPadding},
{"setPosition", lua_RadioButton_setPosition},
{"setSelected", lua_RadioButton_setSelected},
{"setSize", lua_RadioButton_setSize},
{"setSkinColor", lua_RadioButton_setSkinColor},
{"setSkinRegion", lua_RadioButton_setSkinRegion},
{"setStyle", lua_RadioButton_setStyle},
{"setText", lua_RadioButton_setText},
{"setTextAlignment", lua_RadioButton_setTextAlignment},
{"setTextColor", lua_RadioButton_setTextColor},
{"setTextRightToLeft", lua_RadioButton_setTextRightToLeft},
{"setVisible", lua_RadioButton_setVisible},
{"setWidth", lua_RadioButton_setWidth},
{"setX", lua_RadioButton_setX},
{"setY", lua_RadioButton_setY},
{"setZIndex", lua_RadioButton_setZIndex},
{NULL, NULL}
};
const luaL_Reg lua_statics[] =
{
{"ANIMATE_OPACITY", lua_RadioButton_static_ANIMATE_OPACITY},
{"ANIMATE_POSITION", lua_RadioButton_static_ANIMATE_POSITION},
{"ANIMATE_POSITION_X", lua_RadioButton_static_ANIMATE_POSITION_X},
{"ANIMATE_POSITION_Y", lua_RadioButton_static_ANIMATE_POSITION_Y},
{"ANIMATE_SIZE", lua_RadioButton_static_ANIMATE_SIZE},
{"ANIMATE_SIZE_HEIGHT", lua_RadioButton_static_ANIMATE_SIZE_HEIGHT},
{"ANIMATE_SIZE_WIDTH", lua_RadioButton_static_ANIMATE_SIZE_WIDTH},
{"create", lua_RadioButton_static_create},
{NULL, NULL}
};
std::vector<std::string> scopePath;
gameplay::ScriptUtil::registerClass("RadioButton", lua_members, NULL, lua_RadioButton__gc, lua_statics, scopePath);
}
static RadioButton* getInstance(lua_State* state)
{
void* userdata = luaL_checkudata(state, 1, "RadioButton");
luaL_argcheck(state, userdata != NULL, 1, "'RadioButton' expected.");
return (RadioButton*)((gameplay::ScriptUtil::LuaObject*)userdata)->instance;
}
int lua_RadioButton__gc(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
void* userdata = luaL_checkudata(state, 1, "RadioButton");
luaL_argcheck(state, userdata != NULL, 1, "'RadioButton' expected.");
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)userdata;
if (object->owns)
{
RadioButton* instance = (RadioButton*)object->instance;
SAFE_RELEASE(instance);
}
return 0;
}
lua_pushstring(state, "lua_RadioButton__gc - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_addListener(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 3:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TUSERDATA || lua_type(state, 2) == LUA_TTABLE || lua_type(state, 2) == LUA_TNIL) &&
lua_type(state, 3) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
bool param1Valid;
gameplay::ScriptUtil::LuaArray<Control::Listener> param1 = gameplay::ScriptUtil::getObjectPointer<Control::Listener>(2, "ControlListener", false, ¶m1Valid);
if (!param1Valid)
{
lua_pushstring(state, "Failed to convert parameter 1 to type 'Control::Listener'.");
lua_error(state);
}
// Get parameter 2 off the stack.
int param2 = (int)luaL_checkint(state, 3);
RadioButton* instance = getInstance(state);
instance->addListener(param1, param2);
return 0;
}
lua_pushstring(state, "lua_RadioButton_addListener - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 3).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_addRef(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
instance->addRef();
return 0;
}
lua_pushstring(state, "lua_RadioButton_addRef - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_addScript(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TSTRING || lua_type(state, 2) == LUA_TNIL))
{
// Get parameter 1 off the stack.
const char* param1 = gameplay::ScriptUtil::getString(2, false);
RadioButton* instance = getInstance(state);
void* returnPtr = ((void*)instance->addScript(param1));
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = false;
luaL_getmetatable(state, "Script");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
lua_pushstring(state, "lua_RadioButton_addScript - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 2).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_addScriptCallback(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 3:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TUSERDATA || lua_type(state, 2) == LUA_TTABLE || lua_type(state, 2) == LUA_TNIL) &&
(lua_type(state, 3) == LUA_TSTRING || lua_type(state, 3) == LUA_TNIL))
{
// Get parameter 1 off the stack.
bool param1Valid;
gameplay::ScriptUtil::LuaArray<ScriptTarget::Event> param1 = gameplay::ScriptUtil::getObjectPointer<ScriptTarget::Event>(2, "ScriptTargetEvent", false, ¶m1Valid);
if (!param1Valid)
{
lua_pushstring(state, "Failed to convert parameter 1 to type 'ScriptTarget::Event'.");
lua_error(state);
}
// Get parameter 2 off the stack.
const char* param2 = gameplay::ScriptUtil::getString(3, false);
RadioButton* instance = getInstance(state);
instance->addScriptCallback(param1, param2);
return 0;
}
lua_pushstring(state, "lua_RadioButton_addScriptCallback - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 3).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_canFocus(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
bool result = instance->canFocus();
// Push the return value onto the stack.
lua_pushboolean(state, result);
return 1;
}
lua_pushstring(state, "lua_RadioButton_canFocus - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_clearScripts(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
instance->clearScripts();
return 0;
}
lua_pushstring(state, "lua_RadioButton_clearScripts - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_createAnimation(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 3:
{
do
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TSTRING || lua_type(state, 2) == LUA_TNIL) &&
(lua_type(state, 3) == LUA_TSTRING || lua_type(state, 3) == LUA_TNIL))
{
// Get parameter 1 off the stack.
const char* param1 = gameplay::ScriptUtil::getString(2, false);
// Get parameter 2 off the stack.
const char* param2 = gameplay::ScriptUtil::getString(3, false);
RadioButton* instance = getInstance(state);
void* returnPtr = ((void*)instance->createAnimation(param1, param2));
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = false;
luaL_getmetatable(state, "Animation");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
} while (0);
do
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TSTRING || lua_type(state, 2) == LUA_TNIL) &&
(lua_type(state, 3) == LUA_TUSERDATA || lua_type(state, 3) == LUA_TTABLE || lua_type(state, 3) == LUA_TNIL))
{
// Get parameter 1 off the stack.
const char* param1 = gameplay::ScriptUtil::getString(2, false);
// Get parameter 2 off the stack.
bool param2Valid;
gameplay::ScriptUtil::LuaArray<Properties> param2 = gameplay::ScriptUtil::getObjectPointer<Properties>(3, "Properties", false, ¶m2Valid);
if (!param2Valid)
break;
RadioButton* instance = getInstance(state);
void* returnPtr = ((void*)instance->createAnimation(param1, param2));
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = false;
luaL_getmetatable(state, "Animation");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
} while (0);
lua_pushstring(state, "lua_RadioButton_createAnimation - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
case 7:
{
do
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TSTRING || lua_type(state, 2) == LUA_TNIL) &&
lua_type(state, 3) == LUA_TNUMBER &&
lua_type(state, 4) == LUA_TNUMBER &&
(lua_type(state, 5) == LUA_TTABLE || lua_type(state, 5) == LUA_TLIGHTUSERDATA) &&
(lua_type(state, 6) == LUA_TTABLE || lua_type(state, 6) == LUA_TLIGHTUSERDATA) &&
lua_type(state, 7) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
const char* param1 = gameplay::ScriptUtil::getString(2, false);
// Get parameter 2 off the stack.
int param2 = (int)luaL_checkint(state, 3);
// Get parameter 3 off the stack.
unsigned int param3 = (unsigned int)luaL_checkunsigned(state, 4);
// Get parameter 4 off the stack.
gameplay::ScriptUtil::LuaArray<unsigned int> param4 = gameplay::ScriptUtil::getUnsignedIntPointer(5);
// Get parameter 5 off the stack.
gameplay::ScriptUtil::LuaArray<float> param5 = gameplay::ScriptUtil::getFloatPointer(6);
// Get parameter 6 off the stack.
Curve::InterpolationType param6 = (Curve::InterpolationType)luaL_checkint(state, 7);
RadioButton* instance = getInstance(state);
void* returnPtr = ((void*)instance->createAnimation(param1, param2, param3, param4, param5, param6));
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = false;
luaL_getmetatable(state, "Animation");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
} while (0);
lua_pushstring(state, "lua_RadioButton_createAnimation - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
case 9:
{
do
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TSTRING || lua_type(state, 2) == LUA_TNIL) &&
lua_type(state, 3) == LUA_TNUMBER &&
lua_type(state, 4) == LUA_TNUMBER &&
(lua_type(state, 5) == LUA_TTABLE || lua_type(state, 5) == LUA_TLIGHTUSERDATA) &&
(lua_type(state, 6) == LUA_TTABLE || lua_type(state, 6) == LUA_TLIGHTUSERDATA) &&
(lua_type(state, 7) == LUA_TTABLE || lua_type(state, 7) == LUA_TLIGHTUSERDATA) &&
(lua_type(state, 8) == LUA_TTABLE || lua_type(state, 8) == LUA_TLIGHTUSERDATA) &&
lua_type(state, 9) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
const char* param1 = gameplay::ScriptUtil::getString(2, false);
// Get parameter 2 off the stack.
int param2 = (int)luaL_checkint(state, 3);
// Get parameter 3 off the stack.
unsigned int param3 = (unsigned int)luaL_checkunsigned(state, 4);
// Get parameter 4 off the stack.
gameplay::ScriptUtil::LuaArray<unsigned int> param4 = gameplay::ScriptUtil::getUnsignedIntPointer(5);
// Get parameter 5 off the stack.
gameplay::ScriptUtil::LuaArray<float> param5 = gameplay::ScriptUtil::getFloatPointer(6);
// Get parameter 6 off the stack.
gameplay::ScriptUtil::LuaArray<float> param6 = gameplay::ScriptUtil::getFloatPointer(7);
// Get parameter 7 off the stack.
gameplay::ScriptUtil::LuaArray<float> param7 = gameplay::ScriptUtil::getFloatPointer(8);
// Get parameter 8 off the stack.
Curve::InterpolationType param8 = (Curve::InterpolationType)luaL_checkint(state, 9);
RadioButton* instance = getInstance(state);
void* returnPtr = ((void*)instance->createAnimation(param1, param2, param3, param4, param5, param6, param7, param8));
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = false;
luaL_getmetatable(state, "Animation");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
} while (0);
lua_pushstring(state, "lua_RadioButton_createAnimation - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 3, 7 or 9).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_createAnimationFromBy(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 7:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TSTRING || lua_type(state, 2) == LUA_TNIL) &&
lua_type(state, 3) == LUA_TNUMBER &&
(lua_type(state, 4) == LUA_TTABLE || lua_type(state, 4) == LUA_TLIGHTUSERDATA) &&
(lua_type(state, 5) == LUA_TTABLE || lua_type(state, 5) == LUA_TLIGHTUSERDATA) &&
lua_type(state, 6) == LUA_TNUMBER &&
lua_type(state, 7) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
const char* param1 = gameplay::ScriptUtil::getString(2, false);
// Get parameter 2 off the stack.
int param2 = (int)luaL_checkint(state, 3);
// Get parameter 3 off the stack.
gameplay::ScriptUtil::LuaArray<float> param3 = gameplay::ScriptUtil::getFloatPointer(4);
// Get parameter 4 off the stack.
gameplay::ScriptUtil::LuaArray<float> param4 = gameplay::ScriptUtil::getFloatPointer(5);
// Get parameter 5 off the stack.
Curve::InterpolationType param5 = (Curve::InterpolationType)luaL_checkint(state, 6);
// Get parameter 6 off the stack.
unsigned long param6 = (unsigned long)luaL_checkunsigned(state, 7);
RadioButton* instance = getInstance(state);
void* returnPtr = ((void*)instance->createAnimationFromBy(param1, param2, param3, param4, param5, param6));
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = false;
luaL_getmetatable(state, "Animation");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
lua_pushstring(state, "lua_RadioButton_createAnimationFromBy - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 7).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_createAnimationFromTo(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 7:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TSTRING || lua_type(state, 2) == LUA_TNIL) &&
lua_type(state, 3) == LUA_TNUMBER &&
(lua_type(state, 4) == LUA_TTABLE || lua_type(state, 4) == LUA_TLIGHTUSERDATA) &&
(lua_type(state, 5) == LUA_TTABLE || lua_type(state, 5) == LUA_TLIGHTUSERDATA) &&
lua_type(state, 6) == LUA_TNUMBER &&
lua_type(state, 7) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
const char* param1 = gameplay::ScriptUtil::getString(2, false);
// Get parameter 2 off the stack.
int param2 = (int)luaL_checkint(state, 3);
// Get parameter 3 off the stack.
gameplay::ScriptUtil::LuaArray<float> param3 = gameplay::ScriptUtil::getFloatPointer(4);
// Get parameter 4 off the stack.
gameplay::ScriptUtil::LuaArray<float> param4 = gameplay::ScriptUtil::getFloatPointer(5);
// Get parameter 5 off the stack.
Curve::InterpolationType param5 = (Curve::InterpolationType)luaL_checkint(state, 6);
// Get parameter 6 off the stack.
unsigned long param6 = (unsigned long)luaL_checkunsigned(state, 7);
RadioButton* instance = getInstance(state);
void* returnPtr = ((void*)instance->createAnimationFromTo(param1, param2, param3, param4, param5, param6));
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = false;
luaL_getmetatable(state, "Animation");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
lua_pushstring(state, "lua_RadioButton_createAnimationFromTo - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 7).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_destroyAnimation(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
instance->destroyAnimation();
return 0;
}
lua_pushstring(state, "lua_RadioButton_destroyAnimation - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TSTRING || lua_type(state, 2) == LUA_TNIL))
{
// Get parameter 1 off the stack.
const char* param1 = gameplay::ScriptUtil::getString(2, false);
RadioButton* instance = getInstance(state);
instance->destroyAnimation(param1);
return 0;
}
lua_pushstring(state, "lua_RadioButton_destroyAnimation - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1 or 2).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getAbsoluteBounds(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
void* returnPtr = (void*)&(instance->getAbsoluteBounds());
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = false;
luaL_getmetatable(state, "Rectangle");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
lua_pushstring(state, "lua_RadioButton_getAbsoluteBounds - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getAlignment(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
Control::Alignment result = instance->getAlignment();
// Push the return value onto the stack.
lua_pushnumber(state, (int)result);
return 1;
}
lua_pushstring(state, "lua_RadioButton_getAlignment - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getAnimation(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
void* returnPtr = ((void*)instance->getAnimation());
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = false;
luaL_getmetatable(state, "Animation");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
lua_pushstring(state, "lua_RadioButton_getAnimation - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TSTRING || lua_type(state, 2) == LUA_TNIL))
{
// Get parameter 1 off the stack.
const char* param1 = gameplay::ScriptUtil::getString(2, false);
RadioButton* instance = getInstance(state);
void* returnPtr = ((void*)instance->getAnimation(param1));
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = false;
luaL_getmetatable(state, "Animation");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
lua_pushstring(state, "lua_RadioButton_getAnimation - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1 or 2).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getAnimationPropertyComponentCount(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
int param1 = (int)luaL_checkint(state, 2);
RadioButton* instance = getInstance(state);
unsigned int result = instance->getAnimationPropertyComponentCount(param1);
// Push the return value onto the stack.
lua_pushunsigned(state, result);
return 1;
}
lua_pushstring(state, "lua_RadioButton_getAnimationPropertyComponentCount - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 2).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getAnimationPropertyValue(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 3:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER &&
(lua_type(state, 3) == LUA_TUSERDATA || lua_type(state, 3) == LUA_TTABLE || lua_type(state, 3) == LUA_TNIL))
{
// Get parameter 1 off the stack.
int param1 = (int)luaL_checkint(state, 2);
// Get parameter 2 off the stack.
bool param2Valid;
gameplay::ScriptUtil::LuaArray<AnimationValue> param2 = gameplay::ScriptUtil::getObjectPointer<AnimationValue>(3, "AnimationValue", false, ¶m2Valid);
if (!param2Valid)
{
lua_pushstring(state, "Failed to convert parameter 2 to type 'AnimationValue'.");
lua_error(state);
}
RadioButton* instance = getInstance(state);
instance->getAnimationPropertyValue(param1, param2);
return 0;
}
lua_pushstring(state, "lua_RadioButton_getAnimationPropertyValue - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 3).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getAutoSize(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
Control::AutoSize result = instance->getAutoSize();
// Push the return value onto the stack.
lua_pushnumber(state, (int)result);
return 1;
}
lua_pushstring(state, "lua_RadioButton_getAutoSize - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getBorder(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
void* returnPtr = (void*)&(instance->getBorder());
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = false;
luaL_getmetatable(state, "ThemeSideRegions");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
lua_pushstring(state, "lua_RadioButton_getBorder - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
Control::State param1 = (Control::State)luaL_checkint(state, 2);
RadioButton* instance = getInstance(state);
void* returnPtr = (void*)&(instance->getBorder(param1));
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = false;
luaL_getmetatable(state, "ThemeSideRegions");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
lua_pushstring(state, "lua_RadioButton_getBorder - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1 or 2).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getBounds(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
void* returnPtr = (void*)&(instance->getBounds());
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = false;
luaL_getmetatable(state, "Rectangle");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
lua_pushstring(state, "lua_RadioButton_getBounds - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getClip(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
void* returnPtr = (void*)&(instance->getClip());
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = false;
luaL_getmetatable(state, "Rectangle");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
lua_pushstring(state, "lua_RadioButton_getClip - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getClipBounds(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
void* returnPtr = (void*)&(instance->getClipBounds());
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = false;
luaL_getmetatable(state, "Rectangle");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
lua_pushstring(state, "lua_RadioButton_getClipBounds - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getConsumeInputEvents(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
bool result = instance->getConsumeInputEvents();
// Push the return value onto the stack.
lua_pushboolean(state, result);
return 1;
}
lua_pushstring(state, "lua_RadioButton_getConsumeInputEvents - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getCursorColor(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
Control::State param1 = (Control::State)luaL_checkint(state, 2);
RadioButton* instance = getInstance(state);
void* returnPtr = (void*)&(instance->getCursorColor(param1));
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = false;
luaL_getmetatable(state, "Vector4");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
lua_pushstring(state, "lua_RadioButton_getCursorColor - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 2).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getCursorRegion(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
Control::State param1 = (Control::State)luaL_checkint(state, 2);
RadioButton* instance = getInstance(state);
void* returnPtr = (void*)&(instance->getCursorRegion(param1));
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = false;
luaL_getmetatable(state, "Rectangle");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
lua_pushstring(state, "lua_RadioButton_getCursorRegion - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 2).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getCursorUVs(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
Control::State param1 = (Control::State)luaL_checkint(state, 2);
RadioButton* instance = getInstance(state);
void* returnPtr = (void*)&(instance->getCursorUVs(param1));
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = false;
luaL_getmetatable(state, "ThemeUVs");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
lua_pushstring(state, "lua_RadioButton_getCursorUVs - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 2).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getFocusIndex(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
int result = instance->getFocusIndex();
// Push the return value onto the stack.
lua_pushinteger(state, result);
return 1;
}
lua_pushstring(state, "lua_RadioButton_getFocusIndex - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getFont(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
void* returnPtr = ((void*)instance->getFont());
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = false;
luaL_getmetatable(state, "Font");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
lua_pushstring(state, "lua_RadioButton_getFont - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
Control::State param1 = (Control::State)luaL_checkint(state, 2);
RadioButton* instance = getInstance(state);
void* returnPtr = ((void*)instance->getFont(param1));
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = false;
luaL_getmetatable(state, "Font");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
lua_pushstring(state, "lua_RadioButton_getFont - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1 or 2).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getFontSize(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
unsigned int result = instance->getFontSize();
// Push the return value onto the stack.
lua_pushunsigned(state, result);
return 1;
}
lua_pushstring(state, "lua_RadioButton_getFontSize - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
Control::State param1 = (Control::State)luaL_checkint(state, 2);
RadioButton* instance = getInstance(state);
unsigned int result = instance->getFontSize(param1);
// Push the return value onto the stack.
lua_pushunsigned(state, result);
return 1;
}
lua_pushstring(state, "lua_RadioButton_getFontSize - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1 or 2).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getGroupId(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
const char* result = instance->getGroupId();
// Push the return value onto the stack.
lua_pushstring(state, result);
return 1;
}
lua_pushstring(state, "lua_RadioButton_getGroupId - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getHeight(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
float result = instance->getHeight();
// Push the return value onto the stack.
lua_pushnumber(state, result);
return 1;
}
lua_pushstring(state, "lua_RadioButton_getHeight - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getId(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
const char* result = instance->getId();
// Push the return value onto the stack.
lua_pushstring(state, result);
return 1;
}
lua_pushstring(state, "lua_RadioButton_getId - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getImageColor(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 3:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TSTRING || lua_type(state, 2) == LUA_TNIL) &&
lua_type(state, 3) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
const char* param1 = gameplay::ScriptUtil::getString(2, false);
// Get parameter 2 off the stack.
Control::State param2 = (Control::State)luaL_checkint(state, 3);
RadioButton* instance = getInstance(state);
void* returnPtr = (void*)&(instance->getImageColor(param1, param2));
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = false;
luaL_getmetatable(state, "Vector4");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
lua_pushstring(state, "lua_RadioButton_getImageColor - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 3).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getImageRegion(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 3:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TSTRING || lua_type(state, 2) == LUA_TNIL) &&
lua_type(state, 3) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
const char* param1 = gameplay::ScriptUtil::getString(2, false);
// Get parameter 2 off the stack.
Control::State param2 = (Control::State)luaL_checkint(state, 3);
RadioButton* instance = getInstance(state);
void* returnPtr = (void*)&(instance->getImageRegion(param1, param2));
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = false;
luaL_getmetatable(state, "Rectangle");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
lua_pushstring(state, "lua_RadioButton_getImageRegion - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 3).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getImageUVs(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 3:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TSTRING || lua_type(state, 2) == LUA_TNIL) &&
lua_type(state, 3) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
const char* param1 = gameplay::ScriptUtil::getString(2, false);
// Get parameter 2 off the stack.
Control::State param2 = (Control::State)luaL_checkint(state, 3);
RadioButton* instance = getInstance(state);
void* returnPtr = (void*)&(instance->getImageUVs(param1, param2));
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = false;
luaL_getmetatable(state, "ThemeUVs");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
lua_pushstring(state, "lua_RadioButton_getImageUVs - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 3).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getMargin(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
void* returnPtr = (void*)&(instance->getMargin());
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = false;
luaL_getmetatable(state, "ThemeSideRegions");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
lua_pushstring(state, "lua_RadioButton_getMargin - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getOpacity(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
float result = instance->getOpacity();
// Push the return value onto the stack.
lua_pushnumber(state, result);
return 1;
}
lua_pushstring(state, "lua_RadioButton_getOpacity - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
Control::State param1 = (Control::State)luaL_checkint(state, 2);
RadioButton* instance = getInstance(state);
float result = instance->getOpacity(param1);
// Push the return value onto the stack.
lua_pushnumber(state, result);
return 1;
}
lua_pushstring(state, "lua_RadioButton_getOpacity - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1 or 2).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getPadding(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
void* returnPtr = (void*)&(instance->getPadding());
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = false;
luaL_getmetatable(state, "ThemeSideRegions");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
lua_pushstring(state, "lua_RadioButton_getPadding - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getParent(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
void* returnPtr = ((void*)instance->getParent());
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = false;
luaL_getmetatable(state, "Control");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
lua_pushstring(state, "lua_RadioButton_getParent - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getRefCount(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
unsigned int result = instance->getRefCount();
// Push the return value onto the stack.
lua_pushunsigned(state, result);
return 1;
}
lua_pushstring(state, "lua_RadioButton_getRefCount - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getScriptEvent(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TSTRING || lua_type(state, 2) == LUA_TNIL))
{
// Get parameter 1 off the stack.
const char* param1 = gameplay::ScriptUtil::getString(2, false);
RadioButton* instance = getInstance(state);
void* returnPtr = ((void*)instance->getScriptEvent(param1));
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = false;
luaL_getmetatable(state, "ScriptTargetEvent");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
lua_pushstring(state, "lua_RadioButton_getScriptEvent - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 2).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getSkinColor(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
void* returnPtr = (void*)&(instance->getSkinColor());
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = false;
luaL_getmetatable(state, "Vector4");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
lua_pushstring(state, "lua_RadioButton_getSkinColor - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
Control::State param1 = (Control::State)luaL_checkint(state, 2);
RadioButton* instance = getInstance(state);
void* returnPtr = (void*)&(instance->getSkinColor(param1));
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = false;
luaL_getmetatable(state, "Vector4");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
lua_pushstring(state, "lua_RadioButton_getSkinColor - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1 or 2).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getSkinRegion(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
void* returnPtr = (void*)&(instance->getSkinRegion());
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = false;
luaL_getmetatable(state, "Rectangle");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
lua_pushstring(state, "lua_RadioButton_getSkinRegion - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
Control::State param1 = (Control::State)luaL_checkint(state, 2);
RadioButton* instance = getInstance(state);
void* returnPtr = (void*)&(instance->getSkinRegion(param1));
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = false;
luaL_getmetatable(state, "Rectangle");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
lua_pushstring(state, "lua_RadioButton_getSkinRegion - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1 or 2).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getState(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
Control::State result = instance->getState();
// Push the return value onto the stack.
lua_pushnumber(state, (int)result);
return 1;
}
lua_pushstring(state, "lua_RadioButton_getState - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getStyle(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
void* returnPtr = ((void*)instance->getStyle());
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = false;
luaL_getmetatable(state, "ThemeStyle");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
lua_pushstring(state, "lua_RadioButton_getStyle - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getText(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
const char* result = instance->getText();
// Push the return value onto the stack.
lua_pushstring(state, result);
return 1;
}
lua_pushstring(state, "lua_RadioButton_getText - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getTextAlignment(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
Font::Justify result = instance->getTextAlignment();
// Push the return value onto the stack.
lua_pushnumber(state, (int)result);
return 1;
}
lua_pushstring(state, "lua_RadioButton_getTextAlignment - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
Control::State param1 = (Control::State)luaL_checkint(state, 2);
RadioButton* instance = getInstance(state);
Font::Justify result = instance->getTextAlignment(param1);
// Push the return value onto the stack.
lua_pushnumber(state, (int)result);
return 1;
}
lua_pushstring(state, "lua_RadioButton_getTextAlignment - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1 or 2).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getTextColor(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
void* returnPtr = (void*)&(instance->getTextColor());
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = false;
luaL_getmetatable(state, "Vector4");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
lua_pushstring(state, "lua_RadioButton_getTextColor - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
Control::State param1 = (Control::State)luaL_checkint(state, 2);
RadioButton* instance = getInstance(state);
void* returnPtr = (void*)&(instance->getTextColor(param1));
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = false;
luaL_getmetatable(state, "Vector4");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
lua_pushstring(state, "lua_RadioButton_getTextColor - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1 or 2).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getTextRightToLeft(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
bool result = instance->getTextRightToLeft();
// Push the return value onto the stack.
lua_pushboolean(state, result);
return 1;
}
lua_pushstring(state, "lua_RadioButton_getTextRightToLeft - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
Control::State param1 = (Control::State)luaL_checkint(state, 2);
RadioButton* instance = getInstance(state);
bool result = instance->getTextRightToLeft(param1);
// Push the return value onto the stack.
lua_pushboolean(state, result);
return 1;
}
lua_pushstring(state, "lua_RadioButton_getTextRightToLeft - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1 or 2).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getTheme(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
void* returnPtr = ((void*)instance->getTheme());
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = false;
luaL_getmetatable(state, "Theme");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
lua_pushstring(state, "lua_RadioButton_getTheme - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getTopLevelForm(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
void* returnPtr = ((void*)instance->getTopLevelForm());
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = false;
luaL_getmetatable(state, "Form");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
lua_pushstring(state, "lua_RadioButton_getTopLevelForm - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getTypeName(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
const char* result = instance->getTypeName();
// Push the return value onto the stack.
lua_pushstring(state, result);
return 1;
}
lua_pushstring(state, "lua_RadioButton_getTypeName - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getWidth(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
float result = instance->getWidth();
// Push the return value onto the stack.
lua_pushnumber(state, result);
return 1;
}
lua_pushstring(state, "lua_RadioButton_getWidth - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getX(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
float result = instance->getX();
// Push the return value onto the stack.
lua_pushnumber(state, result);
return 1;
}
lua_pushstring(state, "lua_RadioButton_getX - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getY(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
float result = instance->getY();
// Push the return value onto the stack.
lua_pushnumber(state, result);
return 1;
}
lua_pushstring(state, "lua_RadioButton_getY - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_getZIndex(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
int result = instance->getZIndex();
// Push the return value onto the stack.
lua_pushinteger(state, result);
return 1;
}
lua_pushstring(state, "lua_RadioButton_getZIndex - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_hasFocus(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
bool result = instance->hasFocus();
// Push the return value onto the stack.
lua_pushboolean(state, result);
return 1;
}
lua_pushstring(state, "lua_RadioButton_hasFocus - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_hasScriptListener(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 2:
{
do
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TSTRING || lua_type(state, 2) == LUA_TNIL))
{
// Get parameter 1 off the stack.
const char* param1 = gameplay::ScriptUtil::getString(2, false);
RadioButton* instance = getInstance(state);
bool result = instance->hasScriptListener(param1);
// Push the return value onto the stack.
lua_pushboolean(state, result);
return 1;
}
} while (0);
do
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TUSERDATA || lua_type(state, 2) == LUA_TTABLE || lua_type(state, 2) == LUA_TNIL))
{
// Get parameter 1 off the stack.
bool param1Valid;
gameplay::ScriptUtil::LuaArray<ScriptTarget::Event> param1 = gameplay::ScriptUtil::getObjectPointer<ScriptTarget::Event>(2, "ScriptTargetEvent", false, ¶m1Valid);
if (!param1Valid)
break;
RadioButton* instance = getInstance(state);
bool result = instance->hasScriptListener(param1);
// Push the return value onto the stack.
lua_pushboolean(state, result);
return 1;
}
} while (0);
lua_pushstring(state, "lua_RadioButton_hasScriptListener - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 2).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_isChild(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TUSERDATA || lua_type(state, 2) == LUA_TTABLE || lua_type(state, 2) == LUA_TNIL))
{
// Get parameter 1 off the stack.
bool param1Valid;
gameplay::ScriptUtil::LuaArray<Control> param1 = gameplay::ScriptUtil::getObjectPointer<Control>(2, "Control", false, ¶m1Valid);
if (!param1Valid)
{
lua_pushstring(state, "Failed to convert parameter 1 to type 'Control'.");
lua_error(state);
}
RadioButton* instance = getInstance(state);
bool result = instance->isChild(param1);
// Push the return value onto the stack.
lua_pushboolean(state, result);
return 1;
}
lua_pushstring(state, "lua_RadioButton_isChild - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 2).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_isContainer(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
bool result = instance->isContainer();
// Push the return value onto the stack.
lua_pushboolean(state, result);
return 1;
}
lua_pushstring(state, "lua_RadioButton_isContainer - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_isEnabled(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
bool result = instance->isEnabled();
// Push the return value onto the stack.
lua_pushboolean(state, result);
return 1;
}
lua_pushstring(state, "lua_RadioButton_isEnabled - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_isEnabledInHierarchy(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
bool result = instance->isEnabledInHierarchy();
// Push the return value onto the stack.
lua_pushboolean(state, result);
return 1;
}
lua_pushstring(state, "lua_RadioButton_isEnabledInHierarchy - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_isHeightPercentage(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
bool result = instance->isHeightPercentage();
// Push the return value onto the stack.
lua_pushboolean(state, result);
return 1;
}
lua_pushstring(state, "lua_RadioButton_isHeightPercentage - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_isSelected(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
bool result = instance->isSelected();
// Push the return value onto the stack.
lua_pushboolean(state, result);
return 1;
}
lua_pushstring(state, "lua_RadioButton_isSelected - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_isVisible(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
bool result = instance->isVisible();
// Push the return value onto the stack.
lua_pushboolean(state, result);
return 1;
}
lua_pushstring(state, "lua_RadioButton_isVisible - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_isVisibleInHierarchy(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
bool result = instance->isVisibleInHierarchy();
// Push the return value onto the stack.
lua_pushboolean(state, result);
return 1;
}
lua_pushstring(state, "lua_RadioButton_isVisibleInHierarchy - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_isWidthPercentage(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
bool result = instance->isWidthPercentage();
// Push the return value onto the stack.
lua_pushboolean(state, result);
return 1;
}
lua_pushstring(state, "lua_RadioButton_isWidthPercentage - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_isXPercentage(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
bool result = instance->isXPercentage();
// Push the return value onto the stack.
lua_pushboolean(state, result);
return 1;
}
lua_pushstring(state, "lua_RadioButton_isXPercentage - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_isYPercentage(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
bool result = instance->isYPercentage();
// Push the return value onto the stack.
lua_pushboolean(state, result);
return 1;
}
lua_pushstring(state, "lua_RadioButton_isYPercentage - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_release(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
instance->release();
return 0;
}
lua_pushstring(state, "lua_RadioButton_release - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_removeListener(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TUSERDATA || lua_type(state, 2) == LUA_TTABLE || lua_type(state, 2) == LUA_TNIL))
{
// Get parameter 1 off the stack.
bool param1Valid;
gameplay::ScriptUtil::LuaArray<Control::Listener> param1 = gameplay::ScriptUtil::getObjectPointer<Control::Listener>(2, "ControlListener", false, ¶m1Valid);
if (!param1Valid)
{
lua_pushstring(state, "Failed to convert parameter 1 to type 'Control::Listener'.");
lua_error(state);
}
RadioButton* instance = getInstance(state);
instance->removeListener(param1);
return 0;
}
lua_pushstring(state, "lua_RadioButton_removeListener - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 2).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_removeScript(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TSTRING || lua_type(state, 2) == LUA_TNIL))
{
// Get parameter 1 off the stack.
const char* param1 = gameplay::ScriptUtil::getString(2, false);
RadioButton* instance = getInstance(state);
bool result = instance->removeScript(param1);
// Push the return value onto the stack.
lua_pushboolean(state, result);
return 1;
}
lua_pushstring(state, "lua_RadioButton_removeScript - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 2).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_removeScriptCallback(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 3:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TUSERDATA || lua_type(state, 2) == LUA_TTABLE || lua_type(state, 2) == LUA_TNIL) &&
(lua_type(state, 3) == LUA_TSTRING || lua_type(state, 3) == LUA_TNIL))
{
// Get parameter 1 off the stack.
bool param1Valid;
gameplay::ScriptUtil::LuaArray<ScriptTarget::Event> param1 = gameplay::ScriptUtil::getObjectPointer<ScriptTarget::Event>(2, "ScriptTargetEvent", false, ¶m1Valid);
if (!param1Valid)
{
lua_pushstring(state, "Failed to convert parameter 1 to type 'ScriptTarget::Event'.");
lua_error(state);
}
// Get parameter 2 off the stack.
const char* param2 = gameplay::ScriptUtil::getString(3, false);
RadioButton* instance = getInstance(state);
instance->removeScriptCallback(param1, param2);
return 0;
}
lua_pushstring(state, "lua_RadioButton_removeScriptCallback - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 3).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_setAlignment(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
Control::Alignment param1 = (Control::Alignment)luaL_checkint(state, 2);
RadioButton* instance = getInstance(state);
instance->setAlignment(param1);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setAlignment - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 2).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_setAnimationPropertyValue(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 3:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER &&
(lua_type(state, 3) == LUA_TUSERDATA || lua_type(state, 3) == LUA_TTABLE || lua_type(state, 3) == LUA_TNIL))
{
// Get parameter 1 off the stack.
int param1 = (int)luaL_checkint(state, 2);
// Get parameter 2 off the stack.
bool param2Valid;
gameplay::ScriptUtil::LuaArray<AnimationValue> param2 = gameplay::ScriptUtil::getObjectPointer<AnimationValue>(3, "AnimationValue", false, ¶m2Valid);
if (!param2Valid)
{
lua_pushstring(state, "Failed to convert parameter 2 to type 'AnimationValue'.");
lua_error(state);
}
RadioButton* instance = getInstance(state);
instance->setAnimationPropertyValue(param1, param2);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setAnimationPropertyValue - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
case 4:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER &&
(lua_type(state, 3) == LUA_TUSERDATA || lua_type(state, 3) == LUA_TTABLE || lua_type(state, 3) == LUA_TNIL) &&
lua_type(state, 4) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
int param1 = (int)luaL_checkint(state, 2);
// Get parameter 2 off the stack.
bool param2Valid;
gameplay::ScriptUtil::LuaArray<AnimationValue> param2 = gameplay::ScriptUtil::getObjectPointer<AnimationValue>(3, "AnimationValue", false, ¶m2Valid);
if (!param2Valid)
{
lua_pushstring(state, "Failed to convert parameter 2 to type 'AnimationValue'.");
lua_error(state);
}
// Get parameter 3 off the stack.
float param3 = (float)luaL_checknumber(state, 4);
RadioButton* instance = getInstance(state);
instance->setAnimationPropertyValue(param1, param2, param3);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setAnimationPropertyValue - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 3 or 4).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_setAutoSize(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
Control::AutoSize param1 = (Control::AutoSize)luaL_checkint(state, 2);
RadioButton* instance = getInstance(state);
instance->setAutoSize(param1);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setAutoSize - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 2).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_setBorder(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 5:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER &&
lua_type(state, 3) == LUA_TNUMBER &&
lua_type(state, 4) == LUA_TNUMBER &&
lua_type(state, 5) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
float param1 = (float)luaL_checknumber(state, 2);
// Get parameter 2 off the stack.
float param2 = (float)luaL_checknumber(state, 3);
// Get parameter 3 off the stack.
float param3 = (float)luaL_checknumber(state, 4);
// Get parameter 4 off the stack.
float param4 = (float)luaL_checknumber(state, 5);
RadioButton* instance = getInstance(state);
instance->setBorder(param1, param2, param3, param4);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setBorder - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
case 6:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER &&
lua_type(state, 3) == LUA_TNUMBER &&
lua_type(state, 4) == LUA_TNUMBER &&
lua_type(state, 5) == LUA_TNUMBER &&
lua_type(state, 6) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
float param1 = (float)luaL_checknumber(state, 2);
// Get parameter 2 off the stack.
float param2 = (float)luaL_checknumber(state, 3);
// Get parameter 3 off the stack.
float param3 = (float)luaL_checknumber(state, 4);
// Get parameter 4 off the stack.
float param4 = (float)luaL_checknumber(state, 5);
// Get parameter 5 off the stack.
unsigned char param5 = (unsigned char)luaL_checkunsigned(state, 6);
RadioButton* instance = getInstance(state);
instance->setBorder(param1, param2, param3, param4, param5);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setBorder - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 5 or 6).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_setBounds(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TUSERDATA || lua_type(state, 2) == LUA_TNIL))
{
// Get parameter 1 off the stack.
bool param1Valid;
gameplay::ScriptUtil::LuaArray<Rectangle> param1 = gameplay::ScriptUtil::getObjectPointer<Rectangle>(2, "Rectangle", true, ¶m1Valid);
if (!param1Valid)
{
lua_pushstring(state, "Failed to convert parameter 1 to type 'Rectangle'.");
lua_error(state);
}
RadioButton* instance = getInstance(state);
instance->setBounds(*param1);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setBounds - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 2).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_setCanFocus(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TBOOLEAN)
{
// Get parameter 1 off the stack.
bool param1 = gameplay::ScriptUtil::luaCheckBool(state, 2);
RadioButton* instance = getInstance(state);
instance->setCanFocus(param1);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setCanFocus - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 2).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_setConsumeInputEvents(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TBOOLEAN)
{
// Get parameter 1 off the stack.
bool param1 = gameplay::ScriptUtil::luaCheckBool(state, 2);
RadioButton* instance = getInstance(state);
instance->setConsumeInputEvents(param1);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setConsumeInputEvents - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 2).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_setCursorColor(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 3:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TUSERDATA || lua_type(state, 2) == LUA_TNIL) &&
lua_type(state, 3) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
bool param1Valid;
gameplay::ScriptUtil::LuaArray<Vector4> param1 = gameplay::ScriptUtil::getObjectPointer<Vector4>(2, "Vector4", true, ¶m1Valid);
if (!param1Valid)
{
lua_pushstring(state, "Failed to convert parameter 1 to type 'Vector4'.");
lua_error(state);
}
// Get parameter 2 off the stack.
unsigned char param2 = (unsigned char)luaL_checkunsigned(state, 3);
RadioButton* instance = getInstance(state);
instance->setCursorColor(*param1, param2);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setCursorColor - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 3).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_setCursorRegion(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 3:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TUSERDATA || lua_type(state, 2) == LUA_TNIL) &&
lua_type(state, 3) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
bool param1Valid;
gameplay::ScriptUtil::LuaArray<Rectangle> param1 = gameplay::ScriptUtil::getObjectPointer<Rectangle>(2, "Rectangle", true, ¶m1Valid);
if (!param1Valid)
{
lua_pushstring(state, "Failed to convert parameter 1 to type 'Rectangle'.");
lua_error(state);
}
// Get parameter 2 off the stack.
unsigned char param2 = (unsigned char)luaL_checkunsigned(state, 3);
RadioButton* instance = getInstance(state);
instance->setCursorRegion(*param1, param2);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setCursorRegion - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 3).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_setEnabled(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TBOOLEAN)
{
// Get parameter 1 off the stack.
bool param1 = gameplay::ScriptUtil::luaCheckBool(state, 2);
RadioButton* instance = getInstance(state);
instance->setEnabled(param1);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setEnabled - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 2).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_setFocus(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TUSERDATA))
{
RadioButton* instance = getInstance(state);
bool result = instance->setFocus();
// Push the return value onto the stack.
lua_pushboolean(state, result);
return 1;
}
lua_pushstring(state, "lua_RadioButton_setFocus - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_setFocusIndex(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
int param1 = (int)luaL_checkint(state, 2);
RadioButton* instance = getInstance(state);
instance->setFocusIndex(param1);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setFocusIndex - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 2).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_setFont(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TUSERDATA || lua_type(state, 2) == LUA_TTABLE || lua_type(state, 2) == LUA_TNIL))
{
// Get parameter 1 off the stack.
bool param1Valid;
gameplay::ScriptUtil::LuaArray<Font> param1 = gameplay::ScriptUtil::getObjectPointer<Font>(2, "Font", false, ¶m1Valid);
if (!param1Valid)
{
lua_pushstring(state, "Failed to convert parameter 1 to type 'Font'.");
lua_error(state);
}
RadioButton* instance = getInstance(state);
instance->setFont(param1);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setFont - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
case 3:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TUSERDATA || lua_type(state, 2) == LUA_TTABLE || lua_type(state, 2) == LUA_TNIL) &&
lua_type(state, 3) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
bool param1Valid;
gameplay::ScriptUtil::LuaArray<Font> param1 = gameplay::ScriptUtil::getObjectPointer<Font>(2, "Font", false, ¶m1Valid);
if (!param1Valid)
{
lua_pushstring(state, "Failed to convert parameter 1 to type 'Font'.");
lua_error(state);
}
// Get parameter 2 off the stack.
unsigned char param2 = (unsigned char)luaL_checkunsigned(state, 3);
RadioButton* instance = getInstance(state);
instance->setFont(param1, param2);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setFont - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 2 or 3).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_setFontSize(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
unsigned int param1 = (unsigned int)luaL_checkunsigned(state, 2);
RadioButton* instance = getInstance(state);
instance->setFontSize(param1);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setFontSize - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
case 3:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER &&
lua_type(state, 3) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
unsigned int param1 = (unsigned int)luaL_checkunsigned(state, 2);
// Get parameter 2 off the stack.
unsigned char param2 = (unsigned char)luaL_checkunsigned(state, 3);
RadioButton* instance = getInstance(state);
instance->setFontSize(param1, param2);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setFontSize - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 2 or 3).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_setGroupId(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TSTRING || lua_type(state, 2) == LUA_TNIL))
{
// Get parameter 1 off the stack.
const char* param1 = gameplay::ScriptUtil::getString(2, false);
RadioButton* instance = getInstance(state);
instance->setGroupId(param1);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setGroupId - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 2).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_setHeight(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
float param1 = (float)luaL_checknumber(state, 2);
RadioButton* instance = getInstance(state);
instance->setHeight(param1);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setHeight - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
case 3:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER &&
lua_type(state, 3) == LUA_TBOOLEAN)
{
// Get parameter 1 off the stack.
float param1 = (float)luaL_checknumber(state, 2);
// Get parameter 2 off the stack.
bool param2 = gameplay::ScriptUtil::luaCheckBool(state, 3);
RadioButton* instance = getInstance(state);
instance->setHeight(param1, param2);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setHeight - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 2 or 3).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_setId(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TSTRING || lua_type(state, 2) == LUA_TNIL))
{
// Get parameter 1 off the stack.
const char* param1 = gameplay::ScriptUtil::getString(2, false);
RadioButton* instance = getInstance(state);
instance->setId(param1);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setId - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 2).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_setImageColor(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 3:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TSTRING || lua_type(state, 2) == LUA_TNIL) &&
(lua_type(state, 3) == LUA_TUSERDATA || lua_type(state, 3) == LUA_TNIL))
{
// Get parameter 1 off the stack.
const char* param1 = gameplay::ScriptUtil::getString(2, false);
// Get parameter 2 off the stack.
bool param2Valid;
gameplay::ScriptUtil::LuaArray<Vector4> param2 = gameplay::ScriptUtil::getObjectPointer<Vector4>(3, "Vector4", true, ¶m2Valid);
if (!param2Valid)
{
lua_pushstring(state, "Failed to convert parameter 2 to type 'Vector4'.");
lua_error(state);
}
RadioButton* instance = getInstance(state);
instance->setImageColor(param1, *param2);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setImageColor - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
case 4:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TSTRING || lua_type(state, 2) == LUA_TNIL) &&
(lua_type(state, 3) == LUA_TUSERDATA || lua_type(state, 3) == LUA_TNIL) &&
lua_type(state, 4) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
const char* param1 = gameplay::ScriptUtil::getString(2, false);
// Get parameter 2 off the stack.
bool param2Valid;
gameplay::ScriptUtil::LuaArray<Vector4> param2 = gameplay::ScriptUtil::getObjectPointer<Vector4>(3, "Vector4", true, ¶m2Valid);
if (!param2Valid)
{
lua_pushstring(state, "Failed to convert parameter 2 to type 'Vector4'.");
lua_error(state);
}
// Get parameter 3 off the stack.
unsigned char param3 = (unsigned char)luaL_checkunsigned(state, 4);
RadioButton* instance = getInstance(state);
instance->setImageColor(param1, *param2, param3);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setImageColor - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 3 or 4).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_setImageRegion(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 3:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TSTRING || lua_type(state, 2) == LUA_TNIL) &&
(lua_type(state, 3) == LUA_TUSERDATA || lua_type(state, 3) == LUA_TNIL))
{
// Get parameter 1 off the stack.
const char* param1 = gameplay::ScriptUtil::getString(2, false);
// Get parameter 2 off the stack.
bool param2Valid;
gameplay::ScriptUtil::LuaArray<Rectangle> param2 = gameplay::ScriptUtil::getObjectPointer<Rectangle>(3, "Rectangle", true, ¶m2Valid);
if (!param2Valid)
{
lua_pushstring(state, "Failed to convert parameter 2 to type 'Rectangle'.");
lua_error(state);
}
RadioButton* instance = getInstance(state);
instance->setImageRegion(param1, *param2);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setImageRegion - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
case 4:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TSTRING || lua_type(state, 2) == LUA_TNIL) &&
(lua_type(state, 3) == LUA_TUSERDATA || lua_type(state, 3) == LUA_TNIL) &&
lua_type(state, 4) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
const char* param1 = gameplay::ScriptUtil::getString(2, false);
// Get parameter 2 off the stack.
bool param2Valid;
gameplay::ScriptUtil::LuaArray<Rectangle> param2 = gameplay::ScriptUtil::getObjectPointer<Rectangle>(3, "Rectangle", true, ¶m2Valid);
if (!param2Valid)
{
lua_pushstring(state, "Failed to convert parameter 2 to type 'Rectangle'.");
lua_error(state);
}
// Get parameter 3 off the stack.
unsigned char param3 = (unsigned char)luaL_checkunsigned(state, 4);
RadioButton* instance = getInstance(state);
instance->setImageRegion(param1, *param2, param3);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setImageRegion - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 3 or 4).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_setMargin(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 5:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER &&
lua_type(state, 3) == LUA_TNUMBER &&
lua_type(state, 4) == LUA_TNUMBER &&
lua_type(state, 5) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
float param1 = (float)luaL_checknumber(state, 2);
// Get parameter 2 off the stack.
float param2 = (float)luaL_checknumber(state, 3);
// Get parameter 3 off the stack.
float param3 = (float)luaL_checknumber(state, 4);
// Get parameter 4 off the stack.
float param4 = (float)luaL_checknumber(state, 5);
RadioButton* instance = getInstance(state);
instance->setMargin(param1, param2, param3, param4);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setMargin - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 5).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_setOpacity(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
float param1 = (float)luaL_checknumber(state, 2);
RadioButton* instance = getInstance(state);
instance->setOpacity(param1);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setOpacity - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
case 3:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER &&
lua_type(state, 3) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
float param1 = (float)luaL_checknumber(state, 2);
// Get parameter 2 off the stack.
unsigned char param2 = (unsigned char)luaL_checkunsigned(state, 3);
RadioButton* instance = getInstance(state);
instance->setOpacity(param1, param2);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setOpacity - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 2 or 3).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_setPadding(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 5:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER &&
lua_type(state, 3) == LUA_TNUMBER &&
lua_type(state, 4) == LUA_TNUMBER &&
lua_type(state, 5) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
float param1 = (float)luaL_checknumber(state, 2);
// Get parameter 2 off the stack.
float param2 = (float)luaL_checknumber(state, 3);
// Get parameter 3 off the stack.
float param3 = (float)luaL_checknumber(state, 4);
// Get parameter 4 off the stack.
float param4 = (float)luaL_checknumber(state, 5);
RadioButton* instance = getInstance(state);
instance->setPadding(param1, param2, param3, param4);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setPadding - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 5).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_setPosition(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 3:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER &&
lua_type(state, 3) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
float param1 = (float)luaL_checknumber(state, 2);
// Get parameter 2 off the stack.
float param2 = (float)luaL_checknumber(state, 3);
RadioButton* instance = getInstance(state);
instance->setPosition(param1, param2);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setPosition - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 3).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_setSelected(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TBOOLEAN)
{
// Get parameter 1 off the stack.
bool param1 = gameplay::ScriptUtil::luaCheckBool(state, 2);
RadioButton* instance = getInstance(state);
instance->setSelected(param1);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setSelected - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 2).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_setSize(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 3:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER &&
lua_type(state, 3) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
float param1 = (float)luaL_checknumber(state, 2);
// Get parameter 2 off the stack.
float param2 = (float)luaL_checknumber(state, 3);
RadioButton* instance = getInstance(state);
instance->setSize(param1, param2);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setSize - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 3).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_setSkinColor(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TUSERDATA || lua_type(state, 2) == LUA_TNIL))
{
// Get parameter 1 off the stack.
bool param1Valid;
gameplay::ScriptUtil::LuaArray<Vector4> param1 = gameplay::ScriptUtil::getObjectPointer<Vector4>(2, "Vector4", true, ¶m1Valid);
if (!param1Valid)
{
lua_pushstring(state, "Failed to convert parameter 1 to type 'Vector4'.");
lua_error(state);
}
RadioButton* instance = getInstance(state);
instance->setSkinColor(*param1);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setSkinColor - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
case 3:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TUSERDATA || lua_type(state, 2) == LUA_TNIL) &&
lua_type(state, 3) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
bool param1Valid;
gameplay::ScriptUtil::LuaArray<Vector4> param1 = gameplay::ScriptUtil::getObjectPointer<Vector4>(2, "Vector4", true, ¶m1Valid);
if (!param1Valid)
{
lua_pushstring(state, "Failed to convert parameter 1 to type 'Vector4'.");
lua_error(state);
}
// Get parameter 2 off the stack.
unsigned char param2 = (unsigned char)luaL_checkunsigned(state, 3);
RadioButton* instance = getInstance(state);
instance->setSkinColor(*param1, param2);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setSkinColor - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 2 or 3).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_setSkinRegion(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TUSERDATA || lua_type(state, 2) == LUA_TNIL))
{
// Get parameter 1 off the stack.
bool param1Valid;
gameplay::ScriptUtil::LuaArray<Rectangle> param1 = gameplay::ScriptUtil::getObjectPointer<Rectangle>(2, "Rectangle", true, ¶m1Valid);
if (!param1Valid)
{
lua_pushstring(state, "Failed to convert parameter 1 to type 'Rectangle'.");
lua_error(state);
}
RadioButton* instance = getInstance(state);
instance->setSkinRegion(*param1);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setSkinRegion - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
case 3:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TUSERDATA || lua_type(state, 2) == LUA_TNIL) &&
lua_type(state, 3) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
bool param1Valid;
gameplay::ScriptUtil::LuaArray<Rectangle> param1 = gameplay::ScriptUtil::getObjectPointer<Rectangle>(2, "Rectangle", true, ¶m1Valid);
if (!param1Valid)
{
lua_pushstring(state, "Failed to convert parameter 1 to type 'Rectangle'.");
lua_error(state);
}
// Get parameter 2 off the stack.
unsigned char param2 = (unsigned char)luaL_checkunsigned(state, 3);
RadioButton* instance = getInstance(state);
instance->setSkinRegion(*param1, param2);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setSkinRegion - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 2 or 3).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_setStyle(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TUSERDATA || lua_type(state, 2) == LUA_TTABLE || lua_type(state, 2) == LUA_TNIL))
{
// Get parameter 1 off the stack.
bool param1Valid;
gameplay::ScriptUtil::LuaArray<Theme::Style> param1 = gameplay::ScriptUtil::getObjectPointer<Theme::Style>(2, "ThemeStyle", false, ¶m1Valid);
if (!param1Valid)
{
lua_pushstring(state, "Failed to convert parameter 1 to type 'Theme::Style'.");
lua_error(state);
}
RadioButton* instance = getInstance(state);
instance->setStyle(param1);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setStyle - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 2).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_setText(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TSTRING || lua_type(state, 2) == LUA_TNIL))
{
// Get parameter 1 off the stack.
const char* param1 = gameplay::ScriptUtil::getString(2, false);
RadioButton* instance = getInstance(state);
instance->setText(param1);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setText - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 2).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_setTextAlignment(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
Font::Justify param1 = (Font::Justify)luaL_checkint(state, 2);
RadioButton* instance = getInstance(state);
instance->setTextAlignment(param1);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setTextAlignment - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
case 3:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER &&
lua_type(state, 3) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
Font::Justify param1 = (Font::Justify)luaL_checkint(state, 2);
// Get parameter 2 off the stack.
unsigned char param2 = (unsigned char)luaL_checkunsigned(state, 3);
RadioButton* instance = getInstance(state);
instance->setTextAlignment(param1, param2);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setTextAlignment - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 2 or 3).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_setTextColor(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TUSERDATA || lua_type(state, 2) == LUA_TNIL))
{
// Get parameter 1 off the stack.
bool param1Valid;
gameplay::ScriptUtil::LuaArray<Vector4> param1 = gameplay::ScriptUtil::getObjectPointer<Vector4>(2, "Vector4", true, ¶m1Valid);
if (!param1Valid)
{
lua_pushstring(state, "Failed to convert parameter 1 to type 'Vector4'.");
lua_error(state);
}
RadioButton* instance = getInstance(state);
instance->setTextColor(*param1);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setTextColor - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
case 3:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
(lua_type(state, 2) == LUA_TUSERDATA || lua_type(state, 2) == LUA_TNIL) &&
lua_type(state, 3) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
bool param1Valid;
gameplay::ScriptUtil::LuaArray<Vector4> param1 = gameplay::ScriptUtil::getObjectPointer<Vector4>(2, "Vector4", true, ¶m1Valid);
if (!param1Valid)
{
lua_pushstring(state, "Failed to convert parameter 1 to type 'Vector4'.");
lua_error(state);
}
// Get parameter 2 off the stack.
unsigned char param2 = (unsigned char)luaL_checkunsigned(state, 3);
RadioButton* instance = getInstance(state);
instance->setTextColor(*param1, param2);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setTextColor - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 2 or 3).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_setTextRightToLeft(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TBOOLEAN)
{
// Get parameter 1 off the stack.
bool param1 = gameplay::ScriptUtil::luaCheckBool(state, 2);
RadioButton* instance = getInstance(state);
instance->setTextRightToLeft(param1);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setTextRightToLeft - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
case 3:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TBOOLEAN &&
lua_type(state, 3) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
bool param1 = gameplay::ScriptUtil::luaCheckBool(state, 2);
// Get parameter 2 off the stack.
unsigned char param2 = (unsigned char)luaL_checkunsigned(state, 3);
RadioButton* instance = getInstance(state);
instance->setTextRightToLeft(param1, param2);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setTextRightToLeft - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 2 or 3).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_setVisible(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TBOOLEAN)
{
// Get parameter 1 off the stack.
bool param1 = gameplay::ScriptUtil::luaCheckBool(state, 2);
RadioButton* instance = getInstance(state);
instance->setVisible(param1);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setVisible - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 2).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_setWidth(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
float param1 = (float)luaL_checknumber(state, 2);
RadioButton* instance = getInstance(state);
instance->setWidth(param1);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setWidth - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
case 3:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER &&
lua_type(state, 3) == LUA_TBOOLEAN)
{
// Get parameter 1 off the stack.
float param1 = (float)luaL_checknumber(state, 2);
// Get parameter 2 off the stack.
bool param2 = gameplay::ScriptUtil::luaCheckBool(state, 3);
RadioButton* instance = getInstance(state);
instance->setWidth(param1, param2);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setWidth - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 2 or 3).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_setX(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
float param1 = (float)luaL_checknumber(state, 2);
RadioButton* instance = getInstance(state);
instance->setX(param1);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setX - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
case 3:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER &&
lua_type(state, 3) == LUA_TBOOLEAN)
{
// Get parameter 1 off the stack.
float param1 = (float)luaL_checknumber(state, 2);
// Get parameter 2 off the stack.
bool param2 = gameplay::ScriptUtil::luaCheckBool(state, 3);
RadioButton* instance = getInstance(state);
instance->setX(param1, param2);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setX - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 2 or 3).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_setY(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
float param1 = (float)luaL_checknumber(state, 2);
RadioButton* instance = getInstance(state);
instance->setY(param1);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setY - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
case 3:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER &&
lua_type(state, 3) == LUA_TBOOLEAN)
{
// Get parameter 1 off the stack.
float param1 = (float)luaL_checknumber(state, 2);
// Get parameter 2 off the stack.
bool param2 = gameplay::ScriptUtil::luaCheckBool(state, 3);
RadioButton* instance = getInstance(state);
instance->setY(param1, param2);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setY - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 2 or 3).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_setZIndex(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 2:
{
if ((lua_type(state, 1) == LUA_TUSERDATA) &&
lua_type(state, 2) == LUA_TNUMBER)
{
// Get parameter 1 off the stack.
int param1 = (int)luaL_checkint(state, 2);
RadioButton* instance = getInstance(state);
instance->setZIndex(param1);
return 0;
}
lua_pushstring(state, "lua_RadioButton_setZIndex - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 2).");
lua_error(state);
break;
}
}
return 0;
}
int lua_RadioButton_static_ANIMATE_OPACITY(lua_State* state)
{
// Validate the number of parameters.
if (lua_gettop(state) > 0)
{
lua_pushstring(state, "Invalid number of parameters (expected 0).");
lua_error(state);
}
int result = RadioButton::ANIMATE_OPACITY;
// Push the return value onto the stack.
lua_pushinteger(state, result);
return 1;
}
int lua_RadioButton_static_ANIMATE_POSITION(lua_State* state)
{
// Validate the number of parameters.
if (lua_gettop(state) > 0)
{
lua_pushstring(state, "Invalid number of parameters (expected 0).");
lua_error(state);
}
int result = RadioButton::ANIMATE_POSITION;
// Push the return value onto the stack.
lua_pushinteger(state, result);
return 1;
}
int lua_RadioButton_static_ANIMATE_POSITION_X(lua_State* state)
{
// Validate the number of parameters.
if (lua_gettop(state) > 0)
{
lua_pushstring(state, "Invalid number of parameters (expected 0).");
lua_error(state);
}
int result = RadioButton::ANIMATE_POSITION_X;
// Push the return value onto the stack.
lua_pushinteger(state, result);
return 1;
}
int lua_RadioButton_static_ANIMATE_POSITION_Y(lua_State* state)
{
// Validate the number of parameters.
if (lua_gettop(state) > 0)
{
lua_pushstring(state, "Invalid number of parameters (expected 0).");
lua_error(state);
}
int result = RadioButton::ANIMATE_POSITION_Y;
// Push the return value onto the stack.
lua_pushinteger(state, result);
return 1;
}
int lua_RadioButton_static_ANIMATE_SIZE(lua_State* state)
{
// Validate the number of parameters.
if (lua_gettop(state) > 0)
{
lua_pushstring(state, "Invalid number of parameters (expected 0).");
lua_error(state);
}
int result = RadioButton::ANIMATE_SIZE;
// Push the return value onto the stack.
lua_pushinteger(state, result);
return 1;
}
int lua_RadioButton_static_ANIMATE_SIZE_HEIGHT(lua_State* state)
{
// Validate the number of parameters.
if (lua_gettop(state) > 0)
{
lua_pushstring(state, "Invalid number of parameters (expected 0).");
lua_error(state);
}
int result = RadioButton::ANIMATE_SIZE_HEIGHT;
// Push the return value onto the stack.
lua_pushinteger(state, result);
return 1;
}
int lua_RadioButton_static_ANIMATE_SIZE_WIDTH(lua_State* state)
{
// Validate the number of parameters.
if (lua_gettop(state) > 0)
{
lua_pushstring(state, "Invalid number of parameters (expected 0).");
lua_error(state);
}
int result = RadioButton::ANIMATE_SIZE_WIDTH;
// Push the return value onto the stack.
lua_pushinteger(state, result);
return 1;
}
int lua_RadioButton_static_create(lua_State* state)
{
// Get the number of parameters.
int paramCount = lua_gettop(state);
// Attempt to match the parameters to a valid binding.
switch (paramCount)
{
case 1:
{
if ((lua_type(state, 1) == LUA_TSTRING || lua_type(state, 1) == LUA_TNIL))
{
// Get parameter 1 off the stack.
const char* param1 = gameplay::ScriptUtil::getString(1, false);
void* returnPtr = ((void*)RadioButton::create(param1));
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = true;
luaL_getmetatable(state, "RadioButton");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
lua_pushstring(state, "lua_RadioButton_static_create - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
case 2:
{
if ((lua_type(state, 1) == LUA_TSTRING || lua_type(state, 1) == LUA_TNIL) &&
(lua_type(state, 2) == LUA_TUSERDATA || lua_type(state, 2) == LUA_TTABLE || lua_type(state, 2) == LUA_TNIL))
{
// Get parameter 1 off the stack.
const char* param1 = gameplay::ScriptUtil::getString(1, false);
// Get parameter 2 off the stack.
bool param2Valid;
gameplay::ScriptUtil::LuaArray<Theme::Style> param2 = gameplay::ScriptUtil::getObjectPointer<Theme::Style>(2, "ThemeStyle", false, ¶m2Valid);
if (!param2Valid)
{
lua_pushstring(state, "Failed to convert parameter 2 to type 'Theme::Style'.");
lua_error(state);
}
void* returnPtr = ((void*)RadioButton::create(param1, param2));
if (returnPtr)
{
gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
object->instance = returnPtr;
object->owns = true;
luaL_getmetatable(state, "RadioButton");
lua_setmetatable(state, -2);
}
else
{
lua_pushnil(state);
}
return 1;
}
lua_pushstring(state, "lua_RadioButton_static_create - Failed to match the given parameters to a valid function signature.");
lua_error(state);
break;
}
default:
{
lua_pushstring(state, "Invalid number of parameters (expected 1 or 2).");
lua_error(state);
break;
}
}
return 0;
}
}
| 0 | 0.841743 | 1 | 0.841743 | game-dev | MEDIA | 0.769442 | game-dev | 0.538048 | 1 | 0.538048 |
FrSkyRC/ETHOS-Feedback-Community | 3,865 | lua/games/snake/main.lua | -- Lua Snake game
local translations = {en="Lua Snake", fr="Serpent Lua"}
local function name(widget)
local locale = system.getLocale()
return translations[locale] or translations["en"]
end
local wCell = 12
local xMax
local yMax
local game_map = {}
local Head
local Tail
local highscore = 0
local size = 3
local Food = {x=false, y=false}
local direction = "right"
local score = 0
local function create_food()
Food.x, Food.y = math.random(xMax - 1), math.random(yMax - 1)
while game_map[Food.x][Food.y] do
Food.x, Food.y = math.random(xMax - 1), math.random(yMax - 1)
end
game_map[Food.x][Food.y] = "food"
end
local function eat_food()
game_map[Head.x][Head.y] = nil
create_food()
score = score + 1
end
local function check_collision()
if Head.x < 0 or Head.x > xMax then
return true
elseif Head.y < 0 or Head.y > yMax then
return true
elseif ((game_map[Head.x][Head.y]) and (game_map[Head.x][Head.y] ~= "food")) then
return true
end
return false
end
local function move()
if game_map[Tail.x][Tail.y] == "right" then
Tail.dx = 1
Tail.dy = 0
elseif game_map[Tail.x][Tail.y] == "left" then
Tail.dx = -1
Tail.dy = 0
elseif game_map[Tail.x][Tail.y] == "up" then
Tail.dx = 0
Tail.dy = -1
elseif game_map[Tail.x][Tail.y] == "down" then
Tail.dx = 0
Tail.dy = 1
end
game_map[Head.x][Head.y] = direction
Head.x = Head.x + Head.dx
Head.y = Head.y + Head.dy
lcd.invalidate()
if Head.x < 0 or Head.x > xMax or Head.y < 0 or Head.y > yMax then
print("Game over!")
system.exit()
elseif game_map[Head.x][Head.y] == "food" then
eat_food()
else
game_map[Tail.x][Tail.y] = nil
Tail.x = Tail.x + Tail.dx
Tail.y = Tail.y + Tail.dy
end
end
local function create()
local w, h = lcd.getWindowSize()
xMax = math.floor(w / wCell)
yMax = math.floor(h / wCell)
food = false
size = 3
score = 0
Head = {x=3, y=1, dx=1, dy=0}
Tail = {x=1, y=1, dx=1, dy=0}
direction = "right"
for i = 0, xMax, 1 do
game_map[i] = {}
end
for i = 0, size - 1, 1 do
game_map[Tail.x + (i * Tail.dx)][Tail.y + (i * Tail.dy)] = direction
end
create_food()
end
local function wakeup()
move()
end
local function event(widget, category, value, x, y)
print("Event received:", category, value, x, y, KEY_RIGHT_FIRST)
local dir = direction
local result = false
if category == EVT_KEY then
result = true
if value == KEY_RIGHT_FIRST and direction ~= "left" then
dir = "right"
Head.dx = 1
Head.dy = 0
elseif value == KEY_LEFT_FIRST and direction ~= "right" then
dir = "left"
Head.dx = -1
Head.dy = 0
elseif value == KEY_UP_FIRST and direction ~= "down" then
dir = "up"
Head.dx = 0
Head.dy = -1
elseif value == KEY_DOWN_FIRST and direction ~= "up" then
dir = "down"
Head.dx = 0
Head.dy = 1
end
elseif category == EVT_CLOSE then
print("No, you will play until the end!")
result = true
end
direction = dir
return result
end
local function paint()
lcd.color(lcd.RGB(40, 40, 40))
for x = 0, xMax, 1 do
lcd.drawFilledRectangle(x * wCell, 0, 1, yMax * wCell)
end
for y = 0, yMax, 1 do
lcd.drawFilledRectangle(0, y * wCell, xMax * wCell, 1)
end
for x = 0, xMax, 1 do
for y = 0, yMax, 1 do
local cell = game_map[x][y]
if cell ~= nil then
if cell == "food" then
lcd.color(lcd.RGB(79, 195, 247))
else
lcd.color(lcd.RGB(255, 255, 255))
end
lcd.drawFilledRectangle(x * wCell + 1, y * wCell + 1, wCell - 1, wCell - 1)
end
end
end
end
local icon = lcd.loadMask("snake.png")
local function init()
system.registerSystemTool({name=name, icon=icon, create=create, wakeup=wakeup, event=event, paint=paint})
end
return {init=init}
| 0 | 0.72951 | 1 | 0.72951 | game-dev | MEDIA | 0.929801 | game-dev | 0.855807 | 1 | 0.855807 |
folgerwang/UnrealEngine | 35,810 | Engine/Source/Runtime/Engine/Private/HUD.cpp | // Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
/*=============================================================================
HUD.cpp: Heads up Display related functionality
=============================================================================*/
#include "GameFramework/HUD.h"
#include "GenericPlatform/GenericApplication.h"
#include "Misc/App.h"
#include "EngineGlobals.h"
#include "Layout/Margin.h"
#include "CollisionQueryParams.h"
#include "Materials/MaterialInterface.h"
#include "SceneView.h"
#include "GameFramework/PlayerController.h"
#include "Engine/Engine.h"
#include "CanvasItem.h"
#include "CanvasTypes.h"
#include "TextureResource.h"
#include "Engine/Texture.h"
#include "Engine/LocalPlayer.h"
#include "GameFramework/GameModeBase.h"
#include "EngineUtils.h"
#include "Framework/Application/SlateApplication.h"
#include "Components/LineBatchComponent.h"
#include "Engine/Canvas.h"
#include "Logging/TokenizedMessage.h"
#include "Logging/MessageLog.h"
#include "Misc/UObjectToken.h"
#include "DisplayDebugHelpers.h"
#include "DrawDebugHelpers.h"
#include "Components/SkeletalMeshComponent.h"
#include "GameFramework/MovementComponent.h"
#include "UObject/UObjectIterator.h"
DEFINE_LOG_CATEGORY_STATIC(LogHUD, Log, All);
#define LOCTEXT_NAMESPACE "HUD"
FOnShowDebugInfo AHUD::OnShowDebugInfo;
FOnHUDPostRender AHUD::OnHUDPostRender;
// Should we visualize the safe zone? (and if so, title or action?)
TAutoConsoleVariable<int32> GSafeZoneVisualizationModeCVar(
TEXT("r.DebugSafeZone.Mode"),
0,
TEXT("The safe zone visualization mode (0..2)\n")
TEXT(" 0: Disabled (default)\n")
TEXT(" 1: Show Title Safe Zone\n")
TEXT(" 2: Show Action Safe Zone"));
// How opaque should the safe zone visualization be?
TAutoConsoleVariable<float> GSafeZoneVisualizationAlphaCVar(
TEXT("r.DebugSafeZone.OverlayAlpha"),
0.2f,
TEXT("The alpha value of the safe zone overlay (0..1)\n")
TEXT(" default: 0.2"));
const FColor AHUD::WhiteColor(255, 255, 255, 255);
const FColor AHUD::GreenColor(0, 255, 0, 255);
const FColor AHUD::RedColor(255, 0, 0, 255);
AHUD::AHUD(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
PrimaryActorTick.TickGroup = TG_DuringPhysics;
PrimaryActorTick.bCanEverTick = true;
bHidden = true;
bReplicates = false;
bLostFocusPaused = false;
bShowHUD = true;
bCanBeDamaged = false;
bEnableDebugTextShadow = false;
}
void AHUD::SetCanvas(class UCanvas* InCanvas, class UCanvas* InDebugCanvas)
{
Canvas = InCanvas;
DebugCanvas = InDebugCanvas;
}
void AHUD::Draw3DLine(FVector Start, FVector End, FColor LineColor)
{
GetWorld()->LineBatcher->DrawLine(Start, End, LineColor, SDPG_World);
}
void AHUD::Draw2DLine(int32 X1, int32 Y1, int32 X2, int32 Y2, FColor LineColor)
{
check(Canvas);
FCanvasLineItem LineItem(FVector2D(X1, Y1), FVector2D(X2, Y2));
LineItem.SetColor(LineColor);
LineItem.Draw(Canvas->Canvas);
}
void AHUD::PostInitializeComponents()
{
Super::PostInitializeComponents();
PlayerOwner = Cast<APlayerController>(GetOwner());
// e.g. getting material pointers to control effects for gameplay
NotifyBindPostProcessEffects();
}
void AHUD::NotifyBindPostProcessEffects()
{
// overload with custom code e.g. getting material pointers to control effects for gameplay.
}
FVector2D AHUD::GetCoordinateOffset() const
{
FVector2D Offset(0.f, 0.f);
ULocalPlayer* LocalPlayer = Cast<ULocalPlayer>(GetOwningPlayerController()->Player);
if (LocalPlayer)
{
// Create a view family for the game viewport
FSceneViewFamilyContext ViewFamily(FSceneViewFamily::ConstructionValues(
LocalPlayer->ViewportClient->Viewport,
GetWorld()->Scene,
LocalPlayer->ViewportClient->EngineShowFlags)
.SetRealtimeUpdate(true));
// Calculate a view where the player is to update the streaming from the players start location
FVector ViewLocation;
FRotator ViewRotation;
FSceneView* SceneView = LocalPlayer->CalcSceneView(&ViewFamily, /*out*/ ViewLocation, /*out*/ ViewRotation, LocalPlayer->ViewportClient->Viewport);
if (SceneView)
{
Offset.X = - SceneView->UnscaledViewRect.Min.X; // And this will deal with the viewport offset if its a split screen
Offset.Y = - SceneView->UnscaledViewRect.Min.Y;
}
}
return Offset;
}
void AHUD::PostRender()
{
// Theres nothing we can really do without a canvas or a world - so leave now in that case
if ( (GetWorld() == nullptr) || (Canvas == nullptr))
{
return;
}
// Set up delta time
RenderDelta = GetWorld()->TimeSeconds - LastHUDRenderTime;
if ( PlayerOwner != NULL )
{
// draw any debug text in real-time
DrawDebugTextList();
}
if ( bShowDebugInfo )
{
if (DebugCanvas)
{
DebugCanvas->DisplayDebugManager.Initialize(DebugCanvas, GEngine->GetTinyFont(), FVector2D(4.f, 50.f));
ShowDebugInfo(DebugCanvas->DisplayDebugManager.GetMaxCharHeightRef(), DebugCanvas->DisplayDebugManager.GetYPosRef());
}
}
else if ( bShowHUD && FApp::CanEverRender() )
{
DrawHUD();
// No need to do work to determine hit box candidates if there will never be any
if (HitBoxMap.Num() > 0)
{
ULocalPlayer* LocalPlayer = GetOwningPlayerController() ? Cast<ULocalPlayer>(GetOwningPlayerController()->Player) : NULL;
if (LocalPlayer && LocalPlayer->ViewportClient)
{
TArray<FVector2D> ContactPoints;
if (!FSlateApplication::Get().IsFakingTouchEvents())
{
FVector2D MousePosition;
if (LocalPlayer->ViewportClient->GetMousePosition(MousePosition))
{
ContactPoints.Add(MousePosition);
}
}
for (int32 FingerIndex = 0; FingerIndex < EKeys::NUM_TOUCH_KEYS; ++FingerIndex)
{
FVector2D TouchLocation;
bool bPressed = false;
GetOwningPlayerController()->GetInputTouchState((ETouchIndex::Type)FingerIndex, TouchLocation.X, TouchLocation.Y, bPressed);
if (bPressed)
{
ContactPoints.Add(TouchLocation);
}
}
const FVector2D ContactPointOffset = GetCoordinateOffset();
if (!ContactPointOffset.IsZero())
{
for (FVector2D& ContactPoint : ContactPoints)
{
ContactPoint += ContactPointOffset;
}
}
UpdateHitBoxCandidates( MoveTemp(ContactPoints) );
}
}
else if (HitBoxesOver.Num() > 0)
{
// We still need to dispatch any end cursor over messages even if we don't have any hitboxes anymore
for (const FName HitBoxName : HitBoxesOver)
{
NotifyHitBoxEndCursorOver(HitBoxName);
}
HitBoxesOver.Reset();
}
}
if( bShowHitBoxDebugInfo )
{
RenderHitBoxes( Canvas->Canvas );
}
DrawSafeZoneOverlay();
OnHUDPostRender.Broadcast(this, DebugCanvas);
LastHUDRenderTime = GetWorld()->TimeSeconds;
}
void AHUD::DrawActorOverlays(FVector Viewpoint, FRotator ViewRotation)
{
// determine rendered camera position
FVector ViewDir = ViewRotation.Vector();
int32 i = 0;
while (i < PostRenderedActors.Num())
{
if ( PostRenderedActors[i] != NULL )
{
PostRenderedActors[i]->PostRenderFor(PlayerOwner,Canvas,Viewpoint,ViewDir);
i++;
}
else
{
PostRenderedActors.RemoveAt(i,1);
}
}
}
void AHUD::DrawSafeZoneOverlay()
{
#if ENABLE_DRAW_DEBUG
const int32 DebugSafeZoneMode = GSafeZoneVisualizationModeCVar.GetValueOnGameThread();
if ((DebugSafeZoneMode > 0) && (DebugCanvas != nullptr))
{
const float Width = DebugCanvas->SizeX;
const float Height = DebugCanvas->SizeY;
FMargin SafeMargin;
FSlateApplication::Get().GetSafeZoneSize(SafeMargin, FVector2D(Width, Height));
const float UnsafeZoneAlpha = GSafeZoneVisualizationAlphaCVar.GetValueOnGameThread();
const FLinearColor UnsafeZoneColor(1.0f, 0.5f, 0.5f, UnsafeZoneAlpha);
const float HeightOfSides = Height - SafeMargin.GetTotalSpaceAlong<Orient_Vertical>();
FCanvasTileItem TileItem(FVector2D::ZeroVector, GWhiteTexture, UnsafeZoneColor);
TileItem.BlendMode = SE_BLEND_Translucent;
// Top bar
TileItem.Position = FVector2D::ZeroVector;
TileItem.Size = FVector2D(Width, SafeMargin.Top);
DebugCanvas->DrawItem(TileItem);
// Bottom bar
TileItem.Position = FVector2D(0.0f, Height - SafeMargin.Bottom);
TileItem.Size = FVector2D(Width, SafeMargin.Bottom);
DebugCanvas->DrawItem(TileItem);
// Left bar
TileItem.Position = FVector2D(0.0f, SafeMargin.Top);
TileItem.Size = FVector2D(SafeMargin.Left, HeightOfSides);
DebugCanvas->DrawItem(TileItem);
// Right bar
TileItem.Position = FVector2D(Width - SafeMargin.Right, SafeMargin.Top);
TileItem.Size = FVector2D(SafeMargin.Right, HeightOfSides);
DebugCanvas->DrawItem(TileItem);
}
#endif
}
void AHUD::RemovePostRenderedActor(AActor* A)
{
for ( int32 i=0; i<PostRenderedActors.Num(); i++ )
{
if ( PostRenderedActors[i] == A )
{
PostRenderedActors[i] = NULL;
return;
}
}
}
void AHUD::AddPostRenderedActor(AActor* A)
{
// make sure that A is not already in list
for ( int32 i=0; i<PostRenderedActors.Num(); i++ )
{
if ( PostRenderedActors[i] == A )
{
return;
}
}
// add A at first empty slot
for ( int32 i=0; i<PostRenderedActors.Num(); i++ )
{
if ( PostRenderedActors[i] == NULL )
{
PostRenderedActors[i] = A;
return;
}
}
// no empty slot found, so grow array
PostRenderedActors.Add(A);
}
void AHUD::ShowHUD()
{
bShowHUD = !bShowHUD;
}
namespace ShowDebugNames
{
static const FName Reset(TEXT("Reset"));
static const FName HitBox(TEXT("HitBox"));
static const FName Animation(TEXT("Animation"));
static const FName Physics(TEXT("Physics"));
}
void AHUD::ShowDebug(FName DebugType)
{
const bool bPreviousShowDebugInfo = bShowDebugInfo;
if (DebugType == NAME_None)
{
bShowDebugInfo = !bShowDebugInfo;
}
else if (DebugType == ShowDebugNames::HitBox)
{
bShowHitBoxDebugInfo = !bShowHitBoxDebugInfo;
}
else if (DebugType == ShowDebugNames::Reset)
{
DebugDisplay.Reset();
bShowDebugInfo = false;
SaveConfig();
}
else
{
bool bRemoved = false;
if (bShowDebugInfo)
{
// remove debugtype if already in array
if (0 != DebugDisplay.Remove(DebugType))
{
bRemoved = true;
}
}
if (!bRemoved)
{
DebugDisplay.Add(DebugType);
}
bShowDebugInfo = true;
SaveConfig();
}
// Reset Target to ourselves when enabled/disabled
if (bShowDebugInfo != bPreviousShowDebugInfo)
{
ShowDebugTargetActor = nullptr;
}
}
void AHUD::ShowDebugToggleSubCategory(FName Category)
{
if (Category == ShowDebugNames::Reset)
{
ToggledDebugCategories.Reset();
SaveConfig();
}
else
{
if (0 == ToggledDebugCategories.Remove(Category))
{
ToggledDebugCategories.Add(Category);
}
SaveConfig();
}
}
void AHUD::ShowDebugForReticleTargetToggle(TSubclassOf<AActor> DesiredClass)
{
bShowDebugForReticleTarget = !bShowDebugForReticleTarget;
ShowDebugTargetDesiredClass = DesiredClass;
}
bool AHUD::ShouldDisplayDebug(const FName& DebugType) const
{
return bShowDebugInfo && DebugDisplay.Contains(DebugType);
}
void AHUD::ShowDebugInfo(float& YL, float& YPos)
{
if (DebugCanvas != nullptr)
{
// Darken background, so we can read text better.
FLinearColor BackgroundColor(0.f, 0.f, 0.f, 0.2f);
DebugCanvas->Canvas->DrawTile(0, 0, DebugCanvas->ClipX, DebugCanvas->ClipY, 0.f, 0.f, 0.f, 0.f, BackgroundColor);
FDebugDisplayInfo DisplayInfo(DebugDisplay, ToggledDebugCategories);
ShowDebugTargetActor = GetCurrentDebugTargetActor();
// Draw Header.
{
FDisplayDebugManager& DisplayDebugManager = DebugCanvas->DisplayDebugManager;
DisplayDebugManager.SetDrawColor(FColor(255, 0, 0));
DisplayDebugManager.DrawString(FString::Printf(TEXT("Showing Debug for %s, Press [PageUp] and [PageDown] to cycle between targets."), *GetNameSafe(ShowDebugTargetActor)));
}
if (ShowDebugTargetActor && !ShowDebugTargetActor->IsPendingKill())
{
// Draw box around Actor being debugged.
#if ENABLE_DRAW_DEBUG
{
FVector BoundsOrigin, BoundsExtent;
ShowDebugTargetActor->GetActorBounds(true, BoundsOrigin, BoundsExtent);
// Expand extent a little bit
BoundsExtent *= 1.1f;
DrawDebugBox(GetWorld(), BoundsOrigin, BoundsExtent, FColor::Green, false, -1.f, 0, 2.f);
}
#endif
ShowDebugTargetActor->DisplayDebug(DebugCanvas, DisplayInfo, YL, YPos);
if (!bShowDebugForReticleTarget && ShowDebugTargetActor->Role == ROLE_SimulatedProxy)
{
PlayerOwner->DisplayDebug(DebugCanvas, DisplayInfo, YL, YPos);
}
}
if (ShouldDisplayDebug(NAME_Game))
{
AGameModeBase* AuthGameMode = GetWorld()->GetAuthGameMode();
if (AuthGameMode)
{
AuthGameMode->DisplayDebug(DebugCanvas, DisplayInfo, YL, YPos);
}
}
if (bShowDebugInfo)
{
OnShowDebugInfo.Broadcast(this, DebugCanvas, DisplayInfo, YL, YPos);
}
}
}
AActor* AHUD::GetCurrentDebugTargetActor()
{
AActor* DebugTargetActor = nullptr;
// Find targets through the reticle.
if (bShowDebugForReticleTarget && PlayerOwner->PlayerCameraManager)
{
FRotator CamRot; FVector CamLoc; PlayerOwner->GetPlayerViewPoint(CamLoc, CamRot);
FCollisionQueryParams TraceParams(NAME_None, FCollisionQueryParams::GetUnknownStatId(), true, PlayerOwner->PlayerCameraManager->ViewTarget.Target);
FHitResult Hit;
bool bHit = GetWorld()->LineTraceSingleByChannel(Hit, CamLoc, CamRot.Vector() * 100000.f + CamLoc, ECC_WorldDynamic, TraceParams);
if (bHit)
{
AActor* HitActor = Hit.Actor.Get();
if (HitActor && ((ShowDebugTargetDesiredClass == nullptr) || HitActor->IsA(ShowDebugTargetDesiredClass)))
{
DebugTargetActor = HitActor;
}
}
// If we hit something new, return this.
// Otherwise fall back to our last successful hit.
return DebugTargetActor ? DebugTargetActor : ShowDebugTargetActor;
}
else
{
// Otherwise we use our Cached DebugTargetActor.
DebugTargetActor = ShowDebugTargetActor;
}
// If we have no one to view, default to current view target.
if ((DebugTargetActor == nullptr) && PlayerOwner->PlayerCameraManager && PlayerOwner->PlayerCameraManager->ViewTarget.Target)
{
DebugTargetActor = PlayerOwner->PlayerCameraManager->ViewTarget.Target;
}
return DebugTargetActor;
}
void AHUD::AddActorToDebugList(AActor* InActor, TArray<AActor*>& InOutList, UWorld* InWorld)
{
// Only consider actors that are visible, not destroyed and in the same world.
if (InActor && !InActor->IsPendingKill() && (InActor->GetWorld() == InWorld) && InActor->WasRecentlyRendered())
{
InOutList.AddUnique(InActor);
}
}
void AHUD::AddComponentOwnerToDebugList(UActorComponent* InComponent, TArray<AActor*>& InOutList, UWorld* InWorld)
{
if (InComponent && InComponent->GetOwner())
{
AddActorToDebugList(InComponent->GetOwner(), InOutList, InWorld);
}
}
void AHUD::GetDebugActorList(TArray<AActor*>& InOutList)
{
UWorld* World = GetWorld();
// By default, add all Pawns.
for (TActorIterator<APawn> It(World); It; ++It)
{
AddActorToDebugList(*It, InOutList, World);
}
// If we're viewing animations, add all actors using an AnimInstance.
if (ShouldDisplayDebug(ShowDebugNames::Animation))
{
for (TObjectIterator<USkeletalMeshComponent> It; It; ++It)
{
if (It->GetAnimInstance())
{
AddComponentOwnerToDebugList(*It, InOutList, World);
}
}
}
// If we're viewing physics, add all actors using a movement component.
if (ShouldDisplayDebug(ShowDebugNames::Physics))
{
for (TObjectIterator<UMovementComponent> It; It; ++It)
{
AddComponentOwnerToDebugList(*It, InOutList, World);
}
}
}
void AHUD::NextDebugTarget()
{
TArray<AActor*> Targets;
GetDebugActorList(Targets);
// If we have an existing target, find it in list.
// As list can change as actors are spawned and destroyed.
if (ShowDebugTargetActor)
{
if (!Targets.IsValidIndex(CurrentTargetIndex) || (Targets[CurrentTargetIndex] != ShowDebugTargetActor))
{
int32 FoundIndex;
if (Targets.Find(ShowDebugTargetActor, FoundIndex))
{
CurrentTargetIndex = FoundIndex;
}
}
}
CurrentTargetIndex = Targets.Num() > 0 ? (CurrentTargetIndex + 1) % Targets.Num() : INDEX_NONE;
if (Targets.IsValidIndex(CurrentTargetIndex))
{
ShowDebugTargetActor = Targets[CurrentTargetIndex];
}
else if (PlayerOwner->PlayerCameraManager && PlayerOwner->PlayerCameraManager->ViewTarget.Target)
{
ShowDebugTargetActor = PlayerOwner->PlayerCameraManager->ViewTarget.Target;
}
}
void AHUD::PreviousDebugTarget()
{
TArray<AActor*> Targets;
GetDebugActorList(Targets);
// If we have an existing target, find it in list.
// As list can change as actors are spawned and destroyed.
if (ShowDebugTargetActor)
{
if (!Targets.IsValidIndex(CurrentTargetIndex) || (Targets[CurrentTargetIndex] != ShowDebugTargetActor))
{
int32 FoundIndex;
if (Targets.Find(ShowDebugTargetActor, FoundIndex))
{
CurrentTargetIndex = FoundIndex;
}
}
}
CurrentTargetIndex--;
if (CurrentTargetIndex < 0)
{
CurrentTargetIndex = Targets.Num() - 1;
}
if (Targets.IsValidIndex(CurrentTargetIndex))
{
ShowDebugTargetActor = Targets[CurrentTargetIndex];
}
else if (PlayerOwner->PlayerCameraManager && PlayerOwner->PlayerCameraManager->ViewTarget.Target)
{
ShowDebugTargetActor = PlayerOwner->PlayerCameraManager->ViewTarget.Target;
}
}
void AHUD::DrawHUD()
{
HitBoxMap.Reset();
HitBoxHits.Reset();
if ( bShowOverlays && (PlayerOwner != NULL) )
{
FVector ViewPoint;
FRotator ViewRotation;
PlayerOwner->GetPlayerViewPoint(ViewPoint, ViewRotation);
DrawActorOverlays(ViewPoint, ViewRotation);
}
// Blueprint draw
ReceiveDrawHUD(Canvas->SizeX, Canvas->SizeY);
}
UFont* AHUD::GetFontFromSizeIndex(int32 FontSizeIndex) const
{
switch (FontSizeIndex)
{
case 0: return GEngine->GetTinyFont();
case 1: return GEngine->GetSmallFont();
case 2: return GEngine->GetMediumFont();
case 3: return GEngine->GetLargeFont();
}
return GEngine->GetLargeFont();
}
void AHUD::OnLostFocusPause(bool bEnable)
{
if ( bLostFocusPaused == bEnable )
return;
if ( GetNetMode() != NM_Client )
{
bLostFocusPaused = bEnable;
PlayerOwner->SetPause(bEnable);
}
}
void AHUD::DrawDebugTextList()
{
if( (DebugTextList.Num() > 0) && (DebugCanvas != nullptr ) )
{
FRotator CameraRot;
FVector CameraLoc;
PlayerOwner->GetPlayerViewPoint(CameraLoc, CameraRot);
FCanvasTextItem TextItem( FVector2D::ZeroVector, FText::GetEmpty(), GEngine->GetSmallFont(), FLinearColor::White );
for (int32 Idx = 0; Idx < DebugTextList.Num(); Idx++)
{
if (DebugTextList[Idx].SrcActor == NULL)
{
DebugTextList.RemoveAt(Idx--,1);
continue;
}
if( DebugTextList[Idx].Font != NULL )
{
TextItem.Font = DebugTextList[Idx].Font;
}
else
{
TextItem.Font = GEngine->GetSmallFont();
}
float const Alpha = FMath::IsNearlyZero(DebugTextList[Idx].Duration) ? 0.f : (1.f - (DebugTextList[Idx].TimeRemaining / DebugTextList[Idx].Duration));
FVector WorldTextLoc;
if (DebugTextList[Idx].bAbsoluteLocation)
{
WorldTextLoc = FMath::Lerp(DebugTextList[Idx].SrcActorOffset, DebugTextList[Idx].SrcActorDesiredOffset, Alpha);
}
else
{
FVector Offset = FMath::Lerp(DebugTextList[Idx].SrcActorOffset, DebugTextList[Idx].SrcActorDesiredOffset, Alpha);
if( DebugTextList[Idx].bKeepAttachedToActor )
{
WorldTextLoc = DebugTextList[Idx].SrcActor->GetActorLocation() + Offset;
}
else
{
WorldTextLoc = DebugTextList[Idx].OrigActorLocation + Offset;
}
}
if (bEnableDebugTextShadow || DebugTextList[Idx].bDrawShadow)
{
TextItem.EnableShadow(FLinearColor::Black);
}
else
{
TextItem.DisableShadow();
}
// don't draw text behind the camera
if ( ((WorldTextLoc - CameraLoc) | CameraRot.Vector()) > 0.f )
{
FVector ScreenLoc = Canvas->Project(WorldTextLoc);
TextItem.SetColor( DebugTextList[Idx].TextColor );
TextItem.Text = FText::FromString( DebugTextList[Idx].DebugText );
TextItem.Scale = FVector2D( DebugTextList[Idx].FontScale, DebugTextList[Idx].FontScale);
DebugCanvas->DrawItem( TextItem, FVector2D( FMath::CeilToFloat(ScreenLoc.X), FMath::CeilToFloat(ScreenLoc.Y) ) );
}
// do this at the end so even small durations get at least one frame
if (DebugTextList[Idx].TimeRemaining != -1.f)
{
DebugTextList[Idx].TimeRemaining -= RenderDelta;
}
}
// Clear out the list of expired ones (going from the back to reduce copying the remaining portion of the list as it is shrunk, since order matters)
for (int32 Idx = DebugTextList.Num() - 1; Idx >= 0; --Idx)
{
if (DebugTextList[Idx].TimeRemaining != -1.f)
{
if (DebugTextList[Idx].TimeRemaining <= 0.f)
{
DebugTextList.RemoveAt(Idx, 1);
}
}
}
}
}
/// @cond DOXYGEN_WARNINGS
void AHUD::AddDebugText_Implementation(const FString& DebugText,
AActor* SrcActor,
float Duration,
FVector Offset,
FVector DesiredOffset,
FColor TextColor,
bool bSkipOverwriteCheck,
bool bAbsoluteLocation,
bool bKeepAttachedToActor,
UFont* InFont,
float FontScale,
bool bDrawShadow
)
{
// set a default color
if (TextColor == FColor::Transparent)
{
TextColor = FColor::White;
}
// and a default source actor of our pawn
if (SrcActor != NULL)
{
if (DebugText.Len() == 0)
{
RemoveDebugText(SrcActor);
}
else
{
// search for an existing entry
int32 Idx = 0;
if (!bSkipOverwriteCheck)
{
Idx = INDEX_NONE;
for (int32 i = 0; i < DebugTextList.Num() && Idx == INDEX_NONE; ++i)
{
if (DebugTextList[i].SrcActor == SrcActor)
{
Idx = i;
}
}
if (Idx == INDEX_NONE)
{
// manually grow the array one struct element
Idx = DebugTextList.Add(FDebugTextInfo());
}
}
else
{
Idx = DebugTextList.Add(FDebugTextInfo());
}
// assign the new text and actor
DebugTextList[Idx].SrcActor = SrcActor;
DebugTextList[Idx].SrcActorOffset = Offset;
DebugTextList[Idx].SrcActorDesiredOffset = DesiredOffset;
DebugTextList[Idx].DebugText = DebugText;
DebugTextList[Idx].TimeRemaining = Duration;
DebugTextList[Idx].Duration = Duration;
DebugTextList[Idx].TextColor = TextColor;
DebugTextList[Idx].bAbsoluteLocation = bAbsoluteLocation;
DebugTextList[Idx].bKeepAttachedToActor = bKeepAttachedToActor;
DebugTextList[Idx].OrigActorLocation = SrcActor->GetActorLocation();
DebugTextList[Idx].Font = InFont;
DebugTextList[Idx].FontScale = FontScale;
DebugTextList[Idx].bDrawShadow = bDrawShadow;
}
}
}
/** Remove debug text for the specific actor. */
void AHUD::RemoveDebugText_Implementation(AActor* SrcActor, bool bLeaveDurationText)
{
int32 Idx = INDEX_NONE;
for (int32 i = 0; i < DebugTextList.Num() && Idx == INDEX_NONE; ++i)
{
if (DebugTextList[i].SrcActor == SrcActor && (!bLeaveDurationText || DebugTextList[i].TimeRemaining == -1.f))
{
Idx = i;
}
}
if (Idx != INDEX_NONE)
{
DebugTextList.RemoveAt(Idx,1);
}
}
/** Remove all debug text */
void AHUD::RemoveAllDebugStrings_Implementation()
{
DebugTextList.Reset();
}
/// @endcond
void AHUD::NotifyHitBoxClick(FName BoxName)
{
// dispatch BP event
ReceiveHitBoxClick(BoxName);
}
void AHUD::NotifyHitBoxRelease(FName BoxName)
{
// dispatch BP event
ReceiveHitBoxRelease(BoxName);
}
void AHUD::NotifyHitBoxBeginCursorOver(FName BoxName)
{
// dispatch BP event
ReceiveHitBoxBeginCursorOver(BoxName);
}
void AHUD::NotifyHitBoxEndCursorOver(FName BoxName)
{
// dispatch BP event
ReceiveHitBoxEndCursorOver(BoxName);
}
void AHUD::GetTextSize(const FString& Text, float& OutWidth, float& OutHeight, class UFont* Font, float Scale) const
{
if (IsCanvasValid_WarnIfNot())
{
Canvas->TextSize(Font ? Font : GEngine->GetMediumFont(), Text, OutWidth, OutHeight, Scale, Scale);
}
}
void AHUD::DrawText(FString const& Text, FLinearColor Color, float ScreenX, float ScreenY, UFont* Font, float Scale, bool bScalePosition)
{
if (IsCanvasValid_WarnIfNot())
{
if (bScalePosition)
{
ScreenX *= Scale;
ScreenY *= Scale;
}
FCanvasTextItem TextItem( FVector2D( ScreenX, ScreenY ), FText::FromString(Text), Font ? Font : GEngine->GetMediumFont(), Color );
TextItem.Scale = FVector2D( Scale, Scale );
Canvas->DrawItem( TextItem );
}
}
void AHUD::DrawMaterial(UMaterialInterface* Material, float ScreenX, float ScreenY, float ScreenW, float ScreenH, float MaterialU, float MaterialV, float MaterialUWidth, float MaterialVHeight, float Scale, bool bScalePosition, float Rotation, FVector2D RotPivot)
{
if (IsCanvasValid_WarnIfNot() && Material)
{
FCanvasTileItem TileItem( FVector2D( ScreenX, ScreenY ), Material->GetRenderProxy(), FVector2D( ScreenW, ScreenH ) * Scale, FVector2D( MaterialU, MaterialV ), FVector2D( MaterialU+MaterialUWidth, MaterialV +MaterialVHeight) );
TileItem.Rotation = FRotator(0, Rotation, 0);
TileItem.PivotPoint = RotPivot;
if (bScalePosition)
{
TileItem.Position *= Scale;
}
Canvas->DrawItem( TileItem );
}
}
void AHUD::DrawMaterialSimple(UMaterialInterface* Material, float ScreenX, float ScreenY, float ScreenW, float ScreenH, float Scale, bool bScalePosition)
{
if (IsCanvasValid_WarnIfNot() && Material)
{
FCanvasTileItem TileItem( FVector2D( ScreenX, ScreenY ), Material->GetRenderProxy(), FVector2D( ScreenW, ScreenH ) * Scale );
if (bScalePosition)
{
TileItem.Position *= Scale;
}
Canvas->DrawItem( TileItem );
}
}
void AHUD::DrawTexture(UTexture* Texture, float ScreenX, float ScreenY, float ScreenW, float ScreenH, float TextureU, float TextureV, float TextureUWidth, float TextureVHeight, FLinearColor Color, EBlendMode BlendMode, float Scale, bool bScalePosition, float Rotation, FVector2D RotPivot)
{
if (IsCanvasValid_WarnIfNot() && Texture)
{
FCanvasTileItem TileItem( FVector2D( ScreenX, ScreenY ), Texture->Resource, FVector2D( ScreenW, ScreenH ) * Scale, FVector2D( TextureU, TextureV ), FVector2D( TextureU + TextureUWidth, TextureV + TextureVHeight ), Color );
TileItem.Rotation = FRotator(0, Rotation, 0);
TileItem.PivotPoint = RotPivot;
if (bScalePosition)
{
TileItem.Position *= Scale;
}
TileItem.BlendMode = FCanvas::BlendToSimpleElementBlend( BlendMode );
Canvas->DrawItem( TileItem );
}
}
void AHUD::DrawTextureSimple(UTexture* Texture, float ScreenX, float ScreenY, float Scale, bool bScalePosition)
{
if (IsCanvasValid_WarnIfNot() && Texture)
{
FCanvasTileItem TileItem( FVector2D( ScreenX, ScreenY ), Texture->Resource, FLinearColor::White );
if (bScalePosition)
{
TileItem.Position *= Scale;
}
// Apply the scale to the size (which will have been setup from the texture in the constructor).
TileItem.Size *= Scale;
TileItem.BlendMode = SE_BLEND_Translucent;
Canvas->DrawItem( TileItem );
}
}
void AHUD::DrawMaterialTriangle(UMaterialInterface* Material, FVector2D V0_Pos, FVector2D V1_Pos, FVector2D V2_Pos, FVector2D V0_UV, FVector2D V1_UV, FVector2D V2_UV, FLinearColor V0_Color, FLinearColor V1_Color, FLinearColor V2_Color)
{
if (IsCanvasValid_WarnIfNot() && Material)
{
FCanvasTriangleItem TriangleItem(V0_Pos, V1_Pos, V2_Pos, V0_UV, V1_UV, V2_UV, NULL);
TriangleItem.TriangleList[0].V0_Color = V0_Color;
TriangleItem.TriangleList[0].V1_Color = V1_Color;
TriangleItem.TriangleList[0].V2_Color = V2_Color;
TriangleItem.MaterialRenderProxy = Material->GetRenderProxy();
Canvas->DrawItem(TriangleItem);
}
}
FVector AHUD::Project(FVector Location) const
{
if (IsCanvasValid_WarnIfNot())
{
return Canvas->Project(Location);
}
return FVector(0,0,0);
}
void AHUD::Deproject(float ScreenX, float ScreenY, FVector& WorldPosition, FVector& WorldDirection) const
{
WorldPosition = WorldDirection = FVector(0,0,0);
if (IsCanvasValid_WarnIfNot())
{
Canvas->Deproject(FVector2D(ScreenX, ScreenY), WorldPosition, WorldDirection);
}
}
void AHUD::GetActorsInSelectionRectangle(TSubclassOf<class AActor> ClassFilter, const FVector2D& FirstPoint, const FVector2D& SecondPoint, TArray<AActor*>& OutActors, bool bIncludeNonCollidingComponents, bool bActorMustBeFullyEnclosed)
{
// Because this is a HUD function it is likely to get called each tick,
// so make sure any previous contents of the out actor array have been cleared!
OutActors.Reset();
//Create Selection Rectangle from Points
FBox2D SelectionRectangle(ForceInit);
//This method ensures that an appropriate rectangle is generated,
// no matter what the coordinates of first and second point actually are.
SelectionRectangle += FirstPoint;
SelectionRectangle += SecondPoint;
//The Actor Bounds Point Mapping
const FVector BoundsPointMapping[8] =
{
FVector(1.f, 1.f, 1.f),
FVector(1.f, 1.f, -1.f),
FVector(1.f, -1.f, 1.f),
FVector(1.f, -1.f, -1.f),
FVector(-1.f, 1.f, 1.f),
FVector(-1.f, 1.f, -1.f),
FVector(-1.f, -1.f, 1.f),
FVector(-1.f, -1.f, -1.f) };
//~~~
//For Each Actor of the Class Filter Type
for (TActorIterator<AActor> Itr(GetWorld(), ClassFilter); Itr; ++Itr)
{
AActor* EachActor = *Itr;
//Get Actor Bounds //casting to base class, checked by template in the .h
const FBox EachActorBounds = EachActor->GetComponentsBoundingBox(bIncludeNonCollidingComponents); /* All Components? */
//Center
const FVector BoxCenter = EachActorBounds.GetCenter();
//Extents
const FVector BoxExtents = EachActorBounds.GetExtent();
// Build 2D bounding box of actor in screen space
FBox2D ActorBox2D(ForceInit);
for (uint8 BoundsPointItr = 0; BoundsPointItr < 8; BoundsPointItr++)
{
// Project vert into screen space.
const FVector ProjectedWorldLocation = Project(BoxCenter + (BoundsPointMapping[BoundsPointItr] * BoxExtents));
// Add to 2D bounding box
ActorBox2D += FVector2D(ProjectedWorldLocation.X, ProjectedWorldLocation.Y);
}
//Selection Box must fully enclose the Projected Actor Bounds
if (bActorMustBeFullyEnclosed)
{
if(SelectionRectangle.IsInside(ActorBox2D))
{
OutActors.Add(EachActor);
}
}
//Partial Intersection with Projected Actor Bounds
else
{
if (SelectionRectangle.Intersect(ActorBox2D))
{
OutActors.Add(EachActor);
}
}
}
}
void AHUD::DrawRect(FLinearColor Color, float ScreenX, float ScreenY, float Width, float Height)
{
if (IsCanvasValid_WarnIfNot())
{
FCanvasTileItem TileItem( FVector2D(ScreenX, ScreenY), GWhiteTexture, FVector2D( Width, Height ), Color );
TileItem.BlendMode = SE_BLEND_Translucent;
Canvas->DrawItem( TileItem );
}
}
void AHUD::DrawLine(float StartScreenX, float StartScreenY, float EndScreenX, float EndScreenY, FLinearColor LineColor, float LineThickness)
{
if (IsCanvasValid_WarnIfNot())
{
FCanvasLineItem LineItem( FVector2D(StartScreenX, StartScreenY), FVector2D(EndScreenX, EndScreenY) );
LineItem.SetColor( LineColor );
LineItem.LineThickness = LineThickness;
Canvas->DrawItem( LineItem );
}
}
APlayerController* AHUD::GetOwningPlayerController() const
{
return PlayerOwner;
}
APawn* AHUD::GetOwningPawn() const
{
return PlayerOwner ? PlayerOwner->GetPawn() : NULL;
}
void AHUD::RenderHitBoxes( FCanvas* InCanvas )
{
for (const FHUDHitBox& HitBox : HitBoxMap)
{
FLinearColor BoxColor = FLinearColor::White;
if( HitBoxHits.Contains(const_cast<FHUDHitBox*>(&HitBox)))
{
BoxColor = FLinearColor::Red;
}
HitBox.Draw( InCanvas, BoxColor );
}
}
void AHUD::UpdateHitBoxCandidates( TArray<FVector2D> InContactPoints )
{
HitBoxHits.Reset();
for (FHUDHitBox& HitBox : HitBoxMap)
{
bool bAdded = false;
for (int32 ContactPointIndex = InContactPoints.Num() - 1; ContactPointIndex >= 0; --ContactPointIndex)
{
if (HitBox.Contains(InContactPoints[ContactPointIndex]))
{
if (!bAdded)
{
HitBoxHits.Add(&HitBox);
bAdded = true;
}
if (HitBox.ConsumesInput())
{
InContactPoints.RemoveAtSwap(ContactPointIndex);
}
else
{
break;
}
}
}
if (InContactPoints.Num() == 0)
{
break;
}
}
TSet<FName> NotOverHitBoxes = HitBoxesOver;
TArray<FName> NewlyOverHitBoxes;
// Now figure out which boxes we are over and deal with begin/end cursor over messages
for (FHUDHitBox* HitBox : HitBoxHits)
{
const FName HitBoxName = HitBox->GetName();
if (HitBoxesOver.Contains(HitBoxName))
{
NotOverHitBoxes.Remove(HitBoxName);
}
else
{
NewlyOverHitBoxes.AddUnique(HitBoxName);
}
}
// Dispatch the end cursor over messages
for (const FName HitBoxName : NotOverHitBoxes)
{
NotifyHitBoxEndCursorOver(HitBoxName);
HitBoxesOver.Remove(HitBoxName);
}
// Dispatch the newly over hitbox messages
for (const FName HitBoxName : NewlyOverHitBoxes)
{
NotifyHitBoxBeginCursorOver(HitBoxName);
HitBoxesOver.Add(HitBoxName);
}
}
const FHUDHitBox* AHUD::GetHitBoxAtCoordinates( FVector2D InHitLocation, const bool bIsConsumingInput ) const
{
if (HitBoxMap.Num() > 0)
{
InHitLocation -= GetCoordinateOffset();
for (const FHUDHitBox& HitBox : HitBoxMap)
{
if( (!bIsConsumingInput || HitBox.ConsumesInput()) && HitBox.Contains( InHitLocation ) )
{
return &HitBox;
}
}
}
return nullptr;
}
void AHUD::GetHitBoxesAtCoordinates(FVector2D InHitLocation, TArray<const FHUDHitBox*>& OutHitBoxes) const
{
OutHitBoxes.Reset();
if (HitBoxMap.Num() > 0)
{
InHitLocation -= GetCoordinateOffset();
for (const FHUDHitBox& HitBox : HitBoxMap)
{
if (HitBox.Contains(InHitLocation))
{
OutHitBoxes.Add(&HitBox);
}
}
}
}
const FHUDHitBox* AHUD::GetHitBoxWithName( const FName InName ) const
{
for (const FHUDHitBox& HitBox : HitBoxMap)
{
if( HitBox.GetName() == InName )
{
return &HitBox;
}
}
return nullptr;
}
bool AHUD::AnyCurrentHitBoxHits() const
{
return HitBoxHits.Num() != 0;
}
bool AHUD::UpdateAndDispatchHitBoxClickEvents(FVector2D ClickLocation, const EInputEvent InEventType)
{
const bool bIsClickEvent = (InEventType == IE_Pressed || InEventType == IE_DoubleClick);
// Early out to avoid unnecessary expense of calling GetCoordinateOffset
if ((bIsClickEvent && HitBoxMap.Num() == 0) || (!bIsClickEvent && HitBoxHits.Num() == 0))
{
return false;
}
ClickLocation += GetCoordinateOffset();
bool bHit = false;
// If this is a click event we may not have the hit box in the hit list yet (particularly for touch events) so we need to check all HitBoxes
if (bIsClickEvent)
{
for (FHUDHitBox& HitBox : HitBoxMap)
{
if (HitBox.Contains(ClickLocation))
{
bHit = true;
NotifyHitBoxClick(HitBox.GetName());
if (HitBox.ConsumesInput())
{
break; //Early out if this box consumed the click
}
}
}
}
else
{
for (FHUDHitBox* HitBoxHit : HitBoxHits)
{
if (HitBoxHit->Contains(ClickLocation))
{
bHit = true;
if (InEventType == IE_Released)
{
NotifyHitBoxRelease(HitBoxHit->GetName());
}
if (HitBoxHit->ConsumesInput() == true)
{
break; //Early out if this box consumed the click
}
}
}
}
return bHit;
}
void AHUD::AddHitBox(FVector2D Position, FVector2D Size, FName Name, bool bConsumesInput, int32 Priority)
{
if( GetHitBoxWithName(Name) == nullptr )
{
bool bAdded = false;
for (int32 Index = 0; Index < HitBoxMap.Num(); ++Index)
{
if (HitBoxMap[Index].GetPriority() < Priority)
{
HitBoxMap.Insert(FHUDHitBox(Position, Size, Name, bConsumesInput, Priority), Index);
bAdded = true;
break;
}
}
if (!bAdded)
{
HitBoxMap.Add(FHUDHitBox(Position, Size, Name, bConsumesInput, Priority));
}
}
else
{
UE_LOG(LogHUD, Warning, TEXT("Failed to add hitbox named %s as a hitbox with this name already exists"), *Name.ToString());
}
}
bool AHUD::IsCanvasValid_WarnIfNot() const
{
const bool bIsValid = Canvas != NULL;
if (!bIsValid)
{
FMessageLog("PIE").Warning()
->AddToken(FUObjectToken::Create(const_cast<AHUD*>(this)))
->AddToken(FTextToken::Create(LOCTEXT( "PIE_Warning_Message_CanvasCallOutsideOfDrawCanvas", "Canvas Draw functions may only be called during the handling of the DrawHUD event" )));
}
return bIsValid;
}
#undef LOCTEXT_NAMESPACE
| 0 | 0.915219 | 1 | 0.915219 | game-dev | MEDIA | 0.639174 | game-dev,graphics-rendering | 0.946018 | 1 | 0.946018 |
badvision/lawless-legends | 5,214 | Platform/Apple/tools/jace/src/main/java/jace/cheat/Cheats.java | /**
* Copyright 2024 Brendan Robert
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package jace.cheat;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Supplier;
import jace.apple2e.MOS65C02;
import jace.config.DeviceEnum;
import jace.config.InvokableAction;
import jace.core.Device;
import jace.core.RAMEvent;
import jace.core.RAMListener;
import jace.lawless.LawlessHacks;
/**
* Represents some combination of hacks that can be enabled or disabled through
* the configuration interface.
*
* @author Brendan Robert (BLuRry) brendan.robert@gmail.com
*/
public abstract class Cheats extends Device {
public static enum Cheat implements DeviceEnum<Cheats> {
Metacheat("Metacheat", MetaCheat.class, MetaCheat::new),
MontezumasRevenge("Montezuma's Revenge", MontezumasRevengeCheats.class, MontezumasRevengeCheats::new),
PrinceOfPersia("Prince of Persia", PrinceOfPersiaCheats.class, PrinceOfPersiaCheats::new),
LawlessHacks("Lawless Legends Enhancements", LawlessHacks.class, LawlessHacks::new),
ProgramIdentity("Identify program", ProgramIdentity.class, ProgramIdentity::new);
Supplier<Cheats> factory;
String name;
Class<? extends Cheats> clazz;
Cheat(String name, Class<? extends Cheats> clazz, Supplier<Cheats> factory) {
this.name = name;
this.clazz = clazz;
this.factory = factory;
}
@Override
public String getName() {
return name;
}
@Override
public Cheats create() {
return factory.get();
}
@Override
public boolean isInstance(Cheats cheat) {
if (cheat == null) {
return false;
}
return clazz == cheat.getClass();
}
}
boolean cheatsActive = true;
Set<RAMListener> listeners = new HashSet<>();
@InvokableAction(name = "Toggle Cheats", alternatives = "cheat;Plug-in", defaultKeyMapping = "ctrl+shift+m")
public void toggleCheats() {
cheatsActive = !cheatsActive;
if (cheatsActive) {
attach();
} else {
detach();
}
}
public RAMListener bypassCode(String name, int address, int addressEnd) {
int noOperation = MOS65C02.COMMAND.NOP.ordinal();
return addCheat(name, RAMEvent.TYPE.READ, (e) -> e.setNewValue(noOperation), address, addressEnd);
}
public RAMListener forceValue(String name, int value, int... address) {
return addCheat(name, RAMEvent.TYPE.ANY, (e) -> e.setNewValue(value), address);
}
public RAMListener forceValue(String name, int value, Boolean auxFlag, int... address) {
return addCheat(name, RAMEvent.TYPE.ANY, auxFlag, (e) -> e.setNewValue(value), address);
}
public RAMListener addCheat(String name, RAMEvent.TYPE type, RAMEvent.RAMEventHandler handler, int... address) {
RAMListener listener;
if (address.length == 1) {
listener = getMemory().observe(getName() + ": " + name, type, address[0], handler);
} else {
listener = getMemory().observe(getName() + ": " + name, type, address[0], address[1], handler);
}
listeners.add(listener);
return listener;
}
public RAMListener addCheat(String name, RAMEvent.TYPE type, Boolean auxFlag, RAMEvent.RAMEventHandler handler, int... address) {
RAMListener listener;
if (address.length == 1) {
listener = getMemory().observe(getName() + ": " + name, type, address[0], auxFlag, handler);
} else {
listener = getMemory().observe(getName() + ": " + name, type, address[0], address[1], auxFlag, handler);
}
listeners.add(listener);
return listener;
}
@Override
public void attach() {
registerListeners();
}
@Override
public void detach() {
unregisterListeners();
super.detach();
}
public abstract void registerListeners();
protected void unregisterListeners() {
// Create a copy to avoid ConcurrentModificationException
Set<RAMListener> listenersCopy = new HashSet<>(listeners);
listenersCopy.forEach((l) -> {
getMemory().removeListener(l);
});
listeners.clear();
}
public void removeListener(RAMListener l) {
getMemory().removeListener(l);
listeners.remove(l);
}
@Override
public void reconfigure() {
unregisterListeners();
if (cheatsActive) {
registerListeners();
}
}
@Override
public String getShortName() {
return "cheat";
}
}
| 0 | 0.897266 | 1 | 0.897266 | game-dev | MEDIA | 0.583447 | game-dev | 0.946257 | 1 | 0.946257 |
Mithion/ArsMagica2 | 3,585 | src/main/java/am2/spell/components/MeltArmor.java | package am2.spell.components;
import am2.AMCore;
import am2.api.spell.component.interfaces.ISpellComponent;
import am2.api.spell.enums.Affinity;
import am2.particles.AMParticle;
import am2.particles.ParticleHoldPosition;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import java.util.EnumSet;
import java.util.Random;
public class MeltArmor implements ISpellComponent{
private static final String mmpsNBTTagName = "mmmpsmod";
private static final String mmpsChargeTagName = "Current Energy";
@Override
public Object[] getRecipeItems(){
return new Object[]{
new ItemStack(Blocks.sponge)
};
}
@Override
public int getID(){
return 60;
}
@Override
public boolean applyEffectBlock(ItemStack stack, World world, int blockx, int blocky, int blockz, int blockFace, double impactX, double impactY, double impactZ, EntityLivingBase caster){
return false;
}
@Override
public boolean applyEffectEntity(ItemStack stack, World world, EntityLivingBase caster, Entity target){
if (target instanceof EntityPlayer && !world.isRemote){
doMeltArmor(caster, ((EntityPlayer)target).inventory.armorInventory);
return true;
}
return false;
}
private void doMeltArmor(EntityLivingBase caster, ItemStack[] armor){
double mmpsCharge = getMMPSCharge(armor);
for (ItemStack stack : armor){
if (stack == null) continue;
if (!stack.hasTagCompound() || !stack.stackTagCompound.hasKey(mmpsNBTTagName)){
stack.damageItem((int)Math.ceil(stack.getItem().getMaxDamage() * 0.25f), caster);
}else{
NBTTagCompound subCompound = (NBTTagCompound)stack.stackTagCompound.getTag(mmpsNBTTagName);
double charge = stack.stackTagCompound.getDouble(mmpsChargeTagName);
charge -= mmpsCharge * 0.75f;
if (charge < 0) charge = 0;
subCompound.setDouble(mmpsChargeTagName, charge);
}
}
}
private double getMMPSCharge(ItemStack[] armor){
double total = -1;
for (ItemStack stack : armor){
if (stack != null && stack.hasTagCompound()){
NBTTagCompound subCompound = (NBTTagCompound)stack.stackTagCompound.getTag(mmpsNBTTagName);
if (subCompound != null && subCompound.hasKey(mmpsChargeTagName)){
total += subCompound.getDouble(mmpsChargeTagName);
}
}
}
return total;
}
@Override
public float manaCost(EntityLivingBase caster){
return 15;
}
@Override
public float burnout(EntityLivingBase caster){
return 15;
}
@Override
public ItemStack[] reagents(EntityLivingBase caster){
return null;
}
@Override
public void spawnParticles(World world, double x, double y, double z, EntityLivingBase caster, Entity target, Random rand, int colorModifier){
AMParticle particle = (AMParticle)AMCore.proxy.particleManager.spawn(world, "radiant", x + 0.5, y + 0.5, z + 0.5);
if (particle != null){
particle.AddParticleController(new ParticleHoldPosition(particle, 20, 1, false));
particle.setMaxAge(20);
particle.setParticleScale(0.3f);
particle.setRGBColorF(0.7f, 0.4f, 0.2f);
particle.SetParticleAlpha(0.1f);
if (colorModifier > -1){
particle.setRGBColorF(((colorModifier >> 16) & 0xFF) / 255.0f, ((colorModifier >> 8) & 0xFF) / 255.0f, (colorModifier & 0xFF) / 255.0f);
}
}
}
@Override
public EnumSet<Affinity> getAffinity(){
return EnumSet.of(Affinity.FIRE);
}
@Override
public float getAffinityShift(Affinity affinity){
return 0;
}
}
| 0 | 0.903841 | 1 | 0.903841 | game-dev | MEDIA | 0.995067 | game-dev | 0.94281 | 1 | 0.94281 |
XadillaX/sfml.js | 5,820 | third_party/sfml/include/SFML/Window/Sensor.hpp | ////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2023 Laurent Gomila (laurent@sfml-dev.org)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_SENSOR_HPP
#define SFML_SENSOR_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Window/Export.hpp>
#include <SFML/System/Vector3.hpp>
#include <SFML/System/Time.hpp>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief Give access to the real-time state of the sensors
///
////////////////////////////////////////////////////////////
class SFML_WINDOW_API Sensor
{
public:
////////////////////////////////////////////////////////////
/// \brief Sensor type
///
////////////////////////////////////////////////////////////
enum Type
{
Accelerometer, //!< Measures the raw acceleration (m/s^2)
Gyroscope, //!< Measures the raw rotation rates (degrees/s)
Magnetometer, //!< Measures the ambient magnetic field (micro-teslas)
Gravity, //!< Measures the direction and intensity of gravity, independent of device acceleration (m/s^2)
UserAcceleration, //!< Measures the direction and intensity of device acceleration, independent of the gravity (m/s^2)
Orientation, //!< Measures the absolute 3D orientation (degrees)
Count //!< Keep last -- the total number of sensor types
};
////////////////////////////////////////////////////////////
/// \brief Check if a sensor is available on the underlying platform
///
/// \param sensor Sensor to check
///
/// \return True if the sensor is available, false otherwise
///
////////////////////////////////////////////////////////////
static bool isAvailable(Type sensor);
////////////////////////////////////////////////////////////
/// \brief Enable or disable a sensor
///
/// All sensors are disabled by default, to avoid consuming too
/// much battery power. Once a sensor is enabled, it starts
/// sending events of the corresponding type.
///
/// This function does nothing if the sensor is unavailable.
///
/// \param sensor Sensor to enable
/// \param enabled True to enable, false to disable
///
////////////////////////////////////////////////////////////
static void setEnabled(Type sensor, bool enabled);
////////////////////////////////////////////////////////////
/// \brief Get the current sensor value
///
/// \param sensor Sensor to read
///
/// \return The current sensor value
///
////////////////////////////////////////////////////////////
static Vector3f getValue(Type sensor);
};
} // namespace sf
#endif // SFML_SENSOR_HPP
////////////////////////////////////////////////////////////
/// \class sf::Sensor
/// \ingroup window
///
/// sf::Sensor provides an interface to the state of the
/// various sensors that a device provides. It only contains static
/// functions, so it's not meant to be instantiated.
///
/// This class allows users to query the sensors values at any
/// time and directly, without having to deal with a window and
/// its events. Compared to the SensorChanged event, sf::Sensor
/// can retrieve the state of a sensor at any time (you don't need to
/// store and update its current value on your side).
///
/// Depending on the OS and hardware of the device (phone, tablet, ...),
/// some sensor types may not be available. You should always check
/// the availability of a sensor before trying to read it, with the
/// sf::Sensor::isAvailable function.
///
/// You may wonder why some sensor types look so similar, for example
/// Accelerometer and Gravity / UserAcceleration. The first one
/// is the raw measurement of the acceleration, and takes into account
/// both the earth gravity and the user movement. The others are
/// more precise: they provide these components separately, which is
/// usually more useful. In fact they are not direct sensors, they
/// are computed internally based on the raw acceleration and other sensors.
/// This is exactly the same for Gyroscope vs Orientation.
///
/// Because sensors consume a non-negligible amount of current, they are
/// all disabled by default. You must call sf::Sensor::setEnabled for each
/// sensor in which you are interested.
///
/// Usage example:
/// \code
/// if (sf::Sensor::isAvailable(sf::Sensor::Gravity))
/// {
/// // gravity sensor is available
/// }
///
/// // enable the gravity sensor
/// sf::Sensor::setEnabled(sf::Sensor::Gravity, true);
///
/// // get the current value of gravity
/// sf::Vector3f gravity = sf::Sensor::getValue(sf::Sensor::Gravity);
/// \endcode
///
////////////////////////////////////////////////////////////
| 0 | 0.628345 | 1 | 0.628345 | game-dev | MEDIA | 0.556264 | game-dev | 0.617199 | 1 | 0.617199 |
JamesTKhan/Mundus | 2,471 | editor/src/main/com/mbrlabs/mundus/editor/tools/terrain/SmoothTool.java | /*
* Copyright (c) 2023. See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mbrlabs.mundus.editor.tools.terrain;
import com.badlogic.gdx.math.Interpolation;
import com.mbrlabs.mundus.commons.terrain.Terrain;
import com.mbrlabs.mundus.editor.tools.brushes.TerrainBrush;
/**
* Get average height of all vertices in radius, interpolate heights to average height
* will a falloff effect based on distance from radius.
*
* @author JamesTKhan
* @version June 28, 2023
*/
public class SmoothTool extends RadiusTerrainTool {
private float averageHeight = 0;
// Interpolate heights to average height with falloff
private final TerrainBrush.TerrainModifyAction modifier = (brush, terrainComponent, x, z, tVec2, vertexPos) -> {
Terrain terrain = terrainComponent.getTerrainAsset().getTerrain();
final int index = z * terrain.vertexResolution + x;
float heightAtIndex = terrain.heightData[index];
// Determine how much to interpolate based on distance from radius
float elevation = brush.getValueOfBrushPixmap(tVec2.x, tVec2.z, vertexPos.x, vertexPos.z, brush.getScaledRadius(terrainComponent));
float smoothedHeight = Interpolation.smooth2.apply(heightAtIndex, averageHeight, elevation * TerrainBrush.getStrength());
terrain.heightData[index] = smoothedHeight;
};
@Override
public void act(TerrainBrush brush) {
final int[] weights = {0};
final float[] totalHeights = {0};
// Get average height of all vertices in radius
TerrainBrush.TerrainModifyAction heightAverage = (terrainBrush, terrain, x, z, tVec2, vertexPos) -> {
totalHeights[0] += vertexPos.y;
weights[0]++;
};
brush.modifyTerrain(heightAverage, radiusDistanceComparison, true);
averageHeight = totalHeights[0] / weights[0];
brush.modifyTerrain(modifier, radiusDistanceComparison, true);
}
}
| 0 | 0.700012 | 1 | 0.700012 | game-dev | MEDIA | 0.816331 | game-dev | 0.930227 | 1 | 0.930227 |
AkilLabs/Interview-IQ | 10,835 | iq/Lib/site-packages/sqlalchemy/event/registry.py | # event/registry.py
# Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: https://www.opensource.org/licenses/mit-license.php
"""Provides managed registration services on behalf of :func:`.listen`
arguments.
By "managed registration", we mean that event listening functions and
other objects can be added to various collections in such a way that their
membership in all those collections can be revoked at once, based on
an equivalent :class:`._EventKey`.
"""
from __future__ import annotations
import collections
import types
import typing
from typing import Any
from typing import Callable
from typing import cast
from typing import Deque
from typing import Dict
from typing import Generic
from typing import Iterable
from typing import Optional
from typing import Tuple
from typing import TypeVar
from typing import Union
import weakref
from .. import exc
from .. import util
if typing.TYPE_CHECKING:
from .attr import RefCollection
from .base import dispatcher
_ListenerFnType = Callable[..., Any]
_ListenerFnKeyType = Union[int, Tuple[int, int]]
_EventKeyTupleType = Tuple[int, str, _ListenerFnKeyType]
_ET = TypeVar("_ET", bound="EventTarget")
class EventTarget:
"""represents an event target, that is, something we can listen on
either with that target as a class or as an instance.
Examples include: Connection, Mapper, Table, Session,
InstrumentedAttribute, Engine, Pool, Dialect.
"""
__slots__ = ()
dispatch: dispatcher[Any]
_RefCollectionToListenerType = Dict[
"weakref.ref[RefCollection[Any]]",
"weakref.ref[_ListenerFnType]",
]
_key_to_collection: Dict[_EventKeyTupleType, _RefCollectionToListenerType] = (
collections.defaultdict(dict)
)
"""
Given an original listen() argument, can locate all
listener collections and the listener fn contained
(target, identifier, fn) -> {
ref(listenercollection) -> ref(listener_fn)
ref(listenercollection) -> ref(listener_fn)
ref(listenercollection) -> ref(listener_fn)
}
"""
_ListenerToEventKeyType = Dict[
"weakref.ref[_ListenerFnType]",
_EventKeyTupleType,
]
_collection_to_key: Dict[
weakref.ref[RefCollection[Any]],
_ListenerToEventKeyType,
] = collections.defaultdict(dict)
"""
Given a _ListenerCollection or _ClsLevelListener, can locate
all the original listen() arguments and the listener fn contained
ref(listenercollection) -> {
ref(listener_fn) -> (target, identifier, fn),
ref(listener_fn) -> (target, identifier, fn),
ref(listener_fn) -> (target, identifier, fn),
}
"""
def _collection_gced(ref: weakref.ref[Any]) -> None:
# defaultdict, so can't get a KeyError
if not _collection_to_key or ref not in _collection_to_key:
return
ref = cast("weakref.ref[RefCollection[EventTarget]]", ref)
listener_to_key = _collection_to_key.pop(ref)
for key in listener_to_key.values():
if key in _key_to_collection:
# defaultdict, so can't get a KeyError
dispatch_reg = _key_to_collection[key]
dispatch_reg.pop(ref)
if not dispatch_reg:
_key_to_collection.pop(key)
def _stored_in_collection(
event_key: _EventKey[_ET], owner: RefCollection[_ET]
) -> bool:
key = event_key._key
dispatch_reg = _key_to_collection[key]
owner_ref = owner.ref
listen_ref = weakref.ref(event_key._listen_fn)
if owner_ref in dispatch_reg:
return False
dispatch_reg[owner_ref] = listen_ref
listener_to_key = _collection_to_key[owner_ref]
listener_to_key[listen_ref] = key
return True
def _removed_from_collection(
event_key: _EventKey[_ET], owner: RefCollection[_ET]
) -> None:
key = event_key._key
dispatch_reg = _key_to_collection[key]
listen_ref = weakref.ref(event_key._listen_fn)
owner_ref = owner.ref
dispatch_reg.pop(owner_ref, None)
if not dispatch_reg:
del _key_to_collection[key]
if owner_ref in _collection_to_key:
listener_to_key = _collection_to_key[owner_ref]
listener_to_key.pop(listen_ref)
def _stored_in_collection_multi(
newowner: RefCollection[_ET],
oldowner: RefCollection[_ET],
elements: Iterable[_ListenerFnType],
) -> None:
if not elements:
return
oldowner_ref = oldowner.ref
newowner_ref = newowner.ref
old_listener_to_key = _collection_to_key[oldowner_ref]
new_listener_to_key = _collection_to_key[newowner_ref]
for listen_fn in elements:
listen_ref = weakref.ref(listen_fn)
try:
key = old_listener_to_key[listen_ref]
except KeyError:
# can occur during interpreter shutdown.
# see #6740
continue
try:
dispatch_reg = _key_to_collection[key]
except KeyError:
continue
if newowner_ref in dispatch_reg:
assert dispatch_reg[newowner_ref] == listen_ref
else:
dispatch_reg[newowner_ref] = listen_ref
new_listener_to_key[listen_ref] = key
def _clear(
owner: RefCollection[_ET],
elements: Iterable[_ListenerFnType],
) -> None:
if not elements:
return
owner_ref = owner.ref
listener_to_key = _collection_to_key[owner_ref]
for listen_fn in elements:
listen_ref = weakref.ref(listen_fn)
key = listener_to_key[listen_ref]
dispatch_reg = _key_to_collection[key]
dispatch_reg.pop(owner_ref, None)
if not dispatch_reg:
del _key_to_collection[key]
class _EventKey(Generic[_ET]):
"""Represent :func:`.listen` arguments."""
__slots__ = (
"target",
"identifier",
"fn",
"fn_key",
"fn_wrap",
"dispatch_target",
)
target: _ET
identifier: str
fn: _ListenerFnType
fn_key: _ListenerFnKeyType
dispatch_target: Any
_fn_wrap: Optional[_ListenerFnType]
def __init__(
self,
target: _ET,
identifier: str,
fn: _ListenerFnType,
dispatch_target: Any,
_fn_wrap: Optional[_ListenerFnType] = None,
):
self.target = target
self.identifier = identifier
self.fn = fn
if isinstance(fn, types.MethodType):
self.fn_key = id(fn.__func__), id(fn.__self__)
else:
self.fn_key = id(fn)
self.fn_wrap = _fn_wrap
self.dispatch_target = dispatch_target
@property
def _key(self) -> _EventKeyTupleType:
return (id(self.target), self.identifier, self.fn_key)
def with_wrapper(self, fn_wrap: _ListenerFnType) -> _EventKey[_ET]:
if fn_wrap is self._listen_fn:
return self
else:
return _EventKey(
self.target,
self.identifier,
self.fn,
self.dispatch_target,
_fn_wrap=fn_wrap,
)
def with_dispatch_target(self, dispatch_target: Any) -> _EventKey[_ET]:
if dispatch_target is self.dispatch_target:
return self
else:
return _EventKey(
self.target,
self.identifier,
self.fn,
dispatch_target,
_fn_wrap=self.fn_wrap,
)
def listen(self, *args: Any, **kw: Any) -> None:
once = kw.pop("once", False)
once_unless_exception = kw.pop("_once_unless_exception", False)
named = kw.pop("named", False)
target, identifier, fn = (
self.dispatch_target,
self.identifier,
self._listen_fn,
)
dispatch_collection = getattr(target.dispatch, identifier)
adjusted_fn = dispatch_collection._adjust_fn_spec(fn, named)
self = self.with_wrapper(adjusted_fn)
stub_function = getattr(
self.dispatch_target.dispatch._events, self.identifier
)
if hasattr(stub_function, "_sa_warn"):
stub_function._sa_warn()
if once or once_unless_exception:
self.with_wrapper(
util.only_once(
self._listen_fn, retry_on_exception=once_unless_exception
)
).listen(*args, **kw)
else:
self.dispatch_target.dispatch._listen(self, *args, **kw)
def remove(self) -> None:
key = self._key
if key not in _key_to_collection:
raise exc.InvalidRequestError(
"No listeners found for event %s / %r / %s "
% (self.target, self.identifier, self.fn)
)
dispatch_reg = _key_to_collection.pop(key)
for collection_ref, listener_ref in dispatch_reg.items():
collection = collection_ref()
listener_fn = listener_ref()
if collection is not None and listener_fn is not None:
collection.remove(self.with_wrapper(listener_fn))
def contains(self) -> bool:
"""Return True if this event key is registered to listen."""
return self._key in _key_to_collection
def base_listen(
self,
propagate: bool = False,
insert: bool = False,
named: bool = False,
retval: Optional[bool] = None,
asyncio: bool = False,
) -> None:
target, identifier = self.dispatch_target, self.identifier
dispatch_collection = getattr(target.dispatch, identifier)
for_modify = dispatch_collection.for_modify(target.dispatch)
if asyncio:
for_modify._set_asyncio()
if insert:
for_modify.insert(self, propagate)
else:
for_modify.append(self, propagate)
@property
def _listen_fn(self) -> _ListenerFnType:
return self.fn_wrap or self.fn
def append_to_list(
self,
owner: RefCollection[_ET],
list_: Deque[_ListenerFnType],
) -> bool:
if _stored_in_collection(self, owner):
list_.append(self._listen_fn)
return True
else:
return False
def remove_from_list(
self,
owner: RefCollection[_ET],
list_: Deque[_ListenerFnType],
) -> None:
_removed_from_collection(self, owner)
list_.remove(self._listen_fn)
def prepend_to_list(
self,
owner: RefCollection[_ET],
list_: Deque[_ListenerFnType],
) -> bool:
if _stored_in_collection(self, owner):
list_.appendleft(self._listen_fn)
return True
else:
return False
| 0 | 0.917409 | 1 | 0.917409 | game-dev | MEDIA | 0.287561 | game-dev | 0.972727 | 1 | 0.972727 |
awgil/ffxiv_bossmod | 2,583 | BossMod/Modules/Endwalker/Criterion/C02AMR/C022Gorai/FightingSpirits.cs | namespace BossMod.Endwalker.Criterion.C02AMR.C022Gorai;
class FightingSpirits(BossModule module, AID aid) : Components.KnockbackFromCastTarget(module, aid, 16);
class NFightingSpirits(BossModule module) : FightingSpirits(module, AID.NFightingSpiritsAOE);
class SFightingSpirits(BossModule module) : FightingSpirits(module, AID.SFightingSpiritsAOE);
class WorldlyPursuitBait(BossModule module) : Components.GenericBaitAway(module, centerAtTarget: true)
{
private readonly int[] _order = [-1, -1, -1, -1];
private static readonly AOEShapeCross _shape = new(60, 10);
public override void AddHints(int slot, Actor actor, TextHints hints)
{
if (_order[slot] >= 0)
hints.Add($"Order: {_order[slot] + 1}", false);
base.AddHints(slot, actor, hints);
}
// TODO: reconsider when we start showing first hint...
public override void OnCastFinished(Actor caster, ActorCastInfo spell)
{
if ((AID)spell.Action.ID is AID.FightingSpirits)
UpdateBait();
}
public override void OnEventCast(Actor caster, ActorCastEvent spell)
{
if ((AID)spell.Action.ID is AID.NWorldlyPursuitAOE or AID.SWorldlyPursuitAOE)
{
++NumCasts;
UpdateBait();
}
}
public override void OnEventIcon(Actor actor, uint iconID, ulong targetID)
{
var order = (IconID)iconID switch
{
IconID.Order1 => 0,
IconID.Order2 => 1,
IconID.Order3 => 2,
IconID.Order4 => 3,
_ => -1,
};
if (order >= 0 && Raid.TryFindSlot(actor.InstanceID, out var slot))
{
_order[slot] = order;
}
}
private void UpdateBait()
{
CurrentBaits.Clear();
var baiter = Raid[Array.IndexOf(_order, NumCasts)];
if (baiter != null)
CurrentBaits.Add(new(Module.PrimaryActor, baiter, _shape));
}
}
class WorldlyPursuitLast(BossModule module) : Components.GenericAOEs(module)
{
private readonly DateTime _activation = module.WorldState.FutureTime(3.1f);
private static readonly AOEShapeCross _shape = new(60, 10);
public override IEnumerable<AOEInstance> ActiveAOEs(int slot, Actor actor)
{
yield return new(_shape, Module.Center, Angle.FromDirection(Module.Center - Module.PrimaryActor.Position), _activation);
}
public override void OnEventCast(Actor caster, ActorCastEvent spell)
{
if ((AID)spell.Action.ID is AID.NWorldlyPursuitAOE or AID.SWorldlyPursuitAOE)
++NumCasts;
}
}
| 0 | 0.943575 | 1 | 0.943575 | game-dev | MEDIA | 0.913382 | game-dev | 0.960767 | 1 | 0.960767 |
SlashScreen/skelerealms | 2,757 | scripts/puppets/npc_puppet.gd | class_name NPCPuppet
extends CharacterBody3D
## Puppet "brain" for an NPC.
@onready var movement_target_position: Vector3 = position # No world because this agent only works in the scene.
## This is a stealth provider. See the "Sealth Provider" article i nthe documentation for details.
@export var eyes:Node
var npc_component:NPCComponent
var puppeteer:PuppetSpawnerComponent
var view_dir:ViewDirectionComponent
var movement_speed: float = 1.0
var target_reached:bool:
get:
return navigation_agent.is_navigation_finished()
## Called every frame to update the entity's position.
signal change_position(Vector3)
var movement_paused:bool = false
## The navigation agent.
@onready var navigation_agent: NavigationAgent3D = $NavigationAgent3D
# Called when the node enters the scene tree for the first time.
func _ready() -> void:
call_deferred("_actor_setup")
add_to_group("perception_target")
change_position.connect((get_parent().get_parent() as SKEntity)._on_set_position.bind())
puppeteer = $"../../".get_component("PuppetSpawnerComponent")
npc_component = $"../../".get_component("NPCComponent")
view_dir = $"../../".get_component("ViewDirectionComponent")
if npc_component:
puppeteer.printe("Connecting percieved event")
npc_component.entered_combat.connect(draw_weapons.bind())
npc_component.left_combat.connect(lower_weapons.bind())
else:
push_warning("NPC Puppet not a child of an entity with an NPCComponent. Perception turned off.")
func get_puppeteer() -> PuppetSpawnerComponent:
return puppeteer
## Finds the closest point to this puppet, and jumps to it.
## This is to avoid getting stuck in things that it may have phased into while navigating out-of-scene.
func snap_to_navmesh() -> void:
position = NavigationServer3D.map_get_closest_point(NavigationServer3D.get_maps()[0], position)
## Set up navigation.
func _actor_setup() -> void:
# Wait for the first physics frame so the NavigationServer can sync.
await get_tree().physics_frame
snap_to_navmesh() # snap to mesh
# Now that the navigation map is no longer empty, set the movement target.
set_movement_target(movement_target_position)
## Set the target for the NPC.
func set_movement_target(movement_target: Vector3) -> void:
navigation_agent.set_target_position(movement_target)
func pause_nav() -> void:
movement_paused = true
func continue_nav() -> void:
movement_paused = false
func _physics_process(delta) -> void:
npc_component.puppet_request_move.emit(self)
func _process(delta) -> void:
change_position.emit(position)
view_dir.view_rot = rotation
func draw_weapons() -> void:
npc_component.puppet_request_raise_weapons.emit(self)
func lower_weapons() -> void:
npc_component.puppet_request_lower_weapons.emit(self)
| 0 | 0.866216 | 1 | 0.866216 | game-dev | MEDIA | 0.989031 | game-dev | 0.937948 | 1 | 0.937948 |
TaiyitistMC/Taiyitist | 3,907 | modules/taiyitist-server/src/main/java/com/taiyitistmc/mixin/world/level/block/MixinSculkVeinBlock.java | package com.taiyitistmc.mixin.world.level.block;
import java.util.Iterator;
import java.util.concurrent.atomic.AtomicReference;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.tags.TagKey;
import net.minecraft.util.RandomSource;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.SculkSpreader;
import net.minecraft.world.level.block.SculkVeinBlock;
import net.minecraft.world.level.block.state.BlockState;
import org.bukkit.craftbukkit.event.CraftEventFactory;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
@Mixin(SculkVeinBlock.class)
public abstract class MixinSculkVeinBlock {
private final AtomicReference<BlockPos> taiyitist$source = new AtomicReference<>();
private final AtomicReference<BlockPos> taiyitist$pos = new AtomicReference<>();
@Shadow
protected abstract boolean attemptPlaceSculk(SculkSpreader spreader, LevelAccessor level, BlockPos pos, RandomSource random);
@Inject(method = "attemptUseCharge", at = @At("HEAD"))
private void taiyitist$getSource(SculkSpreader.ChargeCursor cursor,
LevelAccessor level,
BlockPos pos, RandomSource random, SculkSpreader spreader,
boolean bl, CallbackInfoReturnable<Integer> cir) {
taiyitist$source.set(pos);
}
@Redirect(method = "attemptUseCharge", at = @At(value = "INVOKE",
target = "Lnet/minecraft/world/level/block/SculkVeinBlock;attemptPlaceSculk(Lnet/minecraft/world/level/block/SculkSpreader;Lnet/minecraft/world/level/LevelAccessor;Lnet/minecraft/core/BlockPos;Lnet/minecraft/util/RandomSource;)Z"))
private boolean taiyitist$attemptPlace(SculkVeinBlock instance, SculkSpreader spreader, LevelAccessor level, BlockPos pos, RandomSource random) {
return attemptPlaceSculk(spreader, level, pos, random, taiyitist$source.get());
}
private boolean attemptPlaceSculk(SculkSpreader spreader, LevelAccessor level, BlockPos pos, RandomSource random, BlockPos sourceBlock) {
taiyitist$pos.set(sourceBlock);
return attemptPlaceSculk(spreader, level, pos, random);
}
@Redirect(method = "attemptPlaceSculk", at = @At(value = "INVOKE",
target = "Lnet/minecraft/world/level/LevelAccessor;setBlock(Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;I)Z"))
private boolean taiyitist$cancelSetBlock(LevelAccessor instance, BlockPos pos, BlockState state, int i) {
return false;
}
@Inject(method = "attemptPlaceSculk", at = @At(value = "INVOKE",
target = "Lnet/minecraft/world/level/LevelAccessor;setBlock(Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;I)Z"),
locals = LocalCapture.CAPTURE_FAILHARD, cancellable = true)
private void taiyitist$setBlock(SculkSpreader spreader, LevelAccessor level, BlockPos pos,
RandomSource random, CallbackInfoReturnable<Boolean> cir,
BlockState blockState, TagKey<Block> tagKey, Iterator var7, Direction direction,
BlockPos blockPos, BlockState blockState2, BlockState blockState3) {
// CraftBukkit start - Call BlockSpreadEvent
if (!CraftEventFactory.handleBlockSpreadEvent(level, taiyitist$pos.get(), blockPos, blockState2, 3)) {
cir.setReturnValue(false);
}
// CraftBukkit end
}
}
| 0 | 0.841343 | 1 | 0.841343 | game-dev | MEDIA | 0.99961 | game-dev | 0.80943 | 1 | 0.80943 |
Aleph-One-Marathon/alephone | 4,341 | Source_Files/RenderOther/fades.h | #ifndef __FADES_H
#define __FADES_H
/*
FADES.H
Copyright (C) 1991-2001 and beyond by Bungie Studios, Inc.
and the "Aleph One" developers.
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.
This license is contained in the file "COPYING",
which is included with this source code; it is available online at
http://www.gnu.org/licenses/gpl.html
Tuesday, April 4, 1995 11:48:29 AM (Jason')
May 17, 2000 (Loren Petrich):
Added separate under-JjaroGoo fade effects
May 20, 2000 (Loren Petrich):
Added XML-parser support
Jan 31, 2001 (Loren Petrich):
Added delayed action for the fader effect, so as to get around certain MacOS oddities
*/
/* ---------- constants */
enum
{
NUMBER_OF_GAMMA_LEVELS= 8,
DEFAULT_GAMMA_LEVEL= 2
};
enum /* fade types */
{
_start_cinematic_fade_in, /* force all colors to black immediately */
_cinematic_fade_in, /* fade in from black */
_long_cinematic_fade_in,
_cinematic_fade_out, /* fade out from black */
_end_cinematic_fade_out, /* force all colors from black immediately */
_fade_red, /* bullets and fist */
_fade_big_red, /* bigger bullets and fists */
_fade_bonus, /* picking up items */
_fade_bright, /* teleporting */
_fade_long_bright, /* nuclear monster detonations */
_fade_yellow, /* explosions */
_fade_big_yellow, /* big explosions */
_fade_purple, /* ? */
_fade_cyan, /* fighter staves and projectiles */
_fade_white, /* absorbed */
_fade_big_white, /* rocket (probably) absorbed */
_fade_orange, /* flamethrower */
_fade_long_orange, /* marathon lava */
_fade_green, /* hunter projectile */
_fade_long_green, /* alien green goo */
_fade_static, /* compiler projectile */
_fade_negative, /* minor fusion projectile */
_fade_big_negative, /* major fusion projectile */
_fade_flicker_negative, /* hummer projectile */
_fade_dodge_purple, /* alien weapon */
_fade_burn_cyan, /* armageddon beast electricity */
_fade_dodge_yellow, /* armageddon beast projectile */
_fade_burn_green, /* hunter projectile */
_fade_tint_green, /* under goo */
_fade_tint_blue, /* under water */
_fade_tint_orange, /* under lava */
_fade_tint_gross, /* under sewage */
_fade_tint_jjaro, /* under JjaroGoo */ // LP addition
NUMBER_OF_FADE_TYPES
};
// LP change: rearranged to get order: water, lava, sewage, jjaro, pfhor
enum /* effect types */
{
_effect_under_water,
_effect_under_lava,
_effect_under_sewage,
_effect_under_jjaro,
_effect_under_goo,
NUMBER_OF_FADE_EFFECT_TYPES
};
// LP addition, since XML does not support direct specification of callbacks
// very well.
// Moved out here for the convenience of OpenGL fader implementations.
enum
{
_tint_fader_type,
_randomize_fader_type,
_negate_fader_type,
_dodge_fader_type,
_burn_fader_type,
_soft_tint_fader_type,
NUMBER_OF_FADER_FUNCTIONS
};
/* ---------- prototypes/FADES.C */
void initialize_fades(void);
bool update_fades(bool game_in_progress = false);
void start_fade(short type);
void stop_fade(void);
bool fade_finished(void);
void set_fade_effect(short type);
void gamma_correct_color_table(struct color_table *uncorrected_color_table, struct color_table *corrected_color_table, short gamma_level);
float get_actual_gamma_adjust(short gamma_level);
void explicit_start_fade(short type, struct color_table *original_color_table, struct color_table *animated_color_table, bool game_in_progress = false);
void full_fade(short type, struct color_table *original_color_table);
// see if the screen was set to black by the last fade
bool fade_blacked_screen(void);
// LP: sets the number of calls of set_fade_effect() that get ignored;
// this is a workaround for a MacOS-version bug where something gets painted on the screen
// after certain dialog boxes are cleared, thus canceling out the fader effect.
void SetFadeEffectDelay(int _FadeEffectDelay);
class InfoTree;
void parse_mml_faders(const InfoTree& root);
void reset_mml_faders();
#endif
| 0 | 0.879614 | 1 | 0.879614 | game-dev | MEDIA | 0.68729 | game-dev,graphics-rendering | 0.894982 | 1 | 0.894982 |
AkiniKites/AloysAdjustments | 11,024 | src/Plugins/AloysAdjustments.Plugins.NPC/NpcPlugin.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using AloysAdjustments.Common.Utility;
using AloysAdjustments.Configuration;
using AloysAdjustments.Logic;
using AloysAdjustments.Logic.Patching;
using AloysAdjustments.Plugins.Common;
using AloysAdjustments.Plugins.Common.Characters;
using AloysAdjustments.Plugins.Common.Data;
using AloysAdjustments.Plugins.NPC.Characters;
using AloysAdjustments.UI;
using AloysAdjustments.Utility;
using EnumsNET;
namespace AloysAdjustments.Plugins.NPC
{
[Flags]
public enum ModelFilter
{
[Description("Main Characters")]
MainCharacters = 1,
[Description("All Characters")]
AllCharacters = 2
}
public class NpcPlugin : InteractivePlugin, INotifyPropertyChanged
{
public override string PluginName => "NPC Models";
private CharacterGenerator CharacterGen { get; }
private NpcPatcher Patcher { get; }
private ModelImageRepo ModelRepo { get; }
public ValuePair<Model> AllNpcStub { get; set; }
public ObservableCollection<ValuePair<Model>> Npcs { get; set; }
public ListCollectionView NpcsView { get; set; }
public ObservableCollection<Model> Models { get; set; }
public ListCollectionView ModelsView { get; set; }
private DelayAction LoadingAction { get; }
public bool Loading { get; set; }
public byte[] ModelImage { get; set; }
public IList SelectedNpcModels { get; set; }
public Model SelectedModelMapping { get; set; }
private ModelFilter _filterValue;
public ModelFilter FilterValue
{
get => _filterValue;
set
{
if (_filterValue == value)
return;
var newVal = value;
var oldVal = _filterValue;
if (newVal.HasFlag(ModelFilter.MainCharacters) && oldVal.HasFlag(ModelFilter.AllCharacters))
newVal = newVal.RemoveFlags(ModelFilter.AllCharacters);
if (newVal.HasFlag(ModelFilter.AllCharacters) && oldVal.HasFlag(ModelFilter.MainCharacters))
newVal = newVal.RemoveFlags(ModelFilter.MainCharacters);
_filterValue = newVal;
OnPropertyChanged(nameof(FilterValue), oldVal, newVal);
}
}
public bool ApplyToAll { get; set; }
public NpcPlugin()
{
IoC.Bind(Configs.LoadModuleConfig<CommonConfig>(CommonConfig.ConfigName));
Reset = new ControlRelay(OnResetAll);
ResetSelected = new ControlRelay(OnResetSelected);
LoadingAction = new DelayAction(() => Loading = true);
CharacterGen = new CharacterGenerator();
Patcher = new NpcPatcher();
ModelRepo = new ModelImageRepo();
PluginControl = new NpcPluginView();
PluginControl.DataContext = this;
Models = new ObservableCollection<Model>();
ModelsView = new ListCollectionView(Models);
ModelsView.Filter = Filter;
ModelsView.CustomSort = Comparer<Model>.Create(CompareModels);
Npcs = new ObservableCollection<ValuePair<Model>>();
NpcsView = new ListCollectionView(Npcs);
NpcsView.Filter = NpcFilter;
NpcsView.CustomSort = Comparer<ValuePair<Model>>.Create((a, b) => CompareModels(a.Default, b.Default));
var allNpc = new Model() {DisplayName = "All Characters"};
AllNpcStub = new ValuePair<Model>(allNpc, allNpc);
}
private int CompareModels(Model m1, Model m2)
{
var m1d = m1.DisplayName.Contains("DLC");
var m2d = m2.DisplayName.Contains("DLC");
var c1 = Comparer<bool>.Default.Compare(m1d, m2d);
return c1 != 0 ? c1 : Comparer<string>.Default.Compare(m1.DisplayName, m2.DisplayName);
}
private void LoadSettings()
{
ApplyToAll = IoC.Settings.ApplyToAllNpcs;
FilterValue = (ModelFilter)IoC.Settings.NpcModelFilter;
}
public override async Task LoadPatch(string path)
{
IoC.Notif.ShowStatus("Loading npcs...");
var map = await Patcher.LoadMap(path);
if (!map.Any())
return;
await Initialize();
using (var defer = NpcsView.DeferRefresh())
{
var models = Models.ToDictionary(x => x.Id, x => x);
foreach (var npc in Npcs.Where(x => x != AllNpcStub))
{
if (map.TryGetValue(npc.Default.Id, out var newId))
{
npc.Value = models[newId];
}
}
}
OnApplyToAll();
}
public override void ApplyChanges(Patch patch)
{
Patcher.CreatePatch(patch, Npcs.Where(x => x != AllNpcStub).ToList());
}
public override async Task Initialize()
{
ResetSelected.Enabled = false;
IoC.Notif.ShowUnknownProgress();
Models.Clear();
await UpdateModelList(x => Models.Add(x));
Npcs.Clear();
await UpdateModelList(x => Npcs.Add(new ValuePair<Model>(x, x)));
Npcs.Add(AllNpcStub);
LoadSettings();
}
private async Task UpdateModelList(Action<Model> add)
{
var models = await LoadCharacterModelList(true);
foreach (var model in models)
{
model.DisplayName = model.ToString();
add(model);
}
models = await LoadCharacterModelList(false);
foreach (var model in models)
{
model.DisplayName = model.ToString();
add(model);
}
}
private async Task<List<CharacterModel>> LoadCharacterModelList(bool unique)
{
return await Async.Run(() =>
{
IoC.Notif.ShowStatus("Loading characters list...");
return CharacterGen.GetCharacterModels(unique);
});
}
public bool Filter(object obj)
{
var model = (CharacterModel)obj;
if (FilterValue.HasFlag(ModelFilter.MainCharacters))
return model.UniqueCharacter;
return true;
}
public bool NpcFilter(object obj)
{
if (ApplyToAll)
return obj == AllNpcStub;
if (obj != AllNpcStub)
{
var model = (CharacterModel)((ValuePair<Model>)obj).Default;
if (FilterValue.HasFlag(ModelFilter.MainCharacters))
return model.UniqueCharacter;
return true;
}
return false;
}
private void OnNpcSelectionChanged()
{
ResetSelected.Enabled = SelectedNpcModels?.Count > 0;
var selectedModelIds = GetSelectedNpcs()
.Where(x => x != AllNpcStub)
.Select(x => x.Value.Id).ToHashSet();
foreach (var model in Models)
{
if (selectedModelIds.Contains(model.Id))
model.Checked = selectedModelIds.Count > 1 ? null : (bool?)true;
else
model.Checked = false;
}
}
private List<ValuePair<Model>> GetSelectedNpcs()
{
if (IoC.Settings.ApplyToAllNpcs)
return Npcs.ToList();
return SelectedNpcModels?.Cast<ValuePair<Model>>().ToList() ?? new List<ValuePair<Model>>();
}
private void OnModelsSelectionChanged()
{
if (SelectedModelMapping == null)
return;
LoadImage(SelectedModelMapping.Name);
SelectedModelMapping.Checked = true;
foreach (var model in Models)
{
if (!ReferenceEquals(SelectedModelMapping, model))
model.Checked = false;
}
foreach (var outfit in GetSelectedNpcs())
UpdateMapping(outfit, SelectedModelMapping);
}
private void UpdateMapping(ValuePair<Model> npc, Model model)
{
npc.Value = model;
}
private void LoadImage(string modelName)
{
LoadingAction.Start(500);
ModelRepo.LoadImage(modelName, (success, image) =>
{
if (SelectedModelMapping?.Name == modelName)
{
LoadingAction.Complete();
ModelImage = image;
Loading = false;
if (success)
IoC.Notif.ShowStatus();
else
IoC.Notif.ShowError("Error downloading image: " + modelName);
}
});
}
private void OnApplyToAll()
{
IoC.Settings.ApplyToAllNpcs = ApplyToAll;
if (ApplyToAll)
{
var tmp = new CharacterModel() { Id = Guid.NewGuid() };
var val = Npcs.Any(x => x != AllNpcStub && x.Modified) ? tmp : AllNpcStub.Default;
AllNpcStub.Value = val;
}
NpcsView.Refresh();
OnNpcSelectionChanged();
}
private void OnFilterValue()
{
IoC.Settings.NpcModelFilter = (int)FilterValue;
NpcsView.Refresh();
ModelsView.Refresh();
}
private Task OnResetSelected()
{
foreach (var npc in GetSelectedNpcs())
npc.Value = npc.Default;
return Task.CompletedTask;
}
private Task OnResetAll()
{
foreach (var npc in Npcs)
npc.Value = npc.Default;
return Task.CompletedTask;
}
public void OnPropertyChanged(string propertyName, object before, object after)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
switch (propertyName)
{
case nameof(SelectedNpcModels):
OnNpcSelectionChanged();
break;
case nameof(SelectedModelMapping):
OnModelsSelectionChanged();
break;
case nameof(ApplyToAll):
OnApplyToAll();
break;
case nameof(FilterValue):
OnFilterValue();
break;
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
| 0 | 0.887052 | 1 | 0.887052 | game-dev | MEDIA | 0.873901 | game-dev | 0.972436 | 1 | 0.972436 |
darkbot-reloaded/DarkBot | 11,395 | src/main/java/com/github/manolo8/darkbot/core/manager/RepairManager.java | package com.github.manolo8.darkbot.core.manager;
import com.github.manolo8.darkbot.Main;
import com.github.manolo8.darkbot.config.ConfigEntity;
import com.github.manolo8.darkbot.core.BotInstaller;
import com.github.manolo8.darkbot.core.entities.bases.BaseRepairStation;
import com.github.manolo8.darkbot.core.itf.Manager;
import com.github.manolo8.darkbot.core.objects.SpriteObject;
import com.github.manolo8.darkbot.core.objects.swf.FlashListInt;
import com.github.manolo8.darkbot.core.objects.swf.FlashListLong;
import com.github.manolo8.darkbot.core.utils.ByteUtils;
import com.github.manolo8.darkbot.extensions.features.handlers.ReviveSelectorHandler;
import com.github.manolo8.darkbot.utils.LogUtils;
import eu.darkbot.api.config.ConfigSetting;
import eu.darkbot.api.extensions.Feature;
import eu.darkbot.api.extensions.selectors.PrioritizedSupplier;
import eu.darkbot.api.extensions.selectors.ReviveSelector;
import eu.darkbot.api.game.enums.ReviveLocation;
import eu.darkbot.api.game.other.Locatable;
import eu.darkbot.api.managers.ConfigAPI;
import eu.darkbot.api.managers.RepairAPI;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import static com.github.manolo8.darkbot.Main.API;
public class RepairManager implements Manager, RepairAPI {
private final Main main;
private final ReviveSelectorHandler reviveHandler;
private final Map<String, OutputStream> streams = new HashMap<>();
private final FlashListInt repairOptions = FlashListInt.ofArray();
private final FlashListLong repairTypes = FlashListLong.ofVector();
private final byte[] patternCache = new byte[40];
private String killerName;
private Locatable deathLocation;
private Instant lastDeath;
private boolean destroyed, shouldInstantRepair = false;
private long userDataAddress, repairAddress, screenManager, beforeReviveTime, afterAvailableWait, lastReviveAttempt;
private int deaths;
public RepairManager(Main main, ReviveSelectorHandler reviveHandler) {
this.main = main;
this.reviveHandler = reviveHandler;
}
@Override
public void install(BotInstaller botInstaller) {
botInstaller.guiManagerAddress.add(value -> repairAddress = 0);
botInstaller.heroInfoAddress.add(value -> userDataAddress = value);
botInstaller.screenManagerAddress.add(value -> screenManager = value);
}
public String getStatus() {
ReviveLocation location = reviveHandler.getBest();
int repairOption = getRepairOptionFromType(location);
int availableIn = optionAvailableIn(repairOption);
int beforeRevive = (int) (((beforeReviveTime + (main.config.GENERAL.SAFETY.WAIT_BEFORE_REVIVE * 1000L))
- System.currentTimeMillis()) / 1000);
return "Reviving at: " + (repairOption == -1 ? "DEFAULT" : location) + ", in " + Math.max(beforeRevive, availableIn) + "s";
}
public boolean setBeforeReviveTime() {
if (beforeReviveTime == -1)
beforeReviveTime = System.currentTimeMillis();
return System.currentTimeMillis() - beforeReviveTime < (main.config.GENERAL.SAFETY.WAIT_BEFORE_REVIVE * 1000L);
}
private void checkInstantRepair() {
if (!shouldInstantRepair || !main.isRunning()
|| main.hero.getHealth().getMaxHp() == 0 || main.config.GENERAL.SAFETY.INSTANT_REPAIR == 0) return;
// have ~25% hp already after revive - do not use instant repair. maybe create setting for min health
if (main.hero.getHealth().hpPercent() >= 0.25) {
shouldInstantRepair = false;
return;
}
if (lastReviveAttempt + 15_000 > System.currentTimeMillis()) {
main.mapManager.entities.basePoints.stream()
.filter(basePoint -> basePoint instanceof BaseRepairStation)
.findAny()
.filter(basePoint -> basePoint.clickable.enabled)
.ifPresent(basePoint -> {
BaseRepairStation repairStation = (BaseRepairStation) basePoint;
int currentRepairs = repairStation.getInstantRepairs();
if (currentRepairs >= main.config.GENERAL.SAFETY.INSTANT_REPAIR) {
repairStation.clickable.click();
System.out.println("Used instant repair! " + currentRepairs);
}
shouldInstantRepair = false;
});
}
}
public void tick() {
boolean alive = isAlive();
if (alive) {
if (main.hero.address != 0) // possibly alive but we are not sure yet
destroyed = false;
checkInstantRepair();
beforeReviveTime = -1;
return;
}
if (!destroyed) {
shouldInstantRepair = true;
destroyed = true;
deaths++;
lastDeath = Instant.now();
if (userDataAddress != 0) // only if hero was alive
deathLocation = main.hero.getLocationInfo().getCurrent().copy();
killerName = API.readString(repairAddress, null, 0x68);
String killerMessage = killerName == null || killerName.isEmpty()
? "You were destroyed by a radiation/mine/unknown"
: "You have been destroyed by: " + killerName;
System.out.println(killerMessage);
if (ConfigEntity.INSTANCE.getConfig().MISCELLANEOUS.LOG_DEATHS)
writeToFile("deaths_" + LogUtils.START_TIME, formatLogMessage(killerMessage));
}
repairOptions.update(API.readLong(repairAddress + 0x58));
repairTypes.update(API.readLong(repairAddress + 0x60));
}
// return true if clicked, false if should wait
public boolean tryRevive() {
// game did cleanup in Repair Manager, nothing to do here anymore. if nothing happens then only reload left
if (repairOptions.isEmpty()) return false;
int repairOption = getRepairOptionFromType(reviveHandler.getBest());
int availableIn = optionAvailableIn(repairOption);
if (availableIn > 0) {
afterAvailableWait = System.currentTimeMillis();
return false;
}
// wait 1 second after the option is available to potentially fix in-game bug
if (System.currentTimeMillis() - afterAvailableWait < 1000) return false;
if (repairOption != -1)
API.writeLong(repairAddress + 32, repairOption);
int selected = API.readInt(repairAddress + 32);
// if any of these is selected, call this method with null param may result in crash
if (selected == 0 || selected == 9
|| !API.callMethodChecked(false, "23(2626)1016341800", 5, repairAddress, 0L)) {
SpriteObject repairGui = new SpriteObject();
repairGui.update(Main.API.readLong(repairAddress + 48));
repairGui.update();
API.mouseClick(repairGui.x() + 263, repairGui.y() + 426);
}
lastReviveAttempt = System.currentTimeMillis();
return true;
}
private boolean isAlive() {
if (repairAddress == 0 && main.guiManager.connecting.lastResetOver(1000)) {
long repairClosure = API.searchClassClosure(this::repairClosurePattern);
if (repairClosure == 0) return true;
repairAddress = API.readLong(repairClosure + 72); // check on next tick
}
return !API.readBoolean(repairAddress + 0x28);
}
@Deprecated
public String getKillerName() {
return killerName;
}
@Deprecated
public boolean isDead() {
return isDestroyed();
}
@Deprecated
public boolean canRespawn(int option) {
return repairOptions.contains(option);
}
public void resetDeaths() {
deaths = 0;
}
private int optionAvailableIn(int repairOption) {
if (repairOption == -1) return -1;
return API.readInt(repairTypes.getOrDefault(repairOption, 0) + 48);
}
private String formatLogMessage(String message) {
return String.format("[%s] %-" + message.length() + "s" + System.lineSeparator(),
LocalDateTime.now().format(LogUtils.LOG_DATE),
message);
}
private void writeToFile(String name, String message) {
try {
OutputStream os = getOrCreateStream(name);
if (os == null) return;
os.write(message.getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
e.printStackTrace();
}
}
private OutputStream getOrCreateStream(String name) {
return this.streams.computeIfAbsent(name, LogUtils::createLogFile);
}
private boolean repairClosurePattern(long addr) {
API.readBytes(addr + 48, patternCache);
return ByteUtils.getInt(patternCache, 0) == 0
&& ByteUtils.getInt(patternCache, 4) == 1
&& ByteUtils.getInt(patternCache, 8) == 2
&& ByteUtils.getInt(patternCache, 12) == 3
&& ByteUtils.getInt(patternCache, 16) == 4
&& ByteUtils.getInt(patternCache, 20) == 0 // align to 8
&& API.readLong(ByteUtils.getLong(patternCache, 24), 0x10) != 0
&& API.readLong(ByteUtils.getLong(patternCache, 32), 0x10) != 0;
}
private int getRepairOptionFromType(ReviveLocation reviveLocation) {
for (int i = 0; i < repairOptions.size(); i++) {
int repairOption = repairOptions.getInt(i);
if (ReviveLocation.of(repairOption) == reviveLocation) {
return repairOption;
}
}
return -1;
}
@Override
public int getDeathAmount() {
return deaths;
}
@Override
public boolean isDestroyed() {
return destroyed;
}
@Override
public int isAvailableIn(ReviveLocation reviveLocation) {
return optionAvailableIn(getRepairOptionFromType(reviveLocation));
}
@Override
public @Nullable String getLastDestroyerName() {
return getKillerName();
}
@Override
public @Nullable Instant getLastDeathTime() {
return lastDeath;
}
@Override
public @Nullable Locatable getLastDeathLocation() {
return deathLocation;
}
@Feature(name = "Revive Supplier", description = "Provides a place where ship should be revived")
public static class DefaultReviveSupplier implements ReviveSelector, PrioritizedSupplier<ReviveLocation> {
private final ConfigSetting<com.github.manolo8.darkbot.config.types.suppliers.ReviveLocation> reviveLocation;
public DefaultReviveSupplier(ConfigAPI config) {
this.reviveLocation = config.requireConfig("general.safety.revive");
}
@Override
public @NotNull PrioritizedSupplier<ReviveLocation> getReviveLocationSupplier() {
return this;
}
@Override
public ReviveLocation get() {
return ReviveLocation.values()[reviveLocation.getValue().ordinal() + 1];
}
}
} | 0 | 0.919984 | 1 | 0.919984 | game-dev | MEDIA | 0.816484 | game-dev | 0.971684 | 1 | 0.971684 |
awgil/ffxiv_bossmod | 10,191 | BossMod/Modules/Shadowbringers/Foray/DelubrumReginae/DRS2StygimolochWarrior/Entrapment.cs | namespace BossMod.Shadowbringers.Foray.DelubrumReginae.DRS2StygimolochWarrior;
class EntrapmentAttract(BossModule module) : Components.Knockback(module, AID.EntrapmentAttract, true)
{
private DateTime _activation;
public override IEnumerable<Source> Sources(int slot, Actor actor)
{
yield return new(new(Module.Center.X, Module.Center.Z + Module.Bounds.Radius), 60, _activation, Kind: Kind.TowardsOrigin);
}
public override void OnCastStarted(Actor caster, ActorCastInfo spell)
{
if ((AID)spell.Action.ID == AID.Entrapment)
_activation = Module.CastFinishAt(spell, 0.8f);
}
}
// the 'board' is 7x7; cell index is zzzxxx (64 bit), with (0,0) corresponding to NW cell
class Entrapment : Components.CastCounter
{
public enum TrapType { Normal, Toad, Ice, Mini }
public struct Pattern
{
public BitMask Normal;
public BitMask Toad;
public BitMask Ice;
public BitMask Mini;
}
protected TrapType TrapToTake; // note that 'normal' means none here
private readonly Pattern[] _allowedPatterns;
private Pattern _curPattern;
private BitMask _uncovered;
private BitMask _exploded;
private BitMask _possiblePatterns;
private Pattern _potentiallyUnsafe;
private bool _possiblePatternsDirty;
public Entrapment(BossModule module, Pattern[] allowedPatterns) : base(module, AID.MassiveExplosion)
{
_allowedPatterns = allowedPatterns;
_possiblePatterns = new((1u << allowedPatterns.Length) - 1);
UpdatePotentiallyUnsafe();
}
public override void Update()
{
if (!_possiblePatternsDirty)
return;
_possiblePatternsDirty = false;
// TODO: ideally it should not be done here, but when reacting to perception cast...
// note that range check is a bit fuzzy - perception range is 15, i've seen traps at ~18.3 uncovered - but sometimes traps at presumably smaller range not uncovered
// so we consider a very conservative range
var player = Raid.Player();
if (player != null)
for (int z = 0; z < 7; ++z)
for (int x = 0; x < 7; ++x)
if (player.Position.InCircle(Module.Center + CellOffset(x, z), 10))
_uncovered.Set(IndexFromCell(x, z));
// remove all patterns that have difference with current state in uncovered areas
if (_possiblePatterns.Any())
{
foreach (var ip in _possiblePatterns.SetBits())
{
ref var p = ref _allowedPatterns[ip];
var diff = (p.Normal ^ _curPattern.Normal) | (p.Toad ^ _curPattern.Toad) | (p.Ice ^ _curPattern.Ice) | (p.Mini ^ _curPattern.Mini);
if ((diff & _uncovered).Any())
_possiblePatterns.Clear(ip);
}
if (_possiblePatterns.None())
ReportError("No matching patterns left...");
}
UpdatePotentiallyUnsafe();
}
public override void AddGlobalHints(GlobalHints hints)
{
hints.Add($"Matching patterns: {(_possiblePatterns.Any() ? string.Join(", ", _possiblePatterns.SetBits()) : "none")}");
}
public override void DrawArenaBackground(int pcSlot, Actor pc)
{
DrawTraps(_curPattern.Normal, false, true);
DrawTraps(_curPattern.Toad, TrapToTake == TrapType.Toad, true);
DrawTraps(_curPattern.Ice, TrapToTake == TrapType.Ice, true);
DrawTraps(_curPattern.Mini, TrapToTake == TrapType.Mini, true);
}
public override void DrawArenaForeground(int pcSlot, Actor pc)
{
DrawTraps(_potentiallyUnsafe.Normal, false, false);
DrawTraps(_potentiallyUnsafe.Toad, TrapToTake == TrapType.Toad, false);
DrawTraps(_potentiallyUnsafe.Ice, TrapToTake == TrapType.Ice, false);
DrawTraps(_potentiallyUnsafe.Mini, TrapToTake == TrapType.Mini, false);
}
public override void OnActorCreated(Actor actor)
{
switch ((OID)actor.OID)
{
case OID.TrapNormal:
AddTrap(ref _curPattern.Normal, actor.Position, false);
break;
case OID.TrapToad:
AddTrap(ref _curPattern.Toad, actor.Position, false);
break;
case OID.TrapIce:
AddTrap(ref _curPattern.Ice, actor.Position, false);
break;
case OID.TrapMini:
AddTrap(ref _curPattern.Mini, actor.Position, false);
break;
}
}
public override void OnEventCast(Actor caster, ActorCastEvent spell)
{
switch ((AID)spell.Action.ID)
{
case AID.MassiveExplosion:
AddTrap(ref _curPattern.Normal, spell.TargetXZ, true);
break;
case AID.Toad:
AddTrap(ref _curPattern.Toad, spell.TargetXZ, true);
break;
case AID.TrappedUnderIce:
AddTrap(ref _curPattern.Ice, spell.TargetXZ, true);
break;
case AID.Mini:
AddTrap(ref _curPattern.Mini, spell.TargetXZ, true);
break;
}
}
private void AddTrap(ref BitMask mask, WPos position, bool exploded)
{
var index = IndexFromOffset(position - Module.Center);
//ReportError($"Trap @ {position} (dist={(position - Raid.Player()!.Position).Length()}) = {index}");
mask.Set(index);
_uncovered.Set(index);
if (exploded)
{
_exploded.Set(index);
++NumCasts;
}
_possiblePatternsDirty = true;
}
private int IndexFromCell(int x, int z) => x is >= 0 and <= 6 && z is >= 0 and <= 6 ? ((z << 3) | x) : -1;
private int IndexFromOffset(WDir offset)
{
var x = (int)Math.Round(offset.X / 5) + 3;
var z = (int)Math.Round(offset.Z / 5) + 3;
return IndexFromCell(x, z);
}
private WDir CellOffset(int x, int z) => 5 * new WDir(x - 3, z - 3);
private WDir CellOffset(int index) => CellOffset(index & 7, index >> 3);
private void DrawTraps(BitMask mask, bool safe, bool background)
{
mask &= ~_exploded; // don't draw already exploded traps
foreach (var index in mask.SetBits())
{
var pos = Module.Center + CellOffset(index);
if (background)
Arena.ZoneCircle(pos, 2.5f, safe ? ArenaColor.SafeFromAOE : ArenaColor.AOE);
else
Arena.AddCircle(pos, 2.5f, safe ? ArenaColor.Safe : ArenaColor.Danger);
}
}
private void UpdatePotentiallyUnsafe()
{
_potentiallyUnsafe = default;
var numMatches = _possiblePatterns.NumSetBits();
if (numMatches == 0)
{
// no matches => all hidden are potentially unsafe
_potentiallyUnsafe.Normal = new BitMask(0x7f7f7f7f7f7f7f) & ~_uncovered;
}
else if (numMatches == 1)
{
// single match => just show everything from the pattern that wasn't yet uncovered
_potentiallyUnsafe = _allowedPatterns[_possiblePatterns.LowestSetBit()];
_potentiallyUnsafe.Normal &= ~_uncovered;
_potentiallyUnsafe.Toad &= ~_uncovered;
_potentiallyUnsafe.Ice &= ~_uncovered;
_potentiallyUnsafe.Mini &= ~_uncovered;
}
else
{
// multiple matches => show everything that wasn't yet uncovered as 'normal'
foreach (var ip in _possiblePatterns.SetBits())
{
ref var p = ref _allowedPatterns[ip];
_potentiallyUnsafe.Normal |= p.Normal | p.Toad | p.Ice | p.Mini;
}
_potentiallyUnsafe.Normal &= ~_uncovered;
}
}
protected static BitMask BuildMask(params int[] bits)
{
var mask = new BitMask();
foreach (var bit in bits)
mask.Set(bit);
return mask;
}
}
class EntrapmentNormal(BossModule module) : Entrapment(module, _allowedPatterns)
{
private static readonly Pattern[] _allowedPatterns = [
new() { Normal = BuildMask( 8, 9, 10, 11, 12, 13, 18, 20, 34, 35, 36, 37, 38, 40, 42, 45) },
new() { Normal = BuildMask( 8, 9, 11, 16, 19, 20, 21, 22, 26, 30, 32, 36, 40, 41, 42, 45) },
new() { Normal = BuildMask( 9, 11, 12, 13, 14, 16, 17, 27, 28, 32, 33, 38, 41, 42, 43, 44) },
new() { Normal = BuildMask( 9, 11, 12, 13, 14, 16, 17, 27, 28, 32, 33, 38, 41, 42, 44, 46) }, // TODO: i'm not sure whether this pattern is real
new() { Normal = BuildMask(10, 11, 13, 14, 19, 20, 21, 24, 25, 30, 33, 34, 35, 36, 44, 45) },
];
}
class EntrapmentInescapable(BossModule module) : Entrapment(module, _allowedPatterns)
{
private static readonly Pattern[] _allowedPatterns = [
new() { Normal = BuildMask(3, 4, 5, 8, 20, 25, 38, 43, 46, 49, 52), Toad = BuildMask(10, 50, 54), Ice = BuildMask(40), Mini = BuildMask(29) },
new() { Normal = BuildMask(2, 5, 8, 11, 14, 16, 25, 29, 46, 49, 51), Toad = BuildMask( 0, 4, 44), Ice = BuildMask(50), Mini = BuildMask(34) },
new() { Normal = BuildMask(5, 8, 11, 16, 18, 22, 24, 29, 43, 49, 53), Toad = BuildMask( 6, 33, 38), Ice = BuildMask( 4), Mini = BuildMask(48) },
new() { Normal = BuildMask(5, 8, 11, 25, 30, 32, 38, 43, 49, 50, 54), Toad = BuildMask(16, 21, 48), Ice = BuildMask(36), Mini = BuildMask( 1) },
];
public override void OnCastStarted(Actor caster, ActorCastInfo spell)
{
var trap = (AID)spell.Action.ID switch
{
AID.SurgingFlames => TrapType.Ice,
AID.SurgingFlood => TrapType.Toad,
AID.WitheringCurse => TrapType.Mini,
_ => TrapType.Normal
};
if (trap != TrapType.Normal)
TrapToTake = trap;
}
}
class LethalBlow(BossModule module) : Components.StandardAOEs(module, AID.LethalBlow, new AOEShapeRect(44, 24));
class LeapingSpark(BossModule module) : Components.CastCounter(module, AID.LeapingSparkAOE);
class Devour(BossModule module) : Components.StandardAOEs(module, AID.Devour, new AOEShapeCone(6, 60.Degrees()));
| 0 | 0.908008 | 1 | 0.908008 | game-dev | MEDIA | 0.887776 | game-dev | 0.968986 | 1 | 0.968986 |
mcclure/bitbucket-backup | 8,491 | repos/musician/contents/desktop/plaid/plaid/core.h | /**
"Plaidgadget" game engine copyright (C) 2008-2009 Evan Balster
This header file contains features globally significant to the game engine.
- Memory Watch, which can assist in the tracking of memory leaks.
- Error Reporting which can be expected to stop the engine.
- Active Modules, which form the main architecture of plaidgadget.
- Smart Pointers, which are generally useful and comply with memory watch.
- Reflection, which provides lots of useful generic functionality.
- Serialization, which is also generally useful and supports smart pointers.
*/
#ifndef PLAIDGADGET_MAIN_H
#define PLAIDGADGET_MAIN_H
#if PLAIDGADGET
#include <vector>
#include <list>
#include <map>
#include "util/types.h"
#include "util/memory.h"
#include "util/ref.h"
//Debug control
#define reportError(X) plaid::_reportError(X, __FILE__, __LINE__)
#define reportWarning(X) plaid::_reportWarning(X, __FILE__, __LINE__)
#define pgNote(X) plaid::_reportNote(X)
//Program error reporting
namespace plaid
{
/*
Various error reporting mechanisms -- reportError creates a "redscreen".
*/
void _reportError(std::string message, const char *fname, int line);
void _reportWarning(std::string message, const char *fname, int line);
void _reportNote(std::string message);
void _reportError(String message, const char *fname, int line);
void _reportWarning(String message, const char *fname, int line);
void _reportNote(String message);
}
//Game engine code proper begins here!
//Anything included after this point gets memory-tracked if memwatch is active.
//Forward declare type_info class...
namespace std {class type_info;}
namespace plaid
{
//Some classes Reflected needs to know about.
class Examine;
class Read;
class Write;
class SerialData;
/*
An object can extend Reflected and register a Type at static time to
enable reflection and serialization at runtime. Very useful!
For classes that can't afford the 2 words of memory overhead,
there will eventually be a means of static reflection.
*/
class Reflected : public RefCounted
{
public:
/*
Member objects represent member variables of a class.
Declared in <plaid/reflect/reflect.h>.
*/
class Member;
/*
Describes a reflected type.
*/
class Type
{
public:
//A cheap non-alphabetic comparator for STL maps and sets
struct CheapCompare
{
bool operator()(const Type &l, const Type &r) const
{return l.cheapCompare(r);}
};
typedef std::vector<Type*> Parents;
typedef std::list<Member*> Members;
typedef std::vector<Member*> FastMembers;
protected:
typedef std::map<String, Member*> MemberMap;
typedef std::pair<String, Member*> MemberPair;
typedef Reflected* (*CreatorFunction)(Read &read);
class Data;
public:
//Default constructor for NULL type.
Type() : data(NULL) {}
~Type() {}
//Null type objects
bool null() const {return !data;}
operator bool() const {return data;}
static Type Null() {return Type();}
/*
Create a "blank" instance of the type.
This function is mainly used by the serialization system.
Some Types do not support this and will return NULL.
*/
Reflected *create(Read &read) const;
/*
Get some descriptive information about the type.
version() relates to serialization.
hash() is a direct hash of the value of name().
*/
String name() const;
String description() const;
Uint32 version() const;
Uint64 hash() const;
/*
Get C++ RTTI information for this Type.
*/
const std::type_info &rtti() const;
/*
Get this Type's parent or a list thereof.
parent() returns an arbitrary parent if there are multiple.
*/
Type parent() const;
const Parents &parents() const;
/*
Returns whether the given type is this type or an acestor of it.
*/
bool is(Type _type) const;
/*
Look up members by name.
*/
Member *operator[](String name) const;
/*
Advanced member lookups used by the serialization system.
*/
const FastMembers &members() const;
const FastMembers &membersStored() const;
const FastMembers &membersSynced() const;
Members membersStored(Uint32 version) const;
Members membersSynced(Uint32 version) const;
Members membersNaive(Uint32 version) const;
/*
Get a detailed description of a runtime object.
*/
String detail() const;
/*
Alphabetical and "cheap" (hash) ordering for Types.
*/
bool operator<(const Type &other) const;
bool cheapCompare(const Type &o) const;
/*
Simple equality checking.
*/
bool operator==(const Type &o) const {return o.data == data;}
bool operator!=(const Type &o) const {return o.data != data;}
/*
Look up a type by its name, hash or typeid value.
*/
static Type lookUp(const String &name);
static Type lookUp(Uint64 hash);
static Type lookUp(const std::type_info &info);
/*
Diagnostic function; prints all registed types to stdout.
*/
static void printTypes();
protected:
Type(Data *_data) : data(_data) {}
static void add(Type type);
protected:
Data *data;
};
public:
//Straightforward enough.
Reflected() {}
virtual ~Reflected() {}
//For backwards compatibility with old saved objects of this type.
virtual void serialConvert(SerialData &data) {}
//Called after all members have been read by deserializer.
virtual void deserialized() {}
//Get Type object describing this object.
virtual Type type() const = 0;
bool is(Type _type) const;
};
typedef Reflected::Member Member;
typedef Reflected::Type Type;
/*
Serializes to a size of zero. Good for plugging holes. Used in Shape.
*/
struct Nothing {};
/*
Represents runtime cache data attached to another object. Used for
things like OpenGL objects attached to shapes, et cetera.
*/
class CacheData : public RefCounted
{
public:
virtual ~CacheData() {}
virtual void invalidate() {}
};
/*
A base class for Module which makes communication with the most
useful built-in modules very easy.
For more info on the modules (than the terse descriptions here) see the
corresponding header files.
*/
class ModuleSet
{
public:
class Program &program; // Controls startup/shutdown, main loop
class Universe &universe; // Generic object manager/messager
class Clock &clock; // Tracks various time metrics
class Randomizer &random; // Generates random numbers
class Graphics &graphics; // Rasterizes and displays visuals
// See submodule: graphics.csg
// See submodule: graphics.text
class Audio &audio; // Used for audio processing/output
class Player &player; // Handles most sources of user input
// UI/console focus can block this
const class Mouse &mouse; // Shorthand for player.mouse
const class Keyboard &keyboard; // Shorthand for player.keyboard
const class Gamepad &gamepad(int); // S-hand for player.gamepad(x)
class Storage &storage; // Handles filesystem I/O
class Network &network; // Online game and HTTP functionality
class Console &console; // An interactive debug terminal
class GUI &gui; // An extensible, flexible UI system
class Scripts &scripts; // Runtime-compiled scripting.
private:
ModuleSet(class Program *source, bool headless);
void cleanup();
friend class Program;
};
/*
Messages are used as a means of sending text commands to modules.
More information available in <plaid/console/console.h>
*/
class Command;
/*
Represents a module which is updated at a fixed framerate.
*/
class Module : public ModuleSet
{
public:
virtual ~Module() {}
virtual void update() {}
virtual void handle(Command &command) {}
protected:
/*
You'll need to call this super constructor from your Module's.
*/
Module(const ModuleSet &modules) : ModuleSet(modules) {}
private:
friend class Program;
friend class ModuleSet;
};
}
#else //PLAIDGADGET
#include "util/types.h"
#include "util/memory.h"
#include "util/ref.h"
//No graphical error handling
#define reportError(X) throw(X)
#define reportWarning(X)
#define pgNote(X)
namespace plaid
{
class Reflected {};
}
#endif //PLAIDGADGET
#endif //PLAIDGADGET_MAIN_H
| 0 | 0.870377 | 1 | 0.870377 | game-dev | MEDIA | 0.807862 | game-dev | 0.684076 | 1 | 0.684076 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.