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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
RevereInc/alley-practice | 3,402 | src/main/java/dev/revere/alley/feature/match/internal/types/FFAMatch.java | package dev.revere.alley.feature.match.internal.types;
import dev.revere.alley.feature.arena.Arena;
import dev.revere.alley.feature.kit.Kit;
import dev.revere.alley.feature.queue.Queue;
import dev.revere.alley.feature.match.Match;
import dev.revere.alley.feature.match.model.internal.MatchGamePlayer;
import dev.revere.alley.feature.match.model.GameParticipant;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.PlayerDeathEvent;
import java.util.ArrayList;
import java.util.List;
/**
* @author Emmy
* @project Alley
* @since 25/04/2025
*/
public class FFAMatch extends Match {
private final List<GameParticipant<MatchGamePlayer>> participants;
private GameParticipant<MatchGamePlayer> winner;
/**
* Constructor for the MatchFFAImpl class.
*
* @param queue The queue associated with this match.
* @param kit The kit used in this match.
* @param arena The arena where the match takes place.
* @param participants The list of participants in the match.
*/
public FFAMatch(Queue queue, Kit kit, Arena arena, List<GameParticipant<MatchGamePlayer>> participants) {
super(queue, kit, arena, false);
this.participants = new ArrayList<>(participants);
}
@Override
public void setupPlayer(Player player) {
super.setupPlayer(player);
Location spawn = this.getArena().getPos1();
player.teleport(spawn);
}
@Override
public void handleRespawn(Player player) {
player.spigot().respawn();
//this.addSpectator(player);
player.teleport(this.getArena().getCenter());
}
@Override
public void handleDisconnect(Player player) {
}
@Override
public List<GameParticipant<MatchGamePlayer>> getParticipants() {
return participants;
}
@Override
public boolean canStartRound() {
return participants.stream().noneMatch(GameParticipant::isAllDead);
}
@Override
public boolean canEndRound() {
long aliveCount = participants.stream().filter(p -> !p.isAllDead()).count();
return aliveCount <= 1;
}
@Override
public boolean canEndMatch() {
return this.canEndRound();
}
@Override
public void handleDeathItemDrop(Player player, PlayerDeathEvent event) {
event.getDrops().clear();
}
@Override
public void handleRoundEnd() {
super.handleRoundEnd();
this.participants.stream()
.filter(participant -> !participant.isAllDead())
.findFirst()
.ifPresent(remaining -> {
this.winner = remaining;
this.winner.getLeader().setEliminated(true);
// temporarily, couldnt be asked to mess with clickables again
this.sendMessage("Winner: " + this.winner.getLeader().getUsername());
String losers = this.participants.stream()
.filter(participant -> participant != this.winner)
.map(GameParticipant::getLeader)
.map(MatchGamePlayer::getUsername)
.reduce((a, b) -> a + ", " + b)
.orElse("None");
this.sendMessage("Losers: " + losers);
})
;
}
}
| 0 | 0.857496 | 1 | 0.857496 | game-dev | MEDIA | 0.847176 | game-dev | 0.896822 | 1 | 0.896822 |
stricq/UPKManager | 1,367 | UpkManager.Domain/Models/UpkFile/Properties/DomainPropertyBoolValue.cs | using System;
using System.Threading.Tasks;
using UpkManager.Domain.Constants;
using UpkManager.Domain.Helpers;
namespace UpkManager.Domain.Models.UpkFile.Properties {
internal sealed class DomainPropertyBoolValue : DomainPropertyValueBase {
#region Properties
private uint boolValue { get; set; }
#endregion Properties
#region Domain Properties
public override PropertyTypes PropertyType => PropertyTypes.BoolProperty;
public override object PropertyValue => boolValue;
public override string PropertyString => $"{boolValue != 0}";
#endregion Domain Properties
#region Domain Methods
public override async Task ReadPropertyValue(ByteArrayReader reader, int size, DomainHeader header) {
boolValue = await Task.Run(() => reader.ReadUInt32());
}
public override void SetPropertyValue(object value) {
if (!(value is bool)) return;
boolValue = Convert.ToUInt32((bool)value);
}
#endregion Domain Methods
#region DomainUpkBuilderBase Implementation
public override int GetBuilderSize() {
BuilderSize = sizeof(uint);
return BuilderSize;
}
public override async Task WriteBuffer(ByteArrayWriter Writer, int CurrentOffset) {
await Task.Run(() => Writer.WriteUInt32(boolValue));
}
#endregion DomainUpkBuilderBase Implementation
}
}
| 0 | 0.712784 | 1 | 0.712784 | game-dev | MEDIA | 0.746461 | game-dev | 0.654237 | 1 | 0.654237 |
EcsRx/ecsrx.unity | 9,854 | src/Assets/Plugins/Zenject/Source/Util/ZenReflectionTypeAnalyzer.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using ModestTree;
#if !NOT_UNITY3D
using UnityEngine;
#endif
namespace Zenject.Internal
{
public static class ReflectionTypeAnalyzer
{
static readonly HashSet<Type> _injectAttributeTypes;
static ReflectionTypeAnalyzer()
{
_injectAttributeTypes = new HashSet<Type>();
_injectAttributeTypes.Add(typeof(InjectAttributeBase));
}
public static void AddCustomInjectAttribute<T>()
where T : Attribute
{
AddCustomInjectAttribute(typeof(T));
}
public static void AddCustomInjectAttribute(Type type)
{
Assert.That(type.DerivesFrom<Attribute>());
_injectAttributeTypes.Add(type);
}
public static ReflectionTypeInfo GetReflectionInfo(Type type)
{
Assert.That(!type.IsEnum(), "Tried to analyze enum type '{0}'. This is not supported", type);
Assert.That(!type.IsArray, "Tried to analyze array type '{0}'. This is not supported", type);
var baseType = type.BaseType();
if (baseType == typeof(object))
{
baseType = null;
}
return new ReflectionTypeInfo(
type, baseType, GetConstructorInfo(type), GetMethodInfos(type),
GetFieldInfos(type), GetPropertyInfos(type));
}
static List<ReflectionTypeInfo.InjectPropertyInfo> GetPropertyInfos(Type type)
{
return type.DeclaredInstanceProperties()
.Where(x => _injectAttributeTypes.Any(a => x.HasAttribute(a)))
.Select(x => new ReflectionTypeInfo.InjectPropertyInfo(
x, GetInjectableInfoForMember(type, x))).ToList();
}
static List<ReflectionTypeInfo.InjectFieldInfo> GetFieldInfos(Type type)
{
return type.DeclaredInstanceFields()
.Where(x => _injectAttributeTypes.Any(a => x.HasAttribute(a)))
.Select(x => new ReflectionTypeInfo.InjectFieldInfo(
x, GetInjectableInfoForMember(type, x)))
.ToList();
}
static List<ReflectionTypeInfo.InjectMethodInfo> GetMethodInfos(Type type)
{
var injectMethodInfos = new List<ReflectionTypeInfo.InjectMethodInfo>();
// Note that unlike with fields and properties we use GetCustomAttributes
// This is so that we can ignore inherited attributes, which is necessary
// otherwise a base class method marked with [Inject] would cause all overridden
// derived methods to be added as well
var methodInfos = type.DeclaredInstanceMethods()
.Where(x => _injectAttributeTypes.Any(a => x.GetCustomAttributes(a, false).Any())).ToList();
for (int i = 0; i < methodInfos.Count; i++)
{
var methodInfo = methodInfos[i];
var injectAttr = methodInfo.AllAttributes<InjectAttributeBase>().SingleOrDefault();
if (injectAttr != null)
{
Assert.That(!injectAttr.Optional && injectAttr.Id == null && injectAttr.Source == InjectSources.Any,
"Parameters of InjectAttribute do not apply to constructors and methodInfos");
}
var injectParamInfos = methodInfo.GetParameters()
.Select(x => CreateInjectableInfoForParam(type, x)).ToList();
injectMethodInfos.Add(
new ReflectionTypeInfo.InjectMethodInfo(methodInfo, injectParamInfos));
}
return injectMethodInfos;
}
static ReflectionTypeInfo.InjectConstructorInfo GetConstructorInfo(Type type)
{
var args = new List<ReflectionTypeInfo.InjectParameterInfo>();
var constructor = TryGetInjectConstructor(type);
if (constructor != null)
{
args.AddRange(constructor.GetParameters().Select(
x => CreateInjectableInfoForParam(type, x)));
}
return new ReflectionTypeInfo.InjectConstructorInfo(constructor, args);
}
static ReflectionTypeInfo.InjectParameterInfo CreateInjectableInfoForParam(
Type parentType, ParameterInfo paramInfo)
{
var injectAttributes = paramInfo.AllAttributes<InjectAttributeBase>().ToList();
Assert.That(injectAttributes.Count <= 1,
"Found multiple 'Inject' attributes on type parameter '{0}' of type '{1}'. Parameter should only have one", paramInfo.Name, parentType);
var injectAttr = injectAttributes.SingleOrDefault();
object identifier = null;
bool isOptional = false;
InjectSources sourceType = InjectSources.Any;
if (injectAttr != null)
{
identifier = injectAttr.Id;
isOptional = injectAttr.Optional;
sourceType = injectAttr.Source;
}
bool isOptionalWithADefaultValue = (paramInfo.Attributes & ParameterAttributes.HasDefault) == ParameterAttributes.HasDefault;
return new ReflectionTypeInfo.InjectParameterInfo(
paramInfo,
new InjectableInfo(
isOptionalWithADefaultValue || isOptional,
identifier,
paramInfo.Name,
paramInfo.ParameterType,
isOptionalWithADefaultValue ? paramInfo.DefaultValue : null,
sourceType));
}
static InjectableInfo GetInjectableInfoForMember(Type parentType, MemberInfo memInfo)
{
var injectAttributes = memInfo.AllAttributes<InjectAttributeBase>().ToList();
Assert.That(injectAttributes.Count <= 1,
"Found multiple 'Inject' attributes on type field '{0}' of type '{1}'. Field should only container one Inject attribute", memInfo.Name, parentType);
var injectAttr = injectAttributes.SingleOrDefault();
object identifier = null;
bool isOptional = false;
InjectSources sourceType = InjectSources.Any;
if (injectAttr != null)
{
identifier = injectAttr.Id;
isOptional = injectAttr.Optional;
sourceType = injectAttr.Source;
}
Type memberType = memInfo is FieldInfo
? ((FieldInfo)memInfo).FieldType : ((PropertyInfo)memInfo).PropertyType;
return new InjectableInfo(
isOptional,
identifier,
memInfo.Name,
memberType,
null,
sourceType);
}
static ConstructorInfo TryGetInjectConstructor(Type type)
{
#if !NOT_UNITY3D
if (type.DerivesFromOrEqual<Component>())
{
return null;
}
#endif
if (type.IsAbstract())
{
return null;
}
var constructors = type.Constructors();
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
// WP8 generates a dummy constructor with signature (internal Classname(UIntPtr dummy))
// So just ignore that
constructors = constructors.Where(c => !IsWp8GeneratedConstructor(c)).ToArray();
#endif
if (constructors.IsEmpty())
{
return null;
}
if (constructors.HasMoreThan(1))
{
var explicitConstructor = (from c in constructors where _injectAttributeTypes.Any(a => c.HasAttribute(a)) select c).SingleOrDefault();
if (explicitConstructor != null)
{
return explicitConstructor;
}
// If there is only one public constructor then use that
// This makes decent sense but is also necessary on WSA sometimes since the WSA generated
// constructor can sometimes be private with zero parameters
var singlePublicConstructor = constructors.Where(x => x.IsPublic).OnlyOrDefault();
if (singlePublicConstructor != null)
{
return singlePublicConstructor;
}
// Choose the one with the least amount of arguments
// This might result in some non obvious errors like null reference exceptions
// but is probably the best trade-off since it allows zenject to be more compatible
// with libraries that don't depend on zenject at all
// Discussion here - https://github.com/svermeulen/Zenject/issues/416
return constructors.OrderBy(x => x.GetParameters().Count()).First();
}
return constructors[0];
}
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
static bool IsWp8GeneratedConstructor(ConstructorInfo c)
{
ParameterInfo[] args = c.GetParameters();
if (args.Length == 1)
{
return args[0].ParameterType == typeof(UIntPtr)
&& (string.IsNullOrEmpty(args[0].Name) || args[0].Name == "dummy");
}
if (args.Length == 2)
{
return args[0].ParameterType == typeof(UIntPtr)
&& args[1].ParameterType == typeof(Int64*)
&& (string.IsNullOrEmpty(args[0].Name) || args[0].Name == "dummy")
&& (string.IsNullOrEmpty(args[1].Name) || args[1].Name == "dummy");
}
return false;
}
#endif
}
}
| 0 | 0.883948 | 1 | 0.883948 | game-dev | MEDIA | 0.283451 | game-dev | 0.95119 | 1 | 0.95119 |
moddio/taro | 3,850 | src/gameClasses/components/EffectComponent.js | var EffectComponent = IgeEntity.extend({
classId: 'EffectComponent',
componentId: 'effect',
init: function (entity) {
var self = this;
// Store the entity that this component has been added to
this._entity = entity;
// attach particle emitters on this item, so we can emit particles
self.particleEmitters = {};
if (entity._stats.effects) {
for (event in entity._stats.effects) {
// load particle emitters
var particles = entity._stats.effects[event].particles;
self.particleEmitters[event] = {};
for (particleTypeId in particles) {
var particleData = particles[particleTypeId];
if (particleData) {
// console.log("particleData", particleData, particleData.dimensions)
if (particleData.dimensions == undefined) {
particleData.dimensions = { width: 5, height: 5 };
}
if (particleData['z-index'] === undefined) {
particleData['z-index'] = {
layer: 3,
depth: 5
};
}
self.particleEmitters[event][particleTypeId] = new IgeParticleEmitter() // Set the particle entity to generate for each particle
.layer(particleData['z-index'].layer)
.depth(particleData['z-index'].depth)
.color(particleData.color)
.size(particleData.dimensions.height, particleData.dimensions.width)
.particle(Particle)
.lifeBase(parseFloat(particleData.lifeBase)) // Set particle life to 300ms
.quantityBase(parseFloat(particleData.quantityBase)) // Set output to 60 particles a second (1000ms)
.quantityTimespan(parseFloat(particleData.quantityTimespan))
.deathOpacityBase(parseFloat(particleData.deathOpacityBase)) // Set the particle's death opacity to zero so it fades out as it's lifespan runs out
.velocityVector(
new IgePoint3d(parseFloat(particleData.velocityVector.baseVector.x), parseFloat(particleData.velocityVector.baseVector.y), 0),
new IgePoint3d(parseFloat(particleData.velocityVector.minVector.x), parseFloat(particleData.velocityVector.minVector.y), 0),
new IgePoint3d(parseFloat(particleData.velocityVector.maxVector.x), parseFloat(particleData.velocityVector.maxVector.y), 0)
)
.particleMountTarget(ige.client.mainScene) // Mount new particles to the object scene
.translateTo(parseFloat(particleData.mountPosition.x), parseFloat(-particleData.mountPosition.y), 0) // Move the particle emitter to the bottom of the ship
.mount(self._entity);
}
}
}
}
},
// start particle and/or sound effect
start: function (event) {
var self = this;
if (this._entity._stats.effects && this._entity._stats.effects[event]) {
var data = this._entity._stats.effects[event];
// emit particles
// the particle emitter must be within myPlayer's camera viewing range
if (
self._entity._translate.x > ige.client.vp1.camera._translate.x - 1000 &&
self._entity._translate.x < ige.client.vp1.camera._translate.x + 1000 &&
self._entity._translate.y > ige.client.vp1.camera._translate.y - 1000 &&
self._entity._translate.y < ige.client.vp1.camera._translate.y + 1000
) {
for (particleTypeId in data.particles) {
if (self.particleEmitters[event] && self.particleEmitters[event][particleTypeId]) {
self.particleEmitters[event][particleTypeId].emitOnce();
}
}
}
// play sound
for (soundId in data.sound) {
if (this._entity._stats.effects && this._entity._stats.effects[event]) {
var data = this._entity._stats.effects[event];
if (data.sound && data.sound[soundId]) {
// console.log('play sound called',this._entity)
ige.sound.playSound(data.sound[soundId], this._entity._translate, soundId);
}
}
}
}
}
});
if (typeof (module) !== 'undefined' && typeof (module.exports) !== 'undefined') { module.exports = EffectComponent; }
| 0 | 0.854722 | 1 | 0.854722 | game-dev | MEDIA | 0.739427 | game-dev | 0.971094 | 1 | 0.971094 |
Simply-Love/Simply-Love-SM5 | 3,971 | BGAnimations/ScreenEvaluation common/Panes/Pane3/Arrows.lua | local player = ...
local pn = ToEnumShortString(player)
local mods = SL[pn].ActiveModifiers
-- a string representing the NoteSkin the player was using
local noteskin = GAMESTATE:GetPlayerState(player):GetCurrentPlayerOptions():NoteSkin()
-- NOTESKIN:LoadActorForNoteSkin() expects the noteskin name to be all lowercase(?)
-- so transform the string to be lowercase
noteskin = noteskin:lower()
-- -----------------------------------------------------------------------
local game = GAMESTATE:GetCurrentGame():GetName()
local style = GAMESTATE:GetCurrentStyle()
local style_name = style:GetName()
local num_columns = style:ColumnsPerPlayer()
local rows = { "W1", "W2", "W3", "W4", "W5", "Miss" }
if mods.ShowFaPlusWindow and mods.ShowFaPlusPane then
rows = { "W0", "W1", "W2", "W3", "W4", "W5", "Miss" }
end
local cols = {}
-- loop num_columns number of time to fill the cols table with
-- info about each column for this game
-- each game (dance, pump, techno, etc.) and each style (single, double, routine, etc.)
-- within each game will have its own unique columns
for i=1,num_columns do
table.insert(cols, style:GetColumnInfo(player, i))
end
local box_width = 230
local box_height = 146
-- more space for double and routine
local styletype = ToEnumShortString(style:GetStyleType())
if not (styletype == "OnePlayerOneSide" or styletype == "TwoPlayersTwoSides") then
box_width = 520
end
local col_width = box_width/num_columns
local row_height = box_height/#rows
-- -----------------------------------------------------------------------
local af = Def.ActorFrame{}
af.InitCommand=function(self) self:xy(-104, _screen.cy-40) end
for i, column in ipairs( cols ) do
local _x = col_width * i
-- Calculating column positioning like this in techno game and dance solor results
-- in each column being ~10px too far left; this does not happen in other games that
-- I've tested. There's probably a cleaner fix involving scaling column.XOffset to
-- fit within the bounds of box_width but this is easer for now.
if game == "techno" or (game == "dance" and style_name == "solo") then
_x = _x + 10
end
-- GetNoteSkinActor() is defined in ./Scripts/SL-Helpers.lua, and performs some
-- rudimentary error handling because NoteSkins From The Internet™ may contain Lua errors
af[#af+1] = LoadActor(THEME:GetPathB("","_modules/NoteSkinPreview.lua"), {noteskin_name=noteskin, column=column.Name})..{
OnCommand=function(self)
self:x( _x ):zoom(0.4):visible(true)
end
}
local miss_bmt = nil
-- for each possible judgment
for j, judgment in ipairs(rows) do
-- don't add rows for TimingWindows that were turned off, but always add Miss
if SL[pn].ActiveModifiers.TimingWindows[j] or j==#rows or (mods.ShowFaPlusWindow and mods.ShowFaPlusPane and SL[pn].ActiveModifiers.TimingWindows[j-1]) then
-- add a BitmapText actor to be the number for this column
af[#af+1] = LoadFont("Common Normal")..{
Text=SL[pn].Stages.Stats[SL.Global.Stages.PlayedThisGame + 1].column_judgments[i][judgment],
InitCommand=function(self)
self:xy(_x, j*row_height + 4)
:zoom(0.9)
if j == #rows then miss_bmt = self end
end
}
if judgment == "W4" or judgment == "W5" then
af[#af+1] = LoadFont("Common Normal")..{
Text=SL[pn].Stages.Stats[SL.Global.Stages.PlayedThisGame + 1].column_judgments[i]["Early"][judgment],
InitCommand=function(self)
self:xy(_x - 1, j*row_height - 6):zoom(0.65):halign(1)
end,
OnCommand=function(self)
self:x( self:GetX() - miss_bmt:GetWidth()/2 )
end
}
end
end
end
-- the number of MissBecauseHeld judgments for this column
af[#af+1] = LoadFont("Common Normal")..{
Text=SL[pn].Stages.Stats[SL.Global.Stages.PlayedThisGame + 1].column_judgments[i].MissBecauseHeld,
InitCommand=function(self)
self:xy(_x - 1, 144):zoom(0.65):halign(1)
end,
OnCommand=function(self)
self:x( self:GetX() - miss_bmt:GetWidth()/2 )
end
}
end
return af | 0 | 0.898157 | 1 | 0.898157 | game-dev | MEDIA | 0.766485 | game-dev | 0.986968 | 1 | 0.986968 |
godlikepanos/anki-3d-engine | 2,952 | ThirdParty/Jolt/Jolt/Physics/Vehicle/VehicleController.h | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
#include <Jolt/ObjectStream/SerializableObject.h>
#include <Jolt/Core/StreamIn.h>
#include <Jolt/Core/StreamOut.h>
#ifdef JPH_DEBUG_RENDERER
#include <Jolt/Renderer/DebugRenderer.h>
#endif // JPH_DEBUG_RENDERER
JPH_NAMESPACE_BEGIN
class PhysicsSystem;
class VehicleController;
class VehicleConstraint;
class WheelSettings;
class Wheel;
class StateRecorder;
/// Basic settings object for interface that controls acceleration / deceleration of the vehicle
class JPH_EXPORT VehicleControllerSettings : public SerializableObject, public RefTarget<VehicleControllerSettings>
{
JPH_DECLARE_SERIALIZABLE_ABSTRACT(JPH_EXPORT, VehicleControllerSettings)
public:
/// Saves the contents of the controller settings in binary form to inStream.
virtual void SaveBinaryState(StreamOut &inStream) const = 0;
/// Restore the contents of the controller settings in binary form from inStream.
virtual void RestoreBinaryState(StreamIn &inStream) = 0;
/// Create an instance of the vehicle controller class
virtual VehicleController * ConstructController(VehicleConstraint &inConstraint) const = 0;
};
/// Runtime data for interface that controls acceleration / deceleration of the vehicle
class JPH_EXPORT VehicleController : public NonCopyable
{
public:
JPH_OVERRIDE_NEW_DELETE
/// Constructor / destructor
explicit VehicleController(VehicleConstraint &inConstraint) : mConstraint(inConstraint) { }
virtual ~VehicleController() = default;
/// Access the vehicle constraint that this controller is part of
VehicleConstraint & GetConstraint() { return mConstraint; }
const VehicleConstraint & GetConstraint() const { return mConstraint; }
protected:
// The functions below are only for the VehicleConstraint
friend class VehicleConstraint;
// Create a new instance of wheel
virtual Wheel * ConstructWheel(const WheelSettings &inWheel) const = 0;
// If the vehicle is allowed to go to sleep
virtual bool AllowSleep() const = 0;
// Called before the wheel probes have been done
virtual void PreCollide(float inDeltaTime, PhysicsSystem &inPhysicsSystem) = 0;
// Called after the wheel probes have been done
virtual void PostCollide(float inDeltaTime, PhysicsSystem &inPhysicsSystem) = 0;
// Solve longitudinal and lateral constraint parts for all of the wheels
virtual bool SolveLongitudinalAndLateralConstraints(float inDeltaTime) = 0;
// Saving state for replay
virtual void SaveState(StateRecorder &inStream) const = 0;
virtual void RestoreState(StateRecorder &inStream) = 0;
#ifdef JPH_DEBUG_RENDERER
// Drawing interface
virtual void Draw(DebugRenderer *inRenderer) const = 0;
#endif // JPH_DEBUG_RENDERER
VehicleConstraint & mConstraint; ///< The vehicle constraint we belong to
};
JPH_NAMESPACE_END
| 0 | 0.912961 | 1 | 0.912961 | game-dev | MEDIA | 0.90324 | game-dev | 0.704929 | 1 | 0.704929 |
TeamLapen/Vampirism | 5,651 | src/main/java/de/teamlapen/vampirism/data/ServerSkillTreeData.java | package de.teamlapen.vampirism.data;
import de.teamlapen.vampirism.api.entity.factions.ISkillNode;
import de.teamlapen.vampirism.api.entity.factions.ISkillTree;
import de.teamlapen.vampirism.api.entity.player.skills.ISkill;
import de.teamlapen.vampirism.entity.player.skills.SkillTreeConfiguration;
import net.minecraft.core.Holder;
import net.minecraft.resources.ResourceKey;
import org.apache.commons.lang3.tuple.Pair;
import org.jetbrains.annotations.NotNull;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
public class ServerSkillTreeData implements ISkillTreeData {
private static ServerSkillTreeData INSTANCE = new ServerSkillTreeData(List.of());
public static void init(List<SkillTreeConfiguration> trees) {
INSTANCE = new ServerSkillTreeData(trees);
}
public static ServerSkillTreeData instance() {
return INSTANCE;
}
private final Map<ResourceKey<ISkillTree>, SkillTreeConfiguration> configuration;
public ServerSkillTreeData(List<SkillTreeConfiguration> trees) {
this.configuration = trees.stream().flatMap(s -> s.skillTree().unwrapKey().map(x -> Pair.of(x, s)).stream()).collect(Collectors.toMap(Pair::getKey, Pair::getValue));
}
public List<SkillTreeConfiguration> getConfigurations() {
return configuration.values().stream().toList();
}
@Override
public Optional<SkillTreeConfiguration.SkillTreeNodeConfiguration> getNodeForSkill(Collection<Holder<ISkillTree>> availableTrees, ISkill<?> skill) {
return availableTrees.stream().filter(tree -> skill.allowedSkillTrees().map(tree::is, tree::is)).map(this::getConfiguration).flatMap(x -> x.getNode(skill).stream()).findAny();
}
@Override
public Optional<Holder<ISkillNode>> getParent(SkillTreeConfiguration.SkillTreeNodeConfiguration node) {
SkillTreeConfiguration treeConfig = node.getTreeConfig();
for (SkillTreeConfiguration.SkillTreeNodeConfiguration child : treeConfig.children()) {
if (child == node) {
return Optional.ofNullable(treeConfig.root());
}
var result = getParent(child, node);
if (result.isPresent()) {
return result;
}
}
return Optional.empty();
}
@Override
public boolean isRoot(Collection<Holder<ISkillTree>> availableTrees, SkillTreeConfiguration.SkillTreeNodeConfiguration skill) {
return availableTrees.stream().map(this::getConfiguration).anyMatch(s -> s.root() == skill.node());
}
@Override
public Optional<Holder<ISkillNode>> getParent(SkillTreeConfiguration.SkillTreeNodeConfiguration current, SkillTreeConfiguration.SkillTreeNodeConfiguration node) {
for (SkillTreeConfiguration.SkillTreeNodeConfiguration child : current.children()) {
if (child == node) {
return Optional.ofNullable(current.node());
}
var result = getParent(child, node);
if (result.isPresent()) {
return result;
}
}
return Optional.empty();
}
public SkillTreeConfiguration getConfiguration(Holder<ISkillTree> tree) {
return configuration.get(tree.unwrapKey().orElseThrow());
}
@Override
public SkillTreeConfiguration.SkillTreeNodeConfiguration getNode(Holder<ISkillTree> tree, Holder<ISkillNode> node) {
SkillTreeConfiguration configuration1 = getConfiguration(tree);
for (SkillTreeConfiguration.SkillTreeNodeConfiguration child : configuration1.children()) {
SkillTreeConfiguration.SkillTreeNodeConfiguration result = getNode(child, node);
if (result != null) {
return result;
}
}
return null;
}
@Override
public SkillTreeConfiguration.SkillTreeNodeConfiguration getNode(SkillTreeConfiguration.SkillTreeNodeConfiguration start, Holder<ISkillNode> node) {
if (start.node() == node) {
return start;
}
for (SkillTreeConfiguration.SkillTreeNodeConfiguration child : start.children()) {
SkillTreeConfiguration.SkillTreeNodeConfiguration result = getNode(child, node);
if (result != null) {
return result;
}
}
return null;
}
@Override
public SkillTreeConfiguration.SkillTreeNodeConfiguration root(Holder<ISkillTree> skillTree) {
SkillTreeConfiguration config = getConfiguration(skillTree);
var root = new SkillTreeConfiguration.SkillTreeNodeConfiguration(config.root(), config.children(), true);
root.setTreeConfig(config);
return root;
}
@Override
public @NotNull Optional<ISkillNode> getAnyLastNode(Holder<ISkillTree> tree, Function<ISkillNode, Boolean> isUnlocked) {
SkillTreeConfiguration.SkillTreeNodeConfiguration root = root(tree);
if (!isUnlocked.apply(root.node().value())) {
return Optional.empty();
}
Queue<SkillTreeConfiguration.SkillTreeNodeConfiguration> queue = new ArrayDeque<>();
queue.add(root);
for (SkillTreeConfiguration.SkillTreeNodeConfiguration node = queue.poll(); node != null; node = queue.poll()) {
List<SkillTreeConfiguration.SkillTreeNodeConfiguration> list = node.children().stream().filter(s -> isUnlocked.apply(s.node().value())).toList();
if (!list.isEmpty()) {
queue.addAll(list);
} else if (!node.isRoot()) {
return Optional.of(node.node().value());
}
}
return Optional.empty();
}
}
| 0 | 0.835532 | 1 | 0.835532 | game-dev | MEDIA | 0.557149 | game-dev | 0.93456 | 1 | 0.93456 |
cping/LGame | 4,001 | Java/Loon-Neo/battle/loon/action/map/battle/BattleCommand.java | /**
* Copyright 2008 - 2019 The Loon Game Engine Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
* @project loon
* @author cping
* @email:javachenpeng@yahoo.com
* @version 0.5
*/
package loon.action.map.battle;
import loon.utils.MathUtils;
public class BattleCommand {
public static class Join extends BattleBaseCommand {
@Override
public String getName() {
return "Join";
}
}
public static class Exit extends BattleBaseCommand {
@Override
public String getName() {
return "Exit";
}
}
public static class Info extends BattleBaseCommand {
@Override
public String getName() {
return "Info";
}
}
private String playerInFlag = "PLAYER_IN";
private String playerOutFlag = "PLAYER_OUT";
private String playerCallFlag = "PLAYER_CALL";
private String playerCurrentFlag = null;
private BattleEvent eventHandler;
private BattleStatus status;
public BattleCommand(BattleEvent eventHandler) {
this.eventHandler = eventHandler;
this.status = new BattleStatus();
}
public boolean addPlayer(Join command) {
BattlePlayer player = command.getPlayer();
if (status.getPlayers().containsKey(player.getId())) {
eventHandler.error(status, player, playerInFlag);
return false;
}
playerCurrentFlag = playerInFlag;
status.getPlayers().put(player.getId(), player);
eventHandler.playerJoin(status, player);
return true;
}
public boolean removePlayer(Exit command) {
BattlePlayer player = command.getPlayer();
if (!status.getPlayers().containsKey(player.getId())) {
eventHandler.error(status, player, playerOutFlag);
return false;
}
playerCurrentFlag = playerOutFlag;
status.getPlayers().remove(player.getId());
return true;
}
public void call(Info command) {
BattlePlayer player = command.getPlayer();
if (!status.getPlayers().containsKey(player.getId())) {
eventHandler.error(status, player, playerCallFlag);
return;
}
playerCurrentFlag = playerCallFlag;
player.setHeads(command.isHeads());
}
public void getGameInfo(Info command) {
eventHandler.gameInfoRequest(status, command.getPlayer());
}
public void startRound() {
status.startRound();
eventHandler.roundStart(status);
}
public void endRound() {
status.endRound(MathUtils.nextBoolean());
eventHandler.roundEnd(status);
for (BattlePlayer player : status.getPlayers().values()) {
eventHandler.call(status, player);
}
}
public void reset() {
status.reset();
}
public boolean isGameEmpty() {
return status.getPlayers().isEmpty();
}
public boolean isAllPlayerCalls() {
for (BattlePlayer player : status.getPlayers().values()) {
if (!player.isCallMade()) {
return false;
}
}
return true;
}
public void otherCommand(BattleBaseCommand command) {
eventHandler.error(status, command.getPlayer(),
command.getName() + " not allowed " + status.getState().toString() + " state.");
}
public String getPlayerInFlag() {
return playerInFlag;
}
public void setPlayerInFlag(String i) {
this.playerInFlag = i;
}
public String getPlayerOutFlag() {
return playerOutFlag;
}
public void setPlayerOutFlag(String o) {
this.playerOutFlag = o;
}
public String getPlayerCallFlag() {
return playerCallFlag;
}
public void setPlayerCallFlag(String c) {
this.playerCallFlag = c;
}
public String getPlayerCurrentFlag() {
return playerCurrentFlag;
}
public void setPlayerCurrentFlag(String cur) {
this.playerCurrentFlag = cur;
}
}
| 0 | 0.840615 | 1 | 0.840615 | game-dev | MEDIA | 0.775082 | game-dev | 0.572012 | 1 | 0.572012 |
Juce-Assets/Juce-Feedbacks | 1,750 | Editor/Documentation/TextMeshPro/TextMeshProColorDocumentation.cs | #if JUCE_TEXT_MESH_PRO_EXTENSIONS
using System;
using UnityEditor;
using Juce.Feedbacks;
using UnityEngine;
namespace Juce.Feedbacks
{
internal class TextMeshProColorDocumentation : IFeedbackDocumentation
{
public Type FeedbackType => typeof(TextMeshProColorFeedback);
public void DrawDocumentation()
{
GUILayout.Label("Changes the target TextMeshProUGUI text to a certain color", EditorStyles.wordWrappedLabel);
EditorGUILayout.Space(2);
using (new EditorGUILayout.VerticalScope(EditorStyles.helpBox))
{
GUILayout.Label("- Target: TextMeshProUGUI component that is going to be affected", EditorStyles.wordWrappedLabel);
}
using (new EditorGUILayout.VerticalScope(EditorStyles.helpBox))
{
GUILayout.Label("- Use Starting Value: enables the starting color", EditorStyles.wordWrappedLabel);
GUILayout.Label("- Start: (if enabled) starting color value", EditorStyles.wordWrappedLabel);
GUILayout.Label("- End: end color value to reach", EditorStyles.wordWrappedLabel);
}
using (new EditorGUILayout.VerticalScope(EditorStyles.helpBox))
{
GenericsDocumentation.DelayDocumentation();
GenericsDocumentation.DurationDocumentation();
}
using (new EditorGUILayout.VerticalScope(EditorStyles.helpBox))
{
GenericsDocumentation.EasingDocumentation();
}
using (new EditorGUILayout.VerticalScope(EditorStyles.helpBox))
{
GenericsDocumentation.LoopDocumentation();
}
}
}
}
#endif | 0 | 0.588469 | 1 | 0.588469 | game-dev | MEDIA | 0.477908 | game-dev,desktop-app | 0.797612 | 1 | 0.797612 |
Direwolf20-MC/BuildingGadgets | 10,764 | src/main/java/com/direwolf20/buildinggadgets/common/tainted/inventory/materials/MaterialList.java | package com.direwolf20.buildinggadgets.common.tainted.inventory.materials;
import com.direwolf20.buildinggadgets.common.tainted.inventory.materials.objects.IUniqueObject;
import com.direwolf20.buildinggadgets.common.util.ref.JsonKeys;
import com.direwolf20.buildinggadgets.common.util.ref.NBTKeys;
import com.direwolf20.buildinggadgets.common.util.tools.JsonBiDiSerializer;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMultiset;
import com.google.common.collect.Multiset;
import com.google.common.collect.PeekingIterator;
import com.google.gson.*;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.resources.ResourceLocation;
import javax.annotation.Nullable;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Objects;
import java.util.function.Function;
/**
* Represents the required Item options for a single block, or a set of blocks. The option with the highest priority is listed
* first, followed by the remaining options in descending priority order.
*/
public final class MaterialList implements Iterable<ImmutableMultiset<IUniqueObject<?>>> {
private static final MaterialList EMPTY = new MaterialList();
public static MaterialList deserialize(CompoundTag nbt, boolean persisted) {
return new MaterialList(readEntry(nbt, persisted));
}
public static MaterialList empty() {
return EMPTY;
}
public static MaterialList of() {
return empty();
}
public static MaterialList of(IUniqueObject<?>... items) {
return simpleBuilder().add(items).build();
}
public static MaterialList of(Iterable<IUniqueObject<?>> items) {
return simpleBuilder().addAll(items).build();
}
public static MaterialList and(MaterialList... materialLists) {
return andBuilder().add(materialLists).build();
}
public static MaterialList or(MaterialList... materialLists) {
return orBuilder().add(materialLists).build();
}
public static SimpleBuilder simpleBuilder() {
return new SimpleBuilder();
}
public static SubEntryBuilder andBuilder() {
return new SubEntryBuilder(AndMaterialListEntry::new);
}
public static SubEntryBuilder orBuilder() {
return new SubEntryBuilder(OrMaterialListEntry::new);
}
@Nullable
static MaterialListEntry.Serializer<?> getSerializerForId(ResourceLocation id) {
MaterialListEntry.Serializer<?> serializer = null;
if (id.equals(NBTKeys.SIMPLE_SERIALIZER_ID))
serializer = SimpleMaterialListEntry.SERIALIZER;
else if (id.equals(NBTKeys.OR_SERIALIZER_ID))
serializer = OrMaterialListEntry.SERIALIZER;
else if (id.equals(NBTKeys.AND_SERIALIZER_ID))
serializer = AndMaterialListEntry.SERIALIZER;
return serializer;
}
static MaterialListEntry<?> readEntry(CompoundTag nbt, boolean persisted) {
ResourceLocation id = new ResourceLocation(nbt.getString(NBTKeys.KEY_SERIALIZER));
MaterialListEntry.Serializer<?> serializer = getSerializerForId(id);
Preconditions.checkArgument(serializer != null,
"Failed to recognize Serializer " + id +
"! If you believe you need another implementation, please contact us and we can sort something out!");
return serializer.readFromNBT(nbt, persisted);
}
@SuppressWarnings("unchecked")
//This is ok - the only unchecked is the implicit cast for writing the data which only uses the appropriate serializer
static CompoundTag writeEntry(MaterialListEntry entry, boolean persisted) {
assert entry.getSerializer().getRegistryName() != null;
CompoundTag res = new CompoundTag();
res.putString(NBTKeys.KEY_SERIALIZER, entry.getSerializer().getRegistryName().toString());
res.put(NBTKeys.KEY_DATA, entry.getSerializer().writeToNBT(entry, persisted));
return res;
}
private final MaterialListEntry rootEntry;
private MaterialList() {
this(new SimpleMaterialListEntry(ImmutableMultiset.of()));
}
private MaterialList(MaterialListEntry rootEntry) {
this.rootEntry = Objects.requireNonNull(rootEntry, "Cannot have a MaterialList without a root entry!");
}
private MaterialListEntry getRootEntry() {
return rootEntry;
}
public Iterable<ImmutableMultiset<IUniqueObject<?>>> getItemOptions() {
return rootEntry instanceof SubMaterialListEntry?
((SubMaterialListEntry) rootEntry).viewOnlySubEntries() :
ImmutableList.of();
}
public ImmutableMultiset<IUniqueObject<?>> getRequiredItems() {
SimpleMaterialListEntry simpleEntry = rootEntry instanceof SubMaterialListEntry?
((SubMaterialListEntry) rootEntry).getCombinedConstantEntry() :
((SimpleMaterialListEntry) rootEntry);
return simpleEntry.getItems();
}
public CompoundTag serialize(boolean persisted) {
return writeEntry(rootEntry, persisted);
}
@Override
@SuppressWarnings("unchecked") //The iterator is independent of the type anyway
public PeekingIterator<ImmutableMultiset<IUniqueObject<?>>> iterator() {
return getRootEntry().iterator();
}
public static final class SubEntryBuilder {
private ImmutableList.Builder<MaterialListEntry<?>> subBuilder;
private final Function<ImmutableList<MaterialListEntry<?>>, MaterialListEntry<?>> factory;
private SubEntryBuilder(Function<ImmutableList<MaterialListEntry<?>>, MaterialListEntry<?>> factory) {
this.subBuilder = ImmutableList.builder();
this.factory = factory;
}
public SubEntryBuilder add(SimpleBuilder builder) {
return add(builder.build());
}
public SubEntryBuilder add(SimpleBuilder... builders) {
return addAllSimpleBuilders(Arrays.asList(builders));
}
public SubEntryBuilder add(SubEntryBuilder builder) {
return add(builder.build());
}
public SubEntryBuilder add(SubEntryBuilder... builders) {
return addAllSubBuilders(Arrays.asList(builders));
}
public SubEntryBuilder add(MaterialList element) {
subBuilder.add(element.getRootEntry());
return this;
}
public SubEntryBuilder add(MaterialList... elements) {
return addAll(Arrays.asList(elements));
}
public SubEntryBuilder addItems(Multiset<IUniqueObject<?>> items) {
subBuilder.add(new SimpleMaterialListEntry(ImmutableMultiset.copyOf(items)));
return this;
}
public SubEntryBuilder addAllItems(Iterable<? extends Multiset<IUniqueObject<?>>> iterable) {
iterable.forEach(this::addItems);
return this;
}
public SubEntryBuilder addAll(Iterable<MaterialList> elements) {
elements.forEach(this::add);
return this;
}
public SubEntryBuilder addAll(Iterator<MaterialList> elements) {
elements.forEachRemaining(this::add);
return this;
}
public SubEntryBuilder addAllSimpleBuilders(Iterable<SimpleBuilder> iterable) {
iterable.forEach(this::add);
return this;
}
public SubEntryBuilder addAllSubBuilders(Iterable<SubEntryBuilder> iterable) {
iterable.forEach(this::add);
return this;
}
public MaterialList build() {
return new MaterialList(factory.apply(subBuilder.build()).simplify());
}
}
public static final class SimpleBuilder {
private ImmutableMultiset.Builder<IUniqueObject<?>> requiredItems;
private SimpleBuilder() {
requiredItems = ImmutableMultiset.builder();
}
public SimpleBuilder addItem(IUniqueObject<?> item, int count) {
requiredItems.addCopies(item, count);
return this;
}
public SimpleBuilder addItem(IUniqueObject<?> item) {
return addItem(item, 1);
}
public SimpleBuilder addAll(Iterable<IUniqueObject<?>> items) {
requiredItems.addAll(items);
return this;
}
public SimpleBuilder setCount(IUniqueObject<?> element, int count) {
requiredItems.setCount(element, count);
return this;
}
public SimpleBuilder add(IUniqueObject<?>... elements) {
requiredItems.add(elements);
return this;
}
public SimpleBuilder addAll(Iterator<? extends IUniqueObject<?>> elements) {
requiredItems.addAll(elements);
return this;
}
public MaterialList build() {
return new MaterialList(new SimpleMaterialListEntry(requiredItems.build()));
}
}
public static final class JsonSerializer implements JsonBiDiSerializer<MaterialList> {
private final boolean printName;
private final boolean extended;
public JsonSerializer(boolean printName, boolean extended) {
this.printName = printName;
this.extended = extended;
}
@Override
@SuppressWarnings("unchecked") // only called on the entry itself... this is ok
public JsonElement serialize(MaterialList src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject res = new JsonObject();
res.add(JsonKeys.MATERIAL_LIST_ROOT_TYPE, context.serialize(src.getRootEntry().getSerializer().getRegistryName()));
res.add(JsonKeys.MATERIAL_LIST_ROOT_ENTRY, src.getRootEntry().getSerializer().asJsonSerializer(printName, extended).serialize(src.getRootEntry(), src.getRootEntry().getClass(), context));
return res;
}
@Override
public MaterialList deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
if (json.isJsonNull())
return MaterialList.empty();
JsonObject object = json.getAsJsonObject();
MaterialListEntry.Serializer<?> serializer = getSerializerForId(context.deserialize(object.get(JsonKeys.MATERIAL_LIST_ROOT_TYPE), ResourceLocation.class));
if (serializer == null)
return MaterialList.empty();
JsonDeserializer<?> jsonSerializer = serializer.asJsonDeserializer();
return new MaterialList((MaterialListEntry) jsonSerializer.deserialize(object.get(JsonKeys.MATERIAL_LIST_ROOT_ENTRY), MaterialListEntry.class, context));
}
}
}
| 0 | 0.843964 | 1 | 0.843964 | game-dev | MEDIA | 0.788263 | game-dev | 0.871606 | 1 | 0.871606 |
ParadiseSS13/Paradise | 1,549 | code/modules/martial_arts/combos/judo/wheelthrow.dm | /datum/martial_combo/judo/wheelthrow
name = "Wheel Throw / Floor Pin"
steps = list(MARTIAL_COMBO_STEP_GRAB, MARTIAL_COMBO_STEP_DISARM, MARTIAL_COMBO_STEP_HARM)
explaination_text = "From an armbar, flip your opponent over your shoulder or pin them to the floor, leaving them stunned."
combo_text_override = "Grab, Disarm, Harm"
/datum/martial_combo/judo/wheelthrow/perform_combo(mob/living/carbon/human/user, mob/living/target, datum/martial_art/MA)
if(!IS_HORIZONTAL(target) || !target.has_status_effect(STATUS_EFFECT_ARMBAR))
return MARTIAL_COMBO_FAIL
if(!IS_HORIZONTAL(user))
target.visible_message("<span class='warning'>[user] raises [target] over [user.p_their()] shoulder, and slams [target.p_them()] into the ground!</span>", \
"<span class='userdanger'>[user] throws you over [user.p_their()] shoulder, slamming you into the ground!</span>")
playsound(get_turf(user), 'sound/magic/tail_swing.ogg', 40, TRUE, -1)
target.SpinAnimation(10, 1)
else
target.visible_message("<span class='warning'>[user] manages to get a hold onto [target], and pinning [target.p_them()] to the ground!</span>", \
"<span class='userdanger'>[user] throws you over [user.p_their()] shoulder, slamming you into the ground!</span>")
playsound(get_turf(user), 'sound/weapons/slam.ogg', 40, TRUE, -1)
target.apply_damage(120, STAMINA)
target.KnockDown(15 SECONDS)
target.SetConfused(10 SECONDS)
add_attack_logs(user, target, "Melee attacked with martial-art [src] : Wheel Throw / Floor Pin", ATKLOG_ALL)
return MARTIAL_COMBO_DONE
| 0 | 0.719134 | 1 | 0.719134 | game-dev | MEDIA | 0.971254 | game-dev | 0.906274 | 1 | 0.906274 |
Space-Stories/space-station-14 | 2,664 | Content.Client/Weapons/Melee/MeleeArcOverlay.cs | using System.Numerics;
using Content.Shared.CombatMode;
using Content.Shared.Weapons.Melee;
using Robust.Client.Graphics;
using Robust.Client.Input;
using Robust.Client.Player;
using Robust.Shared.Enums;
using Robust.Shared.Map;
namespace Content.Client.Weapons.Melee;
/// <summary>
/// Debug overlay showing the arc and range of a melee weapon.
/// </summary>
public sealed class MeleeArcOverlay : Overlay
{
private readonly IEntityManager _entManager;
private readonly IEyeManager _eyeManager;
private readonly IInputManager _inputManager;
private readonly IPlayerManager _playerManager;
private readonly MeleeWeaponSystem _melee;
private readonly SharedCombatModeSystem _combatMode;
private readonly SharedTransformSystem _transform = default!;
public override OverlaySpace Space => OverlaySpace.WorldSpaceBelowFOV;
public MeleeArcOverlay(IEntityManager entManager, IEyeManager eyeManager, IInputManager inputManager, IPlayerManager playerManager, MeleeWeaponSystem melee, SharedCombatModeSystem combatMode, SharedTransformSystem transform)
{
_entManager = entManager;
_eyeManager = eyeManager;
_inputManager = inputManager;
_playerManager = playerManager;
_melee = melee;
_combatMode = combatMode;
_transform = transform;
}
protected override void Draw(in OverlayDrawArgs args)
{
var player = _playerManager.LocalEntity;
if (!_entManager.TryGetComponent<TransformComponent>(player, out var xform) ||
!_combatMode.IsInCombatMode(player))
{
return;
}
if (!_melee.TryGetWeapon(player.Value, out _, out var weapon))
return;
var mousePos = _inputManager.MouseScreenPosition;
var mapPos = _eyeManager.PixelToMap(mousePos);
if (mapPos.MapId != args.MapId)
return;
var playerPos = _transform.GetMapCoordinates(player.Value, xform: xform);
if (mapPos.MapId != playerPos.MapId)
return;
var diff = mapPos.Position - playerPos.Position;
if (diff.Equals(Vector2.Zero))
return;
diff = diff.Normalized() * Math.Min(weapon.Range, diff.Length());
args.WorldHandle.DrawLine(playerPos.Position, playerPos.Position + diff, Color.Aqua);
if (weapon.Angle.Theta == 0)
return;
args.WorldHandle.DrawLine(playerPos.Position, playerPos.Position + new Angle(-weapon.Angle / 2).RotateVec(diff), Color.Orange);
args.WorldHandle.DrawLine(playerPos.Position, playerPos.Position + new Angle(weapon.Angle / 2).RotateVec(diff), Color.Orange);
}
}
| 0 | 0.946818 | 1 | 0.946818 | game-dev | MEDIA | 0.945663 | game-dev | 0.919506 | 1 | 0.919506 |
J4C0B3Y/CommandAPI | 1,697 | bukkit/src/main/java/net/j4c0b3y/api/command/bukkit/listener/AsyncTabListener.java | package net.j4c0b3y.api.command.bukkit.listener;
import com.destroystokyo.paper.event.server.AsyncTabCompleteEvent;
import lombok.RequiredArgsConstructor;
import net.j4c0b3y.api.command.bukkit.BukkitCommandHandler;
import net.j4c0b3y.api.command.bukkit.actor.BukkitActor;
import net.j4c0b3y.api.command.utils.ListUtils;
import net.j4c0b3y.api.command.wrapper.CommandWrapper;
import org.bukkit.command.Command;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import java.util.List;
/**
* @author J4C0B3Y
* @version CommandAPI
* @since 30/08/2024
*/
@RequiredArgsConstructor
public class AsyncTabListener implements Listener {
private final BukkitCommandHandler handler;
@EventHandler
public void onTabComplete(AsyncTabCompleteEvent event) {
if (!event.isCommand() || !event.getBuffer().contains(" ")) return;
List<String> arguments = ListUtils.asList(event.getBuffer().split(" ", -1));
String name = arguments.remove(0);
if (event.getSender() instanceof Player) {
name = name.replaceFirst("/", "");
}
Command command = handler.getRegistry().getKnownCommands().get(name);
if (command == null) return;
CommandWrapper wrapper = handler.getRegistry().getWrappers().get(command);
if (wrapper == null) return;
List<String> suggestions = wrapper.suggest(new BukkitActor(event.getSender(), handler), arguments);
if (suggestions.isEmpty()) {
return;
}
for (String suggestion : suggestions) {
event.getCompletions().add(suggestion);
}
event.setHandled(true);
}
}
| 0 | 0.869605 | 1 | 0.869605 | game-dev | MEDIA | 0.905048 | game-dev | 0.958942 | 1 | 0.958942 |
MongusOrg/LiquidBouncePlusPlus | 8,545 | src/main/java/net/ccbluex/liquidbounce/ui/client/clickgui/newVer/NewUi.java | /*
* LiquidBounce++ Hacked Client
* A free open source mixin-based injection hacked client for Minecraft using Minecraft Forge.
* https://github.com/PlusPlusMC/LiquidBouncePlusPlus/
*/
package net.ccbluex.liquidbounce.ui.client.clickgui.newVer;
import net.ccbluex.liquidbounce.features.module.ModuleCategory;
import net.ccbluex.liquidbounce.features.module.modules.render.NewGUI;
import net.ccbluex.liquidbounce.ui.client.clickgui.newVer.element.CategoryElement;
import net.ccbluex.liquidbounce.ui.client.clickgui.newVer.element.SearchElement;
import net.ccbluex.liquidbounce.ui.client.clickgui.newVer.element.module.ModuleElement;
import net.ccbluex.liquidbounce.ui.font.Fonts;
import net.ccbluex.liquidbounce.utils.MouseUtils;
import net.ccbluex.liquidbounce.utils.AnimationUtils;
import net.ccbluex.liquidbounce.utils.render.RenderUtils;
import net.ccbluex.liquidbounce.utils.render.Stencil;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.util.MathHelper;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.GL11;
import java.awt.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static org.lwjgl.opengl.GL11.*;
public class NewUi extends GuiScreen {
private static NewUi instance;
public static final NewUi getInstance() {
return instance == null ? instance = new NewUi() : instance;
}
public static void resetInstance() {
instance = new NewUi();
}
private NewUi() {
for (ModuleCategory c : ModuleCategory.values())
categoryElements.add(new CategoryElement(c));
categoryElements.get(0).setFocused(true);
}
public final List<CategoryElement> categoryElements = new ArrayList<>();
private float startYAnim = height / 2F;
private float endYAnim = height / 2F;
private SearchElement searchElement;
private float fading = 0F;
public void initGui() {
Keyboard.enableRepeatEvents(true);
for (CategoryElement ce : categoryElements) {
for (ModuleElement me : ce.getModuleElements()) {
if (me.listeningKeybind())
me.resetState();
}
}
searchElement = new SearchElement(40F, 115F, 180F, 20F);
super.initGui();
}
public void onGuiClosed() {
for (CategoryElement ce : categoryElements) {
if (ce.getFocused())
ce.handleMouseRelease(-1, -1, 0, 0, 0, 0, 0);
}
Keyboard.enableRepeatEvents(false);
}
public void drawScreen(int mouseX, int mouseY, float partialTicks) {
// will draw reduced ver once it gets under 1140x780.
drawFullSized(mouseX, mouseY, partialTicks, NewGUI.getAccentColor());
}
private void drawFullSized(int mouseX, int mouseY, float partialTicks, Color accentColor) {
RenderUtils.originalRoundedRect(30F, 30F, this.width - 30F, this.height - 30F, 8F, 0xFF101010);
// something to make it look more like windoze
if (MouseUtils.mouseWithinBounds(mouseX, mouseY, this.width - 54F, 30F, this.width - 30F, 50F))
fading += 0.2F * RenderUtils.deltaTime * 0.045F;
else
fading -= 0.2F * RenderUtils.deltaTime * 0.045F;
fading = MathHelper.clamp_float(fading, 0F, 1F);
RenderUtils.customRounded(this.width - 54F, 30F, this.width - 30F, 50F, 0F, 8F, 0F, 8F, new Color(1F, 0F, 0F, fading).getRGB());
GlStateManager.disableAlpha();
RenderUtils.drawImage(IconManager.removeIcon, this.width - 47, 35, 10, 10);
GlStateManager.enableAlpha();
Stencil.write(true);
RenderUtils.drawFilledCircle(65F, 80F, 25F, new Color(45, 45, 45));
Stencil.erase(true);
if (mc.getNetHandler().getPlayerInfo(mc.thePlayer.getUniqueID()) != null) {
final ResourceLocation skin = mc.getNetHandler().getPlayerInfo(mc.thePlayer.getUniqueID()).getLocationSkin();
glPushMatrix();
glTranslatef(40F, 55F, 0F);
glDisable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glDepthMask(false);
OpenGlHelper.glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO);
glColor4f(1f, 1f, 1f, 1f);
mc.getTextureManager().bindTexture(skin);
Gui.drawScaledCustomSizeModalRect(0, 0, 8F, 8F, 8, 8, 50, 50,
64F, 64F);
glDepthMask(true);
glDisable(GL_BLEND);
glEnable(GL_DEPTH_TEST);
glPopMatrix();
}
Stencil.dispose();
if (Fonts.fontLarge.getStringWidth(mc.thePlayer.getGameProfile().getName()) > 70)
Fonts.fontLarge.drawString(Fonts.fontLarge.trimStringToWidth(mc.thePlayer.getGameProfile().getName(), 50) + "...", 100, 78 - Fonts.fontLarge.FONT_HEIGHT + 15, -1);
else
Fonts.fontLarge.drawString(mc.thePlayer.getGameProfile().getName(), 100, 78 - Fonts.fontLarge.FONT_HEIGHT + 15, -1);
if (searchElement.drawBox(mouseX, mouseY, accentColor)) {
searchElement.drawPanel(mouseX, mouseY, 230, 50, width - 260, height - 80, Mouse.getDWheel(), categoryElements, accentColor);
return;
}
final float elementHeight = 24;
float startY = 140F;
for (CategoryElement ce : categoryElements) {
ce.drawLabel(mouseX, mouseY, 30F, startY, 200F, elementHeight);
if (ce.getFocused()) {
startYAnim = NewGUI.fastRenderValue.get() ? startY + 6F : AnimationUtils.animate(startY + 6F, startYAnim, (startYAnim - (startY + 5F) > 0 ? 0.65F : 0.55F) * RenderUtils.deltaTime * 0.025F);
endYAnim = NewGUI.fastRenderValue.get() ? startY + elementHeight - 6F : AnimationUtils.animate(startY + elementHeight - 6F, endYAnim, (endYAnim - (startY + elementHeight - 5F) < 0 ? 0.65F : 0.55F) * RenderUtils.deltaTime * 0.025F);
ce.drawPanel(mouseX, mouseY, 230, 50, width - 260, height - 80, Mouse.getDWheel(), accentColor);
}
startY += elementHeight;
}
RenderUtils.originalRoundedRect(32F, startYAnim, 34F, endYAnim, 1F, accentColor.getRGB());
super.drawScreen(mouseX, mouseY, partialTicks);
}
protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException {
if (MouseUtils.mouseWithinBounds(mouseX, mouseY, this.width - 54F, 30F, this.width - 30F, 50F)) {
mc.displayGuiScreen(null);
return;
}
final float elementHeight = 24;
float startY = 140F;
searchElement.handleMouseClick(mouseX, mouseY, mouseButton, 230, 50, width - 260, height - 80, categoryElements);
if (!searchElement.isTyping()) for (CategoryElement ce : categoryElements) {
if (ce.getFocused())
ce.handleMouseClick(mouseX, mouseY, mouseButton, 230, 50, width - 260, height - 80);
if (MouseUtils.mouseWithinBounds(mouseX, mouseY, 30F, startY, 230F, startY + elementHeight) && !searchElement.isTyping()) {
categoryElements.forEach(e -> e.setFocused(false));
ce.setFocused(true);
return;
}
startY += elementHeight;
}
}
protected void keyTyped(char typedChar, int keyCode) throws IOException {
for (CategoryElement ce : categoryElements) {
if (ce.getFocused()) {
if (ce.handleKeyTyped(typedChar, keyCode))
return;
}
}
if (searchElement.handleTyping(typedChar, keyCode, 230, 50, width - 260, height - 80, categoryElements))
return;
super.keyTyped(typedChar, keyCode);
}
protected void mouseReleased(int mouseX, int mouseY, int state) {
searchElement.handleMouseRelease(mouseX, mouseY, state, 230, 50, width - 260, height - 80, categoryElements);
if (!searchElement.isTyping())
for (CategoryElement ce : categoryElements) {
if (ce.getFocused())
ce.handleMouseRelease(mouseX, mouseY, state, 230, 50, width - 260, height - 80);
}
super.mouseReleased(mouseX, mouseY, state);
}
@Override
public boolean doesGuiPauseGame() {
return false;
}
}
| 0 | 0.785946 | 1 | 0.785946 | game-dev | MEDIA | 0.846778 | game-dev | 0.983591 | 1 | 0.983591 |
fuse-open/uno | 9,928 | src/compiler/backend/ikvm/Emit/OpCode.cs | /*
Copyright (C) 2008, 2010 Jeroen Frijters
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.
Jeroen Frijters
jeroen@frijters.net
*/
using System;
using System.Diagnostics;
namespace IKVM.Reflection.Emit
{
public struct OpCode
{
private const int ValueCount = 1024;
private const int OperandTypeCount = 19;
private const int FlowControlCount = 9;
private const int StackDiffCount = 5;
private const int OpCodeTypeCount = 6;
private const int StackBehaviourPopCount = 20;
private const int StackBehaviourPushCount = 9;
private static readonly StackBehaviour[] pop = {
StackBehaviour.Pop0,
StackBehaviour.Pop1,
StackBehaviour.Pop1_pop1,
StackBehaviour.Popi,
StackBehaviour.Popi_pop1,
StackBehaviour.Popi_popi,
StackBehaviour.Popi_popi8,
StackBehaviour.Popi_popi_popi,
StackBehaviour.Popi_popr4,
StackBehaviour.Popi_popr8,
StackBehaviour.Popref,
StackBehaviour.Popref_pop1,
StackBehaviour.Popref_popi,
StackBehaviour.Popref_popi_popi,
StackBehaviour.Popref_popi_popi8,
StackBehaviour.Popref_popi_popr4,
StackBehaviour.Popref_popi_popr8,
StackBehaviour.Popref_popi_popref,
StackBehaviour.Varpop,
StackBehaviour.Popref_popi_pop1
};
private static readonly StackBehaviour[] push = {
StackBehaviour.Push0,
StackBehaviour.Push1,
StackBehaviour.Push1_push1,
StackBehaviour.Pushi,
StackBehaviour.Pushi8,
StackBehaviour.Pushr4,
StackBehaviour.Pushr8,
StackBehaviour.Pushref,
StackBehaviour.Varpush
};
private readonly int value;
internal OpCode(int value)
{
this.value = value;
}
public override bool Equals(object obj)
{
return this == obj as OpCode?;
}
public override int GetHashCode()
{
return value;
}
public bool Equals(OpCode other)
{
return this == other;
}
public static bool operator ==(OpCode a, OpCode b)
{
return a.value == b.value;
}
public static bool operator !=(OpCode a, OpCode b)
{
return !(a == b);
}
public short Value
{
get { return (short)(value >> 22); }
}
public int Size
{
get { return value < 0 ? 2 : 1; }
}
#if !GENERATOR
public string Name
{
get { return OpCodes.GetName(this.Value); }
}
#endif
public OperandType OperandType
{
get { return (OperandType)((value & 0x3FFFFF) % OperandTypeCount); }
}
public FlowControl FlowControl
{
get { return (FlowControl)(((value & 0x3FFFFF) / OperandTypeCount) % FlowControlCount); }
}
internal int StackDiff
{
get { return ((((value & 0x3FFFFF) / (OperandTypeCount * FlowControlCount)) % StackDiffCount) - 3); }
}
public OpCodeType OpCodeType
{
get { return (OpCodeType)(((value & 0x3FFFFF) / (OperandTypeCount * FlowControlCount * StackDiffCount)) % OpCodeTypeCount); }
}
public StackBehaviour StackBehaviourPop
{
get { return pop[(((value & 0x3FFFFF) / (OperandTypeCount * FlowControlCount * StackDiffCount * OpCodeTypeCount)) % StackBehaviourPopCount)]; }
}
public StackBehaviour StackBehaviourPush
{
get { return push[(((value & 0x3FFFFF) / (OperandTypeCount * FlowControlCount * StackDiffCount * OpCodeTypeCount * StackBehaviourPopCount)) % StackBehaviourPushCount)]; }
}
#if GENERATOR
static void Main(string[] args)
{
Debug.Assert(pop.Length == StackBehaviourPopCount);
Debug.Assert(push.Length == StackBehaviourPushCount);
CheckEnumRange(typeof(FlowControl), FlowControlCount);
CheckEnumRange(typeof(OpCodeType), OpCodeTypeCount);
CheckEnumRange(typeof(OperandType), OperandTypeCount);
foreach (var field in typeof(System.Reflection.Emit.OpCodes).GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static))
{
System.Reflection.Emit.OpCode opc1 = (System.Reflection.Emit.OpCode)field.GetValue(null);
IKVM.Reflection.Emit.OpCode opc2 = new IKVM.Reflection.Emit.OpCode(Pack(opc1));
Debug.Assert(opc1.Value == opc2.Value);
Debug.Assert(opc1.Size == opc2.Size);
Debug.Assert((int)opc1.FlowControl == (int)opc2.FlowControl);
Debug.Assert((int)opc1.OpCodeType == (int)opc2.OpCodeType);
Debug.Assert((int)opc1.OperandType == (int)opc2.OperandType);
Debug.Assert((int)opc1.StackBehaviourPop == (int)opc2.StackBehaviourPop);
Debug.Assert((int)opc1.StackBehaviourPush == (int)opc2.StackBehaviourPush);
Console.WriteLine("\t\tpublic static readonly OpCode {0} = new OpCode({1});", field.Name, Pack(opc1));
}
Console.WriteLine();
Console.WriteLine("\t\tinternal static string GetName(int value)");
Console.WriteLine("\t\t{");
Console.WriteLine("\t\t\tswitch (value)");
Console.WriteLine("\t\t\t{");
foreach (var field in typeof(System.Reflection.Emit.OpCodes).GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static))
{
System.Reflection.Emit.OpCode opc1 = (System.Reflection.Emit.OpCode)field.GetValue(null);
Console.WriteLine("\t\t\t\tcase {0}:", opc1.Value);
Console.WriteLine("\t\t\t\t\treturn \"{0}\";", opc1.Name);
}
Console.WriteLine("\t\t\t}");
Console.WriteLine("\t\t\tthrow new ArgumentOutOfRangeException();");
Console.WriteLine("\t\t}");
Console.WriteLine();
Console.WriteLine("\t\tpublic static bool TakesSingleByteArgument(OpCode inst)");
Console.WriteLine("\t\t{");
Console.WriteLine("\t\t\tswitch (inst.Value)");
Console.WriteLine("\t\t\t{");
foreach (var field in typeof(System.Reflection.Emit.OpCodes).GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static))
{
System.Reflection.Emit.OpCode opc1 = (System.Reflection.Emit.OpCode)field.GetValue(null);
if (System.Reflection.Emit.OpCodes.TakesSingleByteArgument(opc1))
{
Console.WriteLine("\t\t\t\tcase {0}:", opc1.Value);
}
}
Console.WriteLine("\t\t\t\t\treturn true;");
Console.WriteLine("\t\t\t\tdefault:");
Console.WriteLine("\t\t\t\t\treturn false;");
Console.WriteLine("\t\t\t}");
Console.WriteLine("\t\t}");
}
private static void CheckEnumRange(System.Type type, int count)
{
foreach (var field in type.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static))
{
int value = (int)field.GetValue(null);
Debug.Assert(value >= 0 && value < count);
}
}
static int Pack(System.Reflection.Emit.OpCode opcode)
{
int value = 0;
value *= StackBehaviourPushCount;
value += Map(push, opcode.StackBehaviourPush);
value *= StackBehaviourPopCount;
value += Map(pop, opcode.StackBehaviourPop);
value *= OpCodeTypeCount;
value += (int)opcode.OpCodeType;
value *= StackDiffCount;
value += 3 + GetStackDiff(opcode.StackBehaviourPush) + GetStackDiff(opcode.StackBehaviourPop);
value *= FlowControlCount;
value += (int)opcode.FlowControl;
value *= OperandTypeCount;
value += (int)opcode.OperandType;
return (opcode.Value << 22) | value;
}
private static int Map(StackBehaviour[] array, System.Reflection.Emit.StackBehaviour stackBehaviour)
{
for (int i = 0; i < array.Length; i++)
{
if ((int)array[i] == (int)stackBehaviour)
{
return i;
}
}
throw new InvalidOperationException();
}
static int GetStackDiff(System.Reflection.Emit.StackBehaviour sb)
{
switch (sb)
{
case System.Reflection.Emit.StackBehaviour.Pop0:
case System.Reflection.Emit.StackBehaviour.Push0:
case System.Reflection.Emit.StackBehaviour.Varpop:
case System.Reflection.Emit.StackBehaviour.Varpush:
return 0;
case System.Reflection.Emit.StackBehaviour.Pop1:
case System.Reflection.Emit.StackBehaviour.Popi:
case System.Reflection.Emit.StackBehaviour.Popref:
return -1;
case System.Reflection.Emit.StackBehaviour.Pop1_pop1:
case System.Reflection.Emit.StackBehaviour.Popi_pop1:
case System.Reflection.Emit.StackBehaviour.Popi_popi:
case System.Reflection.Emit.StackBehaviour.Popi_popi8:
case System.Reflection.Emit.StackBehaviour.Popi_popr4:
case System.Reflection.Emit.StackBehaviour.Popi_popr8:
case System.Reflection.Emit.StackBehaviour.Popref_pop1:
case System.Reflection.Emit.StackBehaviour.Popref_popi:
return -2;
case System.Reflection.Emit.StackBehaviour.Popi_popi_popi:
case System.Reflection.Emit.StackBehaviour.Popref_popi_pop1:
case System.Reflection.Emit.StackBehaviour.Popref_popi_popi:
case System.Reflection.Emit.StackBehaviour.Popref_popi_popi8:
case System.Reflection.Emit.StackBehaviour.Popref_popi_popr4:
case System.Reflection.Emit.StackBehaviour.Popref_popi_popr8:
case System.Reflection.Emit.StackBehaviour.Popref_popi_popref:
return -3;
case System.Reflection.Emit.StackBehaviour.Push1:
case System.Reflection.Emit.StackBehaviour.Pushi:
case System.Reflection.Emit.StackBehaviour.Pushi8:
case System.Reflection.Emit.StackBehaviour.Pushr4:
case System.Reflection.Emit.StackBehaviour.Pushr8:
case System.Reflection.Emit.StackBehaviour.Pushref:
return 1;
case System.Reflection.Emit.StackBehaviour.Push1_push1:
return 2;
}
throw new InvalidOperationException();
}
#endif // GENERATOR
}
}
| 0 | 0.801733 | 1 | 0.801733 | game-dev | MEDIA | 0.175795 | game-dev | 0.788438 | 1 | 0.788438 |
umuthopeyildirim/DOOM-Mistral | 14,813 | src/vizdoom/src/win32/i_keyboard.cpp | // HEADER FILES ------------------------------------------------------------
#define WIN32_LEAN_AND_MEAN
#define DIRECTINPUT_VERSION 0x800
#define _WIN32_WINNT 0x0501
#include <windows.h>
#include <dinput.h>
#define USE_WINDOWS_DWORD
#include "i_input.h"
#include "i_system.h"
#include "d_event.h"
#include "d_gui.h"
#include "c_cvars.h"
#include "doomdef.h"
#include "doomstat.h"
#include "win32iface.h"
#include "rawinput.h"
// MACROS ------------------------------------------------------------------
#define DINPUT_BUFFERSIZE 32
// TYPES -------------------------------------------------------------------
class FDInputKeyboard : public FKeyboard
{
public:
FDInputKeyboard();
~FDInputKeyboard();
bool GetDevice();
void ProcessInput();
protected:
LPDIRECTINPUTDEVICE8 Device;
};
class FRawKeyboard : public FKeyboard
{
public:
FRawKeyboard();
~FRawKeyboard();
bool GetDevice();
bool ProcessRawInput(RAWINPUT *rawinput, int code);
protected:
USHORT E1Prefix;
};
// EXTERNAL FUNCTION PROTOTYPES --------------------------------------------
// PUBLIC FUNCTION PROTOTYPES ----------------------------------------------
// PRIVATE FUNCTION PROTOTYPES ---------------------------------------------
// EXTERNAL DATA DECLARATIONS ----------------------------------------------
extern HWND Window;
extern LPDIRECTINPUT8 g_pdi;
extern LPDIRECTINPUT g_pdi3;
extern bool GUICapture;
// PRIVATE DATA DEFINITIONS ------------------------------------------------
// Convert DIK_* code to ASCII using Qwerty keymap
static const BYTE Convert[256] =
{
// 0 1 2 3 4 5 6 7 8 9 A B C D E F
0, 27, '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=', 8, 9, // 0
'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '[', ']', 13, 0, 'a', 's', // 1
'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', 39, '`', 0,'\\', 'z', 'x', 'c', 'v', // 2
'b', 'n', 'm', ',', '.', '/', 0, '*', 0, ' ', 0, 0, 0, 0, 0, 0, // 3
0, 0, 0, 0, 0, 0, 0, '7', '8', '9', '-', '4', '5', '6', '+', '1', // 4
'2', '3', '0', '.', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 5
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 6
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 7
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '=', 0, 0, // 8
0, '@', ':', '_', 0, 0, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, // 9
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // A
0, 0, 0, ',', 0, '/', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // B
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // C
0, 0, 0, 0, 0, 0, 0, 0
};
// PUBLIC DATA DEFINITIONS -------------------------------------------------
FKeyboard *Keyboard;
// Set this to false to make keypad-enter a usable separate key.
CVAR (Bool, k_mergekeys, true, CVAR_ARCHIVE|CVAR_GLOBALCONFIG)
// CODE --------------------------------------------------------------------
//==========================================================================
//
// FKeyboard - Constructor
//
//==========================================================================
FKeyboard::FKeyboard()
{
memset(KeyStates, 0, sizeof(KeyStates));
}
//==========================================================================
//
// FKeyboard - Destructor
//
//==========================================================================
FKeyboard::~FKeyboard()
{
AllKeysUp();
}
//==========================================================================
//
// FKeyboard :: CheckAndSetKey
//
// Returns true if the key was already in the desired state, false if it
// wasn't.
//
//==========================================================================
bool FKeyboard::CheckAndSetKey(int keynum, INTBOOL down)
{
BYTE *statebyte = &KeyStates[keynum >> 3];
BYTE mask = 1 << (keynum & 7);
if (down)
{
if (*statebyte & mask)
{
return true;
}
*statebyte |= mask;
return false;
}
else
{
if (*statebyte & mask)
{
*statebyte &= ~mask;
return false;
}
return true;
}
}
//==========================================================================
//
// FKeyboard :: AllKeysUp
//
// For every key currently marked as down, send a key up event and clear it.
//
//==========================================================================
void FKeyboard::AllKeysUp()
{
event_t ev = { 0 };
ev.type = EV_KeyUp;
for (int i = 0; i < 256/8; ++i)
{
if (KeyStates[i] != 0)
{
BYTE states = KeyStates[i];
int j = 0;
KeyStates[i] = 0;
do
{
if (states & 1)
{
ev.data1 = (i << 3) + j;
ev.data2 = Convert[ev.data1];
D_PostEvent(&ev);
}
states >>= 1;
++j;
}
while (states != 0);
}
}
}
//==========================================================================
//
// FKeyboard :: PostKeyEvent
//
// Posts a keyboard event, but only if the state is different from what we
// currently think it is. (For instance, raw keyboard input sends key
// down events every time the key automatically repeats, so we want to
// discard those.)
//
//==========================================================================
void FKeyboard::PostKeyEvent(int key, INTBOOL down, bool foreground)
{
event_t ev = { 0 };
// Printf("key=%02x down=%02x\n", key, down);
// "Merge" multiple keys that are considered to be the same. If the
// original unmerged key is down, it also needs to go up. (In case
// somebody was holding the key down when they changed this setting.)
if (k_mergekeys)
{
if (key == DIK_NUMPADENTER || key == DIK_RMENU || key == DIK_RCONTROL)
{
k_mergekeys = false;
PostKeyEvent(key, false, foreground);
k_mergekeys = true;
key &= 0x7F;
}
else if (key == DIK_RSHIFT)
{
k_mergekeys = false;
PostKeyEvent(key, false, foreground);
k_mergekeys = true;
key = DIK_LSHIFT;
}
}
if (key == 0x59)
{ // Turn kp= on a Mac keyboard into kp= on a PC98 keyboard.
key = DIK_NUMPADEQUALS;
}
// Generate the event, if appropriate.
if (down)
{
if (!foreground || GUICapture)
{ // Do not generate key down events if we are in the background
// or in "GUI Capture" mode.
return;
}
ev.type = EV_KeyDown;
}
else
{
ev.type = EV_KeyUp;
}
if (CheckAndSetKey(key, down))
{ // Key is already down or up.
return;
}
ev.data1 = key;
ev.data2 = Convert[key];
D_PostEvent(&ev);
}
//==========================================================================
//
// FDInputKeyboard - Constructor
//
//==========================================================================
FDInputKeyboard::FDInputKeyboard()
{
Device = NULL;
}
//==========================================================================
//
// FDInputKeyboard - Destructor
//
//==========================================================================
FDInputKeyboard::~FDInputKeyboard()
{
if (Device != NULL)
{
Device->Release();
Device = NULL;
}
}
//==========================================================================
//
// FDInputKeyboard :: GetDevice
//
// Create the device interface and initialize it.
//
//==========================================================================
bool FDInputKeyboard::GetDevice()
{
HRESULT hr;
if (g_pdi3 != NULL)
{ // DirectInput3 interface
hr = g_pdi3->CreateDevice(GUID_SysKeyboard, (LPDIRECTINPUTDEVICE*)&Device, NULL);
}
else if (g_pdi != NULL)
{ // DirectInput8 interface
hr = g_pdi->CreateDevice(GUID_SysKeyboard, &Device, NULL);
}
else
{
hr = -1;
}
if (FAILED(hr))
{
return false;
}
// Yes, this is a keyboard.
hr = Device->SetDataFormat(&c_dfDIKeyboard);
if (FAILED(hr))
{
ufailit:
Device->Release();
Device = NULL;
return false;
}
// Set cooperative level.
hr = Device->SetCooperativeLevel(Window, DISCL_NONEXCLUSIVE | DISCL_BACKGROUND);
if (FAILED(hr))
{
goto ufailit;
}
// Set buffer size so we can use buffered input.
DIPROPDWORD prop;
prop.diph.dwSize = sizeof(prop);
prop.diph.dwHeaderSize = sizeof(prop.diph);
prop.diph.dwObj = 0;
prop.diph.dwHow = DIPH_DEVICE;
prop.dwData = DINPUT_BUFFERSIZE;
hr = Device->SetProperty(DIPROP_BUFFERSIZE, &prop.diph);
if (FAILED(hr))
{
goto ufailit;
}
Device->Acquire();
return true;
}
//==========================================================================
//
// FDInputKeyboard :: ProcessInput
//
//==========================================================================
void FDInputKeyboard::ProcessInput()
{
DIDEVICEOBJECTDATA od;
DWORD dwElements;
HRESULT hr;
bool foreground = (GetForegroundWindow() == Window);
for (;;)
{
DWORD cbObjectData = g_pdi3 ? sizeof(DIDEVICEOBJECTDATA_DX3) : sizeof(DIDEVICEOBJECTDATA);
dwElements = 1;
hr = Device->GetDeviceData(cbObjectData, &od, &dwElements, 0);
if (hr == DIERR_INPUTLOST || hr == DIERR_NOTACQUIRED)
{
Device->Acquire();
hr = Device->GetDeviceData(cbObjectData, &od, &dwElements, 0);
}
if (FAILED(hr) || !dwElements)
{
break;
}
if (od.dwOfs >= 1 && od.dwOfs <= 255)
{
PostKeyEvent(od.dwOfs, od.dwData & 0x80, foreground);
}
}
}
/**************************************************************************/
/**************************************************************************/
//==========================================================================
//
// FRawKeyboard - Constructor
//
//==========================================================================
FRawKeyboard::FRawKeyboard()
{
E1Prefix = 0;
}
//==========================================================================
//
// FRawKeyboard - Destructor
//
//==========================================================================
FRawKeyboard::~FRawKeyboard()
{
if (MyRegisterRawInputDevices != NULL)
{
RAWINPUTDEVICE rid;
rid.usUsagePage = HID_GENERIC_DESKTOP_PAGE;
rid.usUsage = HID_GDP_KEYBOARD;
rid.dwFlags = RIDEV_REMOVE;
rid.hwndTarget = NULL;
MyRegisterRawInputDevices(&rid, 1, sizeof(rid));
}
}
//==========================================================================
//
// FRawKeyboard :: GetDevice
//
// Ensure the API is present and we can listen for keyboard input.
//
//==========================================================================
bool FRawKeyboard::GetDevice()
{
RAWINPUTDEVICE rid;
if (MyRegisterRawInputDevices == NULL)
{
return false;
}
rid.usUsagePage = HID_GENERIC_DESKTOP_PAGE;
rid.usUsage = HID_GDP_KEYBOARD;
rid.dwFlags = RIDEV_INPUTSINK;
rid.hwndTarget = Window;
if (!MyRegisterRawInputDevices(&rid, 1, sizeof(rid)))
{
return false;
}
return true;
}
//==========================================================================
//
// FRawKeyboard :: ProcessRawInput
//
// Convert scan codes to DirectInput key codes. For the most part, this is
// straight forward: Scan codes without any prefix are passed unmodified.
// Scan codes with an 0xE0 prefix byte are generally passed by ORing them
// with 0x80. And scan codes with an 0xE1 prefix are the annoying Pause key
// which will generate another scan code that looks like Num Lock.
//
// This is a bit complicated only because the state of PC key codes is a bit
// of a mess. Keyboards may use simpler codes internally, but for the sake
// of compatibility, programs are presented with XT-compatible codes. This
// means that keys which were originally a shifted form of another key and
// were split off into a separate key all their own, or which were formerly
// a separate key and are now part of another key (most notable PrtScn and
// SysRq), will still generate code sequences that XT-era software will
// still perceive as the original sequences to use those keys.
//
//==========================================================================
bool FRawKeyboard::ProcessRawInput(RAWINPUT *raw, int code)
{
if (raw->header.dwType != RIM_TYPEKEYBOARD)
{
return false;
}
int keycode = raw->data.keyboard.MakeCode;
if (keycode == 0 && (raw->data.keyboard.Flags & RI_KEY_E0))
{ // Even if the make code is 0, we might still be able to extract a
// useful key from the message.
if (raw->data.keyboard.VKey >= VK_BROWSER_BACK && raw->data.keyboard.VKey <= VK_LAUNCH_APP2)
{
static const BYTE MediaKeys[VK_LAUNCH_APP2 - VK_BROWSER_BACK + 1] =
{
DIK_WEBBACK, DIK_WEBFORWARD, DIK_WEBREFRESH, DIK_WEBSTOP,
DIK_WEBSEARCH, DIK_WEBFAVORITES, DIK_WEBHOME,
DIK_MUTE, DIK_VOLUMEDOWN, DIK_VOLUMEUP,
DIK_NEXTTRACK, DIK_PREVTRACK, DIK_MEDIASTOP, DIK_PLAYPAUSE,
DIK_MAIL, DIK_MEDIASELECT, DIK_MYCOMPUTER, DIK_CALCULATOR
};
keycode = MediaKeys[raw->data.keyboard.VKey - VK_BROWSER_BACK];
}
}
if (keycode < 1 || keycode > 0xFF)
{
return false;
}
if (raw->data.keyboard.Flags & RI_KEY_E1)
{
E1Prefix = raw->data.keyboard.MakeCode;
return false;
}
if (raw->data.keyboard.Flags & RI_KEY_E0)
{
if (keycode == DIK_LSHIFT || keycode == DIK_RSHIFT)
{ // Ignore fake shifts.
return false;
}
keycode |= 0x80;
}
// The sequence for an unshifted pause is E1 1D 45 (E1 Prefix +
// Control + Num Lock).
if (E1Prefix)
{
if (E1Prefix == 0x1D && keycode == DIK_NUMLOCK)
{
keycode = DIK_PAUSE;
E1Prefix = 0;
}
else
{
E1Prefix = 0;
return false;
}
}
// If you press Ctrl+Pause, the keyboard sends the Break make code
// E0 46 instead of the Pause make code.
if (keycode == 0xC6)
{
keycode = DIK_PAUSE;
}
// If you press Ctrl+PrtScn (to get SysRq), the keyboard sends
// the make code E0 37. If you press PrtScn without any modifiers,
// it sends E0 2A E0 37. And if you press Alt+PrtScn, it sends 54
// (which is undefined in the charts I can find.)
if (keycode == 0x54)
{
keycode = DIK_SYSRQ;
}
// If you press any keys in the island between the main keyboard
// and the numeric keypad with Num Lock turned on, they generate
// a fake shift before their actual codes. They do not generate this
// fake shift if Num Lock is off. We unconditionally discard fake
// shifts above, so we don't need to do anything special for these,
// since they are also prefixed by E0 so we can tell them apart from
// their keypad counterparts.
// Okay, we're done translating the keycode. Post it (or ignore it.)
PostKeyEvent(keycode, !(raw->data.keyboard.Flags & RI_KEY_BREAK), code == RIM_INPUT);
return true;
}
//==========================================================================
//
// I_StartupKeyboard
//
//==========================================================================
void I_StartupKeyboard()
{
Keyboard = new FRawKeyboard;
if (Keyboard->GetDevice())
{
return;
}
delete Keyboard;
Keyboard = new FDInputKeyboard;
if (!Keyboard->GetDevice())
{
delete Keyboard;
}
}
| 0 | 0.937728 | 1 | 0.937728 | game-dev | MEDIA | 0.810373 | game-dev | 0.884788 | 1 | 0.884788 |
renzuzu/renzu_bag | 5,342 | client/main.lua | ESX = exports['es_extended']:getSharedObject()
local loaded = false
Citizen.CreateThread(function()
PlayerData = ESX.GetPlayerData()
player = LocalPlayer.state
Wait(2000)
loaded = ESX.PlayerLoaded
for k,v in pairs(Config.item) do
lib.requestModel(v.model) -- preload models
end
end)
RegisterNetEvent('esx:playerLoaded')
AddEventHandler('esx:playerLoaded', function(playerData)
loaded = true
end)
RegisterNetEvent('esx:setJob')
AddEventHandler('esx:setJob', function(job)
PlayerData.job = job
loaded = true
end)
local stash = {}
AddStateBagChangeHandler('bag' --[[key filter]], nil --[[bag filter]], function(bagName, key, value, _unused, replicated)
Wait(0)
if not value then return end
local net = tonumber(bagName:gsub('entity:', ''), 10)
local bag = NetworkGetEntityFromNetworkId(net)
local ent = Entity(bag).state
stash[value.serial] = value
StashZone(value)
end)
Spheres = {}
OpenInventory = function(data)
lib.registerContext({
id = 'inventory_'..data.serial,
title = data.label,
onExit = function()
end,
options = {
{
title = 'Open Inventory',
description = 'Open This Bag',
onSelect = function(args)
TriggerEvent('ox_inventory:openInventory', 'stash', {id = data.serial, name = data.label, slots = data.slots, weight = data.weights, coords = data.coord})
end,
},
{
title = 'Take Bag',
description = 'Take the '..data.label,
onSelect = function(args)
print('Pressed the button!')
Progress('Taking '..data.label)
Pickup()
TriggerServerEvent('renzu_bag:removeplacement',data)
end,
},
},
})
lib.showContext('inventory_'..data.serial)
end
Pickup = function()
lib.requestAnimDict('random@domestic')
TaskPlayAnim(PlayerPedId(), 'random@domestic', 'pickup_low', 2.0, 2.0, -1, 48, 0, false, false,false)
end
Progress = function(text)
lib.progressBar({
duration = 1000,
label = text..'..',
useWhileDead = false,
canCancel = true,
disable = {
car = false,
}
})
end
RegisterNetEvent('renzu_bag:removezone', function(data)
if Spheres[data.serial] then
Spheres[data.serial]:remove()
end
if #(GetEntityCoords(cache.ped) - vec3(data.coord.x,data.coord.y,data.coord.z)) < 2 then
lib.hideTextUI()
end
end)
Wearbag = function(id)
SetPedComponentVariation(cache.ped,5,id,0,2)
end
RegisterNetEvent('renzu_bag:Wearbag', function(slot)
local bags = exports.ox_inventory:Search('slots', 'bag')
for k,v in pairs(bags) do
if v.slot == slot then
return Wearbag(v.metadata.componentid)
end
end
end)
exports('useItem', function(data, slot)
exports.ox_inventory:useItem(data, function(data)
Progress('Opening '..data.metadata.label)
Pickup()
lib.requestModel(data.metadata.model)
local bag = CreateObject(data.metadata.model, GetEntityCoords(cache.ped)+GetEntityForwardVector(cache.ped)*0.8, true, true)
while not DoesEntityExist(bag) do Wait(0) end
PlaceObjectOnGroundProperly(bag)
data.metadata.net = NetworkGetNetworkIdFromEntity(bag)
data.metadata.coord = GetEntityCoords(bag)
Wait(1000)
FreezeEntityPosition(bag,true)
data.item = data.name
TriggerServerEvent('renzu_bag:placeobject',data)
end)
end)
StashZone = function(data)
function onEnter(self)
lib.showTextUI('[E] - Open '..data.label, {
position = "right-center",
icon = 'briefcase',
style = {
borderRadius = 0,
backgroundColor = '#202020',
borderRadius = 20,
borderStyle = 'solid',
borderWidth = '1px',
color = 'white'
}
})
end
function onExit(self)
lib.hideTextUI()
end
function inside(self)
local data = data
if IsControlJustPressed(0,38) then
print(data.serial,data.label)
OpenInventory(data)
end
end
local sphere = lib.zones.sphere({
coords = data.coord,
radius = 2,
debug = false,
inside = inside,
onEnter = onEnter,
onExit = onExit
})
Spheres[data.serial] = sphere
end
Shop = function()
function onEnter(self)
lib.showTextUI('[E] - Buy Bag', {
position = "right-center",
icon = 'hand',
style = {
borderRadius = 0,
backgroundColor = '#48BB78',
color = 'white'
}
})
end
function onExit(self)
lib.hideTextUI()
end
function inside(self)
if IsControlJustPressed(0,38) then
BagShop()
end
end
local sphere = lib.zones.sphere({
coords = Config.Shopcoord,
radius = 1,
debug = false,
inside = inside,
onEnter = onEnter,
onExit = onExit
})
end
BagShop = function()
local options = {}
local secondary = {}
local type = {}
for k,v in pairs(Config.item) do
table.insert(options,{
title = v.label.. ' - Price: '..v.price..'$',
arrow = true,
description = 'Buy '..v.label..' | Slots: '..v.slots,
onSelect = function(args)
TriggerServerEvent('buybag',v)
end,
})
end
lib.registerContext({
id = 'buybags',
title = 'Buy Bags',
onExit = function()
print('Hello there')
end,
options = options
})
lib.showContext('buybags')
end
Citizen.CreateThread(function()
Wait(1000)
if Config.useShop then
local blip = AddBlipForCoord(Config.Shopcoord)
SetBlipSprite(blip, 586)
SetBlipDisplay(blip, 4)
SetBlipScale(blip, 0.8)
SetBlipColour(blip, 3)
SetBlipAsShortRange(blip, true)
BeginTextCommandSetBlipName('STRING')
AddTextComponentSubstringPlayerName('Bag Shop')
EndTextCommandSetBlipName(blip)
Shop()
end
end) | 0 | 0.853093 | 1 | 0.853093 | game-dev | MEDIA | 0.624354 | game-dev | 0.937457 | 1 | 0.937457 |
revolucas/CoC-Xray | 4,109 | src/xrGameSpy/gamespy/sc/scRaceSample/atlas_sc_race_v1.c | ///////////////////////////////////////////////////////////////////////////////
// GameSpy ATLAS Competition System Source File
//
// NOTE: This is an auto-generated file, do not edit this file directly.
///////////////////////////////////////////////////////////////////////////////
#include <string.h>
#include "atlas_sc_race_v1.h"
int atlas_rule_set_version = 1;
int ATLAS_GET_KEY(char* keyName)
{
if(!keyName)
return 0;
if(!strcmp("RACE_TIME", keyName))
return RACE_TIME;
return 0;
}
char* ATLAS_GET_KEY_NAME(int keyId)
{
if(keyId <= 0)
return "";
if(keyId == RACE_TIME)
return "RACE_TIME";
return "";
}
int ATLAS_GET_STAT(char* statName)
{
if(!statName)
return 0;
if(!strcmp("CAREER_WINS", statName))
return CAREER_WINS;
else if(!strcmp("CAREER_LOSSES", statName))
return CAREER_LOSSES;
else if(!strcmp("BEST_RACE_TIME", statName))
return BEST_RACE_TIME;
else if(!strcmp("WORST_RACE_TIME", statName))
return WORST_RACE_TIME;
else if(!strcmp("TOTAL_MATCHES", statName))
return TOTAL_MATCHES;
else if(!strcmp("AVERAGE_RACE_TIME", statName))
return AVERAGE_RACE_TIME;
else if(!strcmp("CURRENT_WIN_STREAK", statName))
return CURRENT_WIN_STREAK;
else if(!strcmp("CURRENT_LOSS_STREAK", statName))
return CURRENT_LOSS_STREAK;
else if(!strcmp("TOTAL_RACE_TIME", statName))
return TOTAL_RACE_TIME;
else if(!strcmp("CAREER_DISCONNECTS", statName))
return CAREER_DISCONNECTS;
else if(!strcmp("DISCONNECT_RATE", statName))
return DISCONNECT_RATE;
else if(!strcmp("CAREER_DRAWS", statName))
return CAREER_DRAWS;
else if(!strcmp("CURRENT_DRAW_STREAK", statName))
return CURRENT_DRAW_STREAK;
else if(!strcmp("CAREER_LONGEST_WIN_STREAK", statName))
return CAREER_LONGEST_WIN_STREAK;
else if(!strcmp("CAREER_LONGEST_LOSS_STREAK", statName))
return CAREER_LONGEST_LOSS_STREAK;
else if(!strcmp("CAREER_LONGEST_DRAW_STREAK", statName))
return CAREER_LONGEST_DRAW_STREAK;
else if(!strcmp("TOTAL_COMPLETE_MATCHES", statName))
return TOTAL_COMPLETE_MATCHES;
else if(!strcmp("RICHARD_TEST1", statName))
return RICHARD_TEST1;
else if(!strcmp("RICHARD_TEST2", statName))
return RICHARD_TEST2;
else if(!strcmp("RICHARD_TEST3", statName))
return RICHARD_TEST3;
return 0;
}
char* ATLAS_GET_STAT_NAME(int statId)
{
if(statId <= 0)
return "";
if(statId == CAREER_WINS)
return "CAREER_WINS";
else if(statId == CAREER_LOSSES)
return "CAREER_LOSSES";
else if(statId == BEST_RACE_TIME)
return "BEST_RACE_TIME";
else if(statId == WORST_RACE_TIME)
return "WORST_RACE_TIME";
else if(statId == TOTAL_MATCHES)
return "TOTAL_MATCHES";
else if(statId == AVERAGE_RACE_TIME)
return "AVERAGE_RACE_TIME";
else if(statId == CURRENT_WIN_STREAK)
return "CURRENT_WIN_STREAK";
else if(statId == CURRENT_LOSS_STREAK)
return "CURRENT_LOSS_STREAK";
else if(statId == TOTAL_RACE_TIME)
return "TOTAL_RACE_TIME";
else if(statId == CAREER_DISCONNECTS)
return "CAREER_DISCONNECTS";
else if(statId == DISCONNECT_RATE)
return "DISCONNECT_RATE";
else if(statId == CAREER_DRAWS)
return "CAREER_DRAWS";
else if(statId == CURRENT_DRAW_STREAK)
return "CURRENT_DRAW_STREAK";
else if(statId == CAREER_LONGEST_WIN_STREAK)
return "CAREER_LONGEST_WIN_STREAK";
else if(statId == CAREER_LONGEST_LOSS_STREAK)
return "CAREER_LONGEST_LOSS_STREAK";
else if(statId == CAREER_LONGEST_DRAW_STREAK)
return "CAREER_LONGEST_DRAW_STREAK";
else if(statId == TOTAL_COMPLETE_MATCHES)
return "TOTAL_COMPLETE_MATCHES";
else if(statId == RICHARD_TEST1)
return "RICHARD_TEST1";
else if(statId == RICHARD_TEST2)
return "RICHARD_TEST2";
else if(statId == RICHARD_TEST3)
return "RICHARD_TEST3";
return "";
}
| 0 | 0.565485 | 1 | 0.565485 | game-dev | MEDIA | 0.414078 | game-dev | 0.895815 | 1 | 0.895815 |
JuppOtto/Google-Cardboard | 1,730 | CardboardTestScene/Assets/Cardboard/DemoScene/Teleport.cs | // Copyright 2014 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Collider))]
public class Teleport : MonoBehaviour {
private CardboardHead head;
private Vector3 startingPosition;
void Start() {
head = Camera.main.GetComponent<StereoController>().Head;
startingPosition = transform.localPosition;
CardboardGUI.IsGUIVisible = true;
CardboardGUI.onGUICallback += this.OnGUI;
}
void Update() {
RaycastHit hit;
bool isLookedAt = GetComponent<Collider>().Raycast(head.Gaze, out hit, Mathf.Infinity);
GetComponent<Renderer>().material.color = isLookedAt ? Color.green : Color.red;
if (Cardboard.SDK.CardboardTriggered && isLookedAt) {
// Teleport randomly.
Vector3 direction = Random.onUnitSphere;
direction.y = Mathf.Clamp(direction.y, 0.5f, 1f);
float distance = 2 * Random.value + 1.5f;
transform.localPosition = direction * distance;
}
}
void OnGUI() {
if (!CardboardGUI.OKToDraw(this)) {
return;
}
if (GUI.Button(new Rect(50, 50, 200, 50), "Reset")) {
transform.localPosition = startingPosition;
}
}
}
| 0 | 0.784756 | 1 | 0.784756 | game-dev | MEDIA | 0.790073 | game-dev,graphics-rendering | 0.858355 | 1 | 0.858355 |
Direwolf20-MC/LaserIO | 1,644 | src/main/java/com/direwolf20/laserio/common/containers/customhandler/FilterCountHandler.java | package com.direwolf20.laserio.common.containers.customhandler;
import com.direwolf20.laserio.common.items.filters.FilterCount;
import net.minecraft.world.item.ItemStack;
import javax.annotation.Nonnull;
public class FilterCountHandler extends FilterBasicHandler {
public FilterCountHandler(int size, ItemStack itemStack) {
super(size, itemStack);
}
@Override
public boolean isItemValid(int slot, @Nonnull ItemStack stack) {
return super.isItemValid(slot, stack);
}
@Override
public int getSlotLimit(int slot) {
return 1;
}
@Override
public ItemStack getStackInSlot(int slot) {
ItemStack returnStack = super.getStackInSlot(slot);
int amt = FilterCount.getSlotCount(this.stack, slot);
if (amt != returnStack.getCount())
returnStack.setCount(amt);
return returnStack;
}
@Override
public void setStackInSlot(int slot, ItemStack stack) {
ItemStack stackCopy = stack.copy();
int amt = stackCopy.getCount();
stackCopy.setCount(1);
super.setStackInSlot(slot, stackCopy);
FilterCount.setSlotCount(this.stack, slot, amt);
}
public void setMBAmountInSlot(int slot, int mbAmt) {
if (mbAmt == -1) return; //Shouldn't happen unless i done did goofed
FilterCount.setSlotAmount(this.stack, slot, mbAmt);
}
public void syncSlots() {
for (int i = 0; i < this.getSlots(); i++) {
if (FilterCount.getSlotAmount(this.stack, i) == 0)
FilterCount.setSlotCount(this.stack, i, this.getStackInSlot(i).getCount());
}
}
}
| 0 | 0.79846 | 1 | 0.79846 | game-dev | MEDIA | 0.850988 | game-dev | 0.961584 | 1 | 0.961584 |
CryptoMorin/XSeries | 18,003 | core/src/main/java/com/cryptomorin/xseries/profiles/ProfilesCore.java | /*
* The MIT License (MIT)
*
* Copyright (c) 2025 Crypto Morin
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.cryptomorin.xseries.profiles;
import com.cryptomorin.xseries.reflection.ReflectiveNamespace;
import com.cryptomorin.xseries.reflection.XReflection;
import com.cryptomorin.xseries.reflection.jvm.FieldMemberHandle;
import com.cryptomorin.xseries.reflection.jvm.MethodMemberHandle;
import com.cryptomorin.xseries.reflection.minecraft.MinecraftClassHandle;
import com.cryptomorin.xseries.reflection.minecraft.MinecraftMapping;
import com.google.common.cache.LoadingCache;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.minecraft.MinecraftSessionService;
import com.mojang.authlib.properties.Property;
import org.jetbrains.annotations.ApiStatus;
import java.lang.invoke.MethodHandle;
import java.net.Proxy;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import static com.cryptomorin.xseries.reflection.XReflection.v;
/**
* Collection of NMS reflection needed to interact with the internal cache.
*/
@SuppressWarnings("unchecked")
@ApiStatus.Internal
public final class ProfilesCore {
public static final Object USER_CACHE, MINECRAFT_SESSION_SERVICE;
public static final Proxy PROXY;
public static final LoadingCache<Object, Object> YggdrasilMinecraftSessionService_insecureProfiles;
public static final boolean SUPPORTS_BUKKIT_PlayerProfile;
public static final Map<String, Object> UserCache_profilesByName;
public static final Map<UUID, Object> UserCache_profilesByUUID;
public static final MethodHandle
MinecraftSessionService_fillProfileProperties, GameProfileCache_get$profileByName$, GameProfileCache_get$profileByUUID$,
CachedUserNameToIdResolver_add,
CraftMetaSkull_profile$getter, CraftMetaSkull_profile$setter,
CraftSkull_profile$setter, CraftSkull_profile$getter,
Property_getValue,
UserCache_getNextOperation,
GameProfileInfo_getProfile, GameProfileInfo_setLastAccess, GameProfileInfo_nameAndId,
NameAndId_id, NameAndId_name, NameAndId$ctor_GameProfile,
ResolvableProfile$constructor, ResolvableProfile_gameProfile;
public static final boolean ResolvableProfile$bukkitSupports;
/**
* In v1.20.2, Mojang switched to {@code record} class types for their {@link Property} class.
*/
public static final boolean NULLABILITY_RECORD_UPDATE = XReflection.supports(1, 20, 2);
static {
Object userCache, minecraftSessionService, insecureProfiles = null;
Proxy proxy;
MethodHandle fillProfileProperties = null, getProfileByName, getProfileByUUID, cacheProfile;
MethodHandle profileSetterMeta, profileGetterMeta;
MethodHandle newResolvableProfile = null, $ResolvableProfile_gameProfile = null, NameAndId$ctor = null;
boolean bukkitUsesResolvableProfile = false;
ReflectiveNamespace ns = XReflection.namespaced()
.imports(GameProfile.class, MinecraftSessionService.class, LoadingCache.class);
MinecraftClassHandle CachedUserNameToIdResolver = ns.ofMinecraft(
"package nms.server.players; public class CachedUserNameToIdResolver"
)
.map(MinecraftMapping.MOJANG, v(21, 9, "CachedUserNameToIdResolver").orElse("GameProfileCache"))
.map(MinecraftMapping.SPIGOT, "UserCache");
SUPPORTS_BUKKIT_PlayerProfile = ns
.ofMinecraft("package org.bukkit; public interface OfflinePlayer")
.method("org.bukkit.profile.PlayerProfile getPlayerProfile()")
.exists();
MinecraftClassHandle GameProfileInfo = CachedUserNameToIdResolver
.inner("private static class GameProfileInfo")
.map(MinecraftMapping.SPIGOT, v(21, 9, "a").orElse("UserCacheEntry"))
.map(MinecraftMapping.OBFUSCATED, "bay$a");
MinecraftClassHandle NameAndId = ns
.ofMinecraft("package nms.server.players; public class NameAndId") // Record class
.map(MinecraftMapping.OBFUSCATED, "bbb");
try {
MinecraftClassHandle CraftMetaSkull = ns.ofMinecraft(
"package cb.inventory; class CraftMetaSkull extends CraftMetaItem implements SkullMeta"
);
// This class has existed since ~v1.20.5, however Bukkit has started using it in their
// classes since Paper v1.20.1b78, its function is basically similar to our Profileable class.
MinecraftClassHandle ResolvableProfile =
ns.ofMinecraft("package nms.world.item.component; public class ResolvableProfile");
if (ResolvableProfile.exists()) {
newResolvableProfile = XReflection.any(
// Introduced in v1.21.9
ResolvableProfile.method("public static ResolvableProfile createResolved(GameProfile gameProfile)")
.map(MinecraftMapping.OBFUSCATED, "a"),
ResolvableProfile.constructor("public ResolvableProfile(GameProfile gameProfile)")
).reflect();
$ResolvableProfile_gameProfile = ResolvableProfile.method("public GameProfile partialProfile()")
.map(MinecraftMapping.MOJANG, v(21, 9, "partialProfile").orElse("gameProfile"))
.map(MinecraftMapping.OBFUSCATED, v(21, 9, "b").v(21, 6, "g").orElse("f"))
.reflect();
bukkitUsesResolvableProfile = CraftMetaSkull.field("private ResolvableProfile profile").exists();
}
// @formatter:off
profileGetterMeta = XReflection.any(
CraftMetaSkull.field("private ResolvableProfile profile"),
CraftMetaSkull.field("private GameProfile profile")
).modify(FieldMemberHandle::getter).reflect();
// @formatter:on
// @formatter:off
// https://github.com/CryptoMorin/XSeries/issues/169
// noinspection MethodMayBeStatic
profileSetterMeta = XReflection.any(
CraftMetaSkull.method("private void setProfile(ResolvableProfile profile)"),
CraftMetaSkull.method("private void setProfile(GameProfile profile)"),
CraftMetaSkull.field ("private GameProfile profile ").setter()
).reflect();
// @formatter:on
MinecraftClassHandle MinecraftServer = ns.ofMinecraft(
"package nms.server; public abstract class MinecraftServer"
);
// Added by Bukkit
Object minecraftServer = MinecraftServer.method("public static MinecraftServer getServer()").reflect().invoke();
// Services is a record class, it existed even in 1.21.8 but we don't need to switch.
MinecraftClassHandle Services = ns.ofMinecraft("package nms.server; public class Services");
boolean usesServices = XReflection.supports(1, 21, 9) && Services.exists();
Object services = null;
if (usesServices) {
services = MinecraftServer.method("public Services services()")
.map(MinecraftMapping.OBFUSCATED, "av")
.reflect().invoke(minecraftServer);
minecraftSessionService = Services.method("public com.mojang.authlib.minecraft.MinecraftSessionService sessionService()")
.map(MinecraftMapping.OBFUSCATED, "c")
.reflect().invoke(services);
} else {
minecraftSessionService = MinecraftServer.method("public MinecraftSessionService getSessionService()")
.named(/* 1.21.3 */ "aq", /* 1.19.4 */ "ay", /* 1.17.1 */ "getMinecraftSessionService", "az", "ao", "am", /* 1.20.4 */ "aD", /* 1.20.6 */ "ar", /* 1.13 */ "ap")
.reflect().invoke(minecraftServer);
}
{
MinecraftClassHandle yggdrasilService = ns.ofMinecraft("package com.mojang.authlib.yggdrasil;" +
"public class YggdrasilMinecraftSessionService implements MinecraftSessionService");
FieldMemberHandle yggdrasilField = yggdrasilService.field().getter();
if (NULLABILITY_RECORD_UPDATE) {
yggdrasilField.signature("private final LoadingCache<UUID, Optional<ProfileResult>> insecureProfiles");
} else {
yggdrasilField.signature("private final LoadingCache<GameProfile, GameProfile> insecureProfiles");
}
MethodHandle insecureProfilesField = yggdrasilField.reflectOrNull();
if (insecureProfilesField != null) {
insecureProfiles = insecureProfilesField.invoke(minecraftSessionService);
}
}
if (usesServices) {
ns.ofMinecraft("package nms.server.players; public interface UserNameToIdResolver")
.map(MinecraftMapping.OBFUSCATED, "bbm");
userCache = Services.method("public UserNameToIdResolver nameToIdCache()")
.map(MinecraftMapping.OBFUSCATED, "f")
.reflect().invoke(services);
} else {
userCache = MinecraftServer.method("public CachedUserNameToIdResolver getProfileCache()")
.named("at", /* 1.21.3 */ "ar", /* 1.18.2 */ "ao", /* 1.20.4 */ "ap", /* 1.20.6 */ "au")
.map(MinecraftMapping.OBFUSCATED, /* 1.9.4 */ "getUserCache")
.reflect().invoke(minecraftServer);
}
if (!NULLABILITY_RECORD_UPDATE) {
fillProfileProperties = ns.of(MinecraftSessionService.class).method(
"public GameProfile fillProfileProperties(GameProfile profile, boolean flag)"
).reflect();
}
// noinspection MethodMayBeStatic
UserCache_getNextOperation = CachedUserNameToIdResolver.method("private long getNextOperation()")
.map(MinecraftMapping.OBFUSCATED, v(21, "e").v(16, "d").orElse("d")).reflectOrNull();
MethodMemberHandle profileByName = CachedUserNameToIdResolver.method().named(/* v1.17.1 */ "getProfile", "a");
MethodMemberHandle profileByUUID = CachedUserNameToIdResolver.method().named(/* v1.17.1 */ "getProfile", "a");
// @formatter:off
getProfileByName = XReflection.anyOf(
() -> profileByName.signature("public GameProfile get(String username)"),
() -> profileByName.signature("public Optional<GameProfile> get(String username)")
).reflect();
getProfileByUUID = XReflection.anyOf(
() -> profileByUUID.signature("public GameProfile get(UUID id)"),
() -> profileByUUID.signature("public Optional<GameProfile> get(UUID id)")
).reflect();
// @formatter:on
if (usesServices) {
NameAndId$ctor = NameAndId.constructor("public NameAndId(GameProfile profile)").reflect();
cacheProfile = CachedUserNameToIdResolver.method("private void add(NameAndId nameAndId)")
.parameters(NameAndId)
.map(MinecraftMapping.OBFUSCATED, "a").reflect();
} else {
cacheProfile = CachedUserNameToIdResolver.method("public void add(GameProfile profile)")
.map(MinecraftMapping.OBFUSCATED, "a").reflect();
}
try {
// Some versions don't have the public getProxy() method. It's very very inconsistent...
proxy = (Proxy) MinecraftServer.field("protected final java.net.Proxy proxy").getter()
.map(MinecraftMapping.OBFUSCATED, v(21, 9, "i")
.v(20, 5, "h").v(20, 3, "i")
.v(19, "j")
.v(18, 2, "n").v(18, "o")
.v(17, "m")
.v(14, "proxy") // v1.14 -> v1.16
.v(13, "c").orElse(/* v1.8 and v1.9 */ "e"))
.reflect().invoke(minecraftServer);
} catch (Throwable ex) {
ProfileLogger.LOGGER.error("Failed to initialize server proxy settings", ex);
proxy = null;
}
} catch (Throwable throwable) {
throw XReflection.throwCheckedException(throwable);
}
MinecraftClassHandle CraftSkull = ns.ofMinecraft(
"package cb.block; public class CraftSkull extends CraftBlockEntityState implements Skull"
);
FieldMemberHandle CraftSkull_profile = XReflection.any(
CraftSkull.field("private ResolvableProfile profile"),
CraftSkull.field("private GameProfile profile")
).getHandle();
Property_getValue = NULLABILITY_RECORD_UPDATE ? null :
ns.of(Property.class).method("public String getValue()").unreflect();
PROXY = proxy;
USER_CACHE = userCache;
CachedUserNameToIdResolver_add = cacheProfile;
MINECRAFT_SESSION_SERVICE = minecraftSessionService;
NameAndId$ctor_GameProfile = NameAndId$ctor;
Objects.requireNonNull(insecureProfiles, () -> "Couldn't find Mojang's insecureProfiles cache " + XReflection.getVersionInformation());
YggdrasilMinecraftSessionService_insecureProfiles = (LoadingCache<Object, Object>) insecureProfiles;
MinecraftSessionService_fillProfileProperties = fillProfileProperties;
GameProfileCache_get$profileByName$ = getProfileByName;
GameProfileCache_get$profileByUUID$ = getProfileByUUID;
CraftMetaSkull_profile$setter = profileSetterMeta;
CraftMetaSkull_profile$getter = profileGetterMeta;
CraftSkull_profile$setter = CraftSkull_profile.setter().unreflect();
CraftSkull_profile$getter = CraftSkull_profile.getter().unreflect();
ResolvableProfile$constructor = newResolvableProfile;
ResolvableProfile_gameProfile = $ResolvableProfile_gameProfile;
ResolvableProfile$bukkitSupports = bukkitUsesResolvableProfile;
GameProfileInfo_getProfile = GameProfileInfo.method("public GameProfile getProfile()")
.map(MinecraftMapping.OBFUSCATED, "a").makeAccessible()
.unwrap().reflectOrNull();
if (GameProfileInfo_getProfile == null) { // 1.21.9
GameProfileInfo_nameAndId = GameProfileInfo.method("public NameAndId nameAndId()")
.map(MinecraftMapping.OBFUSCATED, "a").makeAccessible()
.unwrap().unreflect();
NameAndId_id = NameAndId.method("public UUID id()")
.map(MinecraftMapping.OBFUSCATED, "a").makeAccessible()
.unwrap().unreflect();
NameAndId_name = NameAndId.method("public String name()")
.map(MinecraftMapping.OBFUSCATED, "b").makeAccessible()
.unwrap().unreflect();
} else {
GameProfileInfo_nameAndId = null;
NameAndId_id = null;
NameAndId_name = null;
}
GameProfileInfo_setLastAccess = GameProfileInfo.method("public void setLastAccess(long lastAccess)")
.map(MinecraftMapping.OBFUSCATED, "a").reflectOrNull();
try {
// private final Map<String, UserCache.UserCacheEntry> profilesByName = Maps.newConcurrentMap();
UserCache_profilesByName = (Map<String, Object>) CachedUserNameToIdResolver.field("private final Map<String, UserCache.UserCacheEntry> profilesByName")
.getter().map(MinecraftMapping.OBFUSCATED, v(17, "e").v(16, 2, "c").v(9, "d").orElse("c"))
.reflect().invoke(userCache);
// private final Map<UUID, UserCache.UserCacheEntry> profilesByUUID = Maps.newConcurrentMap();
UserCache_profilesByUUID = (Map<UUID, Object>) CachedUserNameToIdResolver.field("private final Map<UUID, UserCache.UserCacheEntry> profilesByUUID")
.getter().map(MinecraftMapping.OBFUSCATED, v(17, "f").v(16, 2, "d").v(9, "e").orElse("d"))
.reflect().invoke(userCache);
// private final Deque<GameProfile> f = new LinkedBlockingDeque(); Removed in v1.16
// MethodHandle deque = GameProfileCache.field("private final Deque<GameProfile> f")
// .getter().reflectOrNull();
} catch (Throwable e) {
throw new IllegalStateException("Failed to initialize ProfilesCore", e);
}
}
}
| 0 | 0.85677 | 1 | 0.85677 | game-dev | MEDIA | 0.849268 | game-dev | 0.904894 | 1 | 0.904894 |
sedwards2009/extraterm | 4,738 | main/src/emulator/FastControlSequenceParameters.ts | /*
* Copyright 2024 Simon Edwards <simon@simonzone.com>
*
* This source code is licensed under the MIT license which is detailed in the LICENSE.txt file.
*/
interface Param {
codePointIndex: number;
codePoints: Uint32Array;
}
const MAX_PARAMS = 1;
const CODEPOINT_ZERO = 0x30;
const CODEPOINT_NINE = 0x39;
export interface ParameterList {
getParamCount(): number;
getParameterString(paramIndex: number): string;
getParameterInt(paramIndex: number): number;
getDefaultInt(paramIndex: number, def: number): number;
}
export class ControlSequenceParameters implements ParameterList {
#prefixIndex = 0;
#prefixCodePoint1 = 0;
#prefixCodePoint2 = 0;
#paramIndex = 0;
#params: Param[] = [];
constructor() {
for (let i=0; i<MAX_PARAMS; i++) {
this.#params.push({
codePointIndex: 0,
codePoints: new Uint32Array(1024),
});
}
}
hasPrefix(): boolean {
return this.#prefixIndex !== 0;
}
appendPrefix(codePoint: number): boolean {
if (this.#prefixIndex === 2) {
return false;
}
if (this.#prefixIndex === 0) {
this.#prefixCodePoint1 = codePoint;
} else {
this.#prefixCodePoint2 = codePoint;
}
this.#prefixIndex++;
return true;
}
getPrefixString(): string {
if (this.#prefixIndex === 0) {
return "";
}
if (this.#prefixIndex === 1) {
return String.fromCodePoint(this.#prefixCodePoint1);
}
return String.fromCodePoint(this.#prefixCodePoint1, this.#prefixCodePoint2);
}
getPrefixLength(): number {
return this.#prefixIndex;
}
reset(): void {
this.#prefixIndex = 0;
this.#paramIndex = 0;
for (let i=0; i<this.#params.length; i++) {
this.#params[i].codePointIndex = 0;
}
}
getParamCount(): number {
return this.#paramIndex;
}
endParameter(): void {
this.#paramIndex++;
if (this.#paramIndex >= this.#params.length) {
this.#params.push({
codePointIndex: 0,
codePoints: new Uint32Array(1024),
});
}
}
appendParameterCodePoint(codePoint: number):void {
const param = this.#params[this.#paramIndex];
const index = param.codePointIndex;
param.codePoints[index] = codePoint;
param.codePointIndex++;
}
getParameterString(paramIndex: number): string {
const param = this.#params[paramIndex];
return String.fromCodePoint(...param.codePoints.slice(0, param.codePointIndex));
}
getParameterInt(paramIndex: number): number {
const param = this.#params[paramIndex];
let result = 0;
for (let i=0; i<param.codePointIndex; i++) {
const codePoint = param.codePoints[i];
if (codePoint >= CODEPOINT_ZERO && codePoint <= CODEPOINT_NINE) {
result = result * 10 + (codePoint - CODEPOINT_ZERO);
} else {
break;
}
}
return result;
}
// TODO: rename
getDefaultInt(paramIndex: number, def: number): number {
if (paramIndex >= this.#paramIndex) {
return def;
}
return this.getParameterInt(paramIndex);
}
getStringList(): string[] {
const result = [];
for (let i=0; i<this.#paramIndex; i++) {
result.push(this.getParameterString(i));
}
return result;
}
getExpandParameter(paramIndex: number, splitCodePoint: number): ParameterList {
const param = this.#params[paramIndex];
const list: Uint32Array[] = [];
let startI = 0;
const codePoints = param.codePoints;
for (let i=0; i<param.codePointIndex; i++) {
if (codePoints[i] === splitCodePoint) {
list.push(codePoints.slice(startI, i));
startI = i + 1;
}
}
list.push(codePoints.slice(startI, param.codePointIndex));
return new TinyParameterList(list);
}
}
class TinyParameterList {
#paramCodePoints: Uint32Array[];
constructor(paramCodePointsList: Uint32Array[]) {
this.#paramCodePoints = paramCodePointsList;
}
getParamCount(): number {
return this.#paramCodePoints.length;
}
getParameterString(paramIndex: number): string {
const param = this.#paramCodePoints[paramIndex];
return String.fromCodePoint(...param);
}
getParameterInt(paramIndex: number): number {
const paramCodePoints = this.#paramCodePoints[paramIndex];
let result = 0;
for (let i=0; i<paramCodePoints.length; i++) {
const codePoint = paramCodePoints[i];
if (codePoint >= CODEPOINT_ZERO && codePoint <= CODEPOINT_NINE) {
result = result * 10 + (codePoint - CODEPOINT_ZERO);
} else {
break;
}
}
return result;
}
getDefaultInt(paramIndex: number, def: number): number {
if (paramIndex >= this.#paramCodePoints.length) {
return def;
}
return this.getParameterInt(paramIndex);
}
} | 0 | 0.811011 | 1 | 0.811011 | game-dev | MEDIA | 0.35813 | game-dev | 0.793946 | 1 | 0.793946 |
DynamXInc/DynamX | 5,263 | src/main/java/fr/dynamx/common/slopes/PosRotator.java | package fr.dynamx.common.slopes;
import com.jme3.math.Vector3f;
import fr.dynamx.utils.optimization.Vector3fPool;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
public class PosRotator {
private final EnumFacing direction;
public PosRotator(EnumFacing direction) {
this.direction = direction;
}
public BlockPos.MutableBlockPos mute(int i, BlockPos.MutableBlockPos from) {
switch (direction) {
case NORTH:
from.setPos(from.getX(), from.getY(), from.getZ() - i);
break;
case SOUTH:
from.setPos(from.getX(), from.getY(), from.getZ() + i);
break;
case EAST:
from.setPos(from.getX() + i, from.getY(), from.getZ());
break;
case WEST:
from.setPos(from.getX() - i, from.getY(), from.getZ());
break;
}
return from;
}
public BlockPos mute(int i, int x, int y, int z) {
switch (direction) {
case NORTH:
return new BlockPos(x, y, z - i);
case SOUTH:
return new BlockPos(x, y, z + i);
case EAST:
return new BlockPos(x + i, y, z);
case WEST:
return new BlockPos(x - i, y, z);
}
return new BlockPos(x, y, z);
}
public Vector3f mute(int i, int x, float y, int z) {
switch (direction) {
case NORTH:
return Vector3fPool.get(x, y, z - i);
case SOUTH:
return Vector3fPool.get(x, y, z + i);
case EAST:
return Vector3fPool.get(x + i, y, z);
case WEST:
return Vector3fPool.get(x - i, y, z);
}
return Vector3fPool.get(x, y, z);
}
public int getLittleX(int xstart, int xend) {
return direction.getAxis() == EnumFacing.Axis.X ? (direction.getAxisDirection() == EnumFacing.AxisDirection.NEGATIVE ? Math.max(xstart, xend) : Math.min(xstart, xend)) : Math.min(xstart, xend);
}
public int getLittleZ(int zstart, int zend) {
return direction.getAxis() == EnumFacing.Axis.Z ? (direction.getAxisDirection() == EnumFacing.AxisDirection.NEGATIVE ? Math.max(zstart, zend) : Math.min(zstart, zend)) : Math.min(zstart, zend);
}
public int getBigX(int xstart, int xend) {
return direction.getAxis() == EnumFacing.Axis.X ? (direction.getAxisDirection() == EnumFacing.AxisDirection.NEGATIVE ? Math.min(xstart, xend) : Math.max(xstart, xend)) : Math.max(xstart, xend);
}
public int getBigZ(int zstart, int zend) {
return direction.getAxis() == EnumFacing.Axis.Z ? (direction.getAxisDirection() == EnumFacing.AxisDirection.NEGATIVE ? Math.min(zstart, zend) : Math.max(zstart, zend)) : Math.max(zstart, zend);
}
/*public boolean lessOrEqualsX(int x1, int x2, int z1, int z2) {
switch (direction)
{
case NORTH:
return z1 >= z2;
case SOUTH:
return z1 <= z2;
case WEST:
return x1 >= x2;
case EAST:
return x1 <= x2;
}
return false;
}
public boolean lessOrEqualsZ(int x1, int x2, int z1, int z2) {
return lessOrEqualsX(z1, z2, x1, x2);
}*/
public int getTheDir(BlockPos from) {
switch (direction) {
case NORTH:
case SOUTH:
return from.getZ();
}
return from.getX();
}
public int getTheDir(Vector3f from) {
switch (direction) {
case NORTH:
case SOUTH:
return (int) from.z;
}
return (int) from.x;
}
public int getTheOtherDir(BlockPos from) {
switch (direction) {
case NORTH:
case SOUTH:
return from.getX();
}
return from.getZ();
}
public float getTheOtherDir(Vector3f from) {
switch (direction) {
case NORTH:
case SOUTH:
return from.x;
}
return from.z;
}
public BlockPos setTheOtherDir(BlockPos in, int value) {
switch (direction) {
case NORTH:
case SOUTH:
return new BlockPos(value, in.getY(), in.getZ());
}
return new BlockPos(in.getX(), in.getY(), value);
}
/*public int getZ(BlockPos from) {
switch (direction)
{
case NORTH:
case SOUTH:
return from.getX();
}
return from.getZ();
}*/
/*public int followDir(int from) {
if(direction.getAxisDirection() == EnumFacing.AxisDirection.NEGATIVE)
return from-1;
return from+1;
}*/
public int fixBorderX(int x) {
return direction == EnumFacing.WEST ? x + 1 : x;
}
public int fixBorderZ(int z) {
return direction == EnumFacing.NORTH ? z + 1 : z;
}
public int counterFixBorderX(int x) {
return direction == EnumFacing.WEST ? x - 1 : x;
}
public int counterFixBorderZ(int z) {
return direction == EnumFacing.NORTH ? z - 1 : z;
}
}
| 0 | 0.907377 | 1 | 0.907377 | game-dev | MEDIA | 0.490791 | game-dev,graphics-rendering | 0.989619 | 1 | 0.989619 |
b1inkie/dst-api | 5,748 | scripts_619045/prefabs/tacklestation.lua | local assets =
{
Asset("ANIM", "anim/tackle_station.zip"),
Asset("SOUND", "sound/together.fsb"),
}
local prefabs =
{
"tacklesketch",
"small_puff",
}
local sounds =
{
onbuilt = "hookline/common/tackle_station/place",
idle = "hookline/common/tackle_station/proximity_LP",
learn = "hookline/common/tackle_station/recieive_item",
use = "hookline/common/tackle_station/use",
}
local function DropTackleSketches(inst)
for i,k in ipairs(inst.components.craftingstation:GetItems()) do
inst.components.lootdropper:SpawnLootPrefab(k)
end
end
local function onbuilt(inst)
inst.AnimState:PlayAnimation("place")
inst.AnimState:PushAnimation("idle")
inst.SoundEmitter:PlaySound(sounds.onbuilt)
end
local function onhammered(inst, worker)
inst.components.lootdropper:DropLoot()
DropTackleSketches(inst)
local fx = SpawnPrefab("collapse_small")
fx.Transform:SetPosition(inst.Transform:GetWorldPosition())
fx:SetMaterial("metal")
inst:Remove()
end
local function onhit(inst)
if not inst:HasTag("burnt") then
inst.AnimState:PlayAnimation("hit")
if inst.components.prototyper.on then
inst.AnimState:PushAnimation("proximity_loop", true)
else
inst.AnimState:PushAnimation("idle", false)
end
end
end
local function onturnon(inst)
if inst._activetask == nil then
inst:PushEvent("onturnon")
inst.AnimState:PushAnimation("proximity_loop", true)
if not inst.SoundEmitter:PlayingSound("idlesound") then
inst.SoundEmitter:PlaySound(sounds.idle, "idlesound")
end
end
end
local function onturnoff(inst)
if inst._activetask == nil then
inst:PushEvent("onturnoff")
inst.AnimState:PlayAnimation("idle", false)
inst.SoundEmitter:KillSound("idlesound")
end
end
local function doneact(inst)
inst._activetask = nil
if inst.components.prototyper.on then
inst.AnimState:PlayAnimation("proximity_loop", true)
if not inst.SoundEmitter:PlayingSound("idlesound") then
inst.SoundEmitter:PlaySound(sounds.idle, "idlesound")
end
else
inst.AnimState:PushAnimation("idle")
inst.SoundEmitter:KillSound("idlesound")
end
end
local function onuse(inst, hasfx)
inst.AnimState:PlayAnimation("use")
inst.SoundEmitter:PlaySound(sounds.use)
if inst._activetask ~= nil then
inst._activetask:Cancel()
end
inst._activetask = inst:DoTaskInTime(inst.AnimState:GetCurrentAnimationLength(), doneact)
end
local function onactivate(inst)
onuse(inst, true)
end
local function onlearnednewtacklesketch(inst)
inst.AnimState:PlayAnimation("receive_item")
inst.SoundEmitter:PlaySound(sounds.learn)
if inst.components.prototyper.on then
inst.AnimState:PushAnimation("proximity_loop", true)
else
inst.AnimState:PushAnimation("idle", false)
end
end
local function OnHaunt(inst, haunter)
if not inst:HasTag("burnt") and inst.components.prototyper.on then
onuse(inst, false)
else
Launch(inst, haunter, TUNING.LAUNCH_SPEED_SMALL)
end
inst.components.hauntable.hauntvalue = TUNING.HAUNT_TINY
return true
end
local function onburnt(inst)
DropTackleSketches(inst)
inst.components.craftingstation:ForgetAllItems()
DefaultBurntStructureFn(inst)
end
local function onsave(inst, data)
if inst.components.burnable ~= nil and inst.components.burnable:IsBurning() or inst:HasTag("burnt") then
data.burnt = true
end
end
local function onload(inst, data)
if data ~= nil and data.burnt and inst.components.burnable ~= nil then
inst.components.burnable.onburnt(inst)
end
end
local function fn()
local inst = CreateEntity()
inst.entity:AddTransform()
inst.entity:AddAnimState()
inst.entity:AddMiniMapEntity()
inst.entity:AddSoundEmitter()
inst.entity:AddNetwork()
inst:SetDeploySmartRadius(1) --recipe min_spacing/2
MakeObstaclePhysics(inst, .4)
inst.MiniMapEntity:SetPriority(5)
inst.MiniMapEntity:SetIcon("tacklestation.png")
inst.AnimState:SetBank("tackle_station")
inst.AnimState:SetBuild("tackle_station")
inst.AnimState:PlayAnimation("idle")
--prototyper (from prototyper component) added to pristine state for optimization
inst:AddTag("prototyper")
inst:AddTag("structure")
inst:AddTag("tacklestation")
inst.entity:SetPristine()
if not TheWorld.ismastersim then
return inst
end
inst._activetask = nil
inst._soundtasks = {}
inst:AddComponent("inspectable")
inst:AddComponent("lootdropper")
inst:AddComponent("workable")
inst.components.workable:SetWorkAction(ACTIONS.HAMMER)
inst.components.workable:SetWorkLeft(4)
inst.components.workable:SetOnFinishCallback(onhammered)
inst.components.workable:SetOnWorkCallback(onhit)
inst:AddComponent("craftingstation")
inst:AddComponent("prototyper")
inst.components.prototyper.onturnon = onturnon
inst.components.prototyper.onturnoff = onturnoff
inst.components.prototyper.onactivate = onactivate
inst.components.prototyper.trees = TUNING.PROTOTYPER_TREES.FISHING
MakeLargeBurnable(inst, nil, nil, true)
inst.components.burnable:SetOnBurntFn(onburnt)
MakeLargePropagator(inst)
inst:AddComponent("hauntable")
inst.components.hauntable.cooldown = TUNING.HAUNT_COOLDOWN_SMALL
inst.components.hauntable:SetOnHauntFn(OnHaunt)
inst:ListenForEvent("onlearnednewtacklesketch", onlearnednewtacklesketch)
inst:ListenForEvent("onbuilt", onbuilt)
inst.OnSave = onsave
inst.OnLoad = onload
return inst
end
return Prefab("tacklestation", fn, assets, prefabs),
MakePlacer("tacklestation_placer", "tackle_station", "tackle_station", "idle")
| 0 | 0.769197 | 1 | 0.769197 | game-dev | MEDIA | 0.977563 | game-dev | 0.890945 | 1 | 0.890945 |
ChaoticOnyx/OnyxBay | 2,209 | code/modules/ai/ai_behavior.dm | ///Abstract class for an action an AI can take, can range from movement to grabbing a nearby weapon.
/datum/ai_behavior
///What distance you need to be from the target to perform the action
var/required_distance = 1
///Flags for extra behavior
var/behavior_flags = 0
///Cooldown between actions performances, defaults to the value of CLICK_CD_MELEE because that seemed like a nice standard for the speed of AI behavior
///Do not read directly or mutate, instead use get_cooldown()
var/action_cooldown = DEFAULT_QUICK_COOLDOWN
/// Returns the delay to use for this behavior in the moment
/// Override to return a conditional delay
/datum/ai_behavior/proc/get_cooldown(datum/ai_controller/cooldown_for)
return action_cooldown
/// Called by the ai controller when first being added. Additional arguments depend on the behavior type.
/// Return FALSE to cancel
/datum/ai_behavior/proc/setup(datum/ai_controller/controller, ...)
return TRUE
///Called by the AI controller when this action is performed
///Returns a set of flags defined in [code/__DEFINES/ai/ai.dm]
/datum/ai_behavior/proc/perform(seconds_per_tick, datum/ai_controller/controller, ...)
return
///Called when the action is finished. This needs the same args as perform besides the default ones
/datum/ai_behavior/proc/finish_action(datum/ai_controller/controller, succeeded, ...)
LAZYREMOVE(controller.current_behaviors, src)
controller.behavior_args -= type
if(!(behavior_flags & AI_BEHAVIOR_REQUIRE_MOVEMENT)) //If this was a movement task, reset our movement target if necessary
return
if(behavior_flags & AI_BEHAVIOR_KEEP_MOVE_TARGET_ON_FINISH)
return
clear_movement_target(controller)
//controller.ai_movement.stop_moving_towards(controller)
/// Helper proc to ensure consistency in setting the source of the movement target
/datum/ai_behavior/proc/set_movement_target(datum/ai_controller/controller, atom/target)
controller.set_movement_target(type, target)
/// Clear the controller's movement target only if it was us who last set it
/datum/ai_behavior/proc/clear_movement_target(datum/ai_controller/controller)
if (controller.movement_target_source != type)
return
controller.set_movement_target(type, null)
| 0 | 0.962518 | 1 | 0.962518 | game-dev | MEDIA | 0.754983 | game-dev | 0.84493 | 1 | 0.84493 |
apache/felix-dev | 5,961 | eventadmin/impl/src/main/java/org/apache/felix/eventadmin/impl/util/Matchers.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.felix.eventadmin.impl.util;
import java.util.ArrayList;
import java.util.List;
public abstract class Matchers {
private static final char SEP_TOPIC = '/';
private static final char SEP_PCK = '.';
public static Matcher[] createEventTopicMatchers(final String[] config)
{
final Matcher[] matchers;
if ( config == null || config.length == 0 )
{
matchers = null;
}
else
{
final List<Matcher> list = new ArrayList<>();
for(int i=0;i<config.length;i++)
{
String value = config[i];
if ( value != null )
{
value = value.trim();
}
if ( value != null && value.length() > 0 )
{
if ( value.endsWith(".") )
{
list.add(new PackageMatcher(value.substring(0, value.length() - 1), SEP_TOPIC));
}
else if ( value.endsWith("*") )
{
if ( value.equals("*") )
{
return new Matcher[] {new MatcherAll()};
}
list.add(new SubPackageMatcher(value.substring(0, value.length() - 1), SEP_TOPIC));
}
else
{
list.add(new ClassMatcher(value));
}
}
}
if ( list.size() > 0 )
{
matchers = list.toArray(new Matcher[list.size()]);
}
else
{
matchers = null;
}
}
return matchers;
}
public static Matcher[] createPackageMatchers(final String[] ignoreTimeout)
{
final Matchers.Matcher[] ignoreTimeoutMatcher;
if ( ignoreTimeout == null || ignoreTimeout.length == 0 )
{
ignoreTimeoutMatcher = null;
}
else
{
ignoreTimeoutMatcher = new Matchers.Matcher[ignoreTimeout.length];
for(int i=0;i<ignoreTimeout.length;i++)
{
String value = ignoreTimeout[i];
if ( value != null )
{
value = value.trim();
}
if ( value != null && value.length() > 0 )
{
if ( value.endsWith(".") )
{
ignoreTimeoutMatcher[i] = new PackageMatcher(value.substring(0, value.length() - 1), SEP_PCK);
}
else if ( value.endsWith("*") )
{
ignoreTimeoutMatcher[i] = new SubPackageMatcher(value.substring(0, value.length() - 1), SEP_PCK);
}
else
{
ignoreTimeoutMatcher[i] = new ClassMatcher(value);
}
}
}
}
return ignoreTimeoutMatcher;
}
/**
* The matcher interface for checking if timeout handling
* is disabled for the handler.
* Matching is based on the class name of the event handler.
*/
public interface Matcher
{
boolean match(String className);
}
/** Match all. */
private static final class MatcherAll implements Matcher
{
@Override
public boolean match(final String className)
{
return true;
}
}
/** Match a package. */
private static final class PackageMatcher implements Matcher
{
private final String packageName;
private final char sep;
public PackageMatcher(final String name, final char sep)
{
this.packageName = name;
this.sep = sep;
}
@Override
public boolean match(final String className)
{
final int pos = className.lastIndexOf(sep);
return pos > -1 && className.substring(0, pos).equals(packageName);
}
}
/** Match a package or sub package. */
private static final class SubPackageMatcher implements Matcher
{
private final String packageName;
private final char sep;
public SubPackageMatcher(final String name, final char sep)
{
this.packageName = name + sep;
this.sep = sep;
}
@Override
public boolean match(final String className)
{
final int pos = className.lastIndexOf(sep);
return pos > -1 && className.substring(0, pos + 1).startsWith(packageName);
}
}
/** Match a class name. */
private static final class ClassMatcher implements Matcher
{
private final String m_className;
public ClassMatcher(final String name)
{
m_className = name;
}
@Override
public boolean match(final String className)
{
return m_className.equals(className);
}
}
}
| 0 | 0.921384 | 1 | 0.921384 | game-dev | MEDIA | 0.156873 | game-dev | 0.973489 | 1 | 0.973489 |
sebastian-heinz/Arrowgene.DragonsDogmaOnline | 1,960 | Arrowgene.Ddon.Shared/Entity/Structure/CDataClanShopFunctionItem.cs | using Arrowgene.Buffers;
using System.Collections.Generic;
namespace Arrowgene.Ddon.Shared.Entity.Structure
{
public class CDataClanShopFunctionItem
{
public CDataClanShopFunctionItem()
{
FunctionInfo = new();
RequireLineupId = new();
}
public uint LineupId { get; set; }
public uint RequireClanPoint { get; set; }
public byte RequireLevel { get; set; }
public uint IconID { get; set; }
public string Name { get; set; } = string.Empty;
public List<CDataClanShopFunctionInfo> FunctionInfo { get; set; }
public List<CDataCommonU32> RequireLineupId { get; set; }
public class Serializer : EntitySerializer<CDataClanShopFunctionItem>
{
public override void Write(IBuffer buffer, CDataClanShopFunctionItem obj)
{
WriteUInt32(buffer, obj.LineupId);
WriteUInt32(buffer, obj.RequireClanPoint);
WriteByte(buffer, obj.RequireLevel);
WriteUInt32(buffer, obj.IconID);
WriteMtString(buffer, obj.Name);
WriteEntityList<CDataClanShopFunctionInfo>(buffer, obj.FunctionInfo);
WriteEntityList<CDataCommonU32>(buffer, obj.RequireLineupId);
}
public override CDataClanShopFunctionItem Read(IBuffer buffer)
{
CDataClanShopFunctionItem obj = new CDataClanShopFunctionItem();
obj.LineupId = ReadUInt32(buffer);
obj.RequireClanPoint = ReadUInt32(buffer);
obj.RequireLevel = ReadByte(buffer);
obj.IconID = ReadUInt32(buffer);
obj.Name = ReadMtString(buffer);
obj.FunctionInfo = ReadEntityList<CDataClanShopFunctionInfo>(buffer);
obj.RequireLineupId = ReadEntityList<CDataCommonU32>(buffer);
return obj;
}
}
}
}
| 0 | 0.667678 | 1 | 0.667678 | game-dev | MEDIA | 0.111812 | game-dev | 0.543113 | 1 | 0.543113 |
LemLib/LemLib | 21,630 | include/hardware/Motor/MotorGroup.hpp | #pragma once
#include "pros/motor_group.hpp"
#include "hardware/Motor/Motor.hpp"
#include "hardware/Port.hpp"
#include "units/Angle.hpp"
#include <vector>
namespace lemlib {
/**
* @brief MotorGroup class
*
* This class is a handler for a group of lemlib::Motor objects, which themselves are wrappers for ther pros::Motor
* objects. This class allows for easy control of collection of telemetry, as inputs and outputs are unitized. This
* class also enables users to add and remove motors from the group, which is useful when a motor can be moved between
* subsystems using a Power Take Off (PTO) or similar mechanism.
*
* Error handling for the MotorGroup class is a bit different from other hardware classes. This is because
* the MotorGroup class represents a group of motors, any of which could fail. However, as long as one
* motor in the group is functioning properly, the MotorGroup will not throw any errors. In addition, errno will be set
* to whatever error was thrown last, as there may be multiple motors in a motor group.
*/
class MotorGroup : public Encoder {
public:
/**
* @brief Construct a new Motor Group
*
* @param ports list of ports of the motors in the group
* @param outputVelocity the theoretical maximum output velocity of the motor group, after gearing
*
* @b Example:
* @code {.cpp}
* void initialize() {
* // motor group with motors on ports 1, -2, and 3
* // max theoretical output is 360 rpm
* lemlib::MotorGroup motorGroup({1, -2, 3}, 360_rpm);
* }
* @endcode
*/
MotorGroup(std::initializer_list<ReversibleSmartPort> ports, AngularVelocity outputVelocity);
/**
* @brief Create a new Motor Group
*
* @param group the pros motor group to get the ports from
* @param outputVelocity the theoretical maximum output velocity of the motor group, after gearing
*
* @b Example:
* @code {.cpp}
* void initialize() {
* // pros motor group with motors on ports 1, -2, and 3
* pros::MotorGroup prosMotorGroup({1, -2, 3});
* // motor group that uses the same motors as the pros motor group
* // and spins at 600 rpm
* lemlib::MotorGroup motorGroup(prosMotorGroup, 600_rpm);
* }
* @endcode
*/
static MotorGroup from_pros_group(const pros::MotorGroup group, AngularVelocity outputVelocity);
/**
* @brief move the motors at a percent power from -1.0 to +1.0
*
* This function uses the following values of errno when an error state is reached:
*
* ENODEV: the port cannot be configured as a motor
*
* @param percent the power to move the motors at from -1.0 to +1.0
* @return 0 on success
* @return INT_MAX on failure, setting errno
*
* @b Example:
* @code {.cpp}
* void initialize() {
* lemlib::MotorGroup motorGroup({1, -2, 3}, 360_rpm);
*
* // move the motors forward at 50% power
* motorGroup.move(0.5);
* // move the motors backward at 50% power
* motorGroup.move(-0.5);
* // stop the motors
* motorGroup.move(0);
* }
* @endcode
*/
int move(Number percent);
/**
* @brief move the motors at a given angular velocity
*
* This function uses the following values of errno when an error state is reached:
*
* ENODEV: the port cannot be configured as a motor
*
* @param velocity the target angular velocity to move the motors at
* @return 0 on success
* @return INT_MAX on failure, setting errno
*
* @b Example:
* @code {.cpp}
* void initialize() {
* lemlib::MotorGroup motorGroup({1, -2, 3}, 360_rpm);
*
* // move the motors forward at 50 degrees per second
* motorGroup.moveVelocity(50_degps);
* // move the motors backward at 50 degrees per second
* motorGroup.moveVelocity(-50_degps);
* // stop the motors
* motorGroup.moveVelocity(0_degps);
* }
* @endcode
*/
int moveVelocity(AngularVelocity velocity);
/**
* @brief brake the motors
*
* This function uses the following values of errno when an error state is reached:
*
* ENODEV: the port cannot be configured as a motor
*
* This function will stop the motors using the set brake mode
*
* @return 0 on success
* @return INT_MAX on failure, setting errno
*
* @b Example:
* @code {.cpp}
* void initialize() {
* lemlib::MotorGroup motorGroup({1, -2, 3}, 360_rpm);
*
* // move the motors forward at 50% power
* motorGroup.move(0.5);
* // brake the motors
* motorGroup.brake();
* }
* @endcode
*/
int brake();
/**
* @brief set the brake mode of the motors
*
* @param mode the brake mode to set the motors to
* @return 0 on success
*
* @b Example:
* @code {.cpp}
* void initialize() {
* lemlib::MotorGroup motorGroup({1, -2, 3}, 360_rpm);
*
* // set the motors to brake when stopped
* motorGroup.setBrakeMode(lemlib::BrakeMode::BRAKE);
* // set the motors to coast when stopped
* motorGroup.setBrakeMode(lemlib::BrakeMode::COAST);
* // set the motors to hold when stopped
* motorGroup.setBrakeMode(lemlib::BrakeMode::HOLD);
* }
* @endcode
*/
int setBrakeMode(BrakeMode mode);
/**
* @brief get the brake mode of the motor group
*
* @return BrakeMode enum value of the brake mode
*
* @b Example:
* @code {.cpp}
* void initialize() {
* lemlib::MotorGroup motorGroup({1, -2, 3}, 360_rpm);
*
* const lemlib::BrakeMode mode = motorGroup.getBrakeMode();
* if (mode == lemlib::BrakeMode::BRAKE) {
* std::cout << "Brake mode is set to BRAKE!" << std::endl;
* } else if (mode == lemlib::BrakeMode::COAST) {
* std::cout << "Brake mode is set to COAST!" << std::endl;
* } else if (mode == lemlib::BrakeMode::HOLD) {
* std::cout << "Brake mode is set to HOLD!" << std::endl;
* } else {
* std::cout << "Error getting brake mode!" << std::endl;
* }
* }
* @endcode
*/
BrakeMode getBrakeMode();
/**
* @brief whether any of the motors in the motor group are connected
*
* @return 0 no motors are connected
* @return 1 if at least one motor is connected
*
* @b Example:
* @code {.cpp}
* void initialize() {
* lemlib::MotorGroup motorGroup({1, -2, 3}, 360_rpm);
*
* const int result = motorGroup.isConnected();
* if (result == 1) {
* std::cout << "Encoder is connected!" << std::endl;
* } else if (result == 0) {
* std::cout << "Encoder is not connected!" << std::endl;
* } else {
* std::cout << "Error checking if encoder is connected!" << std::endl;
* }
* }
* @endcode
*/
int isConnected() override;
/**
* @brief Get the average relative angle measured by the motors
*
* The relative angle measured by the encoder is the angle of the encoder relative to the last time the encoder
* was reset. As such, it is unbounded.
*
* This function uses the following values of errno when an error state is reached:
*
* ENODEV: the port cannot be configured as a motor
*
* @return Angle the relative angle measured by the encoder
* @return INFINITY if there is an error, setting errno
*
* @b Example:
* @code {.cpp}
* void initialize() {
* lemlib::MotorGroup motorGroup({1, -2, 3}, 360_rpm);
*
* const Angle angle = motorGroup.getAngle();
* if (angle == INFINITY) {
* std::cout << "Error getting relative angle!" << std::endl;
* } else {
* std::cout << "Relative angle: " << to_sDeg(angle) << std::endl;
* }
* }
* @endcode
*/
Angle getAngle() override;
/**
* @brief Set the relative angle of all the motors
*
* This function sets the relative angle of the encoder. The relative angle is the number of rotations the
* encoder has measured since the last reset. This function is non-blocking.
*
* This function uses the following values of errno when an error state is reached:
*
* ENODEV: the port cannot be configured as a motor
*
* @param angle the relative angle to set the measured angle to
* @return 0 on success
* @return INT_MAX on failure, setting errno
*
* @b Example:
* @code {.cpp}
* void initialize() {
* lemlib::MotorGroup motorGroup({1, -2, 3}, 360_rpm);
*
* if (motorGroup.setAngle(0_stDeg) == 0) {
* std::cout << "Relative angle set!" << std::endl;
* std::cout < "Relative angle: " << motorGroup.getAngle().convert(deg) << std::endl; // outputs 0
* } else {
* std::cout << "Error setting relative angle!" << std::endl;
* }
* }
* @endcode
*/
int setAngle(Angle angle) override;
/**
* @brief Get the combined current limit of all motors in the group
*
* This function uses the following values of errno when an error state is reached:
*
* TODO: see how overheating affects this value
*
* ENODEV: the port cannot be configured as a motor
*
* @return Current the combined current limit of the motor group
* @return INFINITY on failure, setting errno
*
* @b Example:
* @code {.cpp}
* void initialize() {
* lemlib::MotorGroup motorGroup({1, -2, 3}, 360_rpm);
*
* // output the current limit to the console
* Current limit = motorGroup.getCurrentLimit();
* if (units::to_amp(limit) == INFINITY) {
* std::cout << "Error getting motor group current limit" << std::endl;
* } else {
* std::cout << "Current Limit: " << units::to_amp(limit) << std::endl;
* }
* }
* @endcode
*/
Current getCurrentLimit();
/**
* @brief set the combined current limit of all motors in the group
*
* This function uses the following values of errno when an error state is reached:
*
* ENODEV: the port cannot be configured as a motor
*
* @param limit the maximum allowed current
* @return 0 on success
* @return INT_MAX on failure, setting errno
*
* @b Example:
* @code {.cpp}
* void initialize() {
* lemlib::MotorGroup motorGroup({1, -2, 3}, 360_rpm);
* // set the current limit to 6 amp
* // every motor in the group will have a current limit of 2 amp
* // making for a total current limit of 6 amp
* motorGroup.setCurrentLimit(6_amp);
* }
* @endcode
*/
int setCurrentLimit(Current limit);
/**
* @brief Get the temperatures of the motors in the motor group
*
* This function uses the following values of errno when an error state is reached:
*
* ENODEV: the port cannot be configured as a motor
*
* @return vector<Temperature> vector of the temperatures of the motors
* @return INFINITY on failure, setting errno
*
* @b Example:
* @code {.cpp}
* void initialize() {
* lemlib::MotorGroup motorGroup({1, -2, 3}, 360_rpm);
*
* // output motor temperatures to the console
* std::vector<Temperature> temperatures = motorGroup.getTemperatures();
* for (lemlib::Motor motor : motorGroup) {
* if (units::to_celsius(temperature) == INFINITY) {
* std::cout << "Error getting motor temperature" << std::endl;
* } else {
* std::cout << "Motor Temperature: " << units::to_celsius(motor.getTemperature()) << std::endl;
* }
* }
* }
* @endcode
*/
std::vector<Temperature> getTemperatures();
/**
* @brief set the output velocity of the motors
*
* @param outputVelocity the theoretical maximum output velocity of the motor group, after gearing, to set
* @return int 0 success
* @return INT_MAX error occurred, setting errno
*
* @b Example:
* @code {.cpp}
* void initialize() {
* lemlib::MotorGroup motorGroup({1, -2, 3}, 360_rpm);
* // set the output velocity to 450 rpm
* motorGroup.setOutputVelocity(450_rpm);
* }
* @endcode
*/
int setOutputVelocity(AngularVelocity outputVelocity);
/**
* @brief Get the number of connected motors in the group
*
* @return int the number of connected motors in the group
*
* @b Example:
* @code {.cpp}
* void initialize() {
* lemlib::MotorGroup motorGroup({1, -2, 3}, 360_rpm);
*
* std::cout << "Number of connected motors: " << motorGroup.getSize() << std::endl;
* }
* @endcode
*/
int getSize();
/**
* @brief Add a motor to the motor group
*
* This function adds a motor to the motor group. If successful, it will set the angle measured by the motor to
* the average angle measured by the motor group. It will also set the brake mode of the motor to that of the
* first working motor in the group. If there are any errors, the motor will still be added to the group and it
* will be configured as soon as it is functional again.
*
* This function uses the following values of errno when an error state is reached:
*
* ENODEV: the port cannot be configured as a motor
*
* @param port the signed port of the motor to be added to the group. Negative ports indicate the motor should
* be reversed
*
* @return 0 on success
* @return INT_MAX on failure, setting errno
*
* @b Example:
* @code {.cpp}
* void initialize() {
* lemlib::MotorGroup motorGroup({1, -2, 3}, 360_rpm);
*
* // add a motor to the group
* motorGroup.addMotor(4);
* }
* @endcode
*/
int addMotor(ReversibleSmartPort port);
/**
* @brief Add a motor to the motor group
*
* This function adds a motor to the motor group. If successful, it will set the angle measured by the motor to
* the average angle measured by the motor group. It will also set the brake mode of the motor to that of the
* first working motor in the group. If there are any errors, the motor will still be added to the group and it
* will be configured as soon as it is functional again.
*
* @param motor the motor to be added to the group
*
* @return 0 on success
* @return INT_MAX on failure, setting errno
*
* @b Example:
* @code {.cpp}
* void initialize() {
* lemlib::MotorGroup motorGroup({1, -2, 3}, 360_rpm);
*
* // add a motor to the group
* pros::Motor motor4(4, pros::v5::MotorGears::green);
* motorGroup.addMotor(motor4);
* }
* @endcode
*/
int addMotor(Motor motor);
/**
* @brief Add a motor to the motor group
*
* This function adds a motor to the motor group. If successful, it will set the angle measured by the motor to
* the average angle measured by the motor group. It will also set the brake mode of the motor to that of the
* first working motor in the group. If there are any errors, the motor will still be added to the group and it
* will be configured as soon as it is functional again.
*
* @param motor the motor to be added to the group
* @param reversed whether the motor should be reversed
*
* @return 0 on success
* @return INT_MAX on failure, setting errno
*
* @b Example:
* @code {.cpp}
* void initialize() {
* lemlib::MotorGroup motorGroup({1, -2, 3}, 360_rpm);
*
* // add a motor to the group, which should be reversed
* pros::Motor motor4(4, pros::v5::MotorGears::green);
* motorGroup.addMotor(motor4, true);
* }
* @endcode
*/
int addMotor(Motor motor, bool reversed);
/**
* @brief Remove a motor from the motor group
*
* @param port the port of the motor to be removed from the group
*
* @b Example:
* @code {.cpp}
* void initialize() {
* lemlib::MotorGroup motorGroup({1, -2, 3}, 360_rpm);
*
* // remove a motor from the group
* motorGroup.removeMotor(4);
* }
* @endcode
*/
void removeMotor(ReversibleSmartPort port);
/**
* @brief Remove a motor from the motor group
*
* @param motor the motor to be removed from the group
*
* @b Example:
* @code {.cpp}
* void initialize() {
* lemlib::MotorGroup motorGroup({1, -2, 3}, 360_rpm);
*
* // remove a motor from the group
* pros::Motor motor4(4, pros::v5::MotorGears::green);
* motorGroup.removeMotor(motor4);
* }
* @endcode
*/
void removeMotor(Motor motor);
private:
struct MotorInfo {
ReversibleSmartPort port;
bool connectedLastCycle;
Angle offset;
};
/**
* @brief Configure a motor so its ready to join the motor group, and return its offset
*
* Motors may be added to the motor group or reconnect to the motor group during runtime. When this happens,
* functions like getAngle() would break as the motor is not configured like other motors in the group. This
* function sets the angle measured by the specified motor to the average angle measured by the group. It also
* sets the brake mode of the motor to be the same as the first working motor in the group.
*
* This function uses the following values of errno when an error state is reached:
*
* ENODEV: the port cannot be configured as a motor
*
* @param port the port of the motor to configure
*
* @return 0 on success
* @return INT_MAX on failure, setting errno
*/
Angle configureMotor(ReversibleSmartPort port);
BrakeMode m_brakeMode = BrakeMode::COAST;
/**
* @brief Get motors in the motor group as a vector of lemlib::Motor objects
*
* This function exists to simplify logic in the MotorGroup source code.
*
* @return const std::vector<Motor> vector of lemlib::Motor objects
*/
const std::vector<Motor> getMotors();
AngularVelocity m_outputVelocity;
/**
* This member variable is a vector of motor information
*
* Ideally, we'd use a vector of lemlib::Motor objects, but this does not work if you want to remove an element
* from the vector as the copy constructor is implicitly deleted.
*
* The ports are signed to indicate whether a motor should be reversed or not.
*
* It also has a bool for every port, which represents whether the motor was connected or not the last time
* `getAngle` was called. This enables the motor group to properly handle a motor reconnect.
*
* It also contains the offset of each motor. This needs to be saved by the motor group, because it can't be
* saved in a motor object, as motor objects are not saved as member variables
*/
std::vector<MotorInfo> m_motors;
};
}; // namespace lemlib
| 0 | 0.947596 | 1 | 0.947596 | game-dev | MEDIA | 0.488236 | game-dev | 0.901778 | 1 | 0.901778 |
penguinsword/foundation | 9,577 | Runtime/OdinSerializer/Utilities/Extensions/GarbageFreeIterators.cs | //-----------------------------------------------------------------------
// <copyright file="GarbageFreeIterators.cs" company="Sirenix IVS">
// Copyright (c) 2018 Sirenix IVS
//
// 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.
// </copyright>
//-----------------------------------------------------------------------
namespace Pancake.OdinSerializer.Utilities
{
using System;
using System.Collections.Generic;
/// <summary>
/// Garbage free enumerator methods.
/// </summary>
public static class GarbageFreeIterators
{
/// <summary>
/// Garbage free enumerator for lists.
/// </summary>
public static ListIterator<T> GFIterator<T>(this List<T> list)
{
return new ListIterator<T>(list);
}
/// <summary>
/// Garbage free enumerator for dictionaries.
/// </summary>
public static DictionaryIterator<T1, T2> GFIterator<T1, T2>(this Dictionary<T1, T2> dictionary)
{
return new DictionaryIterator<T1, T2>(dictionary);
}
/// <summary>
/// Garbage free enumator for dictionary values.
/// </summary>
public static DictionaryValueIterator<T1, T2> GFValueIterator<T1, T2>(this Dictionary<T1, T2> dictionary)
{
return new DictionaryValueIterator<T1, T2>(dictionary);
}
/// <summary>
/// Garbage free enumerator for hashsets.
/// </summary>
public static HashsetIterator<T> GFIterator<T>(this HashSet<T> hashset)
{
return new HashsetIterator<T>(hashset);
}
/// <summary>
/// List iterator.
/// </summary>
public struct ListIterator<T> : IDisposable
{
private bool isNull;
private List<T> list;
private List<T>.Enumerator enumerator;
/// <summary>
/// Creates a list iterator.
/// </summary>
public ListIterator(List<T> list)
{
this.isNull = list == null;
if (this.isNull)
{
this.list = null;
this.enumerator = new List<T>.Enumerator();
}
else
{
this.list = list;
this.enumerator = this.list.GetEnumerator();
}
}
/// <summary>
/// Gets the enumerator.
/// </summary>
public ListIterator<T> GetEnumerator()
{
return this;
}
/// <summary>
/// Gets the current value.
/// </summary>
public T Current
{
get
{
return this.enumerator.Current;
}
}
/// <summary>
/// Moves to the next value.
/// </summary>
public bool MoveNext()
{
if (this.isNull)
{
return false;
}
return this.enumerator.MoveNext();
}
/// <summary>
/// Disposes the iterator.
/// </summary>
public void Dispose()
{
this.enumerator.Dispose();
}
}
/// <summary>
/// Hashset iterator.
/// </summary>
public struct HashsetIterator<T> : IDisposable
{
private bool isNull;
private HashSet<T> hashset;
private HashSet<T>.Enumerator enumerator;
/// <summary>
/// Creates a hashset iterator.
/// </summary>
public HashsetIterator(HashSet<T> hashset)
{
this.isNull = hashset == null;
if (this.isNull)
{
this.hashset = null;
this.enumerator = new HashSet<T>.Enumerator();
}
else
{
this.hashset = hashset;
this.enumerator = this.hashset.GetEnumerator();
}
}
/// <summary>
/// Gets the enumerator.
/// </summary>
public HashsetIterator<T> GetEnumerator()
{
return this;
}
/// <summary>
/// Gets the current value.
/// </summary>
public T Current
{
get
{
return this.enumerator.Current;
}
}
/// <summary>
/// Moves to the next value.
/// </summary>
public bool MoveNext()
{
if (this.isNull)
{
return false;
}
return this.enumerator.MoveNext();
}
/// <summary>
/// Disposes the iterator.
/// </summary>
public void Dispose()
{
this.enumerator.Dispose();
}
}
/// <summary>
/// Dictionary iterator.
/// </summary>
public struct DictionaryIterator<T1, T2> : IDisposable
{
private Dictionary<T1, T2> dictionary;
private Dictionary<T1, T2>.Enumerator enumerator;
private bool isNull;
/// <summary>
/// Creates a dictionary iterator.
/// </summary>
public DictionaryIterator(Dictionary<T1, T2> dictionary)
{
this.isNull = dictionary == null;
if (this.isNull)
{
this.dictionary = null;
this.enumerator = new Dictionary<T1, T2>.Enumerator();
}
else
{
this.dictionary = dictionary;
this.enumerator = this.dictionary.GetEnumerator();
}
}
/// <summary>
/// Gets the enumerator.
/// </summary>
public DictionaryIterator<T1, T2> GetEnumerator()
{
return this;
}
/// <summary>
/// Gets the current value.
/// </summary>
public KeyValuePair<T1, T2> Current
{
get
{
return this.enumerator.Current;
}
}
/// <summary>
/// Moves to the next value.
/// </summary>
public bool MoveNext()
{
if (this.isNull)
{
return false;
}
return this.enumerator.MoveNext();
}
/// <summary>
/// Disposes the iterator.
/// </summary>
public void Dispose()
{
this.enumerator.Dispose();
}
}
/// <summary>
/// Dictionary value iterator.
/// </summary>
public struct DictionaryValueIterator<T1, T2> : IDisposable
{
private Dictionary<T1, T2> dictionary;
private Dictionary<T1, T2>.Enumerator enumerator;
private bool isNull;
/// <summary>
/// Creates a dictionary value iterator.
/// </summary>
public DictionaryValueIterator(Dictionary<T1, T2> dictionary)
{
this.isNull = dictionary == null;
if (this.isNull)
{
this.dictionary = null;
this.enumerator = new Dictionary<T1, T2>.Enumerator();
}
else
{
this.dictionary = dictionary;
this.enumerator = this.dictionary.GetEnumerator();
}
}
/// <summary>
/// Gets the enumerator.
/// </summary>
public DictionaryValueIterator<T1, T2> GetEnumerator()
{
return this;
}
/// <summary>
/// Gets the current value.
/// </summary>
public T2 Current
{
get
{
return this.enumerator.Current.Value;
}
}
/// <summary>
/// Moves to the next value.
/// </summary>
public bool MoveNext()
{
if (this.isNull)
{
return false;
}
return this.enumerator.MoveNext();
}
/// <summary>
/// Disposes the iterator.
/// </summary>
public void Dispose()
{
this.enumerator.Dispose();
}
}
}
} | 0 | 0.865544 | 1 | 0.865544 | game-dev | MEDIA | 0.465417 | game-dev | 0.922144 | 1 | 0.922144 |
rmusser01/tldw_chatbook | 4,137 | tldw_chatbook/Utils/Splash_Screens/environmental/ascii_fire.py | """ASCIIFire splash screen effect."""
import time
from rich.color import Color
import random
from typing import Optional, Any, List, Tuple
from ..base_effect import BaseEffect, register_effect
@register_effect("ascii_fire")
class ASCIIFireEffect(BaseEffect):
"""Realistic fire animation using ASCII characters."""
def __init__(self, parent, title="TLDW Chatbook", width=80, height=24, speed=0.05, **kwargs):
super().__init__(parent, width=width, height=height, speed=speed)
self.width = width
self.height = height
self.speed = speed
self.title = title
self.fire_chars = [' ', '.', ':', '^', '*', '†', '‡', '¥', '§']
self.fire_grid = [[0 for _ in range(width)] for _ in range(height)]
self.embers = []
def update(self) -> Optional[str]:
"""Update fire animation."""
elapsed_time = time.time() - self.start_time
# Add new fire at bottom
for x in range(self.width):
if random.random() < 0.8:
intensity = random.randint(6, 8)
self.fire_grid[self.height - 1][x] = intensity
# Propagate fire upwards
new_grid = [[0 for _ in range(self.width)] for _ in range(self.height)]
for y in range(self.height - 1):
for x in range(self.width):
# Get fire from below with some spreading
below = self.fire_grid[y + 1][x]
left = self.fire_grid[y + 1][x - 1] if x > 0 else 0
right = self.fire_grid[y + 1][x + 1] if x < self.width - 1 else 0
# Average with decay
avg = (below * 0.97 + left * 0.01 + right * 0.01)
new_grid[y][x] = max(0, avg - random.uniform(0, 0.5))
# Copy bottom row
new_grid[self.height - 1] = self.fire_grid[self.height - 1][:]
self.fire_grid = new_grid
# Create embers
if random.random() < 0.1:
self.embers.append({
'x': random.randint(self.width // 3, 2 * self.width // 3),
'y': self.height - 5,
'vy': -random.uniform(0.5, 1.5),
'life': 1.0
})
# Update embers
for ember in self.embers[:]:
ember['y'] += ember['vy']
ember['vy'] += 0.1 # Gravity
ember['life'] -= elapsed_time * 0.5
if ember['life'] <= 0 or ember['y'] >= self.height:
self.embers.remove(ember)
# Return the rendered content
return self.render()
def render(self):
"""Render fire effect."""
grid = [[' ' for _ in range(self.width)] for _ in range(self.height)]
style_grid = [[None for _ in range(self.width)] for _ in range(self.height)]
# Draw fire
for y in range(self.height):
for x in range(self.width):
intensity = self.fire_grid[y][x]
if intensity > 0:
char_index = min(int(intensity), len(self.fire_chars) - 1)
grid[y][x] = self.fire_chars[char_index]
# Color based on intensity
if intensity > 6:
style_grid[y][x] = 'bold white'
elif intensity > 4:
style_grid[y][x] = 'bold yellow'
elif intensity > 2:
style_grid[y][x] = 'red'
else:
style_grid[y][x] = 'dim red'
# Draw embers
for ember in self.embers:
x, y = int(ember['x']), int(ember['y'])
if 0 <= x < self.width and 0 <= y < self.height:
grid[y][x] = '°'
style_grid[y][x] = 'yellow' if ember['life'] > 0.5 else 'dim red'
# Add title in the flames
title_y = self.height // 3
self._add_centered_text(grid, style_grid, self.title, title_y, 'bold white on red')
return self._grid_to_string(grid, style_grid) | 0 | 0.816177 | 1 | 0.816177 | game-dev | MEDIA | 0.480165 | game-dev | 0.800351 | 1 | 0.800351 |
MonoGame/MonoGame.Templates | 11,041 | CSharp/content/MonoGame.2D.StartKit.CSharp/___SafeGameName___.Core/Screens/GameScreen.cs | using System;
using ___SafeGameName___.Core.Inputs;
using ___SafeGameName___.ScreenManagers;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input.Touch;
namespace ___SafeGameName___.Screens;
/// <summary>
/// A screen is a single layer that has update and draw logic, and which
/// can be combined with other layers to build up a complex menu system.
/// For instance the main menu, the options menu, the "are you sure you
/// want to quit" message box, and the main game itself are all implemented
/// as screens.
/// </summary>
public abstract class GameScreen
{
private bool isPopup = false;
/// <summary>
/// Normally when one screen is brought up over the top of another,
/// the first screen will transition off to make room for the new
/// one. This property indicates whether the screen is only a small
/// popup, in which case screens underneath it do not need to bother
/// transitioning off.
/// </summary>
public bool IsPopup
{
get { return isPopup; }
protected set { isPopup = value; }
}
private TimeSpan transitionOnTime = TimeSpan.Zero;
/// <summary>
/// Indicates how long the screen takes to
/// transition on when it is activated.
/// </summary>
public TimeSpan TransitionOnTime
{
get { return transitionOnTime; }
protected set { transitionOnTime = value; }
}
private TimeSpan transitionOffTime = TimeSpan.Zero;
/// <summary>
/// Indicates how long the screen takes to
/// transition off when it is deactivated.
/// </summary>
public TimeSpan TransitionOffTime
{
get { return transitionOffTime; }
protected set { transitionOffTime = value; }
}
private float transitionPosition = 1;
/// <summary>
/// Gets the current position of the screen transition, ranging
/// from zero (fully active, no transition) to one (transitioned
/// fully off to nothing).
/// </summary>
public float TransitionPosition
{
get { return transitionPosition; }
protected set { transitionPosition = value; }
}
/// <summary>
/// Gets the current alpha of the screen transition, ranging
/// from 1 (fully active, no transition) to 0 (transitioned
/// fully off to nothing).
/// </summary>
public float TransitionAlpha
{
get { return 1f - TransitionPosition; }
}
private ScreenState screenState = ScreenState.TransitionOn;
/// <summary>
/// Gets the current screen transition state.
/// </summary>
public ScreenState ScreenState
{
get { return screenState; }
protected set { screenState = value; }
}
private bool isExiting = false;
/// <summary>
/// There are two possible reasons why a screen might be transitioning
/// off. It could be temporarily going away to make room for another
/// screen that is on top of it, or it could be going away for good.
/// This property indicates whether the screen is exiting for real:
/// if set, the screen will automatically remove itself as soon as the
/// transition finishes.
/// </summary>
public bool IsExiting
{
get { return isExiting; }
protected internal set { isExiting = value; }
}
private bool otherScreenHasFocus;
/// <summary>
/// Checks whether this screen is active and can respond to user input.
/// </summary>
public bool IsActive
{
get
{
return !otherScreenHasFocus &&
(screenState == ScreenState.TransitionOn ||
screenState == ScreenState.Active);
}
}
private ScreenManager screenManager;
/// <summary>
/// Gets the manager that this screen belongs to.
/// </summary>
public ScreenManager ScreenManager
{
get { return screenManager; }
internal set { screenManager = value; }
}
private PlayerIndex? controllingPlayer;
/// <summary>
/// Gets the index of the player who is currently controlling this screen,
/// or null if it is accepting input from any player. This is used to lock
/// the game to a specific player profile. The main menu responds to input
/// from any connected gamepad, but whichever player makes a selection from
/// this menu is given control over all subsequent screens, so other gamepads
/// are inactive until the controlling player returns to the main menu.
/// </summary>
public PlayerIndex? ControllingPlayer
{
get { return controllingPlayer; }
internal set { controllingPlayer = value; }
}
private GestureType enabledGestures = GestureType.None;
/// <summary>
/// Gets the gestures the screen is interested in. Screens should be as specific
/// as possible with gestures to increase the accuracy of the gesture engine.
/// For example, most menus only need Tap or perhaps Tap and VerticalDrag to operate.
/// These gestures are handled by the ScreenManager when screens change and
/// all gestures are placed in the InputState passed to the HandleInput method.
/// </summary>
public GestureType EnabledGestures
{
get { return enabledGestures; }
protected set
{
enabledGestures = value;
// the screen manager handles this during screen changes, but
// if this screen is active and the gesture types are changing,
// we have to update the TouchPanel ourself.
if (ScreenState == ScreenState.Active)
{
TouchPanel.EnabledGestures = value;
}
}
}
/// <summary>
/// Load graphics content for the screen, but 1st scale the presentation area.
/// </summary>
public virtual void LoadContent()
{
ScreenManager.ScalePresentationArea();
}
/// <summary>
/// Unload content for the screen.
/// </summary>
public virtual void UnloadContent() { }
/// <summary>
/// Allows the screen to run logic, such as updating the transition position.
/// Unlike HandleInput, this method is called regardless of whether the screen
/// is active, hidden, or in the middle of a transition.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
/// <param name="otherScreenHasFocus">Indicates whether another screen has focus.</param>
/// <param name="coveredByOtherScreen">Indicates whether the screen is covered by another screen.</param>
public virtual void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen)
{
// Stores whether another screen has focus.
this.otherScreenHasFocus = otherScreenHasFocus;
if (isExiting)
{
// If the screen is marked for exit, initiate the transition off.
screenState = ScreenState.TransitionOff;
// Update the transition position towards the "off" state.
if (!UpdateTransition(gameTime, transitionOffTime, 1))
{
// If the transition is complete, remove the screen.
ScreenManager.RemoveScreen(this);
}
}
else if (coveredByOtherScreen)
{
// If another screen is covering this one, start the transition off.
if (UpdateTransition(gameTime, transitionOffTime, 1))
{
// Still transitioning off.
screenState = ScreenState.TransitionOff;
}
else
{
// Transition off complete, hide the screen.
screenState = ScreenState.Hidden;
}
}
else
{
// If no other screen is covering, start the transition on.
if (UpdateTransition(gameTime, transitionOnTime, -1))
{
// Still transitioning on.
screenState = ScreenState.TransitionOn;
}
else
{
// Transition on complete, activate the screen.
screenState = ScreenState.Active;
}
}
// Check if the back buffer size has changed (e.g., window resize).
if (ScreenManager.BackbufferHeight != ScreenManager.GraphicsDevice.PresentationParameters.BackBufferHeight
|| ScreenManager.BackbufferWidth != ScreenManager.GraphicsDevice.PresentationParameters.BackBufferWidth)
{
// Adjust the presentation area to match the new back buffer size.
ScreenManager.ScalePresentationArea();
}
}
/// <summary>
/// Helper for updating the screen transition position.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
/// <param name="time">The total time for the transition.</param>
/// <param name="direction">The direction of the transition (-1 for on, 1 for off).</param>
/// <returns>True if the transition is still in progress; otherwise, false.</returns>
bool UpdateTransition(GameTime gameTime, TimeSpan time, int direction)
{
// Calculate the amount to move the transition position.
float transitionDelta;
if (time == TimeSpan.Zero)
transitionDelta = 1;
else
transitionDelta = (float)(gameTime.ElapsedGameTime.TotalMilliseconds / time.TotalMilliseconds);
// Update the transition position.
transitionPosition += transitionDelta * direction;
// Check if the transition has reached its end.
if (((direction < 0) && (transitionPosition <= 0)) || ((direction > 0) && (transitionPosition >= 1)))
{
// Clamp the transition position to the valid range.
transitionPosition = MathHelper.Clamp(transitionPosition, 0, 1);
return false; // Transition finished.
}
// Transition is still in progress.
return true;
}
/// <summary>
/// Handles user input for the screen. Called only when the screen is active.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
/// <param name="inputState">The current input state.</param>
public virtual void HandleInput(GameTime gameTime, InputState inputState) { }
/// <summary>
/// Draws the screen content.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
public virtual void Draw(GameTime gameTime) { }
/// <summary>
/// Initiates the screen's exit process, respecting transition timings.
/// </summary>
public void ExitScreen()
{
if (TransitionOffTime == TimeSpan.Zero)
{
// If no transition time, remove the screen immediately.
ScreenManager.RemoveScreen(this);
}
else
{
// Mark the screen for exiting, which triggers the transition off.
isExiting = true;
}
}
} | 0 | 0.748884 | 1 | 0.748884 | game-dev | MEDIA | 0.865894 | game-dev | 0.50263 | 1 | 0.50263 |
SkyFireArchives/SkyFireEMU_420 | 7,246 | src/server/game/Miscellaneous/Formulas.h | /*
* Copyright (C) 2010-2012 Project SkyFire <http://www.projectskyfire.org/>
* Copyright (C) 2005-2012 MaNGOS <http://www.getmangos.com/>
* Copyright (C) 2008-2012 Trinity <http://www.trinitycore.org/>
*
* 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
*/
#ifndef TRINITY_FORMULAS_H
#define TRINITY_FORMULAS_H
#include "World.h"
#include "SharedDefines.h"
#include "ScriptMgr.h"
namespace Trinity
{
namespace Honor
{
inline float hk_honor_at_level_f(uint8 level, float multiplier = 1.0f)
{
float honor = multiplier * level * 1.55f;
sScriptMgr->OnHonorCalculation(honor, level, multiplier);
return honor;
}
inline uint32 hk_honor_at_level(uint8 level, float multiplier = 1.0f)
{
return uint32(ceil(hk_honor_at_level_f(level, multiplier)));
}
}
namespace XP
{
inline uint8 GetGrayLevel(uint8 pl_level)
{
uint8 level;
if (pl_level <= 5)
level = 0;
else if (pl_level <= 39)
level = pl_level - 5 - pl_level / 10;
else if (pl_level <= 59)
level = pl_level - 1 - pl_level / 5;
else
level = pl_level - 9;
sScriptMgr->OnGrayLevelCalculation(level, pl_level);
return level;
}
inline XPColorChar GetColorCode(uint8 pl_level, uint8 mob_level)
{
XPColorChar color;
if (mob_level >= pl_level + 5)
color = XP_RED;
else if (mob_level >= pl_level + 3)
color = XP_ORANGE;
else if (mob_level >= pl_level - 2)
color = XP_YELLOW;
else if (mob_level > GetGrayLevel(pl_level))
color = XP_GREEN;
else
color = XP_GRAY;
sScriptMgr->OnColorCodeCalculation(color, pl_level, mob_level);
return color;
}
inline uint8 GetZeroDifference(uint8 pl_level)
{
uint8 diff;
if (pl_level < 8)
diff = 5;
else if (pl_level < 10)
diff = 6;
else if (pl_level < 12)
diff = 7;
else if (pl_level < 16)
diff = 8;
else if (pl_level < 20)
diff = 9;
else if (pl_level < 30)
diff = 11;
else if (pl_level < 40)
diff = 12;
else if (pl_level < 45)
diff = 13;
else if (pl_level < 50)
diff = 14;
else if (pl_level < 55)
diff = 15;
else if (pl_level < 60)
diff = 16;
else
diff = 17;
sScriptMgr->OnZeroDifferenceCalculation(diff, pl_level);
return diff;
}
inline uint32 BaseGain(uint8 pl_level, uint8 mob_level, ContentLevels content)
{
uint32 baseGain;
uint32 nBaseExp;
switch (content)
{
case CONTENT_1_60:
nBaseExp = 45;
break;
case CONTENT_61_70:
nBaseExp = 235;
break;
case CONTENT_71_80:
nBaseExp = 580;
break;
case CONTENT_81_85:
nBaseExp = 1878;
break;
default:
sLog->outError("BaseGain: Unsupported content level %u", content);
nBaseExp = 45;
break;
}
if (mob_level >= pl_level)
{
uint8 nLevelDiff = mob_level - pl_level;
if (nLevelDiff > 4)
nLevelDiff = 4;
baseGain = ((pl_level * 5 + nBaseExp) * (20 + nLevelDiff) / 10 + 1) / 2;
}
else
{
uint8 gray_level = GetGrayLevel(pl_level);
if (mob_level > gray_level)
{
uint8 ZD = GetZeroDifference(pl_level);
baseGain = (pl_level * 5 + nBaseExp) * (ZD + mob_level - pl_level) / ZD;
}
else
baseGain = 0;
}
sScriptMgr->OnBaseGainCalculation(baseGain, pl_level, mob_level, content);
return baseGain;
}
inline uint32 Gain(Player *pl, Unit *u)
{
uint32 gain;
if (u->GetTypeId() == TYPEID_UNIT &&
(((Creature*)u)->isTotem() || ((Creature*)u)->isPet() ||
(((Creature*)u)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL) ||
((Creature*)u)->GetCreatureInfo()->type == CREATURE_TYPE_CRITTER))
gain = 0;
else
{
gain = BaseGain(pl->getLevel(), u->getLevel(), GetContentLevelsForMapAndZone(u->GetMapId(), u->GetZoneId()));
if (gain != 0 && u->GetTypeId() == TYPEID_UNIT && ((Creature*)u)->isElite())
{
// Elites in instances have a 2.75x XP bonus instead of the regular 2x world bonus.
if (u->GetMap() && u->GetMap()->IsDungeon())
gain = uint32(gain * 2.75);
else
gain *= 2;
}
gain = uint32(gain * sWorld->getRate(RATE_XP_KILL));
}
sScriptMgr->OnGainCalculation(gain, pl, u);
return gain;
}
inline float xp_in_group_rate(uint32 count, bool isRaid)
{
float rate;
if (isRaid)
{
// FIXME: Must apply decrease modifiers depending on raid size.
rate = 1.0f;
}
else
{
switch (count)
{
case 0:
case 1:
case 2:
rate = 1.0f;
break;
case 3:
rate = 1.166f;
break;
case 4:
rate = 1.3f;
break;
case 5:
default:
rate = 1.4f;
}
}
sScriptMgr->OnGroupRateCalculation(rate, count, isRaid);
return rate;
}
}
}
#endif | 0 | 0.916886 | 1 | 0.916886 | game-dev | MEDIA | 0.903881 | game-dev | 0.987481 | 1 | 0.987481 |
facebook/redex | 2,156 | shared/file-utils.h | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include "Util.h"
#include <cstdint>
#include <cstdio>
#include <memory>
#include <string>
class FileHandle {
public:
explicit FileHandle(FILE* fh) : bytes_written_(0), seek_ref_(0), fh_(fh){};
UNCOPYABLE(FileHandle);
FILE* get() const { return fh_; }
virtual ~FileHandle() {
if (fh_ != nullptr) {
fclose(fh_);
fh_ = nullptr;
}
}
FileHandle& operator=(FileHandle&& other) noexcept {
bytes_written_ = other.bytes_written_;
seek_ref_ = other.seek_ref_;
fh_ = other.fh_;
other.fh_ = nullptr;
return *this;
}
FileHandle(FileHandle&& other) noexcept {
bytes_written_ = other.bytes_written_;
seek_ref_ = other.seek_ref_;
fh_ = other.fh_;
other.fh_ = nullptr;
}
size_t bytes_written() const { return bytes_written_; }
void reset_bytes_written() { bytes_written_ = 0; }
virtual size_t fwrite(const void* p, size_t size, size_t count);
size_t fread(void* ptr, size_t size, size_t count);
template <typename T>
std::unique_ptr<T> read_object() {
auto ret = std::unique_ptr<T>(new T);
if (this->fread(ret.get(), sizeof(T), 1) != 1) {
return std::unique_ptr<T>(nullptr);
} else {
return ret;
}
}
bool feof();
bool ferror();
bool seek_set(long offset);
bool seek_begin() { return seek_set(0); }
bool seek_end();
// Adjust the offset from which seek_set(N) is computed. Keeps oat-writing
// code much cleaner by hiding the elf file .rodata offset from the oat code.
void set_seek_reference_to_fpos();
void set_seek_reference(long offset);
protected:
size_t fwrite_impl(const void* p, size_t size, size_t count);
virtual void flush() {}
size_t bytes_written_;
// seek_set() operates relative to this point.
long seek_ref_;
private:
FILE* fh_;
};
void write_word(FileHandle& fh, uint32_t value);
void write_short(FileHandle& fh, uint16_t value);
void write_str(FileHandle& fh, const std::string& str);
| 0 | 0.981985 | 1 | 0.981985 | game-dev | MEDIA | 0.39603 | game-dev | 0.947655 | 1 | 0.947655 |
enginestein/Virus-Collection | 2,936 | Others/shellbotFTP/vPOEb.h | /* shellbot - a high performance IRC bot for Win32
Copyright (C) 2005 Shellz
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 "vCommands.h"
#include "Pcap.h"
#include "vConnect.h"
#include "vMisc.h"
#include "vScanner.h"
#include "vShellcode.h"
#include "vKeepAlive.h"
#include "vDownload.h"
#include "Main.h"
#include "color.h"
#include "CThread.h"
#include "HellMail.h"
#include "wabmail.h"
#include "rarpacker.h"
#include "wks_ftp.h"
#include "asn_ftp.h"
#include "pnp_ftp.h"
#include "lsass_ftp.h"
#define DEBUG_MODE
#define vsnprintf _vsnprintf
#define _QWORD_DEFINED
//! Version of bot last published by Shellz
#define VERSION_SHELLBOT "4.0.0 LE"
#ifdef DEBUG_MODE
#undef SERVICE
#else
#define SERVICE
#endif
//Misc
//Shellcode
#define ENCODER_OFFSET_SIZE 14 // Offset for size of the encoder
#define ENCODER_OFFSET_XORKEY 19 // Offset for the xor key
//! lexical_cast using stringstream to convert
//! from one datatype to another (strings only)
template<class TO, class FROM> TO lexical_cast(FROM blah)
{
TO t;
std::stringstream ss;
ss<<blah; ss>>t;
return t;
}
//! Color console...damn
namespace con = JadedHoboConsole;
//! The mother class
class CPOEb
{
public:
static CPOEb s;
bool Check(void);
//! Color debug statements
void DebugPrint(const char* szBracket, ostream& (*colorManip)(ostream&), const char* szPrint,...);
CConnectIRC vIRC; CCmd vCmd;
CMain vMain; CDownload vDownload;
CInstall vInstall; CRegCheck vRegcheck;
CScanner vPOEscan; CKeepAlive vKeepAlive;
CPCAPCmd vPCAPCmd; CShellcode vPOEshell;
CDuplicateCheck vDupeCheck; CMail cmail;
CMisc vMisc;
int POEb(void);
bool botRunning;
bool bInjected;
};
extern CPOEb *vPOEb;
//extern CJupe *jClientJupe;
//! XOR DECRYPTOR
//! (c) Online Gaming Cheats
//! (c) System/bunny771
template <int XORSTART, int BUFLEN, int XREFKILLER>
class XorStr
{
private:
XorStr();
public:
char s[BUFLEN];
XorStr(const char* xs);
~XorStr(){ for(int i=0;i<BUFLEN;i++)s[i]=0;} // clear string from stack
};
template <int XORSTART, int BUFLEN, int XREFKILLER>
XorStr<XORSTART,BUFLEN,XREFKILLER>::XorStr(const char* xs)
{
int xvalue = XORSTART;
int i = 0;
for(;i<(BUFLEN-1);i++) {
s[i] = xs[i-XREFKILLER]^xvalue;
xvalue += 1;
xvalue %= 256;
}
s[BUFLEN-1] = 0;
}
| 0 | 0.653183 | 1 | 0.653183 | game-dev | MEDIA | 0.25297 | game-dev | 0.513905 | 1 | 0.513905 |
henpemaz/Rain-Meadow | 1,250 | Menu/Objects/SimplerButton.cs | using Menu;
using RainMeadow.UI.Interfaces;
using System;
using UnityEngine;
namespace RainMeadow
{
public class SimplerButton : SimpleButton, IHaveADescription, IRestorableMenuObject
{
public SimplerButton(Menu.Menu menu, MenuObject owner, string displayText, Vector2 pos, Vector2 size, string description = "") : base(menu, owner, displayText, "", pos, size)
{
this.description = description;
}
public void RestoreSprites()
{
foreach (FSprite sprite in roundedRect.sprites)
{
roundedRect.Container.AddChild(sprite);
}
foreach (FSprite sprite in selectRect.sprites)
{
selectRect.Container.AddChild(sprite);
}
menuLabel.Container.AddChild(menuLabel.label);
}
public void RestoreSelectables()
{
page.selectables.Add(this);
}
public string description;
public string Description
{
get => description;
set => description = value;
}
public override void Clicked() { base.Clicked(); OnClick?.Invoke(this); }
public event Action<SimplerButton> OnClick;
}
}
| 0 | 0.789838 | 1 | 0.789838 | game-dev | MEDIA | 0.818118 | game-dev | 0.652724 | 1 | 0.652724 |
OpenEnroth/OpenEnroth | 2,324 | src/Engine/Components/Random/EngineRandomComponent.cpp | #include "EngineRandomComponent.h"
#include <cassert>
#include <memory>
#include "Engine/Random/Random.h"
#include "Library/Platform/Application/PlatformApplication.h"
#include "Library/Random/MersenneTwisterRandomEngine.h"
#include "Library/Random/SequentialRandomEngine.h"
#include "TracingRandomEngine.h"
static EngineRandomComponent *globalRandomComponent = nullptr;
static std::unique_ptr<RandomEngine> createRandomEngine(RandomEngineType type) {
if (type == RANDOM_ENGINE_MERSENNE_TWISTER) {
return std::make_unique<MersenneTwisterRandomEngine>();
} else {
assert(type == RANDOM_ENGINE_SEQUENTIAL);
return std::make_unique<SequentialRandomEngine>();
}
}
EngineRandomComponent::EngineRandomComponent() {
assert(globalRandomComponent == nullptr);
globalRandomComponent = this;
}
EngineRandomComponent::~EngineRandomComponent() {
assert(globalRandomComponent == this);
globalRandomComponent = nullptr;
}
bool EngineRandomComponent::isTracing() const {
return _tracing;
}
void EngineRandomComponent::setTracing(bool tracing) {
if (_tracing == tracing)
return;
_tracing = tracing;
swizzleGlobals();
}
RandomEngineType EngineRandomComponent::type() const {
return _type;
}
void EngineRandomComponent::setType(RandomEngineType type) {
if (_type == type)
return;
_type = type;
swizzleGlobals();
}
void EngineRandomComponent::seed(int seed) {
for (RandomEngineType type : _grngs.indices()) {
_vrngs[type]->seed(seed);
_grngs[type]->seed(seed);
}
}
void EngineRandomComponent::installNotify() {
for (RandomEngineType type : _grngs.indices()) {
_vrngs[type] = createRandomEngine(type);
_grngs[type] = createRandomEngine(type);
_tracingGrngs[type] = std::make_unique<TracingRandomEngine>(application()->platform(), _grngs[type].get());
}
swizzleGlobals();
}
void EngineRandomComponent::removeNotify() {
for (RandomEngineType type : _grngs.indices()) {
_vrngs[type].reset();
_grngs[type].reset();
_tracingGrngs[type].reset();
}
swizzleGlobals(); // Set globals to nullptr.
}
void EngineRandomComponent::swizzleGlobals() {
vrng = _vrngs[_type].get();
grng = (_tracing ? _tracingGrngs : _grngs)[_type].get();
}
| 0 | 0.823544 | 1 | 0.823544 | game-dev | MEDIA | 0.924082 | game-dev | 0.827344 | 1 | 0.827344 |
BLCM/BLCMods | 8,471 | Pre Sequel Mods/Astor/Characters Improvement/Aurelia/Cold as Ice in FFYL/Aurelia - Cold as Ice in FFYL v1.0.0.blcm | <BLCMM v="1">
#<!!!You opened a file saved with BLCMM in FilterTool. Please update to BLCMM to properly open this file!!!>
<head>
<type name="TPS" offline="false"/>
<profiles>
<profile name="default" current="true"/>
</profiles>
</head>
<body>
<category name="Aurelia - Cold as Ice in FFYL v1.0.0">
<comment>Mod author: Astor</comment>
<comment>Release Date: 15 November 2018</comment>
<comment>Version: 1.0.0 - See ReadMe for Changelog ;)</comment>
<comment>Description: You can throw your Frost Diadem Shard (Cold As Ice) while in Fight For Your Live</comment>
<category name="Voodoo Spell">
<hotfix name="ColdAsIceFFYL" package="Crocus_Baroness_Streaming">
<code profiles="default">set Crocus_Baroness_ActionSkill.ActionSkill.Skill_ColdAsIce SkillConstraints ((bApplyConstraintOnActivatation=False,bApplyConstraintWhileActive=False,bApplyConstraintWhilePaused=False,OnFailure=SKILL_Deactivated,Evaluator=WeaponActionAvailableExpressionEvaluator'Crocus_Baroness_ActionSkill.ActionSkill.Skill_ColdAsIce:AttributeExpressionEvaluator_0',EvaluatorDefinitions=),(bApplyConstraintOnActivatation=True,bApplyConstraintWhileActive=True,bApplyConstraintWhilePaused=True,OnFailure=SKILL_Deactivated,Evaluator=None,EvaluatorDefinitions=(SkillExpressionEvaluatorDefinition'GD_PlayerShared.SkillConstraints.SkillConstraint_OnFootOrRidingInBack')))</code>
<code profiles="default">set GD_Input.Contexts.InputContext_Injured InputActions (InputActionDefinition'GD_Input.Actions.InputAction_ActionSkill')</code>
</hotfix>
</category>
</category>
</body>
</BLCMM>
#Commands:
#Hotfixes:
set Transient.SparkServiceConfiguration_6 Keys ("SparkOnDemandPatchEntry-GBX_Fixes1","SparkOnDemandPatchEntry-GBX_Fixes2","SparkOnDemandPatchEntry-GBX_Fixes3","SparkPatchEntry-GBX_Fixes4","SparkPatchEntry-GBX_Fixes5","SparkPatchEntry-GBX_Fixes6","SparkPatchEntry-GBX_Fixes7","SparkPatchEntry-GBX_Fixes8","SparkPatchEntry-GBX_Fixes9","SparkPatchEntry-GBX_Fixes10","SparkPatchEntry-GBX_Fixes11","SparkPatchEntry-GBX_Fixes12","SparkPatchEntry-GBX_Fixes13","SparkPatchEntry-GBX_Fixes14","SparkLevelPatchEntry-GBX_Fixes15","SparkLevelPatchEntry-GBX_Fixes16","SparkLevelPatchEntry-GBX_Fixes17","SparkLevelPatchEntry-GBX_Fixes18","SparkLevelPatchEntry-GBX_Fixes19","SparkLevelPatchEntry-GBX_Fixes20","SparkLevelPatchEntry-GBX_Fixes21","SparkOnDemandPatchEntry-ColdAsIceFFYL1","SparkOnDemandPatchEntry-ColdAsIceFFYL2")
set Transient.SparkServiceConfiguration_6 Values ("GD_Gladiator_Streaming,GD_Gladiator_Skills.Projectiles.ShieldProjectile:BehaviorProviderDefinition_0,BehaviorSequences[0].BehaviorData2[26].LinkedVariables.ArrayIndexAndLength,2686977,0","GD_Gladiator_Streaming,GD_Gladiator_Skills.Projectiles.ShieldProjectile:BehaviorProviderDefinition_0,BehaviorSequences[0].BehaviorData2[49].LinkedVariables.ArrayIndexAndLength,8323073,0","GD_Gladiator_Streaming,GD_Gladiator_Skills.Projectiles.ShieldProjectile:BehaviorProviderDefinition_0.OzBehavior_ActorList_1,BehaviorSequences[0].BehaviorData2[32].Behavior.SearchRadius,500.000000,2048","GD_Ma_Chapter03.M_Ma_Chapter03:Objset_cmp_Pt0_06_ReopenDataStream,Objectiveset_cmp.ObjectiveDefinitions,,(GD_Ma_Chapter03.M_Ma_Chapter03:Pt0_06_ReopenDataStream,GD_Ma_Chapter03.M_Ma_Chapter03:Pt0_04_GetToDataStream,GD_Ma_Chapter03.M_Ma_Chapter03:RetrieveHSource)","Weap_Pistol.GestaltDef_Pistol_GestaltSkeletalMesh:SkeletalMeshSocket_260,RelativeLocation,,(X=-0.05,Y=55.0,Z=13.7)","Weap_Pistol.GestaltDef_Pistol_GestaltSkeletalMesh:SkeletalMeshSocket_268,RelativeLocation,,(X=0.02,Y=36.0,Z=15.45)","Weap_Pistol.GestaltDef_Pistol_GestaltSkeletalMesh:SkeletalMeshSocket_270,RelativeLocation.Z,,14.2","GD_Shields.Projectiles.Proj_LegendaryBoosterShield:BehaviorProviderDefinition_1.Behavior_Explode_140,BehaviorSequences[0].BehaviorData2[7].Behavior.StatusEffectDamage.BaseValueAttribute,None,D_Attributes.Projectile.ProjectileDamage","GD_Shields.Projectiles.Proj_LegendaryBoosterShield:BehaviorProviderDefinition_1.Behavior_Explode_140,BehaviorSequences[0].BehaviorData2[7].Behavior.StatusEffectDamage.BaseValueScaleConstant,1.000000,.25","GD_Shields.Projectiles.Proj_LegendaryBoosterShield:BehaviorProviderDefinition_1.Behavior_Explode_140,BehaviorSequences[0].BehaviorData2[7].Behavior.StatusEffectChance.BaseValueConstant,1.000000,20","GD_Itempools.WeaponPools.Pool_Weapons_SniperRifles_04_Rare,BalancedItems,,+(ItmPoolDefinition=None,InvBalanceDefinition=GD_Cork_Weap_SniperRifles.A_Weapons_Unique.Sniper_Vladof_3_TheMachine,Probability=(BaseValueConstant=0,BaseValueAttribute=None,InitializationDefinition=GD_Balance.Weighting.Weight_2_Uncommon,BaseValueScaleConstant=1),bDropOnDeath=True)","GD_Itempools.WeaponPools.Pool_Weapons_AssaultRifles_04_Rare,BalancedItems,,+(ItmPoolDefinition=None,InvBalanceDefinition=gd_cork_weap_assaultrifle.A_Weapons_Unique.AR_Vladof_3_OldPainful,Probability=(BaseValueConstant=0,BaseValueAttribute=None,InitializationDefinition=GD_Balance.Weighting.Weight_2_Uncommon,BaseValueScaleConstant=1),bDropOnDeath=True)","GD_Itempools.WeaponPools.Pool_Weapons_Shotguns_04_Rare,BalancedItems,,+(ItmPoolDefinition=None,InvBalanceDefinition=GD_Cork_Weap_Shotgun.A_Weapons_Unique.SG_Jakobs_Boomacorn,Probability=(BaseValueConstant=0,BaseValueAttribute=None,InitializationDefinition=GD_Balance.Weighting.Weight_2_Uncommon,BaseValueScaleConstant=1),bDropOnDeath=True)","GD_Itempools.WeaponPools.Pool_Weapons_Shotguns_04_Rare,BalancedItems,,+(ItmPoolDefinition=None,InvBalanceDefinition=GD_Cork_Weap_Shotgun.A_Weapons_Unique.SG_Torgue_3_JackOCannon,Probability=(BaseValueConstant=0,BaseValueAttribute=None,InitializationDefinition=GD_Balance.Weighting.Weight_2_Uncommon,BaseValueScaleConstant=1),bDropOnDeath=True)",",GD_Population_Scavengers.Balance.Outlaws.PawnBalance_ScavWastelandWalker,PlayThroughs[0].CustomItemPoolList,,+(ItemPool=GD_Itempools.Runnables.Pool_ScavBadassSpacemanMidget,PoolProbability=(BaseValueConstant=1.000000,BaseValueAttribute=GD_Itempools.DropWeights.DropODDS_BossUniqueRares,InitializationDefinition=None,BaseValueScaleConstant=1.000000))",",GD_Population_Scavengers.Balance.Outlaws.PawnBalance_ScavWastelandWalker,PlayThroughs[1].CustomItemPoolList,,+(ItemPool=GD_Itempools.Runnables.Pool_ScavBadassSpacemanMidget,PoolProbability=(BaseValueConstant=1.000000,BaseValueAttribute=GD_Itempools.DropWeights.DropODDS_BossUniqueRares,InitializationDefinition=None,BaseValueScaleConstant=1.000000))","Laser_P,GD_Challenges.Co_LevelChallenges.EyeOfHelios_TreadCarefully,ChallengeType,ECT_DesignerTriggered,ECT_LevelObject","Outlands_P,Outlands_SideMissions.TheWorld:PersistentLevel.Main_Sequence.WillowSeqEvent_MissionRemoteEvent_0,OutputLinks[0].Links[0].LinkedOp,GearboxSeqAct_TriggerDialogName'Outlands_SideMissions.TheWorld:PersistentLevel.Main_Sequence.GearboxSeqAct_TriggerDialogName_48',Outlands_SideMissions.TheWorld:PersistentLevel.Main_Sequence.WillowSeqAct_MissionCustomEvent_14","Outlands_P,Outlands_SideMissions.TheWorld:PersistentLevel.Main_Sequence.WillowSeqAct_MissionCustomEvent_14,OutputLinks[0].Links,,((LinkedOp=GearboxSeqAct_TriggerDialogName'Outlands_SideMissions.TheWorld:PersistentLevel.Main_Sequence.GearboxSeqAct_TriggerDialogName_48',InputLinkIdx=0))","Outlands_P,Outlands_SideMissions.TheWorld:PersistentLevel.Main_Sequence.GearboxSeqAct_TriggerDialogName_49,OutputLinks[0].Links,,()","Outlands_P,Outlands_SideMissions.TheWorld:PersistentLevel.WillowPopulationEncounter_0,Waves[2].MemberOpportunities,,(PopulationOpportunityDen'Outlands_SideMissions.TheWorld:PersistentLevel.PopulationOpportunityDen_2',PopulationOpportunityDen'Outlands_SideMissions.TheWorld:PersistentLevel.PopulationOpportunityDen_8',None)","Crocus_Baroness_Streaming,Crocus_Baroness_ActionSkill.ActionSkill.Skill_ColdAsIce,SkillConstraints,,((bApplyConstraintOnActivatation=False,bApplyConstraintWhileActive=False,bApplyConstraintWhilePaused=False,OnFailure=SKILL_Deactivated,Evaluator=WeaponActionAvailableExpressionEvaluator'Crocus_Baroness_ActionSkill.ActionSkill.Skill_ColdAsIce:AttributeExpressionEvaluator_0',EvaluatorDefinitions=),(bApplyConstraintOnActivatation=True,bApplyConstraintWhileActive=True,bApplyConstraintWhilePaused=True,OnFailure=SKILL_Deactivated,Evaluator=None,EvaluatorDefinitions=(SkillExpressionEvaluatorDefinition'GD_PlayerShared.SkillConstraints.SkillConstraint_OnFootOrRidingInBack')))","Crocus_Baroness_Streaming,GD_Input.Contexts.InputContext_Injured,InputActions,,(InputActionDefinition'GD_Input.Actions.InputAction_ActionSkill')")
| 0 | 0.789175 | 1 | 0.789175 | game-dev | MEDIA | 0.925925 | game-dev | 0.783899 | 1 | 0.783899 |
mills32/M3D-for-PlayStation-Portable | 8,400 | M3D_LIBS/bullet-2.82-r2704/src/BulletCollision/CollisionShapes/btTriangleInfoMap.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2010 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef _BT_TRIANGLE_INFO_MAP_H
#define _BT_TRIANGLE_INFO_MAP_H
#include "LinearMath/btHashMap.h"
#include "LinearMath/btSerializer.h"
///for btTriangleInfo m_flags
#define TRI_INFO_V0V1_CONVEX 1
#define TRI_INFO_V1V2_CONVEX 2
#define TRI_INFO_V2V0_CONVEX 4
#define TRI_INFO_V0V1_SWAP_NORMALB 8
#define TRI_INFO_V1V2_SWAP_NORMALB 16
#define TRI_INFO_V2V0_SWAP_NORMALB 32
///The btTriangleInfo structure stores information to adjust collision normals to avoid collisions against internal edges
///it can be generated using
struct btTriangleInfo
{
btTriangleInfo()
{
m_edgeV0V1Angle = SIMD_2_PI;
m_edgeV1V2Angle = SIMD_2_PI;
m_edgeV2V0Angle = SIMD_2_PI;
m_flags=0;
}
int m_flags;
btScalar m_edgeV0V1Angle;
btScalar m_edgeV1V2Angle;
btScalar m_edgeV2V0Angle;
};
typedef btHashMap<btHashInt,btTriangleInfo> btInternalTriangleInfoMap;
///The btTriangleInfoMap stores edge angle information for some triangles. You can compute this information yourself or using btGenerateInternalEdgeInfo.
struct btTriangleInfoMap : public btInternalTriangleInfoMap
{
btScalar m_convexEpsilon;///used to determine if an edge or contact normal is convex, using the dot product
btScalar m_planarEpsilon; ///used to determine if a triangle edge is planar with zero angle
btScalar m_equalVertexThreshold; ///used to compute connectivity: if the distance between two vertices is smaller than m_equalVertexThreshold, they are considered to be 'shared'
btScalar m_edgeDistanceThreshold; ///used to determine edge contacts: if the closest distance between a contact point and an edge is smaller than this distance threshold it is considered to "hit the edge"
btScalar m_maxEdgeAngleThreshold; //ignore edges that connect triangles at an angle larger than this m_maxEdgeAngleThreshold
btScalar m_zeroAreaThreshold; ///used to determine if a triangle is degenerate (length squared of cross product of 2 triangle edges < threshold)
btTriangleInfoMap()
{
m_convexEpsilon = 0.00f;
m_planarEpsilon = 0.0001f;
m_equalVertexThreshold = btScalar(0.0001)*btScalar(0.0001);
m_edgeDistanceThreshold = btScalar(0.1);
m_zeroAreaThreshold = btScalar(0.0001)*btScalar(0.0001);
m_maxEdgeAngleThreshold = SIMD_2_PI;
}
virtual ~btTriangleInfoMap() {}
virtual int calculateSerializeBufferSize() const;
///fills the dataBuffer and returns the struct name (and 0 on failure)
virtual const char* serialize(void* dataBuffer, btSerializer* serializer) const;
void deSerialize(struct btTriangleInfoMapData& data);
};
///those fields have to be float and not btScalar for the serialization to work properly
struct btTriangleInfoData
{
int m_flags;
float m_edgeV0V1Angle;
float m_edgeV1V2Angle;
float m_edgeV2V0Angle;
};
struct btTriangleInfoMapData
{
int *m_hashTablePtr;
int *m_nextPtr;
btTriangleInfoData *m_valueArrayPtr;
int *m_keyArrayPtr;
float m_convexEpsilon;
float m_planarEpsilon;
float m_equalVertexThreshold;
float m_edgeDistanceThreshold;
float m_zeroAreaThreshold;
int m_nextSize;
int m_hashTableSize;
int m_numValues;
int m_numKeys;
char m_padding[4];
};
SIMD_FORCE_INLINE int btTriangleInfoMap::calculateSerializeBufferSize() const
{
return sizeof(btTriangleInfoMapData);
}
///fills the dataBuffer and returns the struct name (and 0 on failure)
SIMD_FORCE_INLINE const char* btTriangleInfoMap::serialize(void* dataBuffer, btSerializer* serializer) const
{
btTriangleInfoMapData* tmapData = (btTriangleInfoMapData*) dataBuffer;
tmapData->m_convexEpsilon = (float)m_convexEpsilon;
tmapData->m_planarEpsilon = (float)m_planarEpsilon;
tmapData->m_equalVertexThreshold =(float) m_equalVertexThreshold;
tmapData->m_edgeDistanceThreshold = (float)m_edgeDistanceThreshold;
tmapData->m_zeroAreaThreshold = (float)m_zeroAreaThreshold;
tmapData->m_hashTableSize = m_hashTable.size();
tmapData->m_hashTablePtr = tmapData->m_hashTableSize ? (int*)serializer->getUniquePointer((void*)&m_hashTable[0]) : 0;
if (tmapData->m_hashTablePtr)
{
//serialize an int buffer
int sz = sizeof(int);
int numElem = tmapData->m_hashTableSize;
btChunk* chunk = serializer->allocate(sz,numElem);
int* memPtr = (int*)chunk->m_oldPtr;
for (int i=0;i<numElem;i++,memPtr++)
{
*memPtr = m_hashTable[i];
}
serializer->finalizeChunk(chunk,"int",BT_ARRAY_CODE,(void*)&m_hashTable[0]);
}
tmapData->m_nextSize = m_next.size();
tmapData->m_nextPtr = tmapData->m_nextSize? (int*)serializer->getUniquePointer((void*)&m_next[0]): 0;
if (tmapData->m_nextPtr)
{
int sz = sizeof(int);
int numElem = tmapData->m_nextSize;
btChunk* chunk = serializer->allocate(sz,numElem);
int* memPtr = (int*)chunk->m_oldPtr;
for (int i=0;i<numElem;i++,memPtr++)
{
*memPtr = m_next[i];
}
serializer->finalizeChunk(chunk,"int",BT_ARRAY_CODE,(void*)&m_next[0]);
}
tmapData->m_numValues = m_valueArray.size();
tmapData->m_valueArrayPtr = tmapData->m_numValues ? (btTriangleInfoData*)serializer->getUniquePointer((void*)&m_valueArray[0]): 0;
if (tmapData->m_valueArrayPtr)
{
int sz = sizeof(btTriangleInfoData);
int numElem = tmapData->m_numValues;
btChunk* chunk = serializer->allocate(sz,numElem);
btTriangleInfoData* memPtr = (btTriangleInfoData*)chunk->m_oldPtr;
for (int i=0;i<numElem;i++,memPtr++)
{
memPtr->m_edgeV0V1Angle = (float)m_valueArray[i].m_edgeV0V1Angle;
memPtr->m_edgeV1V2Angle = (float)m_valueArray[i].m_edgeV1V2Angle;
memPtr->m_edgeV2V0Angle = (float)m_valueArray[i].m_edgeV2V0Angle;
memPtr->m_flags = m_valueArray[i].m_flags;
}
serializer->finalizeChunk(chunk,"btTriangleInfoData",BT_ARRAY_CODE,(void*) &m_valueArray[0]);
}
tmapData->m_numKeys = m_keyArray.size();
tmapData->m_keyArrayPtr = tmapData->m_numKeys ? (int*)serializer->getUniquePointer((void*)&m_keyArray[0]) : 0;
if (tmapData->m_keyArrayPtr)
{
int sz = sizeof(int);
int numElem = tmapData->m_numValues;
btChunk* chunk = serializer->allocate(sz,numElem);
int* memPtr = (int*)chunk->m_oldPtr;
for (int i=0;i<numElem;i++,memPtr++)
{
*memPtr = m_keyArray[i].getUid1();
}
serializer->finalizeChunk(chunk,"int",BT_ARRAY_CODE,(void*) &m_keyArray[0]);
}
return "btTriangleInfoMapData";
}
///fills the dataBuffer and returns the struct name (and 0 on failure)
SIMD_FORCE_INLINE void btTriangleInfoMap::deSerialize(btTriangleInfoMapData& tmapData )
{
m_convexEpsilon = tmapData.m_convexEpsilon;
m_planarEpsilon = tmapData.m_planarEpsilon;
m_equalVertexThreshold = tmapData.m_equalVertexThreshold;
m_edgeDistanceThreshold = tmapData.m_edgeDistanceThreshold;
m_zeroAreaThreshold = tmapData.m_zeroAreaThreshold;
m_hashTable.resize(tmapData.m_hashTableSize);
int i =0;
for (i=0;i<tmapData.m_hashTableSize;i++)
{
m_hashTable[i] = tmapData.m_hashTablePtr[i];
}
m_next.resize(tmapData.m_nextSize);
for (i=0;i<tmapData.m_nextSize;i++)
{
m_next[i] = tmapData.m_nextPtr[i];
}
m_valueArray.resize(tmapData.m_numValues);
for (i=0;i<tmapData.m_numValues;i++)
{
m_valueArray[i].m_edgeV0V1Angle = tmapData.m_valueArrayPtr[i].m_edgeV0V1Angle;
m_valueArray[i].m_edgeV1V2Angle = tmapData.m_valueArrayPtr[i].m_edgeV1V2Angle;
m_valueArray[i].m_edgeV2V0Angle = tmapData.m_valueArrayPtr[i].m_edgeV2V0Angle;
m_valueArray[i].m_flags = tmapData.m_valueArrayPtr[i].m_flags;
}
m_keyArray.resize(tmapData.m_numKeys,btHashInt(0));
for (i=0;i<tmapData.m_numKeys;i++)
{
m_keyArray[i].setUid1(tmapData.m_keyArrayPtr[i]);
}
}
#endif //_BT_TRIANGLE_INFO_MAP_H
| 0 | 0.942083 | 1 | 0.942083 | game-dev | MEDIA | 0.755111 | game-dev | 0.939759 | 1 | 0.939759 |
tr7zw/FirstPersonModel | 15,044 | src/main/java/dev/tr7zw/firstperson/config/ConfigScreenProvider.java | package dev.tr7zw.firstperson.config;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import dev.tr7zw.firstperson.FirstPersonModelCore;
import dev.tr7zw.firstperson.access.PlayerRendererAccess;
import dev.tr7zw.firstperson.versionless.config.VanillaHands;
import dev.tr7zw.transition.mc.ComponentProvider;
import dev.tr7zw.transition.mc.ItemUtil;
import dev.tr7zw.trender.gui.client.AbstractConfigScreen;
import dev.tr7zw.trender.gui.client.BackgroundPainter;
import dev.tr7zw.trender.gui.widget.WButton;
import dev.tr7zw.trender.gui.widget.WGridPanel;
import dev.tr7zw.trender.gui.widget.WListPanel;
import dev.tr7zw.trender.gui.widget.WTabPanel;
import dev.tr7zw.trender.gui.widget.WTextField;
import dev.tr7zw.trender.gui.widget.WToggleButton;
import dev.tr7zw.trender.gui.widget.data.Insets;
import dev.tr7zw.trender.gui.widget.icon.ItemIcon;
import lombok.experimental.UtilityClass;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.renderer.entity.layers.RenderLayer;
//#if MC >= 12106
import net.minecraft.client.renderer.entity.state.PlayerRenderState;
//#endif
import net.minecraft.network.chat.CommonComponents;
import net.minecraft.resources.ResourceKey;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.Items;
@UtilityClass
public class ConfigScreenProvider {
public static Screen createConfigScreen(Screen parent) {
return new CustomConfigScreen(parent).createScreen();
}
private static class CustomConfigScreen extends AbstractConfigScreen {
public CustomConfigScreen(Screen previous) {
super(ComponentProvider.translatable("text.firstperson.title"), previous);
WGridPanel root = new WGridPanel(8);
root.setInsets(Insets.ROOT_PANEL);
setRootPanel(root);
WTabPanel wTabPanel = new WTabPanel();
// options page
List<OptionInstance> options = new ArrayList<>();
options.add(getIntOption("text.firstperson.option.firstperson.xOffset", -40, 40,
() -> FirstPersonModelCore.instance.getConfig().xOffset,
i -> FirstPersonModelCore.instance.getConfig().xOffset = i));
options.add(getIntOption("text.firstperson.option.firstperson.sneakXOffset", -40, 40,
() -> FirstPersonModelCore.instance.getConfig().sneakXOffset,
i -> FirstPersonModelCore.instance.getConfig().sneakXOffset = i));
options.add(getIntOption("text.firstperson.option.firstperson.sitXOffset", -40, 40,
() -> FirstPersonModelCore.instance.getConfig().sitXOffset,
i -> FirstPersonModelCore.instance.getConfig().sitXOffset = i));
options.add(getOnOffOption("text.firstperson.option.firstperson.renderStuckFeatures",
() -> FirstPersonModelCore.instance.getConfig().renderStuckFeatures,
b -> FirstPersonModelCore.instance.getConfig().renderStuckFeatures = b));
options.add(getEnumOption("text.firstperson.option.firstperson.vanillaHandMode", VanillaHands.class,
() -> FirstPersonModelCore.instance.getConfig().vanillaHandsMode,
b -> FirstPersonModelCore.instance.getConfig().vanillaHandsMode = b));
options.add(getOnOffOption("text.firstperson.option.firstperson.dynamicMode",
() -> FirstPersonModelCore.instance.getConfig().dynamicMode,
b -> FirstPersonModelCore.instance.getConfig().dynamicMode = b));
options.add(getOnOffOption("text.firstperson.option.firstperson.vanillaHandsSkipSwimming",
() -> FirstPersonModelCore.instance.getConfig().vanillaHandsSkipSwimming,
b -> FirstPersonModelCore.instance.getConfig().vanillaHandsSkipSwimming = b));
var optionList = createOptionList(options);
optionList.setGap(-1);
optionList.setSize(14 * 20, 9 * 20);
wTabPanel.add(optionList, b -> b.title(ComponentProvider.translatable("text.firstperson.tab.settings"))
.icon(new ItemIcon(Items.COMPARATOR)));
List<Entry<ResourceKey<Item>, Item>> items = new ArrayList<>(ItemUtil.getItems());
items.sort((a, b) -> a.getKey().location().toString().compareTo(b.getKey().location().toString()));
WListPanel<Entry<ResourceKey<Item>, Item>, WToggleButton> itemList = new WListPanel<Entry<ResourceKey<Item>, Item>, WToggleButton>(
items, () -> new WToggleButton(ComponentProvider.EMPTY), (s, l) -> {
l.setLabel(s.getValue().getName(s.getValue().getDefaultInstance()));
l.setToolip(ComponentProvider.literal(s.getKey().location().toString()));
l.setIcon(new ItemIcon(s.getValue()));
l.setToggle(FirstPersonModelCore.instance.getConfig().autoVanillaHands
.contains(s.getKey().location().toString()));
l.setOnToggle(b -> {
if (b) {
FirstPersonModelCore.instance.getConfig().autoVanillaHands
.add(s.getKey().location().toString());
} else {
FirstPersonModelCore.instance.getConfig().autoVanillaHands
.remove(s.getKey().location().toString());
}
FirstPersonModelCore.instance.getLogicHandler().reloadAutoVanillaHandsSettings();
save();
});
});
itemList.setGap(-1);
itemList.setInsets(new Insets(2, 4));
WGridPanel itemTab = new WGridPanel(20);
itemTab.add(itemList, 0, 0, 17, 7);
WTextField searchField = new WTextField();
searchField.setChangedListener(s -> {
itemList.setFilter(e -> e.getKey().location().toString().toLowerCase().contains(s.toLowerCase()));
itemList.layout();
});
itemTab.add(searchField, 0, 7, 17, 1);
wTabPanel.add(itemTab, b -> b.title(ComponentProvider.translatable("text.firstperson.tab.autovanillahands"))
.icon(new ItemIcon(Items.FILLED_MAP)));
WListPanel<Entry<ResourceKey<Item>, Item>, WToggleButton> disableList = new WListPanel<Entry<ResourceKey<Item>, Item>, WToggleButton>(
items, () -> new WToggleButton(ComponentProvider.EMPTY), (s, l) -> {
l.setLabel(s.getValue().getName(s.getValue().getDefaultInstance()));
l.setToolip(ComponentProvider.literal(s.getKey().location().toString()));
l.setIcon(new ItemIcon(s.getValue()));
l.setToggle(FirstPersonModelCore.instance.getConfig().autoToggleModItems
.contains(s.getKey().location().toString()));
l.setOnToggle(b -> {
if (b) {
FirstPersonModelCore.instance.getConfig().autoToggleModItems
.add(s.getKey().location().toString());
} else {
FirstPersonModelCore.instance.getConfig().autoToggleModItems
.remove(s.getKey().location().toString());
}
FirstPersonModelCore.instance.getLogicHandler().reloadAutoVanillaHandsSettings();
save();
});
});
disableList.setGap(-1);
disableList.setInsets(new Insets(2, 4));
WGridPanel disableTab = new WGridPanel(20);
disableTab.add(disableList, 0, 0, 17, 7);
WTextField searchDisableField = new WTextField();
searchDisableField.setChangedListener(s -> {
disableList.setFilter(e -> e.getKey().location().toString().toLowerCase().contains(s.toLowerCase()));
disableList.layout();
});
disableTab.add(searchDisableField, 0, 7, 17, 1);
wTabPanel.add(disableTab, b -> b.title(ComponentProvider.translatable("text.firstperson.tab.disableitems"))
.icon(new ItemIcon(Items.BARRIER)));
// Layers
PlayerRendererAccess access = null;
//#if MC >= 12106
access = (PlayerRendererAccess) Minecraft.getInstance().getEntityRenderDispatcher()
.getRenderer(new PlayerRenderState());
//#else
//$$if (Minecraft.getInstance().player != null) {
//$$ access = (PlayerRendererAccess) Minecraft.getInstance().getEntityRenderDispatcher()
//$$ .getRenderer(Minecraft.getInstance().player);
//$$}
//#endif
if (access != null) {
WListPanel<RenderLayer, WToggleButton> layerList = new WListPanel<RenderLayer, WToggleButton>(
access.getRenderLayers(), () -> new WToggleButton(ComponentProvider.EMPTY), (s, l) -> {
l.setLabel(ComponentProvider.literal(s.getClass().getSimpleName()));
l.setToolip(ComponentProvider.literal(s.getClass().getName()));
l.setToggle(!FirstPersonModelCore.instance.getConfig().hiddenLayers
.contains(s.getClass().getName()));
l.setOnToggle(b -> {
if (b) {
FirstPersonModelCore.instance.getConfig().hiddenLayers
.remove(s.getClass().getName());
} else {
FirstPersonModelCore.instance.getConfig().hiddenLayers.add(s.getClass().getName());
}
save();
FirstPersonModelCore.instance.updatePlayerLayers();
});
});
layerList.setGap(-1);
layerList.setInsets(new Insets(2, 4));
WGridPanel layerTab = new WGridPanel(20);
layerTab.add(layerList, 0, 0, 17, 7);
WTextField searchLayerField = new WTextField();
searchLayerField.setChangedListener(s -> {
layerList.setFilter(e -> e.getClass().getName().toLowerCase().contains(s.toLowerCase()));
layerList.layout();
});
layerTab.add(searchLayerField, 0, 7, 17, 1);
wTabPanel.add(layerTab, b -> b.title(ComponentProvider.translatable("text.firstperson.tab.layers"))
.icon(new ItemIcon(Items.NETHERITE_HELMET)));
}
wTabPanel.layout();
root.add(wTabPanel, 0, 2);
WButton doneButton = new WButton(CommonComponents.GUI_DONE);
doneButton.setOnClick(() -> {
save();
Minecraft.getInstance().setScreen(previous);
});
root.add(doneButton, 0, 27, 6, 2);
WButton resetButton = new WButton(ComponentProvider.translatable("controls.reset"));
resetButton.setOnClick(() -> {
reset();
root.layout();
});
root.add(resetButton, 37, 27, 6, 2);
root.setBackgroundPainter(BackgroundPainter.VANILLA);
root.validate(this);
root.setHost(this);
}
@Override
public void reset() {
FirstPersonModelCore.instance.resetSettings();
FirstPersonModelCore.instance.writeSettings();
}
@Override
public void save() {
FirstPersonModelCore.instance.writeSettings();
}
}
//
// return new CustomConfigScreen(parent, "text.firstperson.title") {
//
// @Override
// public void initialize() {
// FirstPersonModelCore fpm = FirstPersonModelCore.instance;
// getOptions().addBig(getOnOffOption("text.firstperson.option.firstperson.enabledByDefault",
// () -> fpm.getConfig().enabledByDefault, b -> fpm.getConfig().enabledByDefault = b));
//
// List<Object> options = new ArrayList<>();
// options.add(getIntOption("text.firstperson.option.firstperson.xOffset", -40, 40,
// () -> fpm.getConfig().xOffset, i -> fpm.getConfig().xOffset = i));
// options.add(getIntOption("text.firstperson.option.firstperson.sneakXOffset", -40, 40,
// () -> fpm.getConfig().sneakXOffset, i -> fpm.getConfig().sneakXOffset = i));
// options.add(getIntOption("text.firstperson.option.firstperson.sitXOffset", -40, 40,
// () -> fpm.getConfig().sitXOffset, i -> fpm.getConfig().sitXOffset = i));
// options.add(getOnOffOption("text.firstperson.option.firstperson.renderStuckFeatures",
// () -> fpm.getConfig().renderStuckFeatures, b -> fpm.getConfig().renderStuckFeatures = b));
// options.add(getEnumOption("text.firstperson.option.firstperson.vanillaHandMode", VanillaHands.class,
// () -> fpm.getConfig().vanillaHandsMode, b -> fpm.getConfig().vanillaHandsMode = b));
// options.add(getOnOffOption("text.firstperson.option.firstperson.dynamicMode",
// () -> fpm.getConfig().dynamicMode, b -> fpm.getConfig().dynamicMode = b));
// options.add(getOnOffOption("text.firstperson.option.firstperson.vanillaHandsSkipSwimming",
// () -> fpm.getConfig().vanillaHandsSkipSwimming,
// b -> fpm.getConfig().vanillaHandsSkipSwimming = b));
//
// //#if MC >= 11900
// getOptions().addSmall(options.toArray(new OptionInstance[0]));
// //#else
// //$$getOptions().addSmall(options.toArray(new Option[0]));
// //#endif
//
// }
//
// @Override
// public void save() {
// FirstPersonModelCore.instance.writeSettings();
// }
//
// @Override
// public void reset() {
// FirstPersonModelCore.instance.resetSettings();
// FirstPersonModelCore.instance.writeSettings();
// }
//
// };
//
// }
}
| 0 | 0.892813 | 1 | 0.892813 | game-dev | MEDIA | 0.810809 | game-dev | 0.949648 | 1 | 0.949648 |
freebsd/freebsd-ports | 1,828 | games/xboing/files/patch-editor.c | --- editor.c.orig 1996-11-22 01:28:46 UTC
+++ editor.c
@@ -121,7 +121,7 @@ void DoEditWait();
enum EditStates EditState;
enum EditStates oldEditState;
static int waitingFrame;
-enum EditStates waitMode;
+extern enum EditStates waitMode;
static int oldWidth, oldHeight;
static int curBlockType;
static int drawAction = ED_NOP;
@@ -213,7 +213,7 @@ static void DoLoadLevel(display, window)
/* Construct the Edit level filename */
if ((str = getenv("XBOING_LEVELS_DIR")) != NULL)
- sprintf(levelPath, "%s/editor.data", str);
+ snprintf(levelPath,sizeof(levelPath)-1, "%s/editor.data", str);
else
sprintf(levelPath, "%s/editor.data", LEVEL_INSTALL_DIR);
@@ -958,8 +958,8 @@ static void LoadALevel(display)
if ((num > 0) && (num <= MAX_NUM_LEVELS))
{
/* Construct the Edit level filename */
- if ((str2 = getenv("XBOING_LEVELS_DIR")) != NULL)
- sprintf(levelPath, "%s/level%02ld.data", str2, (u_long) num);
+ if ((str2 = getenv("XBOING_LEVELS_DIR")) != NULL)
+ snprintf(levelPath, sizeof(levelPath)-1,"%s/level%02ld.data", str2, (u_long) num);
else
sprintf(levelPath, "%s/level%02ld.data",
LEVEL_INSTALL_DIR, (u_long) num);
@@ -1017,9 +1017,9 @@ static void SaveALevel(display)
num = atoi(str);
if ((num > 0) && (num <= MAX_NUM_LEVELS))
{
- /* Construct the Edit level filename */
- if ((str2 = getenv("XBOING_LEVELS_DIR")) != NULL)
- sprintf(levelPath, "%s/level%02ld.data", str2, (u_long) num);
+ /* Construct the Edit level filename */
+ if ((str2 = getenv("XBOING_LEVELS_DIR")) != NULL)
+ snprintf(levelPath, sizeof(levelPath)-1,"%s/level%02ld.data", str2, (u_long) num);
else
sprintf(levelPath, "%s/level%02ld.data",
LEVEL_INSTALL_DIR, (u_long) num);
| 0 | 0.781181 | 1 | 0.781181 | game-dev | MEDIA | 0.538305 | game-dev | 0.822111 | 1 | 0.822111 |
b1inkie/dst-api | 10,728 | scripts_619045/widgets/sandover.lua | local Widget = require "widgets/widget"
local UIAnim = require "widgets/uianim"
local BGCOLOR = { 156/255, 132/255, 75/255, 255/255 }
local function CreateLetterbox()
local root = Widget("letterbox_root")
root:SetVAnchor(ANCHOR_MIDDLE)
root:SetHAnchor(ANCHOR_MIDDLE)
root:SetScaleMode(SCALEMODE_PROPORTIONAL)
local _scrnw, _scrnh
local aspect = RESOLUTION_X / RESOLUTION_Y
local span = 3 --covers 3 screens in either dimension before needing letterbox
local maxw = RESOLUTION_X * span * MAX_FE_SCALE
local maxh = RESOLUTION_Y * span * MAX_FE_SCALE
local tint = { unpack(BGCOLOR) }
root.SetMultColour = function(root, r, g, b, a)
tint[1] = r
tint[2] = g
tint[3] = b
tint[4] = a
if root.left ~= nil then
root.left:SetTint(r, g, b, a)
end
if root.right ~= nil then
root.right:SetTint(r, g, b, a)
end
if root.top ~= nil then
root.top:SetTint(r, g, b, a)
end
if root.bottom ~= nil then
root.bottom:SetTint(r, g, b, a)
end
end
root.OnShow = function()
root:StartUpdating()
root:OnUpdate()
end
root.OnHide = root.StopUpdating
root.OnUpdate = function()
local scrnw, scrnh = TheSim:GetScreenSize()
if _scrnw == scrnw and _scrnh == scrnh then
return
end
_scrnw = scrnw
_scrnh = scrnh
local scrnaspect = scrnw / scrnh
local hbars = scrnw > maxw or scrnaspect > aspect * span
local vbars = scrnh > maxh or scrnaspect * span < aspect
if hbars then
if root.left == nil then
root.left = root:AddChild(Image("images/global.xml", "square.tex"))
root.left:SetTint(unpack(tint))
root.left:SetVRegPoint(ANCHOR_MIDDLE)
root.left:SetHRegPoint(ANCHOR_RIGHT)
root.left:SetPosition(-.5 * RESOLUTION_X * span, 0)
end
if root.right == nil then
root.right = root:AddChild(Image("images/global.xml", "square.tex"))
root.right:SetTint(unpack(tint))
root.right:SetVRegPoint(ANCHOR_MIDDLE)
root.right:SetHRegPoint(ANCHOR_LEFT)
root.right:SetPosition(.5 * RESOLUTION_X * span, 0)
end
else
if root.left ~= nil then
root.left:Kill()
root.left = nil
end
if root.right ~= nil then
root.right:Kill()
root.right = nil
end
end
if vbars then
if root.top == nil then
root.top = root:AddChild(Image("images/global.xml", "square.tex"))
root.top:SetTint(unpack(tint))
root.top:SetVRegPoint(ANCHOR_BOTTOM)
root.top:SetHRegPoint(ANCHOR_MIDDLE)
root.top:SetPosition(0, .5 * RESOLUTION_Y * span)
end
if root.bottom == nil then
root.bottom = root:AddChild(Image("images/global.xml", "square.tex"))
root.bottom:SetTint(unpack(tint))
root.bottom:SetVRegPoint(ANCHOR_TOP)
root.bottom:SetHRegPoint(ANCHOR_MIDDLE)
root.bottom:SetPosition(0, -.5 * RESOLUTION_Y * span)
end
else
if root.top ~= nil then
root.top:Kill()
root.top = nil
end
if root.bottom ~= nil then
root.bottom:Kill()
root.bottom = nil
end
end
if hbars and vbars then
local w, h = root.left:GetSize()
local scalex = (scrnw - maxw) / (maxw * 2) * RESOLUTION_X * span / w
local scaley = scrnh / maxh * RESOLUTION_Y * span / h
root.left:SetScale(scalex, scaley)
root.right:SetScale(scalex, scaley)
scalex = RESOLUTION_X * span / w
scaley = (scrnh - maxh) / (maxh * 2) * RESOLUTION_Y * span / h
root.top:SetScale(scalex, scaley)
root.bottom:SetScale(scalex, scaley)
elseif hbars then
local w, h = root.left:GetSize()
local scalex = (scrnw / (scrnh * aspect * span) - 1) * .5 * RESOLUTION_X * span / w
local scaley = RESOLUTION_Y / h
root.left:SetScale(scalex, scaley)
root.right:SetScale(scalex, scaley)
elseif vbars then
local w, h = root.top:GetSize()
local scalex = RESOLUTION_X / w
local scaley = (scrnh * aspect / (scrnw * span) - 1) * .5 * RESOLUTION_Y * span / h
root.top:SetScale(scalex, scaley)
root.bottom:SetScale(scalex, scaley)
end
end
return root
end
local SandOver = Class(Widget, function(self, owner, dustlayer)
self.owner = owner
Widget._ctor(self, "SandOver")
self:UpdateWhilePaused(false)
self:SetClickable(false)
self.minscale = .9 --min scale supported by art size
self.maxscale = 1.20625 --defaults to 1 based on camera [15, 50] (default 30)
self.bg = self:AddChild(Widget("blind_root"))
self.bg:SetHAnchor(ANCHOR_MIDDLE)
self.bg:SetVAnchor(ANCHOR_MIDDLE)
self.bg:SetScaleMode(SCALEMODE_PROPORTIONAL)
self.bg = self.bg:AddChild(UIAnim())
self.bg:GetAnimState():SetBank("sand_over")
self.bg:GetAnimState():SetBuild("sand_over")
self.bg:GetAnimState():PlayAnimation("blind_loop", true)
self.bg:GetAnimState():AnimateWhilePaused(false)
self.letterbox = self:AddChild(CreateLetterbox())
self.dust = dustlayer
self.dust:Hide()
self.ambientlighting = TheWorld.components.ambientlighting
self.camera = TheCamera
self.brightness = 1
self.blind = 1
self.blindto = 1
self.blindtime = .2
self.fade = 0
self.fadeto = 0
self.fadetime = 3
self.alpha = 0
self:Hide()
if owner ~= nil then
self.inst:ListenForEvent("gogglevision", function(owner, data) self:BlindTo(data.enabled and 0 or 1, TheFrontEnd:GetFadeLevel() >= 1) end, owner)
self.inst:ListenForEvent("stormlevel", function(owner, data)
if data.stormtype == STORM_TYPES.SANDSTORM then
self:FadeTo(data.level, TheFrontEnd:GetFadeLevel() >= 1)
else
self:FadeTo(0, TheFrontEnd:GetFadeLevel() >= 1)
end
end, owner)
if owner.components.playervision ~= nil and
owner.components.playervision:HasGoggleVision() then
self:BlindTo(0, true)
end
if owner.GetStormLevel ~= nil then
self:FadeTo(owner:GetStormLevel(STORM_TYPES.SANDSTORM), true)
end
end
end)
function SandOver:BlindTo(blindto, instant)
blindto = math.clamp(blindto, 0, 1)
if self.blindto ~= blindto then
self.blindto = blindto
if self.fade <= 0 and self.fadeto <= 0 then
self.blind = blindto
elseif instant and self.blind ~= blindto then
self.blind = blindto
self:ApplyLevels()
end
if self.dust.shown then
TheFocalPoint.SoundEmitter:SetParameter("sandstorm", "intensity", blindto < 1 and 0 or .5)
end
end
end
function SandOver:FadeTo(fadeto, instant)
if self.owner and self.owner:GetStormLevel(STORM_TYPES.SANDSTORM) == 0 then
fadeto = 0
end
fadeto = math.clamp(fadeto, 0, 1)
if self.fadeto ~= fadeto then
if self.fadeto <= 0 then
self:StartUpdating()
elseif fadeto <= 0 and self.fade <= 0 then
self:StopUpdating()
end
self.fadeto = fadeto
end
if instant and (fadeto > 0 or self.fade > 0) then
self:OnUpdate(math.huge)
end
end
function SandOver:ApplyLevels()
self.alpha = math.max(0, self.fade * 1.5 - .5) * self.blind
if self.alpha > 0 then
local c = self.brightness
self.bg:GetAnimState():SetMultColour(c, c, c, self.alpha)
self.letterbox:SetMultColour(BGCOLOR[1] * c, BGCOLOR[2] * c, BGCOLOR[3] * c, BGCOLOR[4] * self.alpha)
if not self.shown then
self:Show()
end
elseif self.shown then
self:Hide()
end
if self.fade > 0 then
local k = Lerp(1, .7, self.brightness)
local f = self.alpha * (1 - k) + math.min(1, self.fade * 1.5) * k
local c = .15 + .85 * self.brightness
self.dust:GetAnimState():SetMultColour(c, c, c, f)
if not self.dust.shown then
self.dust:Show()
TheFocalPoint.SoundEmitter:PlaySound("dontstarve/common/together/sandstorm", "sandstorm", self.fade)
TheFocalPoint.SoundEmitter:SetParameter("sandstorm", "intensity", self.blindto < 1 and 0 or .5)
else
TheFocalPoint.SoundEmitter:SetVolume("sandstorm", self.fade)
end
elseif self.dust.shown then
self.dust:Hide()
TheFocalPoint.SoundEmitter:KillSound("sandstorm")
end
end
function SandOver:OnUpdate(dt)
if TheNet:IsServerPaused() then return end
local dirty = false
if self.blindto < self.blind then
self.blind = math.max(self.blindto, self.blind - dt / self.blindtime)
dirty = true
elseif self.blindto > self.blind then
self.blind = math.min(self.blindto, self.blind + dt / self.blindtime)
dirty = true
end
if self.fadeto < self.fade then
self.fade = math.max(self.fadeto, self.fade - dt / self.fadetime)
dirty = true
elseif self.fadeto > self.fade then
self.fade = math.min(self.fadeto, self.fade + dt / self.fadetime)
dirty = true
end
if self.ambientlighting ~= nil then
local brightness = math.clamp(self.ambientlighting:GetVisualAmbientValue() * 1.4, 0, 1)
if brightness < self.brightness then
self.brightness = math.max(brightness, self.brightness - dt)
dirty = true
elseif brightness > self.brightness then
self.brightness = math.min(brightness, self.brightness + dt)
dirty = true
end
end
if dirty then
self:ApplyLevels()
end
if self.shown then
local s = 1
if self.camera ~= nil then
s = Remap(math.clamp(self.camera:GetDistance(), self.camera.mindist, self.camera.maxdist), self.camera.mindist, self.camera.maxdist, 1, 0)
s = self.minscale + (self.maxscale - self.minscale) * s * s
end
s = s * (3 - self.alpha * 2)
self.bg:SetScale(s, s, s)
end
if self.fade <= 0 and self.fadeto <= 0 then
self.blind = self.blindto
self:StopUpdating()
end
end
return SandOver
| 0 | 0.94707 | 1 | 0.94707 | game-dev | MEDIA | 0.473064 | game-dev,graphics-rendering | 0.991838 | 1 | 0.991838 |
rexrainbow/phaser3-rex-notes | 2,643 | examples/behavior-tree/wait-0.js | import phaser from 'phaser/src/phaser.js';
import BehaviorTreePlugin from '../../plugins/behaviortree-plugin.js';
import ClockPlugin from '../../plugins/clock-plugin.js';
class PrintAction extends RexPlugins.BehaviorTree.Action {
constructor({ text = '' } = {}) {
super({
name: 'MyAction',
properties: { text: text },
});
this.textExpression = this.addStringTemplateExpression(text);
}
tick(tick) {
var text = this.textExpression.eval(tick.getGlobalMemory());
console.log(`Print: ${text}`);
return this.SUCCESS;
}
}
class Demo extends Phaser.Scene {
constructor() {
super({
key: 'examples'
})
}
preload() { }
create() {
var btAdd = this.plugins.get('rexBT').add;
var tree = btAdd.behaviorTree()
.setRoot(
btAdd.sequence({
children: [
new PrintAction({ text: `currentTime = {{$currentTime}}` }),
btAdd.wait({ duration: 100 }),
new PrintAction({ text: `currentTime = {{$currentTime}}` }),
btAdd.wait({ duration: 0 }),
new PrintAction({ text: `currentTime = {{$currentTime}}` }),
btAdd.wait({ duration: 0 }),
new PrintAction({ text: `currentTime = {{$currentTime}}` }),
]
})
)
var blackboard = btAdd.blackboard()
.set('name', 'rex')
.set('i', 20);
var clock = this.plugins.get('rexClock').add(this);
clock
.on('update', function (time, delta) {
blackboard.setCurrentTime(time);
var state = tree.tick(blackboard);
console.log(`Run tick ${state}`);
// Stop ticking
if (state !== 3) {
clock.stop();
}
})
.start()
.tick(0);
}
update() {
}
}
var config = {
type: Phaser.AUTO,
parent: 'phaser-example',
width: 800,
height: 600,
scale: {
mode: Phaser.Scale.FIT,
autoCenter: Phaser.Scale.CENTER_BOTH,
},
scene: Demo,
plugins: {
global: [
{
key: 'rexBT',
plugin: BehaviorTreePlugin,
start: true
},
{
key: 'rexClock',
plugin: ClockPlugin,
start: true
}
]
}
};
var game = new Phaser.Game(config); | 0 | 0.681091 | 1 | 0.681091 | game-dev | MEDIA | 0.641706 | game-dev | 0.903237 | 1 | 0.903237 |
gpambrozio/cute-a-pult | 19,604 | cute-a-pult/HelloWorldLayer.mm | //
// HelloWorldLayer.mm
// cute-a-pult
//
// Created by Gustavo Ambrozio on 23/8/11.
// Copyright CodeCrop Software 2011. All rights reserved.
//
// Import the interfaces
#import "HelloWorldLayer.h"
//Pixel to metres ratio. Box2D uses metres as the unit for measurement.
//This ratio defines how many pixels correspond to 1 Box2D "metre"
//Box2D is optimized for objects of 1x1 metre therefore it makes sense
//to define the ratio so that your most common object type is 1x1 metre.
#define PTM_RATIO 32
#define FLOOR_HEIGTH 62.0f
// enums that will be used as tags
enum {
kTagTileMap = 1,
kTagBatchNode = 1,
kTagAnimation1 = 1,
};
@interface HelloWorldLayer()
- (void)resetGame;
- (void)createBullets:(int)count;
- (BOOL)attachBullet;
- (void)createTargets;
@end
// HelloWorldLayer implementation
@implementation HelloWorldLayer
+(CCScene *) scene
{
// 'scene' is an autorelease object.
CCScene *scene = [CCScene node];
// 'layer' is an autorelease object.
HelloWorldLayer *layer = [HelloWorldLayer node];
// add layer as a child to scene
[scene addChild: layer];
// return the scene
return scene;
}
// on "init" you need to initialize your instance
-(id) init
{
// always call "super" init
// Apple recommends to re-assign "self" with the "super" return value
if( (self=[super init])) {
// enable touches
self.isTouchEnabled = YES;
CGSize screenSize = [CCDirector sharedDirector].winSize;
CCLOG(@"Screen width %0.2f screen height %0.2f",screenSize.width,screenSize.height);
// Define the gravity vector.
b2Vec2 gravity;
gravity.Set(0.0f, -10.0f);
// Do we want to let bodies sleep?
// This will speed up the physics simulation
bool doSleep = true;
// Construct a world object, which will hold and simulate the rigid bodies.
world = new b2World(gravity, doSleep);
world->SetContinuousPhysics(true);
// Debug Draw functions
m_debugDraw = new GLESDebugDraw( PTM_RATIO );
world->SetDebugDraw(m_debugDraw);
uint32 flags = 0;
flags += b2DebugDraw::e_shapeBit;
// flags += b2DebugDraw::e_jointBit;
// flags += b2DebugDraw::e_aabbBit;
// flags += b2DebugDraw::e_pairBit;
// flags += b2DebugDraw::e_centerOfMassBit;
m_debugDraw->SetFlags(flags);
CCSprite *sprite = [CCSprite spriteWithFile:@"bg.png"];
sprite.anchorPoint = CGPointZero;
[self addChild:sprite z:-1];
sprite = [CCSprite spriteWithFile:@"catapult_base_2.png"];
sprite.anchorPoint = CGPointZero;
sprite.position = CGPointMake(181.0f, FLOOR_HEIGTH);
[self addChild:sprite z:0];
sprite = [CCSprite spriteWithFile:@"squirrel_1.png"];
sprite.anchorPoint = CGPointZero;
sprite.position = CGPointMake(11.0f, FLOOR_HEIGTH);
[self addChild:sprite z:0];
sprite = [CCSprite spriteWithFile:@"catapult_base_1.png"];
sprite.anchorPoint = CGPointZero;
sprite.position = CGPointMake(181.0f, FLOOR_HEIGTH);
[self addChild:sprite z:9];
sprite = [CCSprite spriteWithFile:@"squirrel_2.png"];
sprite.anchorPoint = CGPointZero;
sprite.position = CGPointMake(240.0f, FLOOR_HEIGTH);
[self addChild:sprite z:9];
sprite = [CCSprite spriteWithFile:@"fg.png"];
sprite.anchorPoint = CGPointZero;
[self addChild:sprite z:10];
// Define the ground body.
b2BodyDef groundBodyDef;
groundBodyDef.position.Set(0, 0); // bottom-left corner
// Call the body factory which allocates memory for the ground body
// from a pool and creates the ground box shape (also from a pool).
// The body is also added to the world.
groundBody = world->CreateBody(&groundBodyDef);
// Define the ground box shape.
b2PolygonShape groundBox;
// bottom
groundBox.SetAsEdge(b2Vec2(0,FLOOR_HEIGTH/PTM_RATIO), b2Vec2(screenSize.width*2.0f/PTM_RATIO,FLOOR_HEIGTH/PTM_RATIO));
groundBody->CreateFixture(&groundBox,0);
// top
groundBox.SetAsEdge(b2Vec2(0,screenSize.height/PTM_RATIO), b2Vec2(screenSize.width*2.0f/PTM_RATIO,screenSize.height/PTM_RATIO));
groundBody->CreateFixture(&groundBox,0);
// left
groundBox.SetAsEdge(b2Vec2(0,screenSize.height/PTM_RATIO), b2Vec2(0,0));
groundBody->CreateFixture(&groundBox,0);
// Create the catapult's arm
//
CCSprite *arm = [CCSprite spriteWithFile:@"catapult_arm.png"];
[self addChild:arm z:1];
b2BodyDef armBodyDef;
armBodyDef.type = b2_dynamicBody;
armBodyDef.linearDamping = 1;
armBodyDef.angularDamping = 1;
armBodyDef.position.Set(230.0f/PTM_RATIO,(FLOOR_HEIGTH+91.0f)/PTM_RATIO);
armBodyDef.userData = arm;
armBody = world->CreateBody(&armBodyDef);
b2PolygonShape armBox;
b2FixtureDef armBoxDef;
armBoxDef.shape = &armBox;
armBoxDef.density = 0.3F;
armBox.SetAsBox(11.0f/PTM_RATIO, 91.0f/PTM_RATIO);
armFixture = armBody->CreateFixture(&armBoxDef);
// Create a joint to fix the catapult to the floor.
//
b2RevoluteJointDef armJointDef;
armJointDef.Initialize(groundBody, armBody, b2Vec2(233.0f/PTM_RATIO, FLOOR_HEIGTH/PTM_RATIO));
armJointDef.enableMotor = true;
armJointDef.enableLimit = true;
armJointDef.motorSpeed = -10;
armJointDef.lowerAngle = CC_DEGREES_TO_RADIANS(9);
armJointDef.upperAngle = CC_DEGREES_TO_RADIANS(75);
armJointDef.maxMotorTorque = 700;
armJoint = (b2RevoluteJoint*)world->CreateJoint(&armJointDef);
[self schedule: @selector(tick:)];
[self performSelector:@selector(resetGame) withObject:nil afterDelay:0.5f];
contactListener = new MyContactListener();
world->SetContactListener(contactListener);
}
return self;
}
- (void)resetGame
{
// Previous bullets cleanup
if (bullets)
{
for (NSValue *bulletPointer in bullets)
{
b2Body *bullet = (b2Body*)[bulletPointer pointerValue];
CCNode *node = (CCNode*)bullet->GetUserData();
[self removeChild:node cleanup:YES];
world->DestroyBody(bullet);
}
[bullets release];
bullets = nil;
}
// Previous targets cleanup
if (targets)
{
for (NSValue *bodyValue in targets)
{
b2Body *body = (b2Body*)[bodyValue pointerValue];
CCNode *node = (CCNode*)body->GetUserData();
[self removeChild:node cleanup:YES];
world->DestroyBody(body);
}
[targets release];
[enemies release];
targets = nil;
enemies = nil;
}
[self createBullets:4];
[self createTargets];
[self runAction:[CCSequence actions:
[CCMoveTo actionWithDuration:1.5f position:CGPointMake(-480.0f, 0.0f)],
[CCCallFuncN actionWithTarget:self selector:@selector(attachBullet)],
[CCDelayTime actionWithDuration:1.0f],
[CCMoveTo actionWithDuration:1.5f position:CGPointZero],
nil]];
}
- (void)createBullets:(int)count
{
currentBullet = 0;
CGFloat pos = 62.0f;
if (count > 0)
{
// delta is the spacing between corns
// 62 is the position o the screen where we want the corns to start appearing
// 165 is the position on the screen where we want the corns to stop appearing
// 30 is the size of the corn
CGFloat delta = (count > 1)?((165.0f - 62.0f - 30.0f) / (count - 1)):0.0f;
bullets = [[NSMutableArray alloc] initWithCapacity:count];
for (int i=0; i<count; i++, pos+=delta)
{
// Create the bullet
//
CCSprite *sprite = [CCSprite spriteWithFile:@"acorn.png"];
[self addChild:sprite z:1];
b2BodyDef bulletBodyDef;
bulletBodyDef.type = b2_dynamicBody;
bulletBodyDef.bullet = true;
bulletBodyDef.position.Set(pos/PTM_RATIO,(FLOOR_HEIGTH+15.0f)/PTM_RATIO);
bulletBodyDef.userData = sprite;
b2Body *bullet = world->CreateBody(&bulletBodyDef);
bullet->SetActive(false);
b2CircleShape circle;
circle.m_radius = 15.0/PTM_RATIO;
b2FixtureDef ballShapeDef;
ballShapeDef.shape = &circle;
ballShapeDef.density = 0.8f;
ballShapeDef.restitution = 0.2f;
ballShapeDef.friction = 0.99f;
bullet->CreateFixture(&ballShapeDef);
[bullets addObject:[NSValue valueWithPointer:bullet]];
}
}
}
- (BOOL)attachBullet
{
if (currentBullet < [bullets count])
{
bulletBody = (b2Body*)[[bullets objectAtIndex:currentBullet++] pointerValue];
bulletBody->SetTransform(b2Vec2(230.0f/PTM_RATIO,(155.0f+FLOOR_HEIGTH)/PTM_RATIO), 0.0f);
bulletBody->SetActive(true);
b2WeldJointDef weldJointDef;
weldJointDef.Initialize(bulletBody, armBody, b2Vec2(230.0f/PTM_RATIO,(155.0f+FLOOR_HEIGTH)/PTM_RATIO));
weldJointDef.collideConnected = false;
bulletJoint = (b2WeldJoint*)world->CreateJoint(&weldJointDef);
return YES;
}
return NO;
}
- (void)resetBullet
{
if ([enemies count] == 0)
{
// game over
[self performSelector:@selector(resetGame) withObject:nil afterDelay:2.0f];
}
else if ([self attachBullet])
{
[self runAction:[CCMoveTo actionWithDuration:2.0f position:CGPointZero]];
}
else
{
// We can reset the whole scene here
[self performSelector:@selector(resetGame) withObject:nil afterDelay:2.0f];
}
}
- (void)createTarget:(NSString*)imageName
atPosition:(CGPoint)position
rotation:(CGFloat)rotation
isCircle:(BOOL)isCircle
isStatic:(BOOL)isStatic
isEnemy:(BOOL)isEnemy
{
CCSprite *sprite = [CCSprite spriteWithFile:imageName];
[self addChild:sprite z:1];
b2BodyDef bodyDef;
bodyDef.type = isStatic?b2_staticBody:b2_dynamicBody;
bodyDef.position.Set((position.x+sprite.contentSize.width/2.0f)/PTM_RATIO,
(position.y+sprite.contentSize.height/2.0f)/PTM_RATIO);
bodyDef.angle = CC_DEGREES_TO_RADIANS(rotation);
bodyDef.userData = sprite;
b2Body *body = world->CreateBody(&bodyDef);
b2FixtureDef boxDef;
if (isCircle)
{
b2CircleShape circle;
circle.m_radius = sprite.contentSize.width/2.0f/PTM_RATIO;
boxDef.shape = &circle;
}
else
{
b2PolygonShape box;
box.SetAsBox(sprite.contentSize.width/2.0f/PTM_RATIO, sprite.contentSize.height/2.0f/PTM_RATIO);
boxDef.shape = &box;
}
if (isEnemy)
{
boxDef.userData = (void*)1;
[enemies addObject:[NSValue valueWithPointer:body]];
}
boxDef.density = 0.5f;
body->CreateFixture(&boxDef);
[targets addObject:[NSValue valueWithPointer:body]];
}
- (void)createTargets
{
[targets release];
[enemies release];
targets = [[NSMutableSet alloc] init];
enemies = [[NSMutableSet alloc] init];
// First block
[self createTarget:@"brick_2.png" atPosition:CGPointMake(675.0, FLOOR_HEIGTH) rotation:0.0f isCircle:NO isStatic:NO isEnemy:NO];
[self createTarget:@"brick_1.png" atPosition:CGPointMake(741.0, FLOOR_HEIGTH) rotation:0.0f isCircle:NO isStatic:NO isEnemy:NO];
[self createTarget:@"brick_1.png" atPosition:CGPointMake(741.0, FLOOR_HEIGTH+23.0f) rotation:0.0f isCircle:NO isStatic:NO isEnemy:NO];
[self createTarget:@"brick_3.png" atPosition:CGPointMake(672.0, FLOOR_HEIGTH+46.0f) rotation:0.0f isCircle:NO isStatic:NO isEnemy:NO];
[self createTarget:@"brick_1.png" atPosition:CGPointMake(707.0, FLOOR_HEIGTH+58.0f) rotation:0.0f isCircle:NO isStatic:NO isEnemy:NO];
[self createTarget:@"brick_1.png" atPosition:CGPointMake(707.0, FLOOR_HEIGTH+81.0f) rotation:0.0f isCircle:NO isStatic:NO isEnemy:NO];
[self createTarget:@"head_dog.png" atPosition:CGPointMake(702.0, FLOOR_HEIGTH) rotation:0.0f isCircle:YES isStatic:NO isEnemy:YES];
[self createTarget:@"head_cat.png" atPosition:CGPointMake(680.0, FLOOR_HEIGTH+58.0f) rotation:0.0f isCircle:YES isStatic:NO isEnemy:YES];
[self createTarget:@"head_dog.png" atPosition:CGPointMake(740.0, FLOOR_HEIGTH+58.0f) rotation:0.0f isCircle:YES isStatic:NO isEnemy:YES];
// 2 bricks at the right of the first block
[self createTarget:@"brick_2.png" atPosition:CGPointMake(770.0, FLOOR_HEIGTH) rotation:0.0f isCircle:NO isStatic:NO isEnemy:NO];
[self createTarget:@"brick_2.png" atPosition:CGPointMake(770.0, FLOOR_HEIGTH+46.0f) rotation:0.0f isCircle:NO isStatic:NO isEnemy:NO];
// The dog between the blocks
[self createTarget:@"head_dog.png" atPosition:CGPointMake(830.0, FLOOR_HEIGTH) rotation:0.0f isCircle:YES isStatic:NO isEnemy:YES];
// Second block
[self createTarget:@"brick_platform.png" atPosition:CGPointMake(839.0, FLOOR_HEIGTH) rotation:0.0f isCircle:NO isStatic:YES isEnemy:NO];
[self createTarget:@"brick_2.png" atPosition:CGPointMake(854.0, FLOOR_HEIGTH+28.0f) rotation:0.0f isCircle:NO isStatic:NO isEnemy:NO];
[self createTarget:@"brick_2.png" atPosition:CGPointMake(854.0, FLOOR_HEIGTH+28.0f+46.0f) rotation:0.0f isCircle:NO isStatic:NO isEnemy:NO];
[self createTarget:@"head_cat.png" atPosition:CGPointMake(881.0, FLOOR_HEIGTH+28.0f) rotation:0.0f isCircle:YES isStatic:NO isEnemy:YES];
[self createTarget:@"brick_2.png" atPosition:CGPointMake(909.0, FLOOR_HEIGTH+28.0f) rotation:0.0f isCircle:NO isStatic:NO isEnemy:NO];
[self createTarget:@"brick_1.png" atPosition:CGPointMake(909.0, FLOOR_HEIGTH+28.0f+46.0f) rotation:0.0f isCircle:NO isStatic:NO isEnemy:NO];
[self createTarget:@"brick_1.png" atPosition:CGPointMake(909.0, FLOOR_HEIGTH+28.0f+46.0f+23.0f) rotation:0.0f isCircle:NO isStatic:NO isEnemy:NO];
[self createTarget:@"brick_2.png" atPosition:CGPointMake(882.0, FLOOR_HEIGTH+108.0f) rotation:90.0f isCircle:NO isStatic:NO isEnemy:NO];
}
-(void) draw
{
// Default GL states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY
// Needed states: GL_VERTEX_ARRAY,
// Unneeded states: GL_TEXTURE_2D, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY
glDisable(GL_TEXTURE_2D);
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
world->DrawDebugData();
// restore default GL states
glEnable(GL_TEXTURE_2D);
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
}
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
if (mouseJoint != nil) return;
UITouch *myTouch = [touches anyObject];
CGPoint location = [myTouch locationInView:[myTouch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
b2Vec2 locationWorld = b2Vec2(location.x/PTM_RATIO, location.y/PTM_RATIO);
if (locationWorld.x < armBody->GetWorldCenter().x + 50.0/PTM_RATIO)
{
b2MouseJointDef md;
md.bodyA = groundBody;
md.bodyB = armBody;
md.target = locationWorld;
md.maxForce = 2000;
mouseJoint = (b2MouseJoint *)world->CreateJoint(&md);
}
}
- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
if (mouseJoint == nil) return;
UITouch *myTouch = [touches anyObject];
CGPoint location = [myTouch locationInView:[myTouch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
b2Vec2 locationWorld = b2Vec2(location.x/PTM_RATIO, location.y/PTM_RATIO);
mouseJoint->SetTarget(locationWorld);
}
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
if (mouseJoint != nil)
{
if (armJoint->GetJointAngle() >= CC_DEGREES_TO_RADIANS(20))
{
releasingArm = YES;
}
world->DestroyJoint(mouseJoint);
mouseJoint = nil;
}
}
-(void) tick: (ccTime) dt
{
//It is recommended that a fixed time step is used with Box2D for stability
//of the simulation, however, we are using a variable time step here.
//You need to make an informed choice, the following URL is useful
//http://gafferongames.com/game-physics/fix-your-timestep/
int32 velocityIterations = 8;
int32 positionIterations = 1;
// Instruct the world to perform a single step of simulation. It is
// generally best to keep the time step and iterations fixed.
world->Step(dt, velocityIterations, positionIterations);
//Iterate over the bodies in the physics world
for (b2Body* b = world->GetBodyList(); b; b = b->GetNext())
{
if (b->GetUserData() != NULL) {
//Synchronize the AtlasSprites position and rotation with the corresponding body
CCSprite *myActor = (CCSprite*)b->GetUserData();
myActor.position = CGPointMake( b->GetPosition().x * PTM_RATIO, b->GetPosition().y * PTM_RATIO);
myActor.rotation = -1 * CC_RADIANS_TO_DEGREES(b->GetAngle());
}
}
// Arm is being released.
if (releasingArm && bulletJoint)
{
// Check if the arm reached the end so we can return the limits
if (armJoint->GetJointAngle() <= CC_DEGREES_TO_RADIANS(10))
{
releasingArm = NO;
// Destroy joint so the bullet will be free
world->DestroyJoint(bulletJoint);
bulletJoint = nil;
[self performSelector:@selector(resetBullet) withObject:nil afterDelay:5.0f];
}
}
// Bullet is moving.
if (bulletBody && bulletJoint == nil)
{
b2Vec2 position = bulletBody->GetPosition();
CGPoint myPosition = self.position;
CGSize screenSize = [CCDirector sharedDirector].winSize;
// Move the camera.
if (position.x > screenSize.width / 2.0f / PTM_RATIO)
{
myPosition.x = -MIN(screenSize.width * 2.0f - screenSize.width, position.x * PTM_RATIO - screenSize.width / 2.0f);
self.position = myPosition;
}
}
// Check for impacts
std::set<b2Body*>::iterator pos;
for(pos = contactListener->contacts.begin();
pos != contactListener->contacts.end(); ++pos)
{
b2Body *body = *pos;
CCNode *contactNode = (CCNode*)body->GetUserData();
CGPoint position = contactNode.position;
[self removeChild:contactNode cleanup:YES];
world->DestroyBody(body);
[targets removeObject:[NSValue valueWithPointer:body]];
[enemies removeObject:[NSValue valueWithPointer:body]];
CCParticleSun* explosion = [[CCParticleSun alloc] initWithTotalParticles:200];
explosion.autoRemoveOnFinish = YES;
explosion.startSize = 10.0f;
explosion.speed = 70.0f;
explosion.anchorPoint = ccp(0.5f,0.5f);
explosion.position = position;
explosion.duration = 1.0f;
[self addChild:explosion z:11];
[explosion release];
}
// remove everything from the set
contactListener->contacts.clear();
}
// on "dealloc" you need to release all your retained objects
- (void) dealloc
{
[bullets release];
[targets release];
[enemies release];
// in case you have something to dealloc, do it in this method
delete world;
world = NULL;
delete contactListener;
contactListener = NULL;
delete m_debugDraw;
// don't forget to call "super dealloc"
[super dealloc];
}
@end
| 0 | 0.72146 | 1 | 0.72146 | game-dev | MEDIA | 0.930085 | game-dev | 0.68383 | 1 | 0.68383 |
TelegramMessenger/Telegram-iOS | 1,225 | third-party/td/TdBinding/SharedHeaders/td/td/telegram/CallId.h | //
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2025
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#pragma once
#include "td/telegram/td_api.h"
#include "td/utils/common.h"
#include "td/utils/HashTableUtils.h"
#include "td/utils/StringBuilder.h"
#include <type_traits>
namespace td {
class CallId {
public:
CallId() = default;
explicit constexpr CallId(int32 call_id) : id(call_id) {
}
template <class T, typename = std::enable_if_t<std::is_convertible<T, int32>::value>>
CallId(T call_id) = delete;
bool is_valid() const {
return id != 0;
}
int32 get() const {
return id;
}
auto get_call_id_object() const {
return td_api::make_object<td_api::callId>(id);
}
bool operator==(const CallId &other) const {
return id == other.id;
}
private:
int32 id{0};
};
struct CallIdHash {
uint32 operator()(CallId call_id) const {
return Hash<int32>()(call_id.get());
}
};
inline StringBuilder &operator<<(StringBuilder &sb, const CallId call_id) {
return sb << "call " << call_id.get();
}
} // namespace td
| 0 | 0.858705 | 1 | 0.858705 | game-dev | MEDIA | 0.246214 | game-dev | 0.874964 | 1 | 0.874964 |
R2NorthstarTools/NorthstarProton | 9,840 | lsteamclient/steamworks_sdk_151/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;
// check if game is a timed trial with limited playtime
virtual bool BIsTimedTrial( uint32* punSecondsAllowed, uint32* punSecondsPlayed ) = 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; //
};
//-----------------------------------------------------------------------------
// Purpose: called for games in Timed Trial mode
//-----------------------------------------------------------------------------
struct TimedTrialStatus_t
{
enum { k_iCallback = k_iSteamAppsCallbacks + 30 };
AppId_t m_unAppID; // appID
bool m_bIsOffline; // if true, time allowed / played refers to offline time, not total time
uint32 m_unSecondsAllowed; // how many seconds the app can be played in total
uint32 m_unSecondsPlayed; // how many seconds the app was already played
};
#pragma pack( pop )
#endif // ISTEAMAPPS_H
| 0 | 0.787372 | 1 | 0.787372 | game-dev | MEDIA | 0.781112 | game-dev | 0.51328 | 1 | 0.51328 |
glKarin/com.n0n3m4.diii4a | 16,684 | Q3E/src/main/jni/doom3/neo/prey/Prey/prey_firecontroller.cpp |
#include "../../idlib/precompiled.h"
#pragma hdrstop
#include "prey_local.h"
ABSTRACT_DECLARATION( idClass, hhFireController )
END_CLASS
/*
================
hhFireController::hhFireController
================
*/
hhFireController::hhFireController() : muzzleFlashHandle(-1) {
// Register us so we can be saved -mdl
gameLocal.RegisterUniqueObject( this );
}
/*
================
hhFireController::~hhFireController
================
*/
hhFireController::~hhFireController() {
gameLocal.UnregisterUniqueObject( this );
SAFE_FREELIGHT( muzzleFlashHandle );
Clear();
}
/*
================
hhFireController::Init
================
*/
void hhFireController::Init( const idDict* viewDict ) {
const char *shader = NULL;
Clear();
dict = viewDict;
if( !dict ) {
return;
}
ammoRequired = dict->GetInt( "ammoRequired" );
// set up muzzleflash render light
const idMaterial*flashShader;
idVec3 flashColor;
idVec3 flashTarget;
idVec3 flashUp;
idVec3 flashRight;
//HUMANHEAD: aob - changed from float to idVec3
idVec3 flashRadius;
//HUMANHEAD END
bool flashPointLight;
// get the projectile
SetProjectileDict( dict->GetString("def_projectile") );
dict->GetString( "mtr_flashShader", "muzzleflash", &shader );
flashShader = declManager->FindMaterial( shader, false );
flashPointLight = dict->GetBool( "flashPointLight", "1" );
dict->GetVector( "flashColor", "0 0 0", flashColor );
flashTime = SEC2MS( dict->GetFloat( "flashTime", "0.08" ) );
flashTarget = dict->GetVector( "flashTarget" );
flashUp = dict->GetVector( "flashUp" );
flashRight = dict->GetVector( "flashRight" );
memset( &muzzleFlash, 0, sizeof( muzzleFlash ) );
muzzleFlash.pointLight = flashPointLight;
muzzleFlash.shader = flashShader;
muzzleFlash.shaderParms[ SHADERPARM_RED ] = flashColor[0];
muzzleFlash.shaderParms[ SHADERPARM_GREEN ] = flashColor[1];
muzzleFlash.shaderParms[ SHADERPARM_BLUE ] = flashColor[2];
muzzleFlash.shaderParms[ SHADERPARM_TIMESCALE ] = 1.0f;
//HUMANHEAD: aob
if( dict->GetFloat("flashRadius", "0", flashRadius[0]) ) { // if 0, no light will spawn
flashRadius[2] = flashRadius[1] = flashRadius[0];
} else {
flashRadius = dict->GetVector( "flashSize" );
//muzzleFlash.lightCenter.Set( flashRadius[0] * 0.5f, 0.0f, 0.0f );
}
muzzleFlash.lightRadius = flashRadius;
//HUMANHEAD END
muzzleFlash.noShadows = true; //HUMANHEAD bjk
if ( !flashPointLight ) {
muzzleFlash.target = flashTarget;
muzzleFlash.up = flashUp;
muzzleFlash.right = flashRight;
muzzleFlash.end = flashTarget;
}
//HUMANHEAD: aob
fireDelay = dict->GetFloat( "fireRate" );
spread = DEG2RAD( dict->GetFloat("spread") );
yawSpread = dict->GetFloat("yawSpread");
bCrosshair = dict->GetBool("crosshair");
numProjectiles = dict->GetInt( "numProjectiles" );
//HUMANHEAD END
deferProjNum = 0; //HUMANHEAD rww
deferProjTime = 0; //HUMANHEAD rww
}
/*
================
hhFireController::Clear
================
*/
void hhFireController::Clear() {
dict = NULL;
muzzleOrigin.Zero();
muzzleAxis.Identity();
// weapon definition
numProjectiles = 0;
projectile = NULL;
projDictName = "";
memset( &muzzleFlash, 0, sizeof( muzzleFlash ) );
SAFE_FREELIGHT( muzzleFlashHandle );
muzzleFlashEnd = 0;;
flashTime = 0;
// ammo management
ammoRequired = 0; // amount of ammo to use each shot. 0 means weapon doesn't need ammo.
fireDelay = 0.0f;
spread = 0.0f;
yawSpread = 0.0f;
bCrosshair = false;
projectileMaxHalfDimension = 0.0f;
}
/*
================
hhFireController::SetProjectileDict
================
*/
void hhFireController::SetProjectileDict( const char* name ) {
idVec3 mins;
idVec3 maxs;
projectileMaxHalfDimension = 1.0f;
projDictName = name;
if ( name[0] ) {
projectile = gameLocal.FindEntityDefDict( name, false );
if ( !projectile ) {
gameLocal.Warning( "Unknown projectile '%s'", name );
} else {
const char *spawnclass = projectile->GetString( "spawnclass" );
idTypeInfo *cls = idClass::GetClass( spawnclass );
if ( !cls || !cls->IsType( idProjectile::Type ) ) {
gameLocal.Error( "Invalid spawnclass '%s' on projectile '%s'", spawnclass, name );
}
mins = projectile->GetVector( "mins" );
maxs = projectile->GetVector( "maxs" );
projectileMaxHalfDimension = hhMath::hhMax( (maxs.y - mins.y) * 0.5f, (maxs.z - mins.z) * 0.5f );
}
} else {
projectile = NULL;
}
}
/*
================
hhFireController::DetermineProjectileAxis
================
*/
idMat3 hhFireController::DetermineProjectileAxis( const idMat3& axis ) {
idVec3 dir = hhUtils::RandomSpreadDir( axis, spread );
idAngles projectileAngles( dir.ToAngles() );
projectileAngles[YAW] += yawSpread*hhMath::Sin(gameLocal.random.RandomFloat()*hhMath::TWO_PI); //rww - seperate optional yaw spread
projectileAngles[2] = axis.ToAngles()[2];
return projectileAngles.ToMat3();
}
/*
================
hhFireController::LaunchProjectiles
================
*/
bool hhFireController::LaunchProjectiles( const idVec3& pushVelocity ) {
if( !GetProjectileOwner() ) {
return false;
}
// check if we're out of ammo or the clip is empty
if( !HasAmmo() ) {
return false;
}
UseAmmo();
// calculate the muzzle position
CalculateMuzzlePosition( muzzleOrigin, muzzleAxis );
if ( !gameLocal.isClient || dict->GetBool("net_clientProjectiles", "1") ) { //HUMANHEAD rww - clientside projectiles, because our weapons make the god of bandwidth weep.
//HUMANHEAD: aob
idVec3 adjustedOrigin = AssureInsideCollisionBBox( muzzleOrigin, GetSelf()->GetAxis(), GetCollisionBBox(), projectileMaxHalfDimension );
idMat3 aimAxis = DetermineAimAxis( adjustedOrigin, GetSelf()->GetAxis() );
//HUMANHEAD END
LaunchProjectiles( adjustedOrigin, aimAxis, pushVelocity, GetProjectileOwner() );
//rww - remove this from here and only do it on the client, we need to create the effect locally and with knowledge
//of if we should get the viewmodel bone or the worldmodel one
//CreateMuzzleFx( muzzleOrigin, muzzleAxis );
}
if (gameLocal.GetLocalPlayer())
{ //rww - create muzzle fx on client
idVec3 localMuzzleOrigin = muzzleOrigin;
idMat3 localMuzzleAxis = muzzleAxis;
if (gameLocal.isMultiplayer) { //rww - check if we should display the actual muzzle flash from a point different than the projectile launch location
idVec3 newOrigin;
idMat3 newAxis;
if (CheckThirdPersonMuzzle(newOrigin, newAxis)) {
localMuzzleOrigin = newOrigin;
localMuzzleAxis = newAxis;
}
}
CreateMuzzleFx( localMuzzleOrigin, localMuzzleAxis );
}
return true;
}
/*
================
hhFireController::CheckDeferredProjectiles
================
*/
void hhFireController::CheckDeferredProjectiles(void) { //rww
assert(!gameLocal.isClient);
if (deferProjTime > gameLocal.time) {
return;
}
//FIXME compensate for intermediate time?
deferProjTime = gameLocal.time + 50; //time is rather arbitrary.
int i = 0;
while (deferProjNum > 0 && i < MAX_NET_PROJECTILES) {
if (!deferProjOwner.IsValid()) {
return;
}
hhProjectile *projectile = SpawnProjectile();
projectile->Create(deferProjOwner.GetEntity(), deferProjLaunchOrigin, deferProjLaunchAxis);
projectile->spawnArgs.Set( "weapontype", GetSelf()->spawnArgs.GetString("ddaname", "") );
projectile->Launch(deferProjLaunchOrigin, DetermineProjectileAxis(deferProjLaunchAxis), deferProjPushVelocity, 0.0f, 1.0f );
deferProjNum--;
i++;
}
}
/*
================
hhFireController::LaunchProjectiles
================
*/
void hhFireController::LaunchProjectiles( const idVec3& launchOrigin, const idMat3& aimAxis, const idVec3& pushVelocity, idEntity* projOwner ) {
if (gameLocal.isMultiplayer && numProjectiles > MAX_NET_PROJECTILES && !dict->GetBool("net_noProjectileDefer", "0") &&
!dict->GetBool("net_clientProjectiles", "1") && !gameLocal.isClient) {
//HUMANHEAD rww - in mp our gigantic single-snapshot projectile spawns tend to be very destructive toward bandwidth.
//and so, projectile deferring.
deferProjNum = numProjectiles;
deferProjTime = 0;
deferProjLaunchOrigin = launchOrigin;
deferProjLaunchAxis = aimAxis;
deferProjPushVelocity = pushVelocity;
deferProjOwner = projOwner;
}
else {
if (gameLocal.isClient && !gameLocal.isNewFrame) {
return;
}
hhProjectile* projectile = NULL;
bool clientProjectiles = dict->GetBool("net_clientProjectiles", "1");
for( int ix = 0; ix < numProjectiles; ++ix ) {
if (clientProjectiles) { //HUMANHEAD rww - clientside projectiles!
projectile = hhProjectile::SpawnClientProjectile( GetProjectileDict() );
}
else {
projectile = SpawnProjectile();
}
projectile->Create( projOwner, launchOrigin, aimAxis );
projectile->spawnArgs.Set( "weapontype", GetSelf()->spawnArgs.GetString("ddaname", "") );
projectile->Launch( launchOrigin, DetermineProjectileAxis(aimAxis), pushVelocity, 0.0f, 1.0f );
}
}
}
/*
================
hhFireController::AssureInsideCollisionBBox
================
*/
idVec3 hhFireController::AssureInsideCollisionBBox( const idVec3& origin, const idMat3& axis, const idBounds& ownerAbsBounds, float projMaxHalfDim ) const {
float distance = 0.0f;
if( !ownerAbsBounds.RayIntersection(origin, -axis[0], distance) ) {
distance = 0.0f;
}
// HUMANHEAD CJR: If the player is touching a portal, then set the projectile inside the player so it has a chance to collide with the portal
idEntity *owner = GetProjectileOwner();
if ( owner && owner->IsType( hhPlayer::Type ) ) {
hhPlayer *player = static_cast<hhPlayer *>(owner);
if ( player->IsPortalColliding() ) { // Player is touching a portal, so force it inside the player bounds
distance = 2.0f * idMath::Fabs( owner->GetPhysics()->GetBounds()[1].y ); // Push back by the player's size
}
} // HUMANHEAD END
//Need to come back half the size of the projectiles bbox to
//guarentee that the whole projectile is in the owners bbox
return origin + (distance + projMaxHalfDim) * -axis[0];
}
/*
================
hhFireController::CalculateMuzzlePosition
================
*/
void hhFireController::CalculateMuzzlePosition( idVec3& origin, idMat3& axis ) {
origin = GetMuzzlePosition();
axis = GetSelf()->GetAxis();
if( g_showProjectileLaunchPoint.GetBool() ) {
idVec3 v = (origin - GetSelf()->GetOrigin()) * GetSelf()->GetAxis().Transpose();
gameLocal.Printf( "Launching from: (relative to weapon): %s\n", v.ToString() );
hhUtils::DebugCross( colorGreen, origin, 5, 5000 );
gameRenderWorld->DebugLine( colorBlue, GetSelf()->GetOrigin(), GetSelf()->GetOrigin() + (v * GetSelf()->GetAxis()), 5000 );
}
}
/*
================
hhFireController::UpdateMuzzleFlashPosition
================
*/
void hhFireController::UpdateMuzzleFlashPosition() {
muzzleFlash.axis = GetSelf()->GetAxis();
muzzleFlash.origin = AssureInsideCollisionBBox( muzzleOrigin, muzzleFlash.axis, GetProjectileOwner()->GetPhysics()->GetAbsBounds(), projectileMaxHalfDimension );
//TEST
/*trace_t trace;
idVec3 flashSize = dict->GetVector( "flashSize" );
if( gameLocal.clip.TracePoint(trace, muzzleFlash.origin, muzzleFlash.origin + muzzleFlash.axis[0] * flashSize[0], MASK_VISIBILITY, GetSelf()) ) {
flashSize[0] *= trace.fraction;
}
muzzleFlash.lightRadius = flashSize;
muzzleFlash.origin += muzzleFlash.axis[0] * flashSize[0] * 0.5f;
muzzleFlash.lightCenter.Set( flashSize[0] * -0.5f, 0.0f, 0.0f );
hhUtils::Swap<float>( muzzleFlash.lightRadius[0], muzzleFlash.lightRadius[2] );
hhUtils::Swap<float>( muzzleFlash.lightCenter[0], muzzleFlash.lightCenter[2] );
muzzleFlash.axis = hhUtils::SwapXZ( muzzleFlash.axis );*/
//TEST
// put the world muzzle flash on the end of the joint, no matter what
//GetGlobalJointTransform( false, flashJointWorld, muzzleOrigin, muzzleFlash.axis );
}
/*
================
hhFireController::MuzzleFlash
================
*/
void hhFireController::MuzzleFlash() {
if (!g_muzzleFlash.GetBool()) {
return;
}
UpdateMuzzleFlashPosition();
if( muzzleFlash.lightRadius[0] < VECTOR_EPSILON || muzzleFlash.lightRadius[1] < VECTOR_EPSILON || muzzleFlash.lightRadius[2] < VECTOR_EPSILON ) {
return;
}
// these will be different each fire
muzzleFlash.shaderParms[ SHADERPARM_TIMEOFFSET ] = -MS2SEC( gameLocal.GetTime() );
muzzleFlash.shaderParms[ SHADERPARM_DIVERSITY ] = gameLocal.random.RandomFloat();
//info.worldMuzzleFlash.shaderParms[ SHADERPARM_TIMEOFFSET ] = -MS2SEC( gameLocal.GetTime() );
//info.worldMuzzleFlash.shaderParms[ SHADERPARM_DIVERSITY ] = renderEntity.shaderParms[ SHADERPARM_DIVERSITY ];
// the light will be removed at this time
muzzleFlashEnd = gameLocal.GetTime() + flashTime;
if ( muzzleFlashHandle != -1 ) {
gameRenderWorld->UpdateLightDef( muzzleFlashHandle, &muzzleFlash );
//gameRenderWorld->UpdateLightDef( info.worldMuzzleFlashHandle, &info.worldMuzzleFlash );
} else {
muzzleFlashHandle = gameRenderWorld->AddLightDef( &muzzleFlash );
//info.worldMuzzleFlashHandle = gameRenderWorld->AddLightDef( &info.worldMuzzleFlash );
}
}
/*
================
hhFireController::UpdateMuzzleFlash
================
*/
void hhFireController::UpdateMuzzleFlash() {
AttemptToRemoveMuzzleFlash();
if( muzzleFlashHandle != -1 ) {
UpdateMuzzleFlashPosition();
if( muzzleFlash.lightRadius[0] < VECTOR_EPSILON || muzzleFlash.lightRadius[1] < VECTOR_EPSILON || muzzleFlash.lightRadius[2] < VECTOR_EPSILON ) { //rww - added to mimic the behaviour of hhFireController::MuzzleFlash
return;
}
gameRenderWorld->UpdateLightDef( muzzleFlashHandle, &muzzleFlash );
//gameRenderWorld->UpdateLightDef( worldMuzzleFlashHandle, &worldMuzzleFlash );
}
}
/*
================
hhFireController::CreateMuzzleFx
================
*/
void hhFireController::CreateMuzzleFx( const idVec3& pos, const idMat3& axis ) {
hhFxInfo fxInfo;
if (!gameLocal.GetLocalPlayer()) { //rww - not at all necessary for ded server
return;
}
if( GetSelf()->IsHidden() || !GetSelf()->GetRenderEntity()->hModel ) {
return;
}
fxInfo.SetNormal( axis[0] );
fxInfo.RemoveWhenDone( true );
fxInfo.SetEntity( GetSelf() );
//GetSelf()->BroadcastFxInfo( dict->GetString("fx_muzzleFlash"), pos, axis, &fxInfo );
//rww - this is now client-only.
GetSelf()->SpawnFxLocal( dict->GetString("fx_muzzleFlash"), pos, axis, &fxInfo, true );
}
/*
================
hhFireController::Save
================
*/
void hhFireController::Save( idSaveGame *savefile ) const {
savefile->WriteDict( dict );
savefile->WriteFloat( yawSpread );
savefile->WriteString( projDictName );
savefile->WriteVec3( muzzleOrigin );
savefile->WriteMat3( muzzleAxis );
savefile->WriteRenderLight( muzzleFlash );
//HUMANHEAD PCF mdl 05/04/06 - Don't save light handles
//savefile->WriteInt( muzzleFlashHandle );
savefile->WriteInt( muzzleFlashEnd );
savefile->WriteInt( flashTime );
savefile->WriteInt( ammoRequired );
savefile->WriteFloat( fireDelay );
savefile->WriteFloat( spread );
savefile->WriteBool( bCrosshair );
savefile->WriteFloat( projectileMaxHalfDimension );
savefile->WriteInt( numProjectiles );
//HUMANHEAD PCF mdl 05/04/06 - Save whether the light is active
savefile->WriteBool( muzzleFlashHandle != -1 );
}
/*
================
hhFireController::Restore
================
*/
void hhFireController::Restore( idRestoreGame *savefile ) {
savefile->ReadDict( &restoredDict );
dict = &restoredDict;
savefile->ReadFloat( yawSpread );
savefile->ReadString( projDictName );
savefile->ReadVec3( muzzleOrigin );
savefile->ReadMat3( muzzleAxis );
savefile->ReadRenderLight( muzzleFlash );
//HUMANHEAD PCF mdl 05/04/06 - Don't save light handles
//savefile->ReadInt( muzzleFlashHandle );
savefile->ReadInt( muzzleFlashEnd );
savefile->ReadInt( flashTime );
savefile->ReadInt( ammoRequired );
savefile->ReadFloat( fireDelay );
savefile->ReadFloat( spread );
savefile->ReadBool( bCrosshair );
savefile->ReadFloat( projectileMaxHalfDimension );
savefile->ReadInt( numProjectiles );
//HUMANHEAD PCF mdl 05/04/06 - Restore the light if necessary
bool bLight;
savefile->ReadBool( bLight );
if ( bLight ) {
muzzleFlashHandle = gameRenderWorld->AddLightDef( &muzzleFlash );
}
SetProjectileDict( projDictName );
}
/*
==============================
hhFireController::GetMuzzlePosition
==============================
*/
idVec3 hhFireController::GetMuzzlePosition() const {
idVec3 muzzle( dict->GetVector("muzzleOffset", "2 0 0") );
return GetSelfConst()->GetOrigin() + ( muzzle * GetSelfConst()->GetAxis() );
}
/*
==============================
hhFireController::GetMuzzlePosition
==============================
*/
bool hhFireController::CheckThirdPersonMuzzle(idVec3 &origin, idMat3 &axis) { //rww
return false;
}
| 0 | 0.91767 | 1 | 0.91767 | game-dev | MEDIA | 0.996259 | game-dev | 0.985689 | 1 | 0.985689 |
hugoam/toy | 13,850 | jams/meta/_blocks.meta.cpp | #include <infra/Cpp20.h>
#ifdef TWO_MODULES
module ._blocks;
#else
#include <cstddef>
#include <stl/new.h>
#include <infra/ToString.h>
#include <infra/ToValue.h>
#include <type/Vector.h>
#include <refl/MetaDecl.h>
#include <refl/Module.h>
#include <meta/infra.meta.h>
#include <meta/jobs.meta.h>
#include <meta/type.meta.h>
#include <meta/tree.meta.h>
#include <meta/pool.meta.h>
#include <meta/refl.meta.h>
#include <meta/ecs.meta.h>
#include <meta/srlz.meta.h>
#include <meta/math.meta.h>
#include <meta/geom.meta.h>
#include <meta/lang.meta.h>
#include <meta/ctx.meta.h>
#include <meta/ui.meta.h>
#include <meta/uio.meta.h>
#include <meta/bgfx.meta.h>
#include <meta/gfx.meta.h>
#include <meta/gfx.ui.meta.h>
#include <meta/frame.meta.h>
#include <meta/util.meta.h>
#include <meta/core.meta.h>
#include <meta/visu.meta.h>
#include <meta/edit.meta.h>
#include <meta/block.meta.h>
#include <meta/shell.meta.h>
#include <meta/_blocks.meta.h>
#include <meta/_blocks.conv.h>
#endif
#include <blocks/Api.h>
using namespace two;
void two_ComponentHandle_Camp__construct_0(void* ref, span<void*> args) { UNUSED(args); new(stl::placeholder(), ref) two::ComponentHandle<Camp>( ); }
void two_ComponentHandle_Camp__copy_construct(void* ref, void* other) { new(stl::placeholder(), ref) two::ComponentHandle<Camp>((*static_cast<two::ComponentHandle<Camp>*>(other))); }
void two_ComponentHandle_Shield__construct_0(void* ref, span<void*> args) { UNUSED(args); new(stl::placeholder(), ref) two::ComponentHandle<Shield>( ); }
void two_ComponentHandle_Shield__copy_construct(void* ref, void* other) { new(stl::placeholder(), ref) two::ComponentHandle<Shield>((*static_cast<two::ComponentHandle<Shield>*>(other))); }
void two_ComponentHandle_Slug__construct_0(void* ref, span<void*> args) { UNUSED(args); new(stl::placeholder(), ref) two::ComponentHandle<Slug>( ); }
void two_ComponentHandle_Slug__copy_construct(void* ref, void* other) { new(stl::placeholder(), ref) two::ComponentHandle<Slug>((*static_cast<two::ComponentHandle<Slug>*>(other))); }
void two_ComponentHandle_Tank__construct_0(void* ref, span<void*> args) { UNUSED(args); new(stl::placeholder(), ref) two::ComponentHandle<Tank>( ); }
void two_ComponentHandle_Tank__copy_construct(void* ref, void* other) { new(stl::placeholder(), ref) two::ComponentHandle<Tank>((*static_cast<two::ComponentHandle<Tank>*>(other))); }
void Faction__construct_0(void* ref, span<void*> args) { new(stl::placeholder(), ref) Faction( *static_cast<uint32_t*>(args[0]), *static_cast<two::Colour*>(args[1]) ); }
void Camp__construct_0(void* ref, span<void*> args) { UNUSED(args); new(stl::placeholder(), ref) Camp( ); }
void Camp__construct_1(void* ref, span<void*> args) { new(stl::placeholder(), ref) Camp( *static_cast<toy::HSpatial*>(args[0]), *static_cast<two::vec3*>(args[1]), *static_cast<Faction*>(args[2]) ); }
void Shield__construct_0(void* ref, span<void*> args) { UNUSED(args); new(stl::placeholder(), ref) Shield( ); }
void Shield__construct_1(void* ref, span<void*> args) { new(stl::placeholder(), ref) Shield( *static_cast<toy::HSpatial*>(args[0]), *static_cast<toy::HEmitter*>(args[1]), *static_cast<Faction*>(args[2]), *static_cast<float*>(args[3]) ); }
void Tank__construct_0(void* ref, span<void*> args) { UNUSED(args); new(stl::placeholder(), ref) Tank( ); }
void Tank__construct_1(void* ref, span<void*> args) { new(stl::placeholder(), ref) Tank( *static_cast<toy::HSpatial*>(args[0]), *static_cast<toy::HMovable*>(args[1]), *static_cast<toy::HEmitter*>(args[2]), *static_cast<toy::HReceptor*>(args[3]), *static_cast<Faction*>(args[4]) ); }
void BlockWorld__construct_0(void* ref, span<void*> args) { new(stl::placeholder(), ref) BlockWorld( *static_cast<stl::string*>(args[0]), *static_cast<two::JobSystem*>(args[1]) ); }
namespace two
{
void _blocks_meta(Module& m)
{
UNUSED(m);
// Base Types
// Enums
// Sequences
// two::ComponentHandle<Camp>
{
Type& t = type<two::ComponentHandle<Camp>>();
static Meta meta = { t, &namspc({ "two" }), "ComponentHandle<Camp>", sizeof(two::ComponentHandle<Camp>), TypeClass::Struct };
// bases
// defaults
// constructors
static Constructor constructors[] = {
{ t, two_ComponentHandle_Camp__construct_0, {} }
};
// copy constructor
static CopyConstructor copy_constructor[] = {
{ t, two_ComponentHandle_Camp__copy_construct }
};
// members
// methods
// static members
static Class cls = { t, {}, {}, constructors, copy_constructor, {}, {}, {}, };
}
// two::ComponentHandle<Shield>
{
Type& t = type<two::ComponentHandle<Shield>>();
static Meta meta = { t, &namspc({ "two" }), "ComponentHandle<Shield>", sizeof(two::ComponentHandle<Shield>), TypeClass::Struct };
// bases
// defaults
// constructors
static Constructor constructors[] = {
{ t, two_ComponentHandle_Shield__construct_0, {} }
};
// copy constructor
static CopyConstructor copy_constructor[] = {
{ t, two_ComponentHandle_Shield__copy_construct }
};
// members
// methods
// static members
static Class cls = { t, {}, {}, constructors, copy_constructor, {}, {}, {}, };
}
// two::ComponentHandle<Slug>
{
Type& t = type<two::ComponentHandle<Slug>>();
static Meta meta = { t, &namspc({ "two" }), "ComponentHandle<Slug>", sizeof(two::ComponentHandle<Slug>), TypeClass::Struct };
// bases
// defaults
// constructors
static Constructor constructors[] = {
{ t, two_ComponentHandle_Slug__construct_0, {} }
};
// copy constructor
static CopyConstructor copy_constructor[] = {
{ t, two_ComponentHandle_Slug__copy_construct }
};
// members
// methods
// static members
static Class cls = { t, {}, {}, constructors, copy_constructor, {}, {}, {}, };
}
// two::ComponentHandle<Tank>
{
Type& t = type<two::ComponentHandle<Tank>>();
static Meta meta = { t, &namspc({ "two" }), "ComponentHandle<Tank>", sizeof(two::ComponentHandle<Tank>), TypeClass::Struct };
// bases
// defaults
// constructors
static Constructor constructors[] = {
{ t, two_ComponentHandle_Tank__construct_0, {} }
};
// copy constructor
static CopyConstructor copy_constructor[] = {
{ t, two_ComponentHandle_Tank__copy_construct }
};
// members
// methods
// static members
static Class cls = { t, {}, {}, constructors, copy_constructor, {}, {}, {}, };
}
// Faction
{
Type& t = type<Faction>();
static Meta meta = { t, &namspc({}), "Faction", sizeof(Faction), TypeClass::Object };
// bases
// defaults
// constructors
static Constructor constructors[] = {
{ t, Faction__construct_0, { { "id", type<uint32_t>(), }, { "colour", type<two::Colour>(), } } }
};
// copy constructor
// members
static Member members[] = {
{ t, offsetof(Faction, m_id), type<uint32_t>(), "id", nullptr, Member::Value, nullptr },
{ t, offsetof(Faction, m_colour), type<two::Colour>(), "colour", nullptr, Member::Value, nullptr }
};
// methods
// static members
static Class cls = { t, {}, {}, constructors, {}, members, {}, {}, };
}
// Camp
{
Type& t = type<Camp>();
static Meta meta = { t, &namspc({}), "Camp", sizeof(Camp), TypeClass::Object };
// bases
// defaults
// constructors
static Constructor constructors[] = {
{ t, Camp__construct_0, {} },
{ t, Camp__construct_1, { { "spatial", type<toy::HSpatial>(), }, { "position", type<two::vec3>(), }, { "faction", type<Faction>(), } } }
};
// copy constructor
// members
static Member members[] = {
{ t, offsetof(Camp, m_position), type<two::vec3>(), "position", nullptr, Member::Value, nullptr },
{ t, offsetof(Camp, m_faction), type<Faction>(), "faction", nullptr, Member::Flags(Member::Pointer|Member::Link), nullptr }
};
// methods
// static members
static Class cls = { t, {}, {}, constructors, {}, members, {}, {}, };
}
// Shield
{
Type& t = type<Shield>();
static Meta meta = { t, &namspc({}), "Shield", sizeof(Shield), TypeClass::Object };
// bases
// defaults
// constructors
static Constructor constructors[] = {
{ t, Shield__construct_0, {} },
{ t, Shield__construct_1, { { "spatial", type<toy::HSpatial>(), }, { "emitter", type<toy::HEmitter>(), }, { "faction", type<Faction>(), }, { "radius", type<float>(), } } }
};
// copy constructor
// members
static Member members[] = {
{ t, offsetof(Shield, m_faction), type<Faction>(), "faction", nullptr, Member::Flags(Member::Pointer|Member::Link), nullptr },
{ t, offsetof(Shield, m_radius), type<float>(), "radius", nullptr, Member::Value, nullptr },
{ t, offsetof(Shield, m_charge), type<float>(), "charge", nullptr, Member::Value, nullptr },
{ t, offsetof(Shield, m_discharge), type<float>(), "discharge", nullptr, Member::Value, nullptr }
};
// methods
// static members
static Class cls = { t, {}, {}, constructors, {}, members, {}, {}, };
}
// Slug
{
Type& t = type<Slug>();
static Meta meta = { t, &namspc({}), "Slug", sizeof(Slug), TypeClass::Object };
// bases
// defaults
static float power_default = 1.f;
// constructors
// copy constructor
// members
static Member members[] = {
{ t, offsetof(Slug, m_source), type<two::vec3>(), "source", nullptr, Member::Value, nullptr },
{ t, offsetof(Slug, m_velocity), type<two::vec3>(), "velocity", nullptr, Member::Value, nullptr },
{ t, offsetof(Slug, m_power), type<float>(), "power", &power_default, Member::Value, nullptr }
};
// methods
// static members
static Class cls = { t, {}, {}, {}, {}, members, {}, {}, };
}
// Tank
{
Type& t = type<Tank>();
static Meta meta = { t, &namspc({}), "Tank", sizeof(Tank), TypeClass::Object };
// bases
// defaults
// constructors
static Constructor constructors[] = {
{ t, Tank__construct_0, {} },
{ t, Tank__construct_1, { { "spatial", type<toy::HSpatial>(), }, { "movable", type<toy::HMovable>(), }, { "emitter", type<toy::HEmitter>(), }, { "receptor", type<toy::HReceptor>(), }, { "faction", type<Faction>(), } } }
};
// copy constructor
// members
// methods
// static members
static Class cls = { t, {}, {}, constructors, {}, {}, {}, {}, };
}
// BlockWorld
{
Type& t = type<BlockWorld>();
static Meta meta = { t, &namspc({}), "BlockWorld", sizeof(BlockWorld), TypeClass::Object };
// bases
static Type* bases[] = { &type<two::Complex>() };
static size_t bases_offsets[] = { base_offset<BlockWorld, two::Complex>() };
// defaults
static two::uvec3 block_subdiv_default = uvec3(20,4,20);
// constructors
static Constructor constructors[] = {
{ t, BlockWorld__construct_0, { { "name", type<stl::string>(), }, { "job_system", type<two::JobSystem>(), } } }
};
// copy constructor
// members
static Member members[] = {
{ t, offsetof(BlockWorld, m_world), type<toy::World>(), "world", nullptr, Member::NonMutable, nullptr },
{ t, offsetof(BlockWorld, m_bullet_world), type<toy::BulletWorld>(), "bullet_world", nullptr, Member::Flags(Member::NonMutable|Member::Component), nullptr },
{ t, offsetof(BlockWorld, m_navmesh), type<toy::Navmesh>(), "navmesh", nullptr, Member::Flags(Member::NonMutable|Member::Component), nullptr },
{ t, offsetof(BlockWorld, m_block_subdiv), type<two::uvec3>(), "block_subdiv", &block_subdiv_default, Member::Value, nullptr },
{ t, offsetof(BlockWorld, m_tile_scale), type<two::vec3>(), "tile_scale", nullptr, Member::Value, nullptr },
{ t, offsetof(BlockWorld, m_block_size), type<two::vec3>(), "block_size", nullptr, Member::Value, nullptr },
{ t, offsetof(BlockWorld, m_world_size), type<two::vec3>(), "world_size", nullptr, Member::Value, nullptr }
};
// methods
// static members
static Class cls = { t, bases, bases_offsets, constructors, {}, members, {}, {}, };
}
// Player
{
Type& t = type<Player>();
static Meta meta = { t, &namspc({}), "Player", sizeof(Player), TypeClass::Object };
// bases
// defaults
// constructors
// copy constructor
// members
// methods
// static members
static Class cls = { t, {}, {}, {}, {}, {}, {}, {}, };
}
{
Type& t = type<two::ComponentHandle<Camp>>();
static Alias alias = { &t, &namspc({}), "HCamp" };
m.m_aliases.push_back(&alias);
}
{
Type& t = type<two::ComponentHandle<Shield>>();
static Alias alias = { &t, &namspc({}), "HShield" };
m.m_aliases.push_back(&alias);
}
{
Type& t = type<two::ComponentHandle<Slug>>();
static Alias alias = { &t, &namspc({}), "HSlug" };
m.m_aliases.push_back(&alias);
}
{
Type& t = type<two::ComponentHandle<Tank>>();
static Alias alias = { &t, &namspc({}), "HTank" };
m.m_aliases.push_back(&alias);
}
m.m_types.push_back(&type<two::ComponentHandle<Camp>>());
m.m_types.push_back(&type<two::ComponentHandle<Shield>>());
m.m_types.push_back(&type<two::ComponentHandle<Slug>>());
m.m_types.push_back(&type<two::ComponentHandle<Tank>>());
m.m_types.push_back(&type<HCamp>());
m.m_types.push_back(&type<HShield>());
m.m_types.push_back(&type<HSlug>());
m.m_types.push_back(&type<HTank>());
m.m_types.push_back(&type<Faction>());
m.m_types.push_back(&type<Camp>());
m.m_types.push_back(&type<Shield>());
m.m_types.push_back(&type<Slug>());
m.m_types.push_back(&type<Tank>());
m.m_types.push_back(&type<BlockWorld>());
m.m_types.push_back(&type<Player>());
}
}
_blocks::_blocks()
: Module("_blocks", { &two_infra::m(), &two_jobs::m(), &two_type::m(), &two_tree::m(), &two_pool::m(), &two_refl::m(), &two_ecs::m(), &two_srlz::m(), &two_math::m(), &two_geom::m(), &two_lang::m(), &two_ctx::m(), &two_ui::m(), &two_uio::m(), &two_bgfx::m(), &two_gfx::m(), &two_gfx_ui::m(), &two_frame::m(), &toy_util::m(), &toy_core::m(), &toy_visu::m(), &toy_edit::m(), &toy_block::m(), &toy_shell::m() })
{
// setup reflection meta data
_blocks_meta(*this);
}
#ifdef _BLOCKS_MODULE
extern "C"
Module& getModule()
{
return _blocks::m();
}
#endif
| 0 | 0.688789 | 1 | 0.688789 | game-dev | MEDIA | 0.865704 | game-dev | 0.648592 | 1 | 0.648592 |
lukasmonk/lucaschess | 51,928 | Engines/Windows/gambitfruit/gfruit4bx/eval.cpp |
// eval.cpp
// includes
#include <cstdlib> // for abs()
#include "attack.h"
#include "board.h"
#include "colour.h"
#include "eval.h"
#include "material.h"
#include "move.h"
#include "option.h"
#include "pawn.h"
#include "piece.h"
#include "see.h"
#include "util.h"
#include "value.h"
#include "vector.h"
// macros
// macro
/*
BitBases
*/
#if defined _WIN32
#define ADD_PIECE(type) {\
egbb_piece[total_pieces] = type;\
egbb_square[total_pieces] = from;\
total_pieces++;\
};
#endif
/*
EndBitbases
*/
#define THROUGH(piece) ((piece)==Empty)
// constants and variables
const int KnightOutpostMatrix[2][256] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 2, 5,10,10, 5, 2, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 2, 5,10,10, 5, 2, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 4, 5, 5, 4, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 4, 5, 5, 4, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 2, 5,10,10, 5, 2, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 2, 5,10,10, 5, 2, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};
static int lazy_eval_cutoff = 50;
static bool KingSafety = false; // true
//static int KingSafetyMargin = 1600;
static bool king_is_safe[ColourNb];
static /* const */ int PieceActivityWeight = 256; // 100%
static /*const */ int ShelterOpening = 256; // 100%
static /* const */ int KingSafetyWeight = 256; // 100%
static /* const */ int PassedPawnWeight = 256; // 100%
static const int MobMove = 1;
static const int MobAttack = 1;
static const int MobDefense = 0;
static const int knight_mob[9] = {-16,-12,-8,-4, 0, 4, 8, 12, 16 };
static const int bishop_mob[14] = {-30,-25,-20,-15,-10,-5, 0, 5, 10, 15, 20, 25, 30, 35 };
static const int rook_mob_open[15] = { -14, -12,-10, -8, -6,-4,-2, 0, 2, 4, 6, 8, 10, 12, 14 };
static const int rook_mob_end[15] = { -28, -24,-20,-16,-12,-8,-4, 0, 4, 8, 12, 16, 20, 24, 28 };
static const int queen_mob_open[27] = {-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13 };
static const int queen_mob_end[27] = {-26,-24,-22,-20,-18,-16,-14,-12,-10,-8,-6,-4,-2,0,2,4,6,8,10,12,14,16,18,20,22,24,26 };
static const int pawns_on_bishop_colour_opening[9] = {9,6,3,0,-3,-6,-9,-12,-15};
static const int pawns_on_bishop_colour_endgame[9] = {12,8,4,0,-4,-8,-12,-16,-20};
static const int RookSemiOpenFileOpening = 10;
static const int RookSemiOpenFileEndgame = 10;
static const int RookOpenFileOpening = 20;
static const int RookOpenFileEndgame = 20;
static const int RookSemiKingFileOpening = 10;
static const int RookKingFileOpening = 20;
static const int RookOnBadPawnFileOpening = 8;
static const int RookOnBadPawnFileEndgame = 8;
static /* const */ int KingAttackOpening = 20; // was 20
static const int knight_tropism_opening = 3;
static const int bishop_tropism_opening = 2;
static const int rook_tropism_opening = 2;
static const int queen_tropism_opening = 2;
static const int knight_tropism_endgame = 3;
static const int bishop_tropism_endgame = 1;
static const int rook_tropism_endgame = 1;
static const int queen_tropism_endgame = 4;
static /* const */ int StormOpening = 10;
static const int Rook7thOpening = 20;
static const int Rook7thEndgame = 40;
static const int Queen7thOpening = 10;
static const int Queen7thEndgame = 20;
static const int TrappedBishop = 100;
static const int BlockedBishop = 50;
static const int BlockedRook = 50;
static const int BlockedCenterPawn = 10;
static const int PassedOpeningMin = 10;
static const int PassedOpeningMax = 70;
static const int PassedEndgameMin = 20;
static const int PassedEndgameMax = 140;
static const int UnstoppablePasser = 800;
static const int FreePasser = 60;
static const int AttackerDistance = 5;
static const int DefenderDistance = 20;
// "constants"
static const int KingAttackWeight[16] = {
0, 0, 128, 192, 224, 240, 248, 252, 254, 255, 256, 256 ,256, 256, 256, 256,
};
// variables
static int MobUnit[ColourNb][PieceNb];
static int KingAttackUnit[PieceNb];
// prototypes
static void eval_draw (const board_t * board, const material_info_t * mat_info, const pawn_info_t * pawn_info, int mul[2]);
static void eval_piece (const board_t * board, const material_info_t * mat_info, const pawn_info_t * pawn_info, int * opening, int * endgame);
static void eval_king (const board_t * board, const material_info_t * mat_info, int * opening, int * endgame);
static void eval_passer (const board_t * board, const pawn_info_t * pawn_info, int * opening, int * endgame);
static void eval_pattern (const board_t * board, int * opening, int * endgame);
static bool unstoppable_passer (const board_t * board, int pawn, int colour);
static bool king_passer (const board_t * board, int pawn, int colour);
static bool free_passer (const board_t * board, int pawn, int colour);
static int pawn_att_dist (int pawn, int king, int colour);
static int pawn_def_dist (int pawn, int king, int colour);
static void draw_init_list (int list[], const board_t * board, int pawn_colour);
static bool draw_krpkr (const int list[], int turn);
static bool draw_kbpkb (const int list[], int turn);
static int shelter_square (const board_t * board, int square, int colour);
static int shelter_file (const board_t * board, int file, int rank, int colour);
static int storm_file (const board_t * board, int file, int colour);
static bool bishop_can_attack (const board_t * board, int to, int colour);
// functions
// eval_init()
void eval_init() {
int colour;
int piece;
// UCI options
PieceActivityWeight = (option_get_int("Piece Activity") * 256 + 50) / 100;
//KingSafetyWeight = (option_get_int("King Safety") * 256 + 50) / 100;
PassedPawnWeight = (option_get_int("Passed Pawns") * 256 + 50) / 100;
ShelterOpening = (option_get_int("Pawn Shelter") * 256 + 50) / 100;
StormOpening = (10 * option_get_int("Pawn Storm")) / 100;
KingAttackOpening = (20 * option_get_int("King Attack")) / 100;
if (option_get_int("Chess Knowledge") == 500) lazy_eval_cutoff = ValueEvalInf;
else lazy_eval_cutoff = (50 * option_get_int("Chess Knowledge")) / 100;
// mobility table
for (colour = 0; colour < ColourNb; colour++) {
for (piece = 0; piece < PieceNb; piece++) {
MobUnit[colour][piece] = 0;
}
}
MobUnit[White][Empty] = MobMove;
MobUnit[White][BP] = MobAttack;
MobUnit[White][BN] = MobAttack;
MobUnit[White][BB] = MobAttack;
MobUnit[White][BR] = MobAttack;
MobUnit[White][BQ] = MobAttack;
MobUnit[White][BK] = MobAttack;
MobUnit[White][WP] = MobDefense;
MobUnit[White][WN] = MobDefense;
MobUnit[White][WB] = MobDefense;
MobUnit[White][WR] = MobDefense;
MobUnit[White][WQ] = MobDefense;
MobUnit[White][WK] = MobDefense;
MobUnit[Black][Empty] = MobMove;
MobUnit[Black][WP] = MobAttack;
MobUnit[Black][WN] = MobAttack;
MobUnit[Black][WB] = MobAttack;
MobUnit[Black][WR] = MobAttack;
MobUnit[Black][WQ] = MobAttack;
MobUnit[Black][WK] = MobAttack;
MobUnit[Black][BP] = MobDefense;
MobUnit[Black][BN] = MobDefense;
MobUnit[Black][BB] = MobDefense;
MobUnit[Black][BR] = MobDefense;
MobUnit[Black][BQ] = MobDefense;
MobUnit[Black][BK] = MobDefense;
// KingAttackUnit[]
for (piece = 0; piece < PieceNb; piece++) {
KingAttackUnit[piece] = 0;
}
KingAttackUnit[WN] = 1;
KingAttackUnit[WB] = 1;
KingAttackUnit[WR] = 2;
KingAttackUnit[WQ] = 4;
KingAttackUnit[BN] = 1;
KingAttackUnit[BB] = 1;
KingAttackUnit[BR] = 2;
KingAttackUnit[BQ] = 4;
}
// eval()
int eval(/*const*/ board_t * board, int alpha, int beta, bool do_le, bool in_check) {
int opening, endgame;
material_info_t mat_info[1];
pawn_info_t pawn_info[1];
int mul[ColourNb];
int phase;
int eval;
int wb, bb;
int lazy_eval;
int tempo;
bool is_cut;
/*
BitBases
*/
#if defined _WIN32
int total_pieces;
int player;
int w_ksq;
int b_ksq;
int egbb_piece[32];
int egbb_square[32];
player = board->turn;
total_pieces = 0;
egbb_piece[0] = 0;
egbb_piece[1] = 0;
egbb_square[1] = 0;
egbb_square[2] = 0;
#endif
/*
End Bitbases
*/
ASSERT(board!=NULL);
ASSERT(board_is_legal(board));
ASSERT(!board_is_check(board)); // exceptions are extremely rare
// init
opening = 0;
endgame = 0;
// material
material_get_info(mat_info,board);
/*
BitBases
*/
#if defined _WIN32
if(egbb_is_loaded && (mat_info->flags & MatBitbaseFlag) != 0) {
const sq_t * ptr;
int from;
int score;
int piece;
int psquare;
//int sq_copy[64];
//for (from=0; from < 64; ++from) {
// sq_copy[from] = board->square[SQUARE_FROM_64(from)];
//}
for (from=0; from < 64; ++from) {
;
if (board->square[SQUARE_FROM_64(from)] == Empty) continue;
switch (board->square[SQUARE_FROM_64(from)]) {
case WP:
ADD_PIECE(_WPAWN);
break;
case BP:
ADD_PIECE(_BPAWN);
break;
case WN:
ADD_PIECE(_WKNIGHT);
break;
case BN:
ADD_PIECE(_BKNIGHT);
break;
case WB:
ADD_PIECE(_WBISHOP);
break;
case BB:
ADD_PIECE(_BBISHOP);
break;
case WR:
ADD_PIECE(_WROOK);
break;
case BR:
ADD_PIECE(_BROOK);
break;
case WQ:
ADD_PIECE(_WQUEEN);
break;
case BQ:
ADD_PIECE(_BQUEEN);
break;
case WK:
w_ksq = from;
break;
case BK:
b_ksq = from;
break;
default:
break;
}
}
score = probe_egbb(player,w_ksq,b_ksq,
egbb_piece[0],egbb_square[0],egbb_piece[1],egbb_square[1]);
if(score != _NOTFOUND) {
if (score == 0) {
return ValueDraw;
} else {
return score;
}
}
}
#endif
/*
End bitbases
*/
opening += mat_info->opening;
endgame += mat_info->endgame;
mul[White] = mat_info->mul[White];
mul[Black] = mat_info->mul[Black];
// PST
opening += board->opening;
endgame += board->endgame;
// draw
eval_draw(board,mat_info,pawn_info,mul);
if (mat_info->mul[White] < mul[White]) mul[White] = mat_info->mul[White];
if (mat_info->mul[Black] < mul[Black]) mul[Black] = mat_info->mul[Black];
if (mul[White] == 0 && mul[Black] == 0) return ValueDraw;
is_cut = false;
/*
// Tempo
if (COLOUR_IS_WHITE(board->turn)){
opening += 20;
endgame += 10;
} else{
opening -= 20;
endgame -= 10;
}
*/
phase = mat_info->phase;
lazy_eval = ((opening * (256 - mat_info->phase)) + (endgame * mat_info->phase)) / 256;
if (COLOUR_IS_BLACK(board->turn)) lazy_eval = -lazy_eval;
/* lazy Cutoff */
if (do_le && !in_check && board->piece_size[White] > 2 && board->piece_size[Black] > 2) {
ASSERT(eval>=-ValueEvalInf&&eval<=+ValueEvalInf);
//if (lazy_eval - lazy_eval_cutoff >= beta)
// return (lazy_eval);
if (lazy_eval + board->pvalue + lazy_eval_cutoff <= alpha) {
//return (lazy_eval+board->pvalue);
is_cut = true;
goto cut;
}
// ende lazy cuttoff
}
// pawns
pawn_get_info(pawn_info,board);
opening += pawn_info->opening;
endgame += pawn_info->endgame;
// eval
eval_piece(board,mat_info,pawn_info,&opening,&endgame);
eval_king(board,mat_info,&opening,&endgame);
eval_passer(board,pawn_info,&opening,&endgame);
eval_pattern(board,&opening,&endgame);
cut:
// phase mix
//phase = mat_info->phase;
eval = ((opening * (256 - phase)) + (endgame * phase)) / 256;
// drawish bishop endgames
if ((mat_info->flags & DrawBishopFlag) != 0) {
wb = board->piece[White][1];
ASSERT(PIECE_IS_BISHOP(board->square[wb]));
bb = board->piece[Black][1];
ASSERT(PIECE_IS_BISHOP(board->square[bb]));
if (SQUARE_COLOUR(wb) != SQUARE_COLOUR(bb)) {
if (mul[White] == 16) mul[White] = 8; // 1/2
if (mul[Black] == 16) mul[Black] = 8; // 1/2
}
}
// draw bound
if (eval > ValueDraw) {
eval = (eval * mul[White]) / 16;
} else if (eval < ValueDraw) {
eval = (eval * mul[Black]) / 16;
}
// value range
if (eval < -ValueEvalInf) eval = -ValueEvalInf;
if (eval > +ValueEvalInf) eval = +ValueEvalInf;
ASSERT(eval>=-ValueEvalInf&&eval<=+ValueEvalInf);
// turn
if (COLOUR_IS_BLACK(board->turn)) eval = -eval;
if (!is_cut) board->pvalue = abs(eval - lazy_eval);
ASSERT(!value_is_mate(eval));
// Tempo
tempo = 10;//((10 * (256 - phase)) + (20 * phase)) / 256;
// Tempo draw bound
if (COLOUR_IS_WHITE(board->turn)) {
if (eval > ValueDraw) {
tempo = (tempo * mul[White]) / 16;
} else if (eval < ValueDraw) {
tempo = (tempo * mul[Black]) / 16;
}
} else {
if (eval < ValueDraw) {
tempo = (tempo * mul[White]) / 16;
} else if (eval > ValueDraw) {
tempo = (tempo * mul[Black]) / 16;
}
}
return (eval+tempo);
}
// eval_draw()
static void eval_draw(const board_t * board, const material_info_t * mat_info, const pawn_info_t * pawn_info, int mul[2]) {
int colour;
int me, opp;
int pawn, king;
int pawn_file;
int prom;
int list[7+1];
ASSERT(board!=NULL);
ASSERT(mat_info!=NULL);
ASSERT(pawn_info!=NULL);
ASSERT(mul!=NULL);
// draw patterns
for (colour = 0; colour < ColourNb; colour++) {
me = colour;
opp = COLOUR_OPP(me);
// KB*P+K* draw
if ((mat_info->cflags[me] & MatRookPawnFlag) != 0) {
pawn = pawn_info->single_file[me];
if (pawn != SquareNone) { // all pawns on one file
pawn_file = SQUARE_FILE(pawn);
if (pawn_file == FileA || pawn_file == FileH) {
king = KING_POS(board,opp);
prom = PAWN_PROMOTE(pawn,me);
if (DISTANCE(king,prom) <= 1 && !bishop_can_attack(board,prom,me)) {
mul[me] = 0;
}
}
}
}
// K(B)P+K+ draw
if ((mat_info->cflags[me] & MatBishopFlag) != 0) {
pawn = pawn_info->single_file[me];
if (pawn != SquareNone) { // all pawns on one file
king = KING_POS(board,opp);
if (SQUARE_FILE(king) == SQUARE_FILE(pawn)
&& PAWN_RANK(king,me) > PAWN_RANK(pawn,me)
&& !bishop_can_attack(board,king,me)) {
mul[me] = 1; // 1/16
}
}
}
// KNPK* draw
if ((mat_info->cflags[me] & MatKnightFlag) != 0) {
pawn = board->pawn[me][0];
king = KING_POS(board,opp);
if (SQUARE_FILE(king) == SQUARE_FILE(pawn)
&& PAWN_RANK(king,me) > PAWN_RANK(pawn,me)
&& PAWN_RANK(pawn,me) <= Rank6) {
mul[me] = 1; // 1/16
}
}
}
// recognisers, only heuristic draws here!
if (false) {
} else if (mat_info->recog == MAT_KRPKR) {
// KRPKR (white)
draw_init_list(list,board,White);
if (draw_krpkr(list,board->turn)) {
mul[White] = 1; // 1/16;
mul[Black] = 1; // 1/16;
}
} else if (mat_info->recog == MAT_KRKRP) {
// KRPKR (black)
draw_init_list(list,board,Black);
if (draw_krpkr(list,COLOUR_OPP(board->turn))) {
mul[White] = 1; // 1/16;
mul[Black] = 1; // 1/16;
}
} else if (mat_info->recog == MAT_KBPKB) {
// KBPKB (white)
draw_init_list(list,board,White);
if (draw_kbpkb(list,board->turn)) {
mul[White] = 1; // 1/16;
mul[Black] = 1; // 1/16;
}
} else if (mat_info->recog == MAT_KBKBP) {
// KBPKB (black)
draw_init_list(list,board,Black);
if (draw_kbpkb(list,COLOUR_OPP(board->turn))) {
mul[White] = 1; // 1/16;
mul[Black] = 1; // 1/16;
}
}
}
// eval_piece()
static void eval_piece(const board_t * board, const material_info_t * mat_info, const pawn_info_t * pawn_info, int * opening, int * endgame) {
int colour;
int op[ColourNb], eg[ColourNb];
int me, opp;
int opp_flag;
const sq_t * ptr;
int from, to;
int piece;
int mob;
int capture;
const int * unit;
int rook_file, king_file;
int king;
int delta;
int king_rank,piece_rank,new_mob, piece_file;
ASSERT(board!=NULL);
ASSERT(mat_info!=NULL);
ASSERT(pawn_info!=NULL);
ASSERT(opening!=NULL);
ASSERT(endgame!=NULL);
// init
op[0] = op[1] = eg[0] = eg[1] = 0;
// eval
for (colour = 0; colour < ColourNb; colour++) {
me = colour;
opp = COLOUR_OPP(me);
opp_flag = COLOUR_FLAG(opp);
unit = MobUnit[me];
// piece loop
for (ptr = &board->piece[me][1]; (from=*ptr) != SquareNone; ptr++) { // HACK: no king
piece = board->square[from];
switch (PIECE_TYPE(piece)) {
case Knight64:
// mobility
mob = 0;
mob += unit[board->square[from-33]];
mob += unit[board->square[from-31]];
mob += unit[board->square[from-18]];
mob += unit[board->square[from-14]];
mob += unit[board->square[from+14]];
mob += unit[board->square[from+18]];
mob += unit[board->square[from+31]];
mob += unit[board->square[from+33]];
op[me] += knight_mob[mob];
eg[me] += knight_mob[mob];
king = KING_POS(board,opp);
king_file = SQUARE_FILE(king);
king_rank = SQUARE_RANK(king);
piece_file = SQUARE_FILE(from);
piece_rank = SQUARE_RANK(from);
op[me] += (knight_tropism_opening * 8) - (((abs(king_file-piece_file) + abs(king_rank-piece_rank)) * knight_tropism_opening));
eg[me] += (knight_tropism_endgame * 8) - (((abs(king_file-piece_file) + abs(king_rank-piece_rank)) * knight_tropism_endgame));
// outpost
mob = 0;
if (me == White) {
if (board->square[from-17] == WP)
mob += KnightOutpostMatrix[me][from];
if (board->square[from-15] == WP)
mob += KnightOutpostMatrix[me][from];
}
else {
if (board->square[from+17] == BP)
mob += KnightOutpostMatrix[me][from];
if (board->square[from+15] == BP)
mob += KnightOutpostMatrix[me][from];
}
op[me] += mob;
// eg[me] += mob;
break;
case Bishop64:
// mobility
mob = 0;
for (to = from-17; capture=board->square[to], THROUGH(capture); to -= 17) mob += MobMove;
mob += unit[capture];
for (to = from-15; capture=board->square[to], THROUGH(capture); to -= 15) mob += MobMove;
mob += unit[capture];
for (to = from+15; capture=board->square[to], THROUGH(capture); to += 15) mob += MobMove;
mob += unit[capture];
for (to = from+17; capture=board->square[to], THROUGH(capture); to += 17) mob += MobMove;
mob += unit[capture];
op[me] += bishop_mob[mob];
eg[me] += bishop_mob[mob];
king = KING_POS(board,opp);
king_file = SQUARE_FILE(king);
king_rank = SQUARE_RANK(king);
piece_file = SQUARE_FILE(from);
piece_rank = SQUARE_RANK(from);
op[me] += (bishop_tropism_opening * 8) - (((abs(king_file-piece_file) + abs(king_rank-piece_rank)) * bishop_tropism_opening));
eg[me] += (bishop_tropism_endgame * 8) - (((abs(king_file-piece_file) + abs(king_rank-piece_rank)) * bishop_tropism_endgame));
if (SQUARE_COLOUR(from) == White) {
op[me] += pawns_on_bishop_colour_opening[pawn_info->wsp[me]];
eg[me] += pawns_on_bishop_colour_endgame[pawn_info->wsp[me]];
} else {
if (me == White) {
op[me] += pawns_on_bishop_colour_opening[(board->number[WhitePawn12] - pawn_info->wsp[me])];
eg[me] += pawns_on_bishop_colour_endgame[(board->number[WhitePawn12] - pawn_info->wsp[me])];
} else {
op[me] += pawns_on_bishop_colour_opening[(board->number[BlackPawn12] - pawn_info->wsp[me])];
eg[me] += pawns_on_bishop_colour_endgame[(board->number[BlackPawn12] - pawn_info->wsp[me])];
}
}
break;
case Rook64:
// mobility
mob = 0;
for (to = from-16; capture=board->square[to], THROUGH(capture); to -= 16) mob += MobMove;
mob += unit[capture];
for (to = from- 1; capture=board->square[to], THROUGH(capture); to -= 1) mob += MobMove;
mob += unit[capture];
for (to = from+ 1; capture=board->square[to], THROUGH(capture); to += 1) mob += MobMove;
mob += unit[capture];
for (to = from+16; capture=board->square[to], THROUGH(capture); to += 16) mob += MobMove;
mob += unit[capture];
op[me] += rook_mob_open[mob];
eg[me] += rook_mob_end[mob];
king = KING_POS(board,opp);
king_file = SQUARE_FILE(king);
king_rank = SQUARE_RANK(king);
piece_file = SQUARE_FILE(from);
piece_rank = SQUARE_RANK(from);
op[me] += (rook_tropism_opening * 8) - (((abs(king_file-piece_file) + abs(king_rank-piece_rank)) * rook_tropism_opening));
eg[me] += (rook_tropism_endgame * 8) - (((abs(king_file-piece_file) + abs(king_rank-piece_rank)) * rook_tropism_endgame));
// open file
op[me] -= RookOpenFileOpening / 2;
eg[me] -= RookOpenFileEndgame / 2;
rook_file = SQUARE_FILE(from);
if (board->pawn_file[me][rook_file] == 0) { // no friendly pawn
op[me] += RookSemiOpenFileOpening;
eg[me] += RookSemiOpenFileEndgame;
if (board->pawn_file[opp][rook_file] == 0) { // no enemy pawn
op[me] += RookOpenFileOpening - RookSemiOpenFileOpening;
eg[me] += RookOpenFileEndgame - RookSemiOpenFileEndgame;
} else {
switch (rook_file) {
case FileA:
if ((pawn_info->badpawns[opp] & BadPawnFileA) != 0) {
op[me] += RookOnBadPawnFileOpening;
eg[me] += RookOnBadPawnFileEndgame;
}
break;
case FileB:
if ((pawn_info->badpawns[opp] & BadPawnFileB) != 0) {
op[me] += RookOnBadPawnFileOpening;
eg[me] += RookOnBadPawnFileEndgame;
}
break;
case FileC:
if ((pawn_info->badpawns[opp] & BadPawnFileC) != 0) {
op[me] += RookOnBadPawnFileOpening;
eg[me] += RookOnBadPawnFileEndgame;
}
break;
case FileD:
if ((pawn_info->badpawns[opp] & BadPawnFileD) != 0) {
op[me] += RookOnBadPawnFileOpening;
eg[me] += RookOnBadPawnFileEndgame;
}
break;
case FileE:
if ((pawn_info->badpawns[opp] & BadPawnFileE) != 0) {
op[me] += RookOnBadPawnFileOpening;
eg[me] += RookOnBadPawnFileEndgame;
}
break;
case FileF:
if ((pawn_info->badpawns[opp] & BadPawnFileF) != 0) {
op[me] += RookOnBadPawnFileOpening;
eg[me] += RookOnBadPawnFileEndgame;
}
break;
case FileG:
if ((pawn_info->badpawns[opp] & BadPawnFileG) != 0) {
op[me] += RookOnBadPawnFileOpening;
eg[me] += RookOnBadPawnFileEndgame;
}
break;
case FileH:
if ((pawn_info->badpawns[opp] & BadPawnFileH) != 0) {
op[me] += RookOnBadPawnFileOpening;
eg[me] += RookOnBadPawnFileEndgame;
}
break;
}
}
if ((mat_info->cflags[opp] & MatKingFlag) != 0) {
king = KING_POS(board,opp);
king_file = SQUARE_FILE(king);
delta = abs(rook_file-king_file); // file distance
if (delta <= 1) {
op[me] += RookSemiKingFileOpening;
if (delta == 0) op[me] += RookKingFileOpening - RookSemiKingFileOpening;
}
}
}
// 7th rank
if (PAWN_RANK(from,me) == Rank7) {
if ((pawn_info->flags[opp] & BackRankFlag) != 0 // opponent pawn on 7th rank
|| PAWN_RANK(KING_POS(board,opp),me) == Rank8) {
op[me] += Rook7thOpening;
eg[me] += Rook7thEndgame;
}
}
break;
case Queen64:
// mobility
mob = 0;
for (to = from-17; capture=board->square[to], THROUGH(capture); to -= 17) mob += MobMove;
mob += unit[capture];
for (to = from-16; capture=board->square[to], THROUGH(capture); to -= 16) mob += MobMove;
mob += unit[capture];
for (to = from-15; capture=board->square[to], THROUGH(capture); to -= 15) mob += MobMove;
mob += unit[capture];
for (to = from- 1; capture=board->square[to], THROUGH(capture); to -= 1) mob += MobMove;
mob += unit[capture];
for (to = from+ 1; capture=board->square[to], THROUGH(capture); to += 1) mob += MobMove;
mob += unit[capture];
for (to = from+15; capture=board->square[to], THROUGH(capture); to += 15) mob += MobMove;
mob += unit[capture];
for (to = from+16; capture=board->square[to], THROUGH(capture); to += 16) mob += MobMove;
mob += unit[capture];
for (to = from+17; capture=board->square[to], THROUGH(capture); to += 17) mob += MobMove;
mob += unit[capture];
op[me] += queen_mob_open[mob];
eg[me] += queen_mob_end[mob];
king = KING_POS(board,opp);
king_file = SQUARE_FILE(king);
king_rank = SQUARE_RANK(king);
piece_file = SQUARE_FILE(from);
piece_rank = SQUARE_RANK(from);
op[me] += (queen_tropism_opening * 8) - (((abs(king_file-piece_file) + abs(king_rank-piece_rank)) * queen_tropism_opening));
eg[me] += (queen_tropism_endgame * 8) - (((abs(king_file-piece_file) + abs(king_rank-piece_rank)) * queen_tropism_endgame));
// 7th rank
if (PAWN_RANK(from,me) == Rank7) {
if ((pawn_info->flags[opp] & BackRankFlag) != 0 // opponent pawn on 7th rank
|| PAWN_RANK(KING_POS(board,opp),me) == Rank8) {
op[me] += Queen7thOpening;
eg[me] += Queen7thEndgame;
}
}
break;
}
}
}
// update
*opening += ((op[White] - op[Black]) * PieceActivityWeight) / 256;
*endgame += ((eg[White] - eg[Black]) * PieceActivityWeight) / 256;
}
// eval_king()
static void eval_king(const board_t * board, const material_info_t * mat_info, int * opening, int * endgame) {
int colour;
int op[ColourNb], eg[ColourNb];
int me, opp;
int from;
int penalty_1, penalty_2;
int tmp;
int penalty;
int king;
const sq_t * ptr;
int piece;
int attack_tot;
int piece_nb;
int king_file, king_rank;
ASSERT(board!=NULL);
ASSERT(mat_info!=NULL);
ASSERT(opening!=NULL);
ASSERT(endgame!=NULL);
// init
op[0] = op[1] = eg[0] = eg[1] = 0;
// white pawn shelter
if ((mat_info->cflags[White] & MatKingFlag) != 0) {
/* Thomas simple pattern king safety */
king_is_safe[White] = false;
if (KingSafety) {
if (board->square[G1] == WK || board->square[H1] == WK) {
if (board->square[G2] == WP && (board->square[H2] == WP || board->square[H3] == WP)) {
king_is_safe[White] = true;
}
else if (board->square[F2] == WP && board->square[G3] == WP && board->square[H2] == WP) {
king_is_safe[White] = true;
}
}
else if (board->square[B1] == WK || board->square[A1] == WK) {
if (board->square[B2] == WP && (board->square[A2] == WP || board->square[A3] == WP)) {
king_is_safe[White] = true;
}
else if (board->square[C2] == WP && board->square[B3] == WP && board->square[A2] == WP) {
king_is_safe[White] = true;
}
}
}
if (king_is_safe[White] == false) {
me = White;
// king
penalty_1 = shelter_square(board,KING_POS(board,me),me);
// castling
penalty_2 = penalty_1;
if ((board->flags & FlagsWhiteKingCastle) != 0) {
tmp = shelter_square(board,G1,me);
if (tmp < penalty_2) penalty_2 = tmp;
}
if ((board->flags & FlagsWhiteQueenCastle) != 0) {
tmp = shelter_square(board,B1,me);
if (tmp < penalty_2) penalty_2 = tmp;
}
ASSERT(penalty_2>=0&&penalty_2<=penalty_1);
// penalty
penalty = (penalty_1 + penalty_2) / 2;
ASSERT(penalty>=0);
op[me] -= (penalty * ShelterOpening) / 256;
}
}
// black pawn shelter
if ((mat_info->cflags[Black] & MatKingFlag) != 0) {
king_is_safe[Black] = false;
if (KingSafety) {
if (board->square[G8] == BK || board->square[H8] == BK) {
if (board->square[G7] == BP && (board->square[H7] == BP || board->square[H6] == BP)) {
king_is_safe[Black] = true;
}
else if (board->square[F7] == BP && board->square[G6] == BP && board->square[H7] == BP) {
king_is_safe[Black] = true;
}
}
else if (board->square[B8] == BK || board->square[A8] == BK) {
if (board->square[B7] == BP && (board->square[A7] == BP || board->square[A6] == BP)) {
king_is_safe[Black] = true;
}
else if (board->square[C7] == BP && board->square[B6] == BP && board->square[A7] == BP) {
king_is_safe[Black] = true;
}
}
}
if (king_is_safe[Black] == false) {
me = Black;
// king
penalty_1 = shelter_square(board,KING_POS(board,me),me);
// castling
penalty_2 = penalty_1;
if ((board->flags & FlagsBlackKingCastle) != 0) {
tmp = shelter_square(board,G8,me);
if (tmp < penalty_2) penalty_2 = tmp;
}
if ((board->flags & FlagsBlackQueenCastle) != 0) {
tmp = shelter_square(board,B8,me);
if (tmp < penalty_2) penalty_2 = tmp;
}
ASSERT(penalty_2>=0&&penalty_2<=penalty_1);
// penalty
penalty = (penalty_1 + penalty_2) / 2;
ASSERT(penalty>=0);
op[me] -= (penalty * ShelterOpening) / 256;
}
}
// king attacks
for (colour = 0; colour < ColourNb; colour++) {
if ((mat_info->cflags[colour] & MatKingFlag) != 0) {
me = colour;
opp = COLOUR_OPP(me);
king = KING_POS(board,me);
king_file = SQUARE_FILE(king);
king_rank = SQUARE_RANK(king);
// piece attacks
attack_tot = 0;
piece_nb = 0;
for (ptr = &board->piece[opp][1]; (from=*ptr) != SquareNone; ptr++) { // HACK: no king
piece = board->square[from];
if (piece_attack_king(board,piece,from,king)) {
piece_nb++;
attack_tot += KingAttackUnit[piece];
}
/* else{
if ((abs(king_file-SQUARE_FILE(from)) + abs(king_rank-SQUARE_RANK(from))) <= 4){
piece_nb++;
attack_tot += KingAttackUnit[piece];
}
} */
}
// scoring
ASSERT(piece_nb>=0&&piece_nb<16);
op[colour] -= (attack_tot * KingAttackOpening * KingAttackWeight[piece_nb]) / 256;
}
}
// update
*opening += (op[White] - op[Black]);
*endgame += (eg[White] - eg[Black]);
}
// eval_passer()
static void eval_passer(const board_t * board, const pawn_info_t * pawn_info, int * opening, int * endgame) {
int colour;
int op[ColourNb], eg[ColourNb];
int att, def;
int bits;
int file, rank;
int sq;
int min, max;
int delta;
int white_passed_nb, black_passed_nb;
ASSERT(board!=NULL);
ASSERT(pawn_info!=NULL);
ASSERT(opening!=NULL);
ASSERT(endgame!=NULL);
// init
op[0] = op[1] = eg[0] = eg[1] = 0;
white_passed_nb = 0;
black_passed_nb = 0;
// passed pawns
for (colour = 0; colour < ColourNb; colour++) {
att = colour;
def = COLOUR_OPP(att);
for (bits = pawn_info->passed_bits[att]; bits != 0; bits &= bits-1) {
file = BIT_FIRST(bits);
ASSERT(file>=FileA&&file<=FileH);
rank = BIT_LAST(board->pawn_file[att][file]);
ASSERT(rank>=Rank2&&rank<=Rank7);
sq = SQUARE_MAKE(file,rank);
if (COLOUR_IS_BLACK(att)) sq = SQUARE_RANK_MIRROR(sq);
ASSERT(PIECE_IS_PAWN(board->square[sq]));
ASSERT(COLOUR_IS(board->square[sq],att));
// opening scoring
op[att] += quad(PassedOpeningMin,PassedOpeningMax,rank);
// endgame scoring init
min = PassedEndgameMin;
max = PassedEndgameMax;
delta = max - min;
ASSERT(delta>0);
// "dangerous" bonus
if (board->piece_size[def] <= 1 // defender has no piece
&& (unstoppable_passer(board,sq,att) || king_passer(board,sq,att))) {
delta += UnstoppablePasser;
} else if (free_passer(board,sq,att)) {
delta += FreePasser;
}
// king-distance bonus
delta -= pawn_att_dist(sq,KING_POS(board,att),att) * AttackerDistance;
delta += pawn_def_dist(sq,KING_POS(board,def),att) * DefenderDistance;
// endgame scoring
eg[att] += min;
if (delta > 0) eg[att] += quad(0,delta,rank);
}
}
// update
*opening += ((op[White] - op[Black]) * PassedPawnWeight) / 256;
*endgame += ((eg[White] - eg[Black]) * PassedPawnWeight) / 256;
}
// eval_pattern()
static void eval_pattern(const board_t * board, int * opening, int * endgame) {
ASSERT(board!=NULL);
ASSERT(opening!=NULL);
ASSERT(endgame!=NULL);
// trapped bishop (7th rank)
if ((board->square[A7] == WB && board->square[B6] == BP)
|| (board->square[B8] == WB && board->square[C7] == BP)) {
*opening -= TrappedBishop;
*endgame -= TrappedBishop;
}
if ((board->square[H7] == WB && board->square[G6] == BP)
|| (board->square[G8] == WB && board->square[F7] == BP)) {
*opening -= TrappedBishop;
*endgame -= TrappedBishop;
}
if ((board->square[A2] == BB && board->square[B3] == WP)
|| (board->square[B1] == BB && board->square[C2] == WP)) {
*opening += TrappedBishop;
*endgame += TrappedBishop;
}
if ((board->square[H2] == BB && board->square[G3] == WP)
|| (board->square[G1] == BB && board->square[F2] == WP)) {
*opening += TrappedBishop;
*endgame += TrappedBishop;
}
// trapped bishop (6th rank)
if (board->square[A6] == WB && board->square[B5] == BP) {
*opening -= TrappedBishop / 2;
*endgame -= TrappedBishop / 2;
}
if (board->square[H6] == WB && board->square[G5] == BP) {
*opening -= TrappedBishop / 2;
*endgame -= TrappedBishop / 2;
}
if (board->square[A3] == BB && board->square[B4] == WP) {
*opening += TrappedBishop / 2;
*endgame += TrappedBishop / 2;
}
if (board->square[H3] == BB && board->square[G4] == WP) {
*opening += TrappedBishop / 2;
*endgame += TrappedBishop / 2;
}
// blocked bishop
if (board->square[D2] == WP && board->square[D3] != Empty && board->square[C1] == WB) {
*opening -= BlockedBishop;
}
if (board->square[E2] == WP && board->square[E3] != Empty && board->square[F1] == WB) {
*opening -= BlockedBishop;
}
if (board->square[D7] == BP && board->square[D6] != Empty && board->square[C8] == BB) {
*opening += BlockedBishop;
}
if (board->square[E7] == BP && board->square[E6] != Empty && board->square[F8] == BB) {
*opening += BlockedBishop;
}
// blocked rook
if ((board->square[C1] == WK || board->square[B1] == WK)
&& (board->square[A1] == WR || board->square[A2] == WR || board->square[B1] == WR)) {
*opening -= BlockedRook;
}
if ((board->square[F1] == WK || board->square[G1] == WK)
&& (board->square[H1] == WR || board->square[H2] == WR || board->square[G1] == WR)) {
*opening -= BlockedRook;
}
if ((board->square[C8] == BK || board->square[B8] == BK)
&& (board->square[A8] == BR || board->square[A7] == BR || board->square[B8] == BR)) {
*opening += BlockedRook;
}
if ((board->square[F8] == BK || board->square[G8] == BK)
&& (board->square[H8] == BR || board->square[H7] == BR || board->square[G8] == BR)) {
*opening += BlockedRook;
}
// White center pawn blocked
if (board->square[E2] == BP && board->square[E3] != Empty) {
*opening -= BlockedCenterPawn;
}
if (board->square[D2] == BP && board->square[D3] != Empty) {
*opening -= BlockedCenterPawn;
}
// Black center pawn blocked
if (board->square[E7] == BP && board->square[E6] != Empty) {
*opening += BlockedCenterPawn;
}
if (board->square[D7] == BP && board->square[D6] != Empty) {
*opening += BlockedCenterPawn;
}
}
// unstoppable_passer()
static bool unstoppable_passer(const board_t * board, int pawn, int colour) {
int me, opp;
int file, rank;
int king;
int prom;
const sq_t * ptr;
int sq;
int dist;
ASSERT(board!=NULL);
ASSERT(SQUARE_IS_OK(pawn));
ASSERT(COLOUR_IS_OK(colour));
me = colour;
opp = COLOUR_OPP(me);
file = SQUARE_FILE(pawn);
rank = PAWN_RANK(pawn,me);
king = KING_POS(board,opp);
// clear promotion path?
for (ptr = &board->piece[me][0]; (sq=*ptr) != SquareNone; ptr++) {
if (SQUARE_FILE(sq) == file && PAWN_RANK(sq,me) > rank) {
return false; // "friendly" blocker
}
}
// init
if (rank == Rank2) {
pawn += PAWN_MOVE_INC(me);
rank++;
ASSERT(rank==PAWN_RANK(pawn,me));
}
ASSERT(rank>=Rank3&&rank<=Rank7);
prom = PAWN_PROMOTE(pawn,me);
dist = DISTANCE(pawn,prom);
ASSERT(dist==Rank8-rank);
if (board->turn == opp) dist++;
if (DISTANCE(king,prom) > dist) return true; // not in the square
return false;
}
// king_passer()
static bool king_passer(const board_t * board, int pawn, int colour) {
int me;
int king;
int file;
int prom;
ASSERT(board!=NULL);
ASSERT(SQUARE_IS_OK(pawn));
ASSERT(COLOUR_IS_OK(colour));
me = colour;
king = KING_POS(board,me);
file = SQUARE_FILE(pawn);
prom = PAWN_PROMOTE(pawn,me);
if (DISTANCE(king,prom) <= 1
&& DISTANCE(king,pawn) <= 1
&& (SQUARE_FILE(king) != file
|| (file != FileA && file != FileH))) {
return true;
}
return false;
}
// free_passer()
static bool free_passer(const board_t * board, int pawn, int colour) {
int me, opp;
int inc;
int sq;
int move;
ASSERT(board!=NULL);
ASSERT(SQUARE_IS_OK(pawn));
ASSERT(COLOUR_IS_OK(colour));
me = colour;
opp = COLOUR_OPP(me);
inc = PAWN_MOVE_INC(me);
sq = pawn + inc;
ASSERT(SQUARE_IS_OK(sq));
if (board->square[sq] != Empty) return false;
move = MOVE_MAKE(pawn,sq);
if (see_move(move,board) < 0) return false;
return true;
}
// pawn_att_dist()
static int pawn_att_dist(int pawn, int king, int colour) {
int me;
int inc;
int target;
ASSERT(SQUARE_IS_OK(pawn));
ASSERT(SQUARE_IS_OK(king));
ASSERT(COLOUR_IS_OK(colour));
me = colour;
inc = PAWN_MOVE_INC(me);
target = pawn + inc;
return DISTANCE(king,target);
}
// pawn_def_dist()
static int pawn_def_dist(int pawn, int king, int colour) {
int me;
int inc;
int target;
ASSERT(SQUARE_IS_OK(pawn));
ASSERT(SQUARE_IS_OK(king));
ASSERT(COLOUR_IS_OK(colour));
me = colour;
inc = PAWN_MOVE_INC(me);
target = pawn + inc;
return DISTANCE(king,target);
}
// draw_init_list()
static void draw_init_list(int list[], const board_t * board, int pawn_colour) {
int pos;
int att, def;
const sq_t * ptr;
int sq;
int pawn;
int i;
ASSERT(list!=NULL);
ASSERT(board!=NULL);
ASSERT(COLOUR_IS_OK(pawn_colour));
// init
pos = 0;
att = pawn_colour;
def = COLOUR_OPP(att);
ASSERT(board->pawn_size[att]==1);
ASSERT(board->pawn_size[def]==0);
// att
for (ptr = &board->piece[att][0]; (sq=*ptr) != SquareNone; ptr++) {
list[pos++] = sq;
}
for (ptr = &board->pawn[att][0]; (sq=*ptr) != SquareNone; ptr++) {
list[pos++] = sq;
}
// def
for (ptr = &board->piece[def][0]; (sq=*ptr) != SquareNone; ptr++) {
list[pos++] = sq;
}
for (ptr = &board->pawn[def][0]; (sq=*ptr) != SquareNone; ptr++) {
list[pos++] = sq;
}
// end marker
ASSERT(pos==board->piece_nb);
list[pos] = SquareNone;
// file flip?
pawn = board->pawn[att][0];
if (SQUARE_FILE(pawn) >= FileE) {
for (i = 0; i < pos; i++) {
list[i] = SQUARE_FILE_MIRROR(list[i]);
}
}
// rank flip?
if (COLOUR_IS_BLACK(pawn_colour)) {
for (i = 0; i < pos; i++) {
list[i] = SQUARE_RANK_MIRROR(list[i]);
}
}
}
// draw_krpkr()
static bool draw_krpkr(const int list[], int turn) {
int wk, wr, wp, bk, br;
int wp_file, wp_rank;
int bk_file, bk_rank;
int br_file, br_rank;
int prom;
ASSERT(list!=NULL);
ASSERT(COLOUR_IS_OK(turn));
// load
wk = *list++;
ASSERT(SQUARE_IS_OK(wk));
wr = *list++;
ASSERT(SQUARE_IS_OK(wr));
wp = *list++;
ASSERT(SQUARE_IS_OK(wp));
ASSERT(SQUARE_FILE(wp)<=FileD);
bk = *list++;
ASSERT(SQUARE_IS_OK(bk));
br = *list++;
ASSERT(SQUARE_IS_OK(br));
ASSERT(*list==SquareNone);
// test
wp_file = SQUARE_FILE(wp);
wp_rank = SQUARE_RANK(wp);
bk_file = SQUARE_FILE(bk);
bk_rank = SQUARE_RANK(bk);
br_file = SQUARE_FILE(br);
br_rank = SQUARE_RANK(br);
prom = PAWN_PROMOTE(wp,White);
if (false) {
} else if (bk == prom) {
// TODO: rook near Rank1 if wp_rank == Rank6?
if (br_file > wp_file) return true;
} else if (bk_file == wp_file && bk_rank > wp_rank) {
return true;
} else if (wr == prom && wp_rank == Rank7 && (bk == G7 || bk == H7) && br_file == wp_file) {
if (br_rank <= Rank3) {
if (DISTANCE(wk,wp) > 1) return true;
} else { // br_rank >= Rank4
if (DISTANCE(wk,wp) > 2) return true;
}
}
return false;
}
// draw_kbpkb()
static bool draw_kbpkb(const int list[], int turn) {
int wk, wb, wp, bk, bb;
int inc;
int end, to;
int delta, inc_2;
int sq;
ASSERT(list!=NULL);
ASSERT(COLOUR_IS_OK(turn));
// load
wk = *list++;
ASSERT(SQUARE_IS_OK(wk));
wb = *list++;
ASSERT(SQUARE_IS_OK(wb));
wp = *list++;
ASSERT(SQUARE_IS_OK(wp));
ASSERT(SQUARE_FILE(wp)<=FileD);
bk = *list++;
ASSERT(SQUARE_IS_OK(bk));
bb = *list++;
ASSERT(SQUARE_IS_OK(bb));
ASSERT(*list==SquareNone);
// opposit colour?
if (SQUARE_COLOUR(wb) == SQUARE_COLOUR(bb)) return false; // TODO
// blocked pawn?
inc = PAWN_MOVE_INC(White);
end = PAWN_PROMOTE(wp,White) + inc;
for (to = wp+inc; to != end; to += inc) {
ASSERT(SQUARE_IS_OK(to));
if (to == bb) return true; // direct blockade
delta = to - bb;
ASSERT(delta_is_ok(delta));
if (PSEUDO_ATTACK(BB,delta)) {
inc_2 = DELTA_INC_ALL(delta);
ASSERT(inc_2!=IncNone);
sq = bb;
do {
sq += inc_2;
ASSERT(SQUARE_IS_OK(sq));
ASSERT(sq!=wk);
ASSERT(sq!=wb);
ASSERT(sq!=wp);
ASSERT(sq!=bb);
if (sq == to) return true; // indirect blockade
} while (sq != bk);
}
}
return false;
}
// shelter_square()
static int shelter_square(const board_t * board, int square, int colour) {
int penalty;
int file, rank;
ASSERT(board!=NULL);
ASSERT(SQUARE_IS_OK(square));
ASSERT(COLOUR_IS_OK(colour));
penalty = 0;
file = SQUARE_FILE(square);
rank = PAWN_RANK(square,colour);
penalty += (shelter_file(board,file,rank,colour) * 2);
if (file != FileA) penalty += (shelter_file(board,file-1,rank,colour));
if (file != FileH) penalty += (shelter_file(board,file+1,rank,colour));
if (penalty == 0) penalty = 11; // weak back rank
penalty += storm_file(board,file,colour);
if (file != FileA) penalty += storm_file(board,file-1,colour);
if (file != FileH) penalty += storm_file(board,file+1,colour);
return penalty;
}
// shelter_file()
static int shelter_file(const board_t * board, int file, int rank, int colour) {
int dist;
int penalty;
ASSERT(board!=NULL);
ASSERT(file>=FileA&&file<=FileH);
ASSERT(rank>=Rank1&&rank<=Rank8);
ASSERT(COLOUR_IS_OK(colour));
dist = BIT_FIRST(board->pawn_file[colour][file]&BitGE[rank]);
ASSERT(dist>=Rank2&&dist<=Rank8);
dist = Rank8 - dist;
ASSERT(dist>=0&&dist<=6);
penalty = 36 - dist * dist;
ASSERT(penalty>=0&&penalty<=36);
return penalty;
}
// storm_file()
static int storm_file(const board_t * board, int file, int colour) {
int dist;
int penalty;
ASSERT(board!=NULL);
ASSERT(file>=FileA&&file<=FileH);
ASSERT(COLOUR_IS_OK(colour));
dist = BIT_LAST(board->pawn_file[COLOUR_OPP(colour)][file]);
ASSERT(dist>=Rank1&&dist<=Rank7);
penalty = 0;
switch (dist) {
case Rank4:
penalty = StormOpening * 1;
break;
case Rank5:
penalty = StormOpening * 3;
break;
case Rank6:
penalty = StormOpening * 6;
break;
}
return penalty;
}
// bishop_can_attack()
static bool bishop_can_attack(const board_t * board, int to, int colour) {
const sq_t * ptr;
int from;
int piece;
ASSERT(board!=NULL);
ASSERT(SQUARE_IS_OK(to));
ASSERT(COLOUR_IS_OK(colour));
for (ptr = &board->piece[colour][1]; (from=*ptr) != SquareNone; ptr++) { // HACK: no king
piece = board->square[from];
if (PIECE_IS_BISHOP(piece) && SQUARE_COLOUR(from) == SQUARE_COLOUR(to)) {
return true;
}
}
return false;
}
// end of eval.cpp
| 0 | 0.977368 | 1 | 0.977368 | game-dev | MEDIA | 0.643093 | game-dev | 0.850735 | 1 | 0.850735 |
Bozar/GodotRoguelikeTutorial | 1,311 | 10/scene/main/MainScene.gd | extends "res://library/RootNodeTemplate.gd"
const INIT_WORLD: String = "InitWorld"
const PC_MOVE: String = "PCMove"
const PC_ATTACK: String = "PCMove/PCAttack"
const NPC: String = "EnemyAI"
const SCHEDULE: String = "Schedule"
const DUNGEON: String = "DungeonBoard"
const REMOVE: String = "RemoveObject"
const SIDEBAR: String = "MainGUI/MainHBox/SidebarVBox"
const MODELINE: String = "MainGUI/MainHBox/Modeline"
const SIGNAL_BIND: Array = [
[
"sprite_created", "_on_InitWorld_sprite_created",
INIT_WORLD,
PC_MOVE, NPC, SCHEDULE, DUNGEON,
],
[
"turn_started", "_on_Schedule_turn_started",
SCHEDULE,
PC_MOVE, NPC, SIDEBAR,
],
[
"turn_ended", "_on_Schedule_turn_ended",
SCHEDULE,
MODELINE,
],
[
"sprite_removed", "_on_RemoveObject_sprite_removed",
REMOVE,
DUNGEON, SCHEDULE,
],
[
"enemy_warned", "_on_EnemyAI_enemy_warned",
NPC,
MODELINE,
],
[
"pc_moved", "_on_PCMove_pc_moved",
PC_MOVE,
MODELINE,
],
[
"pc_attacked", "_on_PCAttack_pc_attacked",
PC_ATTACK,
MODELINE,
],
]
const NODE_REF: Array = [
[
"_ref_DungeonBoard",
DUNGEON,
PC_MOVE, PC_ATTACK, REMOVE, INIT_WORLD,
],
[
"_ref_Schedule",
SCHEDULE,
PC_MOVE, NPC, PC_ATTACK,
],
[
"_ref_RemoveObject",
REMOVE,
PC_ATTACK,
],
]
func _init().(SIGNAL_BIND, NODE_REF) -> void:
pass
| 0 | 0.595392 | 1 | 0.595392 | game-dev | MEDIA | 0.864365 | game-dev | 0.663446 | 1 | 0.663446 |
iscle/SpaceCadetPinball | 12,627 | SpaceCadetPinball/loader.cpp | #include "pch.h"
#include "loader.h"
#include "GroupData.h"
#include "pb.h"
#include "pinball.h"
#include "Sound.h"
#include "zdrv.h"
errorMsg loader::loader_errors[] =
{
errorMsg{0, "Bad Handle"},
errorMsg{1, "No Type Field"},
errorMsg{2, "No Attributes Field"},
errorMsg{3, "Wrong Type: MATERIAL Expected"},
errorMsg{4, "Wrong Type: KICKER Expected"},
errorMsg{5, "Wrong Type: AN_OBJECT Expected"},
errorMsg{6, "Wrong Type: A_STATE Expected"},
errorMsg{7, "STATES (re)defined in a state"},
errorMsg{9, "Unrecognized Attribute"},
errorMsg{0x0A, "Unrecognized float Attribute"},
errorMsg{0x0B, "No float Attributes Field"},
errorMsg{0x0D, "float Attribute not found"},
errorMsg{0x0C, "state_index out of range"},
errorMsg{0x0F, "loader_material() reports failure"},
errorMsg{0x0E, "loader_kicker() reports failure"},
errorMsg{0x10, "loader_state_id() reports failure"},
errorMsg{0x8, "# walls doesn't match data size"},
errorMsg{0x11, "loader_query_visual_states()"},
errorMsg{0x12, "loader_query_visual()"},
errorMsg{0x15, "loader_material()"},
errorMsg{0x14, "loader_kicker()"},
errorMsg{0x16, "loader_query_attribute()"},
errorMsg{0x17, "loader_query_iattribute()"},
errorMsg{0x13, "loader_query_name()"},
errorMsg{0x18, "loader_state_id()"},
errorMsg{0x19, "loader_get_sound_id()"},
errorMsg{0x1A, "sound reference is not A_SOUND record"},
errorMsg{-1, "Unknown"},
};
int loader::sound_count = 1;
int loader::loader_sound_count;
DatFile* loader::loader_table;
DatFile* loader::sound_record_table;
soundListStruct loader::sound_list[65];
int loader::error(int errorCode, int captionCode)
{
auto curCode = loader_errors;
const char *errorText = nullptr, *errorCaption = nullptr;
auto index = 0;
while (curCode->Code >= 0)
{
if (errorCode == curCode->Code)
errorText = curCode->Message;
if (captionCode == curCode->Code)
errorCaption = curCode->Message;
curCode++;
index++;
}
if (!errorText)
errorText = loader_errors[index].Message;
SpaceCadetPinballJNI::show_error_dialog(errorCaption, errorText);
return -1;
}
void loader::default_vsi(visualStruct* visual)
{
visual->CollisionGroup = 0;
visual->Kicker.Threshold = 8.9999999e10f;
visual->Kicker.HardHitSoundId = 0;
visual->Smoothness = 0.94999999f;
visual->Elasticity = 0.60000002f;
visual->FloatArrCount = 0;
visual->SoftHitSoundId = 0;
visual->Bitmap = nullptr;
visual->ZMap = nullptr;
visual->SoundIndex3 = 0;
visual->SoundIndex4 = 0;
}
void loader::loadfrom(DatFile* datFile)
{
loader_table = datFile;
sound_record_table = loader_table;
for (auto groupIndex = 0; groupIndex < static_cast<int>(datFile->Groups.size()); ++groupIndex)
{
auto value = reinterpret_cast<int16_t*>(datFile->field(groupIndex, FieldTypes::ShortValue));
if (value && *value == 202)
{
if (sound_count < 65)
{
sound_list[sound_count].WavePtr = nullptr;
sound_list[sound_count].GroupIndex = groupIndex;
sound_count++;
}
}
}
loader_sound_count = sound_count;
}
void loader::unload()
{
for (int index = 1; index < sound_count; ++index)
{
Sound::FreeSound(sound_list[index].WavePtr);
sound_list[index].Loaded = 0;
sound_list[index].WavePtr = nullptr;
}
sound_count = 1;
}
int loader::get_sound_id(int groupIndex)
{
int16_t soundIndex = 1;
if (sound_count <= 1)
{
error(25, 26);
return -1;
}
while (sound_list[soundIndex].GroupIndex != groupIndex)
{
++soundIndex;
if (soundIndex >= sound_count)
{
error(25, 26);
return -1;
}
}
if (!sound_list[soundIndex].Loaded && !sound_list[soundIndex].WavePtr)
{
WaveHeader wavHeader{};
int soundGroupId = sound_list[soundIndex].GroupIndex;
sound_list[soundIndex].Duration = 0.0;
if (soundGroupId > 0 && !pinball::quickFlag)
{
auto value = reinterpret_cast<int16_t*>(loader_table->field(soundGroupId,
FieldTypes::ShortValue));
if (value && *value == 202)
{
std::string fileName = loader_table->field(soundGroupId, FieldTypes::String);
// File name is in lower case, while game data is in upper case.
std::transform(fileName.begin(), fileName.end(), fileName.begin(),
[](unsigned char c) { return std::toupper(c); });
if (pb::FullTiltMode)
{
// FT sounds are in SOUND subfolder
fileName.insert(0, 1, PathSeparator);
fileName.insert(0, "SOUND");
}
auto filePath = pinball::make_path_name(fileName);
auto file = fopen(filePath.c_str(), "rb");
if (file)
{
fread(&wavHeader, 1, sizeof wavHeader, file);
fclose(file);
}
auto sampleCount = wavHeader.data_size / (wavHeader.channels * (wavHeader.bits_per_sample / 8.0));
sound_list[soundIndex].Duration = static_cast<float>(sampleCount / wavHeader.sample_rate);
sound_list[soundIndex].WavePtr = Sound::LoadWaveFile(filePath);
}
}
}
++sound_list[soundIndex].Loaded;
return soundIndex;
}
int loader::query_handle(LPCSTR lpString)
{
return loader_table->record_labeled(lpString);
}
short loader::query_visual_states(int groupIndex)
{
short result;
if (groupIndex < 0)
return error(0, 17);
auto shortArr = reinterpret_cast<int16_t*>(loader_table->field(groupIndex, FieldTypes::ShortArray));
if (shortArr && *shortArr == 100)
result = shortArr[1];
else
result = 1;
return result;
}
char* loader::query_name(int groupIndex)
{
if (groupIndex < 0)
{
error(0, 19);
return nullptr;
}
return loader_table->field(groupIndex, FieldTypes::GroupName);
}
int16_t* loader::query_iattribute(int groupIndex, int firstValue, int* arraySize)
{
if (groupIndex < 0)
{
error(0, 22);
return nullptr;
}
for (auto skipIndex = 0;; ++skipIndex)
{
auto shortArr = reinterpret_cast<int16_t*>(loader_table->field_nth(groupIndex,
FieldTypes::ShortArray, skipIndex));
if (!shortArr)
break;
if (*shortArr == firstValue)
{
*arraySize = loader_table->field_size(groupIndex, FieldTypes::ShortArray) / 2 - 1;
return shortArr + 1;
}
}
error(2, 23);
*arraySize = 0;
return nullptr;
}
float* loader::query_float_attribute(int groupIndex, int groupIndexOffset, int firstValue)
{
if (groupIndex < 0)
{
error(0, 22);
return nullptr;
}
int stateId = state_id(groupIndex, groupIndexOffset);
if (stateId < 0)
{
error(16, 22);
return nullptr;
}
for (auto skipIndex = 0;; ++skipIndex)
{
auto floatArr = reinterpret_cast<float*>(loader_table->field_nth(stateId, FieldTypes::FloatArray,
skipIndex));
if (!floatArr)
break;
if (static_cast<int16_t>(floor(*floatArr)) == firstValue)
return floatArr + 1;
}
error(13, 22);
return nullptr;
}
float loader::query_float_attribute(int groupIndex, int groupIndexOffset, int firstValue, float defVal)
{
if (groupIndex < 0)
{
error(0, 22);
return NAN;
}
int stateId = state_id(groupIndex, groupIndexOffset);
if (stateId < 0)
{
error(16, 22);
return NAN;
}
for (auto skipIndex = 0;; ++skipIndex)
{
auto floatArr = reinterpret_cast<float*>(loader_table->field_nth(stateId,
FieldTypes::FloatArray, skipIndex));
if (!floatArr)
break;
if (static_cast<int16_t>(floor(*floatArr)) == firstValue)
return floatArr[1];
}
if (!isnan(defVal))
return defVal;
error(13, 22);
return NAN;
}
int loader::material(int groupIndex, visualStruct* visual)
{
if (groupIndex < 0)
return error(0, 21);
auto shortArr = reinterpret_cast<int16_t*>(loader_table->field(groupIndex, FieldTypes::ShortValue));
if (!shortArr)
return error(1, 21);
if (*shortArr != 300)
return error(3, 21);
auto floatArr = reinterpret_cast<float*>(loader_table->field(groupIndex, FieldTypes::FloatArray));
if (!floatArr)
return error(11, 21);
int floatArrLength = loader_table->field_size(groupIndex, FieldTypes::FloatArray) / 4;
for (auto index = 0; index < floatArrLength; index += 2)
{
switch (static_cast<int>(floor(floatArr[index])))
{
case 301:
visual->Smoothness = floatArr[index + 1];
break;
case 302:
visual->Elasticity = floatArr[index + 1];
break;
case 304:
visual->SoftHitSoundId = get_sound_id(static_cast<int>(floor(floatArr[index + 1])));
break;
default:
return error(9, 21);
}
}
return 0;
}
float loader::play_sound(int soundIndex)
{
if (soundIndex <= 0)
return 0.0;
Sound::PlaySound(sound_list[soundIndex].WavePtr, pb::time_ticks);
return sound_list[soundIndex].Duration;
}
int loader::state_id(int groupIndex, int groupIndexOffset)
{
auto visualState = query_visual_states(groupIndex);
if (visualState <= 0)
return error(12, 24);
auto shortArr = reinterpret_cast<int16_t*>(loader_table->field(groupIndex, FieldTypes::ShortValue));
if (!shortArr)
return error(1, 24);
if (*shortArr != 200)
return error(5, 24);
if (groupIndexOffset > visualState)
return error(12, 24);
if (!groupIndexOffset)
return groupIndex;
groupIndex += groupIndexOffset;
shortArr = reinterpret_cast<int16_t*>(loader_table->field(groupIndex, FieldTypes::ShortValue));
if (!shortArr)
return error(1, 24);
if (*shortArr != 201)
return error(6, 24);
return groupIndex;
}
int loader::kicker(int groupIndex, visualKickerStruct* kicker)
{
if (groupIndex < 0)
return error(0, 20);
auto shortArr = reinterpret_cast<int16_t*>(loader_table->field(groupIndex, FieldTypes::ShortValue));
if (!shortArr)
return error(1, 20);
if (*shortArr != 400)
return error(4, 20);
auto floatArr = reinterpret_cast<float*>(loader_table->field(groupIndex, FieldTypes::FloatArray));
if (!floatArr)
return error(11, 20);
int floatArrLength = loader_table->field_size(groupIndex, FieldTypes::FloatArray) / 4;
if (floatArrLength <= 0)
return 0;
for (auto index = 0; index < floatArrLength;)
{
int floorVal = static_cast<int>(floor(*floatArr++));
switch (floorVal)
{
case 401:
kicker->Threshold = *floatArr;
break;
case 402:
kicker->Boost = *floatArr;
break;
case 403:
kicker->ThrowBallMult = *floatArr;
break;
case 404:
kicker->ThrowBallAcceleration = *reinterpret_cast<vector_type*>(floatArr);
floatArr += 3;
index += 4;
break;
case 405:
kicker->ThrowBallAngleMult = *floatArr;
break;
case 406:
kicker->HardHitSoundId = get_sound_id(static_cast<int>(floor(*floatArr)));
break;
default:
return error(10, 20);
}
if (floorVal != 404)
{
floatArr++;
index += 2;
}
}
return 0;
}
int loader::query_visual(int groupIndex, int groupIndexOffset, visualStruct* visual)
{
default_vsi(visual);
if (groupIndex < 0)
return error(0, 18);
auto stateId = state_id(groupIndex, groupIndexOffset);
if (stateId < 0)
return error(16, 18);
visual->Bitmap = loader_table->GetBitmap(stateId);
visual->ZMap = loader_table->GetZMap(stateId);
auto shortArr = reinterpret_cast<int16_t*>(loader_table->field(stateId, FieldTypes::ShortArray));
if (shortArr)
{
unsigned int shortArrSize = loader_table->field_size(stateId, FieldTypes::ShortArray);
for (auto index = 0u; index < shortArrSize / 2;)
{
switch (shortArr[0])
{
case 100:
if (groupIndexOffset)
return error(7, 18);
break;
case 300:
if (material(shortArr[1], visual))
return error(15, 18);
break;
case 304:
visual->SoftHitSoundId = get_sound_id(shortArr[1]);
break;
case 400:
if (kicker(shortArr[1], &visual->Kicker))
return error(14, 18);
break;
case 406:
visual->Kicker.HardHitSoundId = get_sound_id(shortArr[1]);
break;
case 602:
visual->CollisionGroup |= 1 << shortArr[1];
break;
case 1100:
visual->SoundIndex4 = get_sound_id(shortArr[1]);
break;
case 1101:
visual->SoundIndex3 = get_sound_id(shortArr[1]);
break;
case 1500:
shortArr += 7;
index += 7;
break;
default:
return error(9, 18);
}
shortArr += 2;
index += 2;
}
}
if (!visual->CollisionGroup)
visual->CollisionGroup = 1;
auto floatArr = reinterpret_cast<float*>(loader_table->field(stateId, FieldTypes::FloatArray));
if (!floatArr)
return 0;
if (*floatArr != 600.0f)
return 0;
visual->FloatArrCount = loader_table->field_size(stateId, FieldTypes::FloatArray) / 4 / 2 - 2;
auto floatVal = static_cast<int>(floor(floatArr[1]) - 1.0f);
switch (floatVal)
{
case 0:
visual->FloatArrCount = 1;
break;
case 1:
visual->FloatArrCount = 2;
break;
default:
if (floatVal != visual->FloatArrCount)
return error(8, 18);
break;
}
visual->FloatArr = floatArr + 2;
return 0;
}
| 0 | 0.940981 | 1 | 0.940981 | game-dev | MEDIA | 0.715339 | game-dev | 0.987923 | 1 | 0.987923 |
TabooLib/adyeshach | 5,247 | project/common-impl/src/main/kotlin/ink/ptms/adyeshach/impl/entity/DefaultControllable.kt | package ink.ptms.adyeshach.impl.entity
import ink.ptms.adyeshach.core.entity.Controllable
import ink.ptms.adyeshach.core.entity.StandardTags
import ink.ptms.adyeshach.core.entity.TagContainer
import ink.ptms.adyeshach.core.entity.controller.Controller
import ink.ptms.adyeshach.core.entity.path.ResultNavigation
import ink.ptms.adyeshach.core.event.AdyeshachControllerAddEvent
import ink.ptms.adyeshach.core.event.AdyeshachControllerRemoveEvent
import ink.ptms.adyeshach.impl.util.ChunkAccess
import org.bukkit.Location
import org.bukkit.entity.Entity
import java.util.*
/**
* Adyeshach
* ink.ptms.adyeshach.impl.entity.DefaultControllable
*
* @author 坏黑
* @since 2022/6/19 21:57
*/
@Suppress("UNCHECKED_CAST")
interface DefaultControllable : Controllable {
override var isFreeze: Boolean
set(value) {
this as TagContainer
setTag(StandardTags.IS_FROZEN, if (value) "true" else null)
}
get() {
this as TagContainer
return hasTag(StandardTags.IS_FROZEN)
}
override fun getController(): List<Controller> {
this as DefaultEntityInstance
return controller.toList()
}
override fun <T : Controller> getController(controller: String): T? {
this as DefaultEntityInstance
return this.controller.firstOrNull { it.id() == controller } as? T
}
override fun <T : Controller> getController(controller: Class<T>): T? {
this as DefaultEntityInstance
return this.controller.firstOrNull { it.javaClass == controller } as? T
}
override fun registerController(controller: Controller): Boolean {
this as DefaultEntityInstance
// 添加事件
if (AdyeshachControllerAddEvent(this, controller).call()) {
// 移除相同的控制器
this.controller.removeIf { it.id() == controller.id() }
this.controller.add(controller)
return true
}
return false
}
override fun unregisterController(controller: String): Boolean {
this as DefaultEntityInstance
return unregister(this.controller.firstOrNull { it.id() == controller } ?: return true)
}
override fun unregisterController(controller: Controller): Boolean {
this as DefaultEntityInstance
return unregister(this.controller.firstOrNull { it == controller } ?: return true)
}
override fun <T : Controller> unregisterController(controller: Class<T>): Boolean {
this as DefaultEntityInstance
return unregister(this.controller.firstOrNull { it.javaClass == controller } ?: return true)
}
override fun resetController() {
this as DefaultEntityInstance
this.controller.forEach { unregisterController(it.javaClass) }
}
override fun controllerLookAt(entity: Entity) {
this as DefaultEntityInstance
this.bionicSight.setLookAt(entity)
}
override fun controllerLookAt(entity: Entity, yMaxRotSpeed: Float, xMaxRotAngle: Float) {
this as DefaultEntityInstance
this.bionicSight.setLookAt(entity, yMaxRotSpeed, xMaxRotAngle)
}
override fun controllerLookAt(wantedX: Double, wantedY: Double, wantedZ: Double) {
this as DefaultEntityInstance
this.bionicSight.setLookAt(wantedX, wantedY, wantedZ)
}
override fun controllerLookAt(wantedX: Double, wantedY: Double, wantedZ: Double, yMaxRotSpeed: Float) {
this as DefaultEntityInstance
this.bionicSight.setLookAt(wantedX, wantedY, wantedZ, yMaxRotSpeed, 40f)
}
override fun controllerLookAt(wantedX: Double, wantedY: Double, wantedZ: Double, yMaxRotSpeed: Float, xMaxRotAngle: Float) {
this as DefaultEntityInstance
this.bionicSight.setLookAt(wantedX, wantedY, wantedZ, yMaxRotSpeed, xMaxRotAngle)
}
override fun controllerMoveTo(location: Location) {
this as DefaultEntityInstance
moveTarget = location
}
override fun controllerMoveBy(locations: List<Location>, speed: Double, fixHeight: Boolean) {
if (locations.isEmpty()) {
return
}
this as DefaultEntityInstance
// 克隆坐标列表
val newList = locations.map { it.clone() }
// 修正路径高度
if (fixHeight) {
newList.forEach { p -> p.y = ChunkAccess.getChunkAccess(world).getBlockHighest(p.x, p.y, p.z) }
}
// 设置移动路径
moveFrames = ResultNavigation(newList.map { it.toVector() }.toMutableList()).toInterpolated(world, speed)
}
override fun controllerStopMove() {
this as DefaultEntityInstance
moveFrames = null
}
override fun random(): Random {
this as DefaultEntityInstance
return this.brain.getRandom()
}
private fun unregister(controller: Controller): Boolean {
this as DefaultEntityInstance
// 移除事件
if (AdyeshachControllerRemoveEvent(this, controller).call()) {
this.controller.remove(controller)
// 从执行容器中移除
if (this.brain.getRunningControllers()[controller.group()] == controller) {
this.brain.getRunningControllers().remove(controller.group())
}
return true
}
return false
}
} | 0 | 0.923479 | 1 | 0.923479 | game-dev | MEDIA | 0.930511 | game-dev | 0.910599 | 1 | 0.910599 |
pinky39/grove | 1,042 | source/Grove/CardsLibrary/MentalDiscipline.cs | namespace Grove.CardsLibrary
{
using System.Collections.Generic;
using AI.TargetingRules;
using AI.TimingRules;
using Costs;
using Effects;
public class MentalDiscipline : CardTemplateSource
{
public override IEnumerable<CardTemplate> GetCards()
{
yield return Card
.Named("Mental Discipline")
.ManaCost("{1}{U}{U}")
.Type("Enchantment")
.Text("{1}{U}, Discard a card: Draw a card.")
.FlavorText("Barrin drowned his doubts about Urza's project by delving ever deeper into its details.")
.ActivatedAbility(p =>
{
p.Text = "{1}{U}, Discard a card: Draw a card.";
p.Cost = new AggregateCost(
new PayMana("{1}{U}".Parse()),
new DiscardTarget());
p.Effect = () => new DrawCards(1);
p.TargetSelector.AddCost(trg => trg.Is.Card().In.OwnersHand());
p.TimingRule(new DefaultCyclingTimingRule());
p.TargetingRule(new CostDiscardCard());
});
}
}
} | 0 | 0.889134 | 1 | 0.889134 | game-dev | MEDIA | 0.856738 | game-dev | 0.989963 | 1 | 0.989963 |
ProjectIgnis/CardScripts | 3,378 | official/c83199011.lua | --スプリガンズ・コール!
--Springans Call!
--Logical Nonsense
local s,id=GetID()
function s.initial_effect(c)
--Special Summon 1 "Springans" monster or "Fallen of Albaz" from your GY
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(id,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetHintTiming(0,TIMINGS_CHECK_MONSTER_E)
e1:SetCountLimit(1,id)
e1:SetTarget(s.target)
e1:SetOperation(s.activate)
c:RegisterEffect(e1)
--Attach 1 Fusion Monster that lists "Fallen of Albaz" from your Extra Deck to 1 "Springans" Xyz Monster you control
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(id,1))
e2:SetType(EFFECT_TYPE_QUICK_O)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetCode(EVENT_FREE_CHAIN)
e2:SetRange(LOCATION_GRAVE)
e2:SetHintTiming(0,TIMING_STANDBY_PHASE|TIMINGS_CHECK_MONSTER_E)
e2:SetCountLimit(1,{id,1})
e2:SetCondition(aux.exccon)
e2:SetCost(s.matcost)
e2:SetTarget(s.mattg)
e2:SetOperation(s.matop)
c:RegisterEffect(e2)
end
s.listed_series={SET_SPRINGANS}
s.listed_names={CARD_ALBAZ}
function s.spfilter(c,e,tp)
return (c:IsSetCard(SET_SPRINGANS) or c:IsCode(CARD_ALBAZ)) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function s.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_GRAVE) and s.spfilter(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingTarget(s.spfilter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,s.spfilter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function s.activate(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)
end
end
function s.cfilter(c)
return c:IsType(TYPE_FUSION) and c:IsAbleToRemoveAsCost()
end
function s.matcost(e,tp,eg,ep,ev,re,r,rp,chk)
local c=e:GetHandler()
if chk==0 then return c:IsAbleToRemoveAsCost()
and Duel.IsExistingMatchingCard(s.cfilter,tp,LOCATION_GRAVE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectMatchingCard(tp,s.cfilter,tp,LOCATION_GRAVE,0,1,1,nil)
g:AddCard(c)
Duel.Remove(g,POS_FACEUP,REASON_COST)
end
function s.xyzfilter(c)
return c:IsFaceup() and c:IsType(TYPE_XYZ) and c:IsSetCard(SET_SPRINGANS)
end
function s.matfilter(c)
return c:IsType(TYPE_FUSION) and c:ListsCodeAsMaterial(CARD_ALBAZ) and not c:IsForbidden()
end
function s.mattg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_MZONE) and s.xyzfilter(chkc) end
if chk==0 then return Duel.IsExistingTarget(s.xyzfilter,tp,LOCATION_MZONE,0,1,nil)
and Duel.IsExistingMatchingCard(s.matfilter,tp,LOCATION_EXTRA,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TARGET)
Duel.SelectTarget(tp,s.xyzfilter,tp,LOCATION_MZONE,0,1,1,nil)
end
function s.matop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and tc:IsType(TYPE_XYZ) and not tc:IsImmuneToEffect(e) then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_XMATERIAL)
local g=Duel.SelectMatchingCard(tp,s.matfilter,tp,LOCATION_EXTRA,0,1,1,nil)
if #g>0 then
Duel.Overlay(tc,g)
end
end
end | 0 | 0.945877 | 1 | 0.945877 | game-dev | MEDIA | 0.971364 | game-dev | 0.969548 | 1 | 0.969548 |
rexrainbow/phaser3-rex-notes | 1,692 | templates/gameobjectshell/shell/Shell.js | import ComponentBase from '../../../plugins/utils/componentbase/ComponentBase.js';
import CreateLayerManager from './methods/CreateLayerManager.js';
import CreateBackground from './methods/CreateBackground.js';
import CreateMainPanel from './methods/CreateMainPanel.js';
import CreateControlPoints from './methods/CreateControlPoints.js';
import CreateCameraController from './methods/CreateCameraController.js';
import Methods from './methods/Methods.js';
import { OnSelectGameObject, OnUnSelectGameObject } from './methods/SelectGameObjectMethods.js';
const GetValue = Phaser.Utils.Objects.GetValue;
class Shell extends ComponentBase {
constructor(scene, config) {
if (config === undefined) {
config = {};
}
super(scene, config);
// this.scene
this.onSelectGameObjectCallback = GetValue(config, 'onSelectGameObject', OnSelectGameObject);
this.onUnSelectGameObjectCallback = GetValue(config, 'onUnSelectGameObject', OnUnSelectGameObject);
CreateLayerManager.call(this, config);
CreateBackground.call(this, config);
CreateMainPanel.call(this, config);
CreateControlPoints.call(this, config);
CreateCameraController.call(this, config);
/*
- Click game object on 'monitor' layer to open properties editor
- Click background (outside of any game object) will set binding target to undefined,
also set properties editor to invisible
*/
}
destroy(fromScene) {
this.emit('destroy');
super.destroy(fromScene);
return this;
}
}
Object.assign(
Shell.prototype,
Methods,
)
export default Shell; | 0 | 0.775746 | 1 | 0.775746 | game-dev | MEDIA | 0.78136 | game-dev | 0.719785 | 1 | 0.719785 |
Dreaming381/lsss-wip | 45,073 | Packages/com.latios.latiosframework/Core/Framework/LatiosWorldUnmanaged.cs | using System.Runtime.InteropServices;
using Unity.Burst;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Entities;
using Unity.Entities.Exposed;
using Unity.Jobs;
using Unity.Mathematics;
namespace Latios
{
/// <summary>
/// An unmanaged representation of the LatiosWorld. You can copy and use this structure inside a Burst-Compiled ISystem.
/// Up to 1023 LatiosWorldUnmanaged instances can be present at once.
/// </summary>
public unsafe struct LatiosWorldUnmanaged
{
internal LatiosWorldUnmanagedImpl* m_impl;
internal int m_index;
internal int m_version;
/// <summary>
/// Checks if this instance is valid. Will throw if the instance used to be valid but was disposed.
/// </summary>
public bool isValid
{
get
{
if (m_impl == null)
return false;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!LatiosWorldUnmanagedTracking.CheckHandle(m_index, m_version))
throw new System.InvalidOperationException("LatiosWorldUnmanaged is uninitialized. You must fetch a valid instance from SystemState.");
#endif
return true;
}
}
/// <summary>
/// If set to true, the World will stop updating systems if an exception is caught by the LatiosWorld.
/// </summary>
public bool zeroToleranceForExceptions
{
get
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!LatiosWorldUnmanagedTracking.CheckHandle(m_index, m_version))
throw new System.InvalidOperationException("LatiosWorldUnmanaged is uninitialized. You must fetch a valid instance from SystemState.");
#endif
return m_impl->m_zeroToleranceForExceptionsEnabled;
}
set
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!LatiosWorldUnmanagedTracking.CheckHandle(m_index, m_version))
throw new System.InvalidOperationException("LatiosWorldUnmanaged is uninitialized. You must fetch a valid instance from SystemState.");
#endif
m_impl->m_zeroToleranceForExceptionsEnabled = value;
}
}
/// <summary>
/// Obtains the managed LatiosWorld. Not Burst-compatible.
/// </summary>
public LatiosWorld latiosWorld
{
get
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!LatiosWorldUnmanagedTracking.CheckHandle(m_index, m_version))
throw new System.InvalidOperationException("LatiosWorldUnmanaged is uninitialized. You must fetch a valid instance from SystemState.");
#endif
return m_impl->m_worldUnmanaged.EntityManager.World as LatiosWorld;
}
}
#region blackboards
/// <summary>
/// The worldBlackboardEntity associated with this world
/// </summary>
public BlackboardEntity worldBlackboardEntity
{
get
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!LatiosWorldUnmanagedTracking.CheckHandle(m_index, m_version))
throw new System.InvalidOperationException("LatiosWorldUnmanaged is uninitialized. You must fetch a valid instance from SystemState.");
#endif
return m_impl->m_worldBlackboardEntity;
}
}
/// <summary>
/// The current sceneBlackboardEntity associated with this world
/// </summary>
public BlackboardEntity sceneBlackboardEntity
{
get
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!LatiosWorldUnmanagedTracking.CheckHandle(m_index, m_version))
throw new System.InvalidOperationException("LatiosWorldUnmanaged is uninitialized. You must fetch a valid instance from SystemState.");
if (m_impl->m_sceneBlackboardEntity == Entity.Null)
{
throw new System.InvalidOperationException(
"The sceneBlackboardEntity has not been initialized yet. If you are trying to access this entity in OnCreate(), please use OnNewScene() or another callback instead.");
}
#endif
return m_impl->m_sceneBlackboardEntity;
}
}
// HasComponent checks Exists internally.
internal bool isSceneBlackboardEntityCreated => m_impl->m_worldUnmanaged.EntityManager.HasComponent<SceneBlackboardTag>(m_impl->m_sceneBlackboardEntity);
internal BlackboardEntity CreateSceneBlackboardEntity()
{
m_impl->m_sceneBlackboardEntity = new BlackboardEntity(m_impl->m_worldUnmanaged.EntityManager.CreateEntity(), this);
sceneBlackboardEntity.AddComponentData(new SceneBlackboardTag());
m_impl->m_worldUnmanaged.EntityManager.SetName(sceneBlackboardEntity, "Scene Blackboard Entity");
return m_impl->m_sceneBlackboardEntity;
}
#endregion
#region sync point
/// <summary>
/// The main syncPoint system from which to get command buffers.
/// Command buffers retrieved from this property from within a system will have dependencies managed automatically
/// </summary>
public ref Systems.SyncPointPlaybackSystem syncPoint
{
get
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!LatiosWorldUnmanagedTracking.CheckHandle(m_index, m_version))
throw new System.InvalidOperationException("LatiosWorldUnmanaged is uninitialized. You must fetch a valid instance from SystemState.");
if (m_impl->m_syncPointPlaybackSystem == null)
{
throw new System.InvalidOperationException("There is no initialized SyncPointPlaybackSystem in the World.");
}
#endif
return ref m_impl->GetSyncPoint();
}
}
#endregion
#region managed structs
/// <summary>
/// Adds a managed struct component to the entity. This implicitly adds the managed struct component's AssociatedComponentType as well.
/// If the entity already contains the managed struct component, the managed struct component will be overwritten with the new value.
/// </summary>
/// <typeparam name="T">The struct type implementing IManagedComponent</typeparam>
/// <param name="entity">The entity to add the managed struct component to</param>
/// <param name="component">The data for the managed struct component</param>
/// <returns>False if the component was already present, true otherwise</returns>
public bool AddManagedStructComponent<T>(Entity entity, T managedStructComponent) where T : struct, IManagedStructComponent,
InternalSourceGen.StaticAPI.IManagedStructComponentSourceGenerated
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!LatiosWorldUnmanagedTracking.CheckHandle(m_index, m_version))
throw new System.InvalidOperationException("LatiosWorldUnmanaged is uninitialized. You must fetch a valid instance from SystemState.");
#endif
if (m_impl->m_managedStructStorage == default)
{
var managedStructStorage = new ManagedStructComponentStorage();
m_impl->m_managedStructStorage = GCHandle.Alloc(managedStructStorage, GCHandleType.Normal);
}
var em = m_impl->m_worldUnmanaged.EntityManager;
bool hasAssociated = em.AddComponent(entity, managedStructComponent.componentType);
em.AddComponent(entity, managedStructComponent.cleanupType);
(m_impl->m_managedStructStorage.Target as ManagedStructComponentStorage).AddComponent(entity, managedStructComponent);
return hasAssociated;
}
/// <summary>
/// Removes a managed struct component from the entity. This implicitly removes the managed struct component's AssociatedComponentType as well.
/// </summary>
/// <typeparam name="T">The struct type implementing IManagedComponent</typeparam>
/// <param name="entity">The entity to remove the managed struct component from</param>
/// <returns>Returns true if the entity had the managed struct component, false otherwise</returns>
public bool RemoveManagedStructComponent<T>(Entity entity) where T : struct, IManagedStructComponent, InternalSourceGen.StaticAPI.IManagedStructComponentSourceGenerated
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!LatiosWorldUnmanagedTracking.CheckHandle(m_index, m_version))
throw new System.InvalidOperationException("LatiosWorldUnmanaged is uninitialized. You must fetch a valid instance from SystemState.");
#endif
if (m_impl->m_managedStructStorage == default)
{
var managedStructStorage = new ManagedStructComponentStorage();
m_impl->m_managedStructStorage = GCHandle.Alloc(managedStructStorage, GCHandleType.Normal);
}
var storage = (m_impl->m_managedStructStorage.Target as ManagedStructComponentStorage);
var em = m_impl->m_worldUnmanaged.EntityManager;
bool hadAssociated = em.RemoveComponent(entity, storage.GetExistType<T>());
em.RemoveComponent(entity, storage.GetCleanupType<T>());
storage.RemoveComponent<T>(entity);
return hadAssociated;
}
/// <summary>
/// Gets the managed struct component instance from the entity
/// </summary>
/// <typeparam name="T">The struct type implementing IManagedComponent</typeparam>
public T GetManagedStructComponent<T>(Entity entity) where T : struct, IManagedStructComponent, InternalSourceGen.StaticAPI.IManagedStructComponentSourceGenerated
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!LatiosWorldUnmanagedTracking.CheckHandle(m_index, m_version))
throw new System.InvalidOperationException("LatiosWorldUnmanaged is uninitialized. You must fetch a valid instance from SystemState.");
#endif
if (m_impl->m_managedStructStorage == default)
{
var managedStructStorage = new ManagedStructComponentStorage();
m_impl->m_managedStructStorage = GCHandle.Alloc(managedStructStorage, GCHandleType.Normal);
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!m_impl->m_worldUnmanaged.EntityManager.HasComponent(entity, (m_impl->m_managedStructStorage.Target as ManagedStructComponentStorage).GetExistType<T>()))
throw new System.InvalidOperationException($"Entity {entity} does not have a component of type: {typeof(T).Name}");
#endif
return (m_impl->m_managedStructStorage.Target as ManagedStructComponentStorage).GetOrAddDefaultComponent<T>(entity);
}
/// <summary>
/// Sets the managed struct component instance for the entity.
/// Throws if the entity does not have the managed struct component
/// </summary>
/// <typeparam name="T">The struct type implementing IManagedComponent</typeparam>
/// <param name="entity">The entity which has the managed struct component to be replaced</param>
/// <param name="component">The new managed struct component value</param>
public void SetManagedStructComponent<T>(Entity entity, T managedStructComponent) where T : struct, IManagedStructComponent,
InternalSourceGen.StaticAPI.IManagedStructComponentSourceGenerated
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!LatiosWorldUnmanagedTracking.CheckHandle(m_index, m_version))
throw new System.InvalidOperationException("LatiosWorldUnmanaged is uninitialized. You must fetch a valid instance from SystemState.");
if (!m_impl->m_worldUnmanaged.EntityManager.HasComponent(entity, managedStructComponent.componentType))
throw new System.InvalidOperationException($"Entity {entity} does not have a component of type: {typeof(T).Name}");
#endif
if (m_impl->m_managedStructStorage == default)
{
var managedStructStorage = new ManagedStructComponentStorage();
m_impl->m_managedStructStorage = GCHandle.Alloc(managedStructStorage, GCHandleType.Normal);
}
(m_impl->m_managedStructStorage.Target as ManagedStructComponentStorage).AddComponent(entity, managedStructComponent);
}
/// <summary>
/// Returns true if the entity has the managed struct component. False otherwise.
/// </summary>
/// <typeparam name="T">The struct type implementing IManagedComponent</typeparam>
public bool HasManagedStructComponent<T>(Entity entity) where T : struct, IManagedStructComponent, InternalSourceGen.StaticAPI.IManagedStructComponentSourceGenerated
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!LatiosWorldUnmanagedTracking.CheckHandle(m_index, m_version))
throw new System.InvalidOperationException("LatiosWorldUnmanaged is uninitialized. You must fetch a valid instance from SystemState.");
#endif
var em = m_impl->m_worldUnmanaged.EntityManager;
if (m_impl->m_managedStructStorage == default)
{
var managedStructStorage = new ManagedStructComponentStorage();
m_impl->m_managedStructStorage = GCHandle.Alloc(managedStructStorage, GCHandleType.Normal);
}
var storage = (m_impl->m_managedStructStorage.Target as ManagedStructComponentStorage);
return em.HasComponent(entity, storage.GetExistType<T>());
}
internal ManagedStructComponentStorage GetManagedStructStorage()
{
if (m_impl->m_managedStructStorage == default)
{
var managedStructStorage = new ManagedStructComponentStorage();
m_impl->m_managedStructStorage = GCHandle.Alloc(managedStructStorage, GCHandleType.Normal);
return managedStructStorage;
}
return (m_impl->m_managedStructStorage.Target as ManagedStructComponentStorage);
}
#endregion
#region collection components
/// <summary>
/// Adds a collection component to the entity. This implicitly adds the collection component's AssociatedComponentType as well.
/// If the currently executing system is tracked by a Latios ComponentSystemGroup, then the collection component's dependency
/// is automatically updated with the final Dependency of the currently running system and any generated Dispose handle is merged
/// with the currently executing system's Dependency.
/// This function implicitly adds the collection component's associated component type to the entity as well.
/// If the entity already has the associated component type, this method returns false. The collection component will be set regardless.
/// </summary>
/// <typeparam name="T">The struct type implementing ICollectionComponent</typeparam>
/// <param name="entity">The entity in which the collection component should be added</param>
/// <param name="collectionComponent">The collection component value</param>
/// <returns>True if the component was added, false if it was set</returns>
public bool AddOrSetCollectionComponentAndDisposeOld<T>(Entity entity, T collectionComponent) where T : unmanaged, ICollectionComponent,
InternalSourceGen.StaticAPI.ICollectionComponentSourceGenerated
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!LatiosWorldUnmanagedTracking.CheckHandle(m_index, m_version))
throw new System.InvalidOperationException("LatiosWorldUnmanaged is uninitialized. You must fetch a valid instance from SystemState.");
#endif
var em = m_impl->m_worldUnmanaged.EntityManager;
bool addedAssociated = em.HasComponent(entity, collectionComponent.componentType);
if (addedAssociated)
{
if (!em.HasComponent(entity, collectionComponent.cleanupType))
em.AddComponent(entity, collectionComponent.cleanupType);
}
else
em.AddComponent(entity, new ComponentTypeSet(collectionComponent.componentType, collectionComponent.cleanupType));
m_impl->m_worldUnmanaged.EntityManager.AddComponent(entity, collectionComponent.cleanupType);
var replaced = m_impl->m_collectionComponentStorage.AddOrSetCollectionComponentAndDisposeOld(entity, collectionComponent, out var disposeHandle, out var newRef);
m_impl->m_collectionDependencies.Add(new LatiosWorldUnmanagedImpl.CollectionDependency
{
handle = newRef.collectionHandle,
extraDisposeDependency = disposeHandle,
hasExtraDisposeDependency = replaced,
wasReadOnly = false
});
return !addedAssociated;
}
/// <summary>
/// Removes the collection component from the entity and disposes it.
/// This implicitly removes the collection component's AssociatedComponentType as well.
/// If the currently executing system is tracked by a Latios ComponentSystemGroup, its Dependency property is combined with the disposal job.
/// Otherwise the disposal job is forced to complete.
/// </summary>
/// <typeparam name="T">The struct type implementing ICollectionComponent</typeparam>
/// <param name="entity">The entity in that has the collection component which should be removed</param>
/// <returns>True if the entity had the AssociatedComponentType, false otherwise</returns>
public bool RemoveCollectionComponentAndDispose<T>(Entity entity) where T : unmanaged, ICollectionComponent, InternalSourceGen.StaticAPI.ICollectionComponentSourceGenerated
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!LatiosWorldUnmanagedTracking.CheckHandle(m_index, m_version))
throw new System.InvalidOperationException("LatiosWorldUnmanaged is uninitialized. You must fetch a valid instance from SystemState.");
#endif
var type = m_impl->m_collectionComponentStorage.GetExistType<T>();
bool hadAssociated = m_impl->m_worldUnmanaged.EntityManager.RemoveComponent(entity, type);
m_impl->m_worldUnmanaged.EntityManager.RemoveComponent(entity, m_impl->m_collectionComponentStorage.GetCleanupType<T>());
var disposed = m_impl->m_collectionComponentStorage.RemoveIfPresentAndDisposeCollectionComponent<T>(entity, out var disposeHandle);
if (disposed)
m_impl->CompleteOrMergeDisposeDependency(disposeHandle);
return hadAssociated;
}
/// <summary>
/// Gets the collection component and its dependency.
/// If the currently executing system is tracked by a Latios ComponentSystemGroup, then the collection component's dependency
/// is automatically updated with the final Dependency of the currently running system, and all necessary JobHandles stored with the
/// collection component are merged with the currently executing system's Dependency.
/// </summary>
/// <typeparam name="T">The struct type implementing ICollectionComponent</typeparam>
/// <param name="entity">The entity that has the collection component</param>
/// <param name="readOnly">Specifies if the collection component will only be read by the system</param>
/// <returns>The collection component instance</returns>
public T GetCollectionComponent<T>(Entity entity, bool readOnly) where T : unmanaged, ICollectionComponent, InternalSourceGen.StaticAPI.ICollectionComponentSourceGenerated
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!LatiosWorldUnmanagedTracking.CheckHandle(m_index, m_version))
throw new System.InvalidOperationException("LatiosWorldUnmanaged is uninitialized. You must fetch a valid instance from SystemState.");
var type = m_impl->m_collectionComponentStorage.GetExistType<T>();
if (!m_impl->m_worldUnmanaged.EntityManager.HasComponent(entity, type))
throw new System.InvalidOperationException($"Entity {entity} does not have a component of type: {typeof(T).Name}");
#endif
var collectionRef = m_impl->m_collectionComponentStorage.GetOrAddDefaultCollectionComponent<T>(entity);
m_impl->CompleteOrMergeDependencies(readOnly, ref collectionRef.readHandles, ref collectionRef.writeHandle);
m_impl->m_collectionDependencies.Add(new LatiosWorldUnmanagedImpl.CollectionDependency
{
handle = collectionRef.collectionHandle,
extraDisposeDependency = default,
hasExtraDisposeDependency = false,
wasReadOnly = readOnly
});
return collectionRef.collectionRef;
}
// Note: Always ReadWrite. This method is not recommended unless you know what you are doing.
public T GetCollectionComponent<T>(Entity entity, out JobHandle combinedReadWriteHandle) where T : unmanaged, ICollectionComponent,
InternalSourceGen.StaticAPI.ICollectionComponentSourceGenerated
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!LatiosWorldUnmanagedTracking.CheckHandle(m_index, m_version))
throw new System.InvalidOperationException("LatiosWorldUnmanaged is uninitialized. You must fetch a valid instance from SystemState.");
var type = m_impl->m_collectionComponentStorage.GetExistType<T>();
if (!m_impl->m_worldUnmanaged.EntityManager.HasComponent(entity, type))
throw new System.InvalidOperationException($"Entity {entity} does not have a component of type: {typeof(T).Name}");
#endif
var collectionRef = m_impl->m_collectionComponentStorage.GetOrAddDefaultCollectionComponent<T>(entity);
{
var handleArray = new NativeArray<JobHandle>(collectionRef.readHandles.Length + 1, Allocator.Temp);
handleArray[0] = collectionRef.writeHandle;
for (int i = 0; i < collectionRef.readHandles.Length; i++)
handleArray[i + 1] = collectionRef.readHandles[i];
combinedReadWriteHandle = JobHandle.CombineDependencies(handleArray);
}
m_impl->m_collectionDependencies.Add(new LatiosWorldUnmanagedImpl.CollectionDependency
{
handle = collectionRef.collectionHandle,
extraDisposeDependency = default,
hasExtraDisposeDependency = false,
wasReadOnly = false
});
return collectionRef.collectionRef;
}
/// <summary>
/// Replaces the collection component's content with the new value, disposing the old instance.
/// If the currently executing system is tracked by a Latios ComponentSystemGroup, then the collection component's dependency
/// is automatically updated with the final Dependency of the currently running system and any generated Dispose handle is merged
/// with the currently executing system's Dependency.
/// </summary>
/// <typeparam name="T">The struct type implementing ICollectionComponent</typeparam>
/// <param name="entity">The entity that has the collection component to be replaced</param>
/// <param name="collectionComponent">The new collection component value</param>
public void SetCollectionComponentAndDisposeOld<T>(Entity entity, T collectionComponent) where T : unmanaged, ICollectionComponent,
InternalSourceGen.StaticAPI.ICollectionComponentSourceGenerated
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!LatiosWorldUnmanagedTracking.CheckHandle(m_index, m_version))
throw new System.InvalidOperationException("LatiosWorldUnmanaged is uninitialized. You must fetch a valid instance from SystemState.");
if (!m_impl->m_worldUnmanaged.EntityManager.HasComponent(entity, collectionComponent.componentType))
throw new System.InvalidOperationException($"Entity {entity} does not have a component of type: {typeof(T).Name}");
#endif
var replaced = m_impl->m_collectionComponentStorage.AddOrSetCollectionComponentAndDisposeOld(entity, collectionComponent, out var disposeHandle, out var newRef);
m_impl->m_collectionDependencies.Add(new LatiosWorldUnmanagedImpl.CollectionDependency
{
handle = newRef.collectionHandle,
extraDisposeDependency = disposeHandle,
hasExtraDisposeDependency = replaced,
wasReadOnly = false
});
}
/// <summary>
/// Returns true if the entity has the associated component type for the collection component type
/// </summary>
/// <typeparam name="T">The struct type implementing ICollectionComponent</typeparam>
public bool HasCollectionComponent<T>(Entity entity) where T : unmanaged, ICollectionComponent, InternalSourceGen.StaticAPI.ICollectionComponentSourceGenerated
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!LatiosWorldUnmanagedTracking.CheckHandle(m_index, m_version))
throw new System.InvalidOperationException("LatiosWorldUnmanaged is uninitialized. You must fetch a valid instance from SystemState.");
#endif
var type = m_impl->m_collectionComponentStorage.GetExistType<T>();
return m_impl->m_worldUnmanaged.EntityManager.HasComponent(entity, type);
}
/// <summary>
/// Provides a dependency for the collection component attached to the entity.
/// The collection component will no longer be automatically updated with the final Dependency of the currently executing system.
/// If the collection component was retrieved, added, or set outside of a tracked system execution and used in jobs, then you
/// must call this method to ensure correct behavior.
/// </summary>
/// <typeparam name="T">The struct type implementing ICollectionComponent</typeparam>
/// <param name="entity">The entity with the collection component whose dependency should be updated</param>
/// <param name="handle">The new dependency for the collection component</param>
/// <param name="isReadOnlyHandle">True if the dependency to update only read the collection component</param>
public void UpdateCollectionComponentDependency<T>(Entity entity, JobHandle handle, bool isReadOnlyHandle) where T : unmanaged, ICollectionComponent,
InternalSourceGen.StaticAPI.ICollectionComponentSourceGenerated
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!LatiosWorldUnmanagedTracking.CheckHandle(m_index, m_version))
throw new System.InvalidOperationException("LatiosWorldUnmanaged is uninitialized. You must fetch a valid instance from SystemState.");
#endif
m_impl->ClearCollectionDependency(entity, BurstRuntime.GetHashCode64<T>());
if (!m_impl->m_collectionComponentStorage.TryGetCollectionComponent<T>(entity, out var storedRef))
return;
if (isReadOnlyHandle)
{
if (storedRef.readHandles.Length == storedRef.readHandles.Capacity)
{
var handleArray = new NativeArray<JobHandle>(storedRef.readHandles.Length + 1, Allocator.Temp);
handleArray[0] = handle;
for (int i = 0; i < storedRef.readHandles.Length; i++)
handleArray[i + 1] = storedRef.readHandles[i];
storedRef.readHandles.Clear();
storedRef.readHandles.Add(JobHandle.CombineDependencies(handleArray));
}
else
storedRef.readHandles.Add(handle);
}
else
{
storedRef.writeHandle = handle;
storedRef.readHandles.Clear();
}
}
/// <summary>
/// Specifies that the accessed collection component on the specified entity was operated fully by the main thread.
/// The collection component will no longer be automatically updated with the final Dependency of the currently executing system.
/// If the collection component was retrieved, added, or set outside of a tracked system execution but not used in jobs, then you
/// must call this method to ensure correct behavior.
/// </summary>
/// <typeparam name="T">The struct type implementing ICollectionComponent</typeparam>
/// <param name="entity">The entity with the collection component that was accessed, modified, or replaced</param>
/// <param name="wasAccessedAsReadOnly">True if the main thread requested the collection component as readOnly</param>
public void UpdateCollectionComponentMainThreadAccess<T>(Entity entity, bool wasAccessedAsReadOnly) where T : unmanaged, ICollectionComponent,
InternalSourceGen.StaticAPI.ICollectionComponentSourceGenerated
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!LatiosWorldUnmanagedTracking.CheckHandle(m_index, m_version))
throw new System.InvalidOperationException("LatiosWorldUnmanaged is uninitialized. You must fetch a valid instance from SystemState.");
#endif
m_impl->ClearCollectionDependency(entity, BurstRuntime.GetHashCode64<T>());
if (wasAccessedAsReadOnly)
return;
if (m_impl->m_collectionComponentStorage.TryGetCollectionComponent<T>(entity, out var storedRef))
{
storedRef.writeHandle = default;
storedRef.readHandles.Clear();
}
}
/// <summary>
/// Gets an instance of the Collection Aspect from the entity.
/// </summary>
/// <typeparam name="T">The struct type implementing ICollectionAspect</typeparam>
/// <param name="entity">The entity that has the underlying components the ICollectionAspect expects</param>
/// <returns>The Collection Aspect instance</returns>
public T GetCollectionAspect<T>(Entity entity) where T : unmanaged, ICollectionAspect<T>
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!LatiosWorldUnmanagedTracking.CheckHandle(m_index, m_version))
throw new System.InvalidOperationException("LatiosWorldUnmanaged is uninitialized. You must fetch a valid instance from SystemState.");
#endif
return default(T).CreateCollectionAspect(this, m_impl->m_worldUnmanaged.EntityManager, entity);
}
/// <summary>
/// Completes all jobs tracked by collection components. NOT Burst-compatible.
/// </summary>
public void CompleteAllTrackedJobs()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!LatiosWorldUnmanagedTracking.CheckHandle(m_index, m_version))
throw new System.InvalidOperationException("LatiosWorldUnmanaged is uninitialized. You must fetch a valid instance from SystemState.");
#endif
foreach (var dep in m_impl->m_collectionDependencies)
if (dep.hasExtraDisposeDependency)
dep.extraDisposeDependency.Complete();
m_impl->m_collectionComponentStorage.CompleteEverything();
}
#endregion
}
internal static class LatiosWorldUnmanagedTracking
{
public static readonly SharedStatic<FixedList4096Bytes<int> > s_handles = SharedStatic<FixedList4096Bytes<int> >.GetOrCreate<LatiosWorldUnmanagedImpl>();
public static void CreateHandle(out int index, out int version)
{
if (s_handles.Data.Length == s_handles.Data.Capacity)
{
for (int i = 0; i < s_handles.Data.Length; i++)
{
if (s_handles.Data[i] < 0)
{
index = i;
version = s_handles.Data[i] = math.abs(s_handles.Data[i]) + 1;
return;
}
}
index = 0;
version = 0;
}
else
{
index = s_handles.Data.Length;
version = 1;
s_handles.Data.Add(1);
}
}
public static void DestroyHandle(int index, int version)
{
if (s_handles.Data[index] == version)
s_handles.Data[index] = -version;
}
public static bool CheckHandle(int index, int version)
{
if (version == 0)
return false;
return s_handles.Data[index] == version;
}
}
internal unsafe struct LatiosWorldUnmanagedImpl
{
public BlackboardEntity m_worldBlackboardEntity;
public BlackboardEntity m_sceneBlackboardEntity;
public GCHandle m_unmanagedSystemInterfacesDispatcher;
public GCHandle m_managedStructStorage;
public CollectionComponentStorage m_collectionComponentStorage;
public WorldUnmanaged m_worldUnmanaged;
public UnsafeList<SystemHandle> m_executingSystemStack;
public UnsafeList<CollectionDependency> m_collectionDependencies;
public bool m_zeroToleranceForExceptionsEnabled;
public bool m_errorState;
public bool m_registeredSystemOnce;
public Systems.SyncPointPlaybackSystem* m_syncPointPlaybackSystem;
public void BeginDependencyTracking(SystemHandle system)
{
// Clear dependencies registered due to OnCreate.
// Todo: What if jobs were scheduled before first dependency tracking? Is there an earlier opportunity to detect this?
if (!m_registeredSystemOnce)
{
m_collectionDependencies.Clear();
m_registeredSystemOnce = true;
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (m_syncPointPlaybackSystem != null && m_syncPointPlaybackSystem->hasPendingJobHandlesToAquire)
{
if (m_executingSystemStack.IsEmpty)
{
var text = m_worldUnmanaged.ResolveSystemStateRef(system).DebugName;
UnityEngine.Debug.LogError(
$"An unresolved sync point dependency was detected that originated outside of any Latios ComponentSystemGroup. See Core/\"Automatic Dependency Management Errors.md\" in the documentation. Beginning execution of {text}.");
m_errorState = true;
}
else
{
var lastSystem = m_executingSystemStack[m_executingSystemStack.Length - 1];
var text = m_worldUnmanaged.ResolveSystemStateRef(lastSystem).DebugName;
UnityEngine.Debug.LogError(
$"{text} has a pending auto-dependency on syncPoint but a new system has started executing. This is not allowed. See Core/\"Automatic Dependency Management Errors.md\" in the documentation.");
m_errorState = true;
}
}
if (!m_collectionDependencies.IsEmpty)
{
if (m_executingSystemStack.IsEmpty)
{
var text = m_worldUnmanaged.ResolveSystemStateRef(system).DebugName;
UnityEngine.Debug.LogError(
$"An unresolved collection component dependency was detected that originated outside of any Latios ComponentSystemGroup. See Core/\"Automatic Dependency Management Errors.md\" in the documentation. Beginning execution of {text}.");
m_errorState = true;
}
else
{
var lastSystem = m_executingSystemStack[m_executingSystemStack.Length - 1];
var text = m_worldUnmanaged.ResolveSystemStateRef(lastSystem).DebugName;
UnityEngine.Debug.LogError(
$"{text} has a pending auto-dependency on a collection component but a new system has started executing. This is not allowed. See Core/\"Automatic Dependency Management Errors.md\" in the documentation.");
m_errorState = true;
}
}
#endif
m_executingSystemStack.Add(system);
}
public void EndDependencyTracking(SystemHandle system, bool hadError)
{
m_errorState |= hadError;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (m_executingSystemStack.IsEmpty || m_executingSystemStack[m_executingSystemStack.Length - 1] != system)
{
m_errorState = true;
var currentSystemName = m_worldUnmanaged.ResolveSystemStateRef(system).DebugName;
if (!m_executingSystemStack.IsEmpty)
{
var lastSystem = m_executingSystemStack[m_executingSystemStack.Length - 1];
var lastSystemName = m_worldUnmanaged.ResolveSystemStateRef(lastSystem).DebugName;
throw new System.InvalidOperationException(
$"LatiosWorldUnmanaged encountered a dependency tracking mismatch. Please report this bug! Current System: {currentSystemName}, previous: {lastSystemName}");
}
throw new System.InvalidOperationException(
$"LatiosWorldUnmanaged encountered a dependency tracking mismatch. Please report this bug! Current System: {currentSystemName}, empty stack");
}
#endif
var dependency = m_worldUnmanaged.ResolveSystemStateRef(system).Dependency;
if (!dependency.Equals(default))
{
if (m_syncPointPlaybackSystem != null && m_syncPointPlaybackSystem->hasPendingJobHandlesToAquire)
{
m_syncPointPlaybackSystem->AddJobHandleForProducer(dependency);
}
foreach (var dep in m_collectionDependencies)
{
if (m_collectionComponentStorage.IsHandleValid(in dep.handle))
{
if (dep.wasReadOnly)
{
if (dep.handle.readHandles.Length == dep.handle.readHandles.Capacity)
{
var handleArray = new NativeArray<JobHandle>(dep.handle.readHandles.Length + 1, Allocator.Temp);
handleArray[0] = dependency;
for (int i = 0; i < dep.handle.readHandles.Length; i++)
handleArray[i + 1] = dep.handle.readHandles[i];
dep.handle.readHandles.Clear();
dep.handle.readHandles.Add(JobHandle.CombineDependencies(handleArray));
}
else
dep.handle.readHandles.Add(dependency);
}
else
{
dep.handle.writeHandle = dependency;
dep.handle.readHandles.Clear();
}
}
}
m_collectionDependencies.Clear();
}
else
{
if (m_syncPointPlaybackSystem != null && m_syncPointPlaybackSystem->hasPendingJobHandlesToAquire)
{
m_syncPointPlaybackSystem->AddMainThreadCompletionForProducer();
}
foreach (var dep in m_collectionDependencies)
{
if (!dep.wasReadOnly)
{
// Write job was completed. Clear everything.
if (m_collectionComponentStorage.IsHandleValid(in dep.handle))
{
dep.handle.writeHandle = default;
dep.handle.readHandles.Clear();
}
}
}
m_collectionDependencies.Clear();
}
m_executingSystemStack.Length--;
}
public void CompleteOrMergeDisposeDependency(JobHandle handle)
{
if (!m_executingSystemStack.IsEmpty && m_executingSystemStack[m_executingSystemStack.Length - 1] == m_worldUnmanaged.GetCurrentlyExecutingSystem())
{
ref var state = ref m_worldUnmanaged.ResolveSystemStateRef(m_executingSystemStack[m_executingSystemStack.Length - 1]);
state.Dependency = JobHandle.CombineDependencies(state.Dependency, handle);
}
else
{
handle.Complete();
}
}
public void CompleteOrMergeDependencies(bool isReadOnly, ref FixedList512Bytes<JobHandle> readHandles, ref JobHandle writeHandle)
{
if (writeHandle.Equals(default(JobHandle)))
{
if (isReadOnly || readHandles.IsEmpty)
return;
}
if (!m_executingSystemStack.IsEmpty && m_executingSystemStack[m_executingSystemStack.Length - 1] == m_worldUnmanaged.GetCurrentlyExecutingSystem())
{
ref var state = ref m_worldUnmanaged.ResolveSystemStateRef(m_executingSystemStack[m_executingSystemStack.Length - 1]);
if (isReadOnly)
{
state.Dependency = JobHandle.CombineDependencies(state.Dependency, writeHandle);
}
else
{
var handleArray = new NativeArray<JobHandle>(readHandles.Length + 2, Allocator.Temp);
handleArray[0] = state.Dependency;
handleArray[1] = writeHandle;
for (int i = 0; i < readHandles.Length; i++)
handleArray[i + 2] = readHandles[i];
state.Dependency = JobHandle.CombineDependencies(handleArray);
}
}
else
{
if (isReadOnly)
{
writeHandle.Complete();
writeHandle = default;
}
else
{
var handleArray = new NativeArray<JobHandle>(readHandles.Length + 1, Allocator.Temp);
handleArray[0] = writeHandle;
for (int i = 0; i < readHandles.Length; i++)
handleArray[i + 1] = readHandles[i];
JobHandle.CompleteAll(handleArray);
writeHandle = default;
readHandles.Clear();
}
}
}
public void ClearCollectionDependency(Entity entity, long typeHash)
{
for (int i = 0; i < m_collectionDependencies.Length; i++)
{
ref var dep = ref m_collectionDependencies.ElementAt(i);
if (dep.handle.entity == entity && dep.handle.typeHash == typeHash)
{
m_collectionDependencies.RemoveAtSwapBack(i);
i--;
}
}
}
public ref Systems.SyncPointPlaybackSystem GetSyncPoint()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (m_syncPointPlaybackSystem == null)
throw new System.InvalidOperationException("No SyncPointPlaybackSystem exists in the LatiosWorld.");
#endif
return ref *m_syncPointPlaybackSystem;
}
public bool isAllowedToRun => !(m_zeroToleranceForExceptionsEnabled && m_errorState);
public struct CollectionDependency
{
public CollectionComponentHandle handle;
public JobHandle extraDisposeDependency;
public bool wasReadOnly;
public bool hasExtraDisposeDependency;
}
}
}
| 0 | 0.970023 | 1 | 0.970023 | game-dev | MEDIA | 0.924791 | game-dev | 0.880491 | 1 | 0.880491 |
Pan4ur/ThunderHack-Recode | 11,767 | src/main/java/thunder/hack/utility/world/HoleUtility.java | package thunder.hack.utility.world;
import net.minecraft.block.Block;
import net.minecraft.block.Blocks;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.math.Vec3i;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import static thunder.hack.features.modules.Module.mc;
public final class HoleUtility {
public static final Vec3i[] VECTOR_PATTERN = {
new Vec3i(0, 0, 1),
new Vec3i(0, 0, -1),
new Vec3i(1, 0, 0),
new Vec3i(-1, 0, 0)
};
public static @NotNull List<BlockPos> getHolePoses(@NotNull Vec3d from) {
List<BlockPos> positions = new ArrayList<>();
double decimalX = from.getX() - Math.floor(from.getX());
double decimalZ = from.getZ() - Math.floor(from.getZ());
int offX = calcOffset(decimalX);
int offZ = calcOffset(decimalZ);
positions.add(getPos(from));
for (int x = 0; x <= Math.abs(offX); ++x) {
for (int z = 0; z <= Math.abs(offZ); ++z) {
int properX = x * offX;
int properZ = z * offZ;
positions.add(Objects.requireNonNull(getPos(from)).add(properX, 0, properZ));
}
}
return positions;
}
public static @NotNull List<BlockPos> getSurroundPoses(@NotNull Vec3d from) {
final BlockPos fromPos = BlockPos.ofFloored(from);
final ArrayList<BlockPos> tempOffsets = new ArrayList<>();
final double decimalX = Math.abs(from.getX()) - Math.floor(Math.abs(from.getX()));
final double decimalZ = Math.abs(from.getZ()) - Math.floor(Math.abs(from.getZ()));
final int lengthXPos = calcLength(decimalX, false);
final int lengthXNeg = calcLength(decimalX, true);
final int lengthZPos = calcLength(decimalZ, false);
final int lengthZNeg = calcLength(decimalZ, true);
for (int x = 1; x < lengthXPos + 1; ++x) {
tempOffsets.add(addToPlayer(fromPos, x, 0.0, 1 + lengthZPos));
tempOffsets.add(addToPlayer(fromPos, x, 0.0, -(1 + lengthZNeg)));
}
for (int x = 0; x <= lengthXNeg; ++x) {
tempOffsets.add(addToPlayer(fromPos, -x, 0.0, 1 + lengthZPos));
tempOffsets.add(addToPlayer(fromPos, -x, 0.0, -(1 + lengthZNeg)));
}
for (int z = 1; z < lengthZPos + 1; ++z) {
tempOffsets.add(addToPlayer(fromPos, 1 + lengthXPos, 0.0, z));
tempOffsets.add(addToPlayer(fromPos, -(1 + lengthXNeg), 0.0, z));
}
for (int z = 0; z <= lengthZNeg; ++z) {
tempOffsets.add(addToPlayer(fromPos, 1 + lengthXPos, 0.0, -z));
tempOffsets.add(addToPlayer(fromPos, -(1 + lengthXNeg), 0.0, -z));
}
return tempOffsets;
}
private static @NotNull BlockPos getPos(@NotNull Vec3d from) {
return BlockPos.ofFloored(from.getX(), from.getY() - Math.floor(from.getY()) > 0.8 ? Math.floor(from.getY()) + 1.0 : Math.floor(from.getY()), from.getZ());
}
public static int calcOffset(double dec) {
return dec >= 0.7 ? 1 : (dec <= 0.3 ? -1 : 0);
}
public static int calcLength(double decimal, boolean negative) {
if (negative) return decimal <= 0.3 ? 1 : 0;
return decimal >= 0.7 ? 1 : 0;
}
public static BlockPos addToPlayer(@NotNull BlockPos playerPos, double x, double y, double z) {
if (playerPos.getX() < 0) x = -x;
if (playerPos.getY() < 0) y = -y;
if (playerPos.getZ() < 0) z = -z;
return playerPos.add(BlockPos.ofFloored(x, y, z));
}
public static boolean isHole(BlockPos pos) {
return isSingleHole(pos)
|| validTwoBlockIndestructible(pos) || validTwoBlockBedrock(pos)
|| validQuadIndestructible(pos) || validQuadBedrock(pos);
}
public static boolean isSingleHole(BlockPos pos) {
return validIndestructible(pos) || validBedrock(pos);
}
public static boolean validIndestructible(@NotNull BlockPos pos) {
return !validBedrock(pos)
&& (isIndestructible(pos.add(0, -1, 0)) || isBedrock(pos.add(0, -1, 0)))
&& (isIndestructible(pos.add(1, 0, 0)) || isBedrock(pos.add(1, 0, 0)))
&& (isIndestructible(pos.add(-1, 0, 0)) || isBedrock(pos.add(-1, 0, 0)))
&& (isIndestructible(pos.add(0, 0, 1)) || isBedrock(pos.add(0, 0, 1)))
&& (isIndestructible(pos.add(0, 0, -1)) || isBedrock(pos.add(0, 0, -1)))
&& isReplaceable(pos)
&& isReplaceable(pos.add(0, 1, 0))
&& isReplaceable(pos.add(0, 2, 0));
}
public static boolean validBedrock(@NotNull BlockPos pos) {
return isBedrock(pos.add(0, -1, 0))
&& isBedrock(pos.add(1, 0, 0))
&& isBedrock(pos.add(-1, 0, 0))
&& isBedrock(pos.add(0, 0, 1))
&& isBedrock(pos.add(0, 0, -1))
&& isReplaceable(pos)
&& isReplaceable(pos.add(0, 1, 0))
&& isReplaceable(pos.add(0, 2, 0));
}
public static boolean validTwoBlockBedrock(@NotNull BlockPos pos) {
if (!isReplaceable(pos)) return false;
Vec3i addVec = getTwoBlocksDirection(pos);
// If addVec not found -> hole incorrect
if (addVec == null)
return false;
BlockPos[] checkPoses = new BlockPos[]{pos, pos.add(addVec)};
// Check surround poses of checkPoses
for (BlockPos checkPos : checkPoses) {
if(!isReplaceable(checkPos.add(0, 1, 0)) || !isReplaceable(checkPos.add(0, 2, 0)))
return false;
BlockPos downPos = checkPos.down();
if (!isBedrock(downPos))
return false;
for (Vec3i vec : VECTOR_PATTERN) {
BlockPos reducedPos = checkPos.add(vec);
if (!isBedrock(reducedPos) && !reducedPos.equals(pos) && !reducedPos.equals(pos.add(addVec)))
return false;
}
}
return true;
}
public static boolean validTwoBlockIndestructible(@NotNull BlockPos pos) {
if (!isReplaceable(pos)) return false;
Vec3i addVec = getTwoBlocksDirection(pos);
// If addVec not found -> hole incorrect
if (addVec == null)
return false;
BlockPos[] checkPoses = new BlockPos[]{pos, pos.add(addVec)};
// Check surround poses of checkPoses
boolean wasIndestrictible = false;
for (BlockPos checkPos : checkPoses) {
BlockPos downPos = checkPos.down();
if (isIndestructible(downPos))
wasIndestrictible = true;
else if (!isBedrock(downPos))
return false;
if(!isReplaceable(checkPos.add(0, 1, 0)) || !isReplaceable(checkPos.add(0, 2, 0)))
return false;
for (Vec3i vec : VECTOR_PATTERN) {
BlockPos reducedPos = checkPos.add(vec);
if (isIndestructible(reducedPos)) {
wasIndestrictible = true;
continue;
}
if (!isBedrock(reducedPos) && !reducedPos.equals(pos) && !reducedPos.equals(pos.add(addVec)))
return false;
}
}
return wasIndestrictible;
}
private static @Nullable Vec3i getTwoBlocksDirection(BlockPos pos) {
// Try to get direction
for (Vec3i vec : VECTOR_PATTERN) {
if (isReplaceable(pos.add(vec)))
return vec;
}
return null;
}
public static boolean validQuadIndestructible(@NotNull BlockPos pos) {
List<BlockPos> checkPoses = getQuadDirection(pos);
// If checkPoses not found -> hole incorrect
if (checkPoses == null)
return false;
boolean wasIndestrictible = false;
for (BlockPos checkPos : checkPoses) {
BlockPos downPos = checkPos.down();
if (isIndestructible(downPos)) {
wasIndestrictible = true;
} else if (!isBedrock(downPos)) {
return false;
}
if(!isReplaceable(checkPos.add(0, 1, 0)) || !isReplaceable(checkPos.add(0, 2, 0)))
return false;
for (Vec3i vec : VECTOR_PATTERN) {
BlockPos reducedPos = checkPos.add(vec);
if (isIndestructible(reducedPos)) {
wasIndestrictible = true;
continue;
}
if (!isBedrock(reducedPos) && !checkPoses.contains(reducedPos)) {
return false;
}
}
}
return wasIndestrictible;
}
public static boolean validQuadBedrock(@NotNull BlockPos pos) {
List<BlockPos> checkPoses = getQuadDirection(pos);
// If checkPoses not found -> hole incorrect
if (checkPoses == null)
return false;
for (BlockPos checkPos : checkPoses) {
BlockPos downPos = checkPos.down();
if (!isBedrock(downPos))
return false;
if(!isReplaceable(checkPos.add(0, 1, 0)) || !isReplaceable(checkPos.add(0, 2, 0)))
return false;
for (Vec3i vec : VECTOR_PATTERN) {
BlockPos reducedPos = checkPos.add(vec);
if (!isBedrock(reducedPos) && !checkPoses.contains(reducedPos)) {
return false;
}
}
}
return true;
}
private static @Nullable List<BlockPos> getQuadDirection(@NotNull BlockPos pos) {
// Try to get direction
List<BlockPos> dirList = new ArrayList<>();
dirList.add(pos);
if (!isReplaceable(pos))
return null;
if (isReplaceable(pos.add(1, 0, 0)) && isReplaceable(pos.add(0, 0, 1)) && isReplaceable(pos.add(1, 0, 1))) {
dirList.add(pos.add(1, 0, 0));
dirList.add(pos.add(0, 0, 1));
dirList.add(pos.add(1, 0, 1));
}
if (isReplaceable(pos.add(-1, 0, 0)) && isReplaceable(pos.add(0, 0, -1)) && isReplaceable(pos.add(-1, 0, -1))) {
dirList.add(pos.add(-1, 0, 0));
dirList.add(pos.add(0, 0, -1));
dirList.add(pos.add(-1, 0, -1));
}
if (isReplaceable(pos.add(1, 0, 0)) && isReplaceable(pos.add(0, 0, -1)) && isReplaceable(pos.add(1, 0, -1))) {
dirList.add(pos.add(1, 0, 0));
dirList.add(pos.add(0, 0, -1));
dirList.add(pos.add(1, 0, -1));
}
if (isReplaceable(pos.add(-1, 0, 0)) && isReplaceable(pos.add(0, 0, 1)) && isReplaceable(pos.add(-1, 0, 1))) {
dirList.add(pos.add(-1, 0, 0));
dirList.add(pos.add(0, 0, 1));
dirList.add(pos.add(-1, 0, 1));
}
if (dirList.size() != 4)
return null;
return dirList;
}
private static boolean isIndestructible(BlockPos bp) {
if (mc.world == null) return false;
Block block = mc.world.getBlockState(bp).getBlock();
return block == Blocks.OBSIDIAN || block == Blocks.NETHERITE_BLOCK
|| block == Blocks.CRYING_OBSIDIAN || block == Blocks.RESPAWN_ANCHOR;
}
private static boolean isBedrock(BlockPos bp) {
if (mc.world == null) return false;
return mc.world.getBlockState(bp).getBlock() == Blocks.BEDROCK;
}
private static boolean isReplaceable(BlockPos bp) {
if (mc.world == null) return false;
return mc.world.getBlockState(bp).isReplaceable();
}
}
| 0 | 0.798403 | 1 | 0.798403 | game-dev | MEDIA | 0.843272 | game-dev | 0.974896 | 1 | 0.974896 |
oddmax/match3-mvc-ecs-example | 10,513 | Assets/Plugins/DOTween/Modules/DOTweenModuleUnityVersion.cs | // Author: Daniele Giardini - http://www.demigiant.com
// Created: 2018/07/13
using System;
using UnityEngine;
using DG.Tweening.Core;
#pragma warning disable 1591
namespace DG.Tweening
{
/// <summary>
/// Shortcuts/functions that are not strictly related to specific Modules
/// but are available only on some Unity versions
/// </summary>
public static class DOTweenModuleUnityVersion
{
#if UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_5 || UNITY_2017_1_OR_NEWER
#region Unity 4.3 or Newer
#region Material
/// <summary>Tweens a Material's color using the given gradient
/// (NOTE 1: only uses the colors of the gradient, not the alphas - NOTE 2: creates a Sequence, not a Tweener).
/// Also stores the image as the tween's target so it can be used for filtered operations</summary>
/// <param name="gradient">The gradient to use</param><param name="duration">The duration of the tween</param>
public static Sequence DOGradientColor(this Material target, Gradient gradient, float duration)
{
Sequence s = DOTween.Sequence();
GradientColorKey[] colors = gradient.colorKeys;
int len = colors.Length;
for (int i = 0; i < len; ++i) {
GradientColorKey c = colors[i];
if (i == 0 && c.time <= 0) {
target.color = c.color;
continue;
}
float colorDuration = i == len - 1
? duration - s.Duration(false) // Verifies that total duration is correct
: duration * (i == 0 ? c.time : c.time - colors[i - 1].time);
s.Append(target.DOColor(c.color, colorDuration).SetEase(Ease.Linear));
}
return s;
}
/// <summary>Tweens a Material's named color property using the given gradient
/// (NOTE 1: only uses the colors of the gradient, not the alphas - NOTE 2: creates a Sequence, not a Tweener).
/// Also stores the image as the tween's target so it can be used for filtered operations</summary>
/// <param name="gradient">The gradient to use</param>
/// <param name="property">The name of the material property to tween (like _Tint or _SpecColor)</param>
/// <param name="duration">The duration of the tween</param>
public static Sequence DOGradientColor(this Material target, Gradient gradient, string property, float duration)
{
Sequence s = DOTween.Sequence();
GradientColorKey[] colors = gradient.colorKeys;
int len = colors.Length;
for (int i = 0; i < len; ++i) {
GradientColorKey c = colors[i];
if (i == 0 && c.time <= 0) {
target.color = c.color;
continue;
}
float colorDuration = i == len - 1
? duration - s.Duration(false) // Verifies that total duration is correct
: duration * (i == 0 ? c.time : c.time - colors[i - 1].time);
s.Append(target.DOColor(c.color, property, colorDuration).SetEase(Ease.Linear));
}
return s;
}
#endregion
#endregion
#endif
#if UNITY_5_3_OR_NEWER || UNITY_2017_1_OR_NEWER
#region CustomYieldInstructions (Unity 5.3 or Newer)
/// <summary>
/// Returns a <see cref="CustomYieldInstruction"/> that waits until the tween is killed or complete.
/// It can be used inside a coroutine as a yield.
/// <para>Example usage:</para><code>yield return myTween.WaitForCompletion(true);</code>
/// </summary>
public static CustomYieldInstruction WaitForCompletion(this Tween t, bool returnCustomYieldInstruction)
{
if (!t.active) {
if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t);
return null;
}
return new DOTweenCYInstruction.WaitForCompletion(t);
}
/// <summary>
/// Returns a <see cref="CustomYieldInstruction"/> that waits until the tween is killed or rewinded.
/// It can be used inside a coroutine as a yield.
/// <para>Example usage:</para><code>yield return myTween.WaitForRewind();</code>
/// </summary>
public static CustomYieldInstruction WaitForRewind(this Tween t, bool returnCustomYieldInstruction)
{
if (!t.active) {
if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t);
return null;
}
return new DOTweenCYInstruction.WaitForRewind(t);
}
/// <summary>
/// Returns a <see cref="CustomYieldInstruction"/> that waits until the tween is killed.
/// It can be used inside a coroutine as a yield.
/// <para>Example usage:</para><code>yield return myTween.WaitForKill();</code>
/// </summary>
public static CustomYieldInstruction WaitForKill(this Tween t, bool returnCustomYieldInstruction)
{
if (!t.active) {
if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t);
return null;
}
return new DOTweenCYInstruction.WaitForKill(t);
}
/// <summary>
/// Returns a <see cref="CustomYieldInstruction"/> that waits until the tween is killed or has gone through the given amount of loops.
/// It can be used inside a coroutine as a yield.
/// <para>Example usage:</para><code>yield return myTween.WaitForElapsedLoops(2);</code>
/// </summary>
/// <param name="elapsedLoops">Elapsed loops to wait for</param>
public static CustomYieldInstruction WaitForElapsedLoops(this Tween t, int elapsedLoops, bool returnCustomYieldInstruction)
{
if (!t.active) {
if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t);
return null;
}
return new DOTweenCYInstruction.WaitForElapsedLoops(t, elapsedLoops);
}
/// <summary>
/// Returns a <see cref="CustomYieldInstruction"/> that waits until the tween is killed or has reached the given position (loops included, delays excluded).
/// It can be used inside a coroutine as a yield.
/// <para>Example usage:</para><code>yield return myTween.WaitForPosition(2.5f);</code>
/// </summary>
/// <param name="position">Position (loops included, delays excluded) to wait for</param>
public static CustomYieldInstruction WaitForPosition(this Tween t, float position, bool returnCustomYieldInstruction)
{
if (!t.active) {
if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t);
return null;
}
return new DOTweenCYInstruction.WaitForPosition(t, position);
}
/// <summary>
/// Returns a <see cref="CustomYieldInstruction"/> that waits until the tween is killed or started
/// (meaning when the tween is set in a playing state the first time, after any eventual delay).
/// It can be used inside a coroutine as a yield.
/// <para>Example usage:</para><code>yield return myTween.WaitForStart();</code>
/// </summary>
public static CustomYieldInstruction WaitForStart(this Tween t, bool returnCustomYieldInstruction)
{
if (!t.active) {
if (Debugger.logPriority > 0) Debugger.LogInvalidTween(t);
return null;
}
return new DOTweenCYInstruction.WaitForStart(t);
}
#endregion
#endif
}
// █████████████████████████████████████████████████████████████████████████████████████████████████████████████████████
// ███ CLASSES █████████████████████████████████████████████████████████████████████████████████████████████████████████
// █████████████████████████████████████████████████████████████████████████████████████████████████████████████████████
#if UNITY_5_3_OR_NEWER || UNITY_2017_1_OR_NEWER
public static class DOTweenCYInstruction
{
public class WaitForCompletion : CustomYieldInstruction
{
public override bool keepWaiting { get {
return t.active && !t.IsComplete();
}}
readonly Tween t;
public WaitForCompletion(Tween tween)
{
t = tween;
}
}
public class WaitForRewind : CustomYieldInstruction
{
public override bool keepWaiting { get {
return t.active && (!t.playedOnce || t.position * (t.CompletedLoops() + 1) > 0);
}}
readonly Tween t;
public WaitForRewind(Tween tween)
{
t = tween;
}
}
public class WaitForKill : CustomYieldInstruction
{
public override bool keepWaiting { get {
return t.active;
}}
readonly Tween t;
public WaitForKill(Tween tween)
{
t = tween;
}
}
public class WaitForElapsedLoops : CustomYieldInstruction
{
public override bool keepWaiting { get {
return t.active && t.CompletedLoops() < elapsedLoops;
}}
readonly Tween t;
readonly int elapsedLoops;
public WaitForElapsedLoops(Tween tween, int elapsedLoops)
{
t = tween;
this.elapsedLoops = elapsedLoops;
}
}
public class WaitForPosition : CustomYieldInstruction
{
public override bool keepWaiting { get {
return t.active && t.position * (t.CompletedLoops() + 1) < position;
}}
readonly Tween t;
readonly float position;
public WaitForPosition(Tween tween, float position)
{
t = tween;
this.position = position;
}
}
public class WaitForStart : CustomYieldInstruction
{
public override bool keepWaiting { get {
return t.active && !t.playedOnce;
}}
readonly Tween t;
public WaitForStart(Tween tween)
{
t = tween;
}
}
}
#endif
}
| 0 | 0.923029 | 1 | 0.923029 | game-dev | MEDIA | 0.772111 | game-dev | 0.899065 | 1 | 0.899065 |
harsh-vardhhan/Ludo | 8,492 | lib/component/ui_components/ludo_dice.dart | import 'dart:async';
import 'dart:math';
import 'package:flame/components.dart';
import 'package:flame/events.dart';
import 'package:flame/effects.dart';
import 'package:flutter/material.dart';
import 'package:flame/geometry.dart';
// user files
import 'dice_face_component.dart';
import '../../state/game_state.dart';
import '../../state/audio_manager.dart';
import '../../state/player.dart';
import '../../ludo_board.dart';
import '../controller/lower_controller.dart';
import 'token.dart';
import '../../ludo.dart';
class LudoDice extends PositionComponent with TapCallbacks {
static const double borderRadiusFactor =
0.2; // Precomputed factor for border radius
static const double innerSizeFactor =
0.9; // Precomputed factor for inner size
// final gameState = GameState();
final double faceSize; // size of the square
late final double borderRadius; // radius of the curved edges
late final double innerRectangleWidth; // width of the inner rectangle
late final double innerRectangleHeight; // height of the inner rectangle
late final RectangleComponent innerRectangle; // inner rectangle component
late final DiceFaceComponent diceFace; // The dice face showing dots
final Player player;
void playSound() async {
await AudioManager.playDiceSound();
}
@override
void onTapDown(TapDownEvent event) async {
if (!player.enableDice ||
!player.isCurrentTurn ||
player != GameState().currentPlayer) {
return; // Exit if the player cannot roll the dice
}
// Disable dice to prevent multiple taps
final world = parent?.parent?.parent?.parent?.parent;
GameState().hidePointer();
player.enableDice = false;
// Roll the dice and update the dice face
GameState().diceNumber = Random().nextInt(6) + 1;
diceFace.updateDiceValue(GameState().diceNumber);
playSound();
// Apply dice rotation effect
_applyDiceRollEffect();
await Future.delayed(const Duration(milliseconds: 300));
if (world is! World) return; // Ensure the world is available
// Handle dice roll based on the number
final handleRoll =
GameState().diceNumber == 6 ? _handleSixRoll : _handleNonSixRoll;
handleRoll(
world, GameState().ludoBoard as LudoBoard, GameState().diceNumber);
}
// Apply a 360-degree rotation effect to the dice
FutureOr<void> _applyDiceRollEffect() {
add(
RotateEffect.by(
tau, // Full 360-degree rotation (2π radians)
EffectController(
duration: 0.3, // Reduced duration
curve: Curves.linear, // Simpler curve
),
),
);
return Future.value();
}
// Handle logic when the player rolls a 6
void _handleSixRoll(World world, LudoBoard ludoBoard, int diceNumber) {
player.grantAnotherTurn();
if (player.hasRolledThreeConsecutiveSixes()) {
GameState().switchToNextPlayer();
return;
}
// Filter tokens once and reuse the lists
final tokensInBase = player.tokens
.where((token) => token.state == TokenState.inBase)
.toList();
final tokensOnBoard = player.tokens
.where((token) => token.state == TokenState.onBoard)
.toList();
final movableTokens =
tokensOnBoard.where((token) => token.spaceToMove()).toList();
final allMovableTokens = [...movableTokens, ...tokensInBase];
// if only one token can move, move it
if (allMovableTokens.length == 1) {
if (allMovableTokens.first.state == TokenState.inBase) {
moveOutOfBase(
world: world,
token: allMovableTokens.first,
tokenPath: GameState().getTokenPath(player.playerId),
);
} else if (allMovableTokens.first.state == TokenState.onBoard) {
_moveForwardSingleToken(
world, ludoBoard, diceNumber, allMovableTokens.first);
}
return;
} else if (allMovableTokens.length > 1) {
_enableManualTokenSelection(world, tokensInBase, tokensOnBoard);
} else if (allMovableTokens.isEmpty) {
GameState().switchToNextPlayer();
return;
}
}
// Handle logic for non-six dice rolls
void _handleNonSixRoll(World world, LudoBoard ludoBoard, int diceNumber) {
final tokensOnBoard = player.tokens
.where((token) => token.state == TokenState.onBoard)
.toList();
// if no tokens on board, switch to next player
if (tokensOnBoard.isEmpty) {
GameState().switchToNextPlayer();
return;
}
final movableTokens =
tokensOnBoard.where((token) => token.spaceToMove()).toList();
final tokensInBase = player.tokens
.where((token) => token.state == TokenState.inBase)
.toList();
// if only one token can move, move it
if (movableTokens.length == 1) {
_moveForwardSingleToken(
world, ludoBoard, diceNumber, movableTokens.first);
return;
} else if (movableTokens.length > 1) {
_enableManualTokenSelection(world, tokensInBase, tokensOnBoard);
} else if (movableTokens.isEmpty) {
GameState().switchToNextPlayer();
return;
}
}
// Enable manual selection if multiple tokens can move
void _enableManualTokenSelection(
World world, List<Token> tokensInBase, List<Token> tokensOnBoard) {
GameState().hidePointer();
player.enableDice = false;
for (var token in player.tokens) {
token.enableToken = true;
}
if (tokensInBase.isNotEmpty && tokensOnBoard.isNotEmpty) {
GameState().enableMoveFromBoth();
addTokenTrail(tokensInBase, tokensOnBoard);
} else if (tokensInBase.isNotEmpty) {
GameState().enableMoveFromBase();
addTokenTrail(tokensInBase, tokensOnBoard);
} else if (tokensOnBoard.isNotEmpty) {
addTokenTrail(tokensInBase, tokensOnBoard);
GameState().enableMoveOnBoard();
}
}
// Move the token forward on the board
void _moveForwardSingleToken(
World world, LudoBoard ludoBoard, int diceNumber, Token token) {
moveForward(
world: world,
token: token,
tokenPath: GameState().getTokenPath(player.playerId),
diceNumber: diceNumber,
);
}
LudoDice({required this.faceSize, required this.player}) {
// Pre-calculate values to avoid repeated calculations
final double borderRadiusValue = faceSize * borderRadiusFactor;
final double innerWidth = faceSize * innerSizeFactor;
final double innerHeight = faceSize * innerSizeFactor;
final Vector2 innerSize = Vector2(innerWidth, innerHeight);
final Vector2 innerPosition = Vector2(
(faceSize - innerWidth) / 2, // Center horizontally
(faceSize - innerHeight) / 2 // Center vertically
);
// Assign pre-calculated values
borderRadius = borderRadiusValue;
innerRectangleWidth = innerWidth;
innerRectangleHeight = innerHeight;
// Initialize the size of the component
size = Vector2.all(faceSize);
// Set the anchor to center for center rotation
anchor = Anchor.center;
// Initialize the dice face component
diceFace = DiceFaceComponent(faceSize: innerWidth, diceValue: 6);
// Initialize the inner rectangle component
final innerRectangle = RoundedRectangle(
size: innerSize,
position: innerPosition,
paint: Paint()..color = Colors.white,
borderRadius: 15.0, // Customize corner radius
children: [diceFace],
);
// Add the inner rectangle to this component
add(innerRectangle);
}
@override
void render(Canvas canvas) {
super.render(canvas);
// Create paint for the square
final paint = Paint()
..color = Color(0xFFD6D6D6)
..style = PaintingStyle.fill;
// Define the rounded rectangle
final rect = Rect.fromLTWH(0, 0, size.x, size.y);
final radius = Radius.circular(borderRadius);
final rrect = RRect.fromRectAndRadius(rect, radius);
// Draw the rounded rectangle
canvas.drawRRect(rrect, paint);
}
}
class RoundedRectangle extends PositionComponent {
final Paint paint;
final double borderRadius;
RoundedRectangle({
required Vector2 size,
required this.paint,
this.borderRadius = 10.0, // Default corner radius
super.position,
super.children,
}) : super(size: size);
@override
void render(Canvas canvas) {
final rect = Rect.fromLTWH(0, 0, size.x, size.y);
final rrect = RRect.fromRectAndRadius(rect, Radius.circular(borderRadius));
canvas.drawRRect(rrect, paint);
super.render(canvas);
}
}
| 0 | 0.967991 | 1 | 0.967991 | game-dev | MEDIA | 0.760202 | game-dev | 0.97918 | 1 | 0.97918 |
CreativeDesigner3D/BlenderSource | 44,763 | extern/mantaflow/preprocessed/grid4d.h |
// DO NOT EDIT !
// This file is generated using the MantaFlow preprocessor (prep generate).
/******************************************************************************
*
* MantaFlow fluid solver framework
* Copyright 2011 Tobias Pfaff, Nils Thuerey
*
* This program is free software, distributed under the terms of the
* Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Grid representation
*
******************************************************************************/
#ifndef _GRID4D_H
#define _GRID4D_H
#include "manta.h"
#include "vectorbase.h"
#include "vector4d.h"
#include "kernel.h"
namespace Manta {
//! Base class for all grids
class Grid4dBase : public PbClass {
public:
enum Grid4dType { TypeNone = 0, TypeReal = 1, TypeInt = 2, TypeVec3 = 4, TypeVec4 = 8 };
Grid4dBase(FluidSolver *parent);
static int _W_0(PyObject *_self, PyObject *_linargs, PyObject *_kwds)
{
PbClass *obj = Pb::objFromPy(_self);
if (obj)
delete obj;
try {
PbArgs _args(_linargs, _kwds);
bool noTiming = _args.getOpt<bool>("notiming", -1, 0);
pbPreparePlugin(0, "Grid4dBase::Grid4dBase", !noTiming);
{
ArgLocker _lock;
FluidSolver *parent = _args.getPtr<FluidSolver>("parent", 0, &_lock);
obj = new Grid4dBase(parent);
obj->registerObject(_self, &_args);
_args.check();
}
pbFinalizePlugin(obj->getParent(), "Grid4dBase::Grid4dBase", !noTiming);
return 0;
}
catch (std::exception &e) {
pbSetError("Grid4dBase::Grid4dBase", e.what());
return -1;
}
}
//! Get the grids X dimension
inline int getSizeX() const
{
return mSize.x;
}
static PyObject *_W_1(PyObject *_self, PyObject *_linargs, PyObject *_kwds)
{
try {
PbArgs _args(_linargs, _kwds);
Grid4dBase *pbo = dynamic_cast<Grid4dBase *>(Pb::objFromPy(_self));
bool noTiming = _args.getOpt<bool>("notiming", -1, 0);
pbPreparePlugin(pbo->getParent(), "Grid4dBase::getSizeX", !noTiming);
PyObject *_retval = nullptr;
{
ArgLocker _lock;
pbo->_args.copy(_args);
_retval = toPy(pbo->getSizeX());
pbo->_args.check();
}
pbFinalizePlugin(pbo->getParent(), "Grid4dBase::getSizeX", !noTiming);
return _retval;
}
catch (std::exception &e) {
pbSetError("Grid4dBase::getSizeX", e.what());
return 0;
}
}
//! Get the grids Y dimension
inline int getSizeY() const
{
return mSize.y;
}
static PyObject *_W_2(PyObject *_self, PyObject *_linargs, PyObject *_kwds)
{
try {
PbArgs _args(_linargs, _kwds);
Grid4dBase *pbo = dynamic_cast<Grid4dBase *>(Pb::objFromPy(_self));
bool noTiming = _args.getOpt<bool>("notiming", -1, 0);
pbPreparePlugin(pbo->getParent(), "Grid4dBase::getSizeY", !noTiming);
PyObject *_retval = nullptr;
{
ArgLocker _lock;
pbo->_args.copy(_args);
_retval = toPy(pbo->getSizeY());
pbo->_args.check();
}
pbFinalizePlugin(pbo->getParent(), "Grid4dBase::getSizeY", !noTiming);
return _retval;
}
catch (std::exception &e) {
pbSetError("Grid4dBase::getSizeY", e.what());
return 0;
}
}
//! Get the grids Z dimension
inline int getSizeZ() const
{
return mSize.z;
}
static PyObject *_W_3(PyObject *_self, PyObject *_linargs, PyObject *_kwds)
{
try {
PbArgs _args(_linargs, _kwds);
Grid4dBase *pbo = dynamic_cast<Grid4dBase *>(Pb::objFromPy(_self));
bool noTiming = _args.getOpt<bool>("notiming", -1, 0);
pbPreparePlugin(pbo->getParent(), "Grid4dBase::getSizeZ", !noTiming);
PyObject *_retval = nullptr;
{
ArgLocker _lock;
pbo->_args.copy(_args);
_retval = toPy(pbo->getSizeZ());
pbo->_args.check();
}
pbFinalizePlugin(pbo->getParent(), "Grid4dBase::getSizeZ", !noTiming);
return _retval;
}
catch (std::exception &e) {
pbSetError("Grid4dBase::getSizeZ", e.what());
return 0;
}
}
//! Get the grids T dimension
inline int getSizeT() const
{
return mSize.t;
}
static PyObject *_W_4(PyObject *_self, PyObject *_linargs, PyObject *_kwds)
{
try {
PbArgs _args(_linargs, _kwds);
Grid4dBase *pbo = dynamic_cast<Grid4dBase *>(Pb::objFromPy(_self));
bool noTiming = _args.getOpt<bool>("notiming", -1, 0);
pbPreparePlugin(pbo->getParent(), "Grid4dBase::getSizeT", !noTiming);
PyObject *_retval = nullptr;
{
ArgLocker _lock;
pbo->_args.copy(_args);
_retval = toPy(pbo->getSizeT());
pbo->_args.check();
}
pbFinalizePlugin(pbo->getParent(), "Grid4dBase::getSizeT", !noTiming);
return _retval;
}
catch (std::exception &e) {
pbSetError("Grid4dBase::getSizeT", e.what());
return 0;
}
}
//! Get the grids dimensions
inline Vec4i getSize() const
{
return mSize;
}
static PyObject *_W_5(PyObject *_self, PyObject *_linargs, PyObject *_kwds)
{
try {
PbArgs _args(_linargs, _kwds);
Grid4dBase *pbo = dynamic_cast<Grid4dBase *>(Pb::objFromPy(_self));
bool noTiming = _args.getOpt<bool>("notiming", -1, 0);
pbPreparePlugin(pbo->getParent(), "Grid4dBase::getSize", !noTiming);
PyObject *_retval = nullptr;
{
ArgLocker _lock;
pbo->_args.copy(_args);
_retval = toPy(pbo->getSize());
pbo->_args.check();
}
pbFinalizePlugin(pbo->getParent(), "Grid4dBase::getSize", !noTiming);
return _retval;
}
catch (std::exception &e) {
pbSetError("Grid4dBase::getSize", e.what());
return 0;
}
}
//! Get Stride in X dimension
inline IndexInt getStrideX() const
{
return 1;
}
//! Get Stride in Y dimension
inline IndexInt getStrideY() const
{
return mSize.x;
}
//! Get Stride in Z dimension
inline IndexInt getStrideZ() const
{
return mStrideZ;
}
//! Get Stride in T dimension
inline IndexInt getStrideT() const
{
return mStrideT;
}
inline Real getDx()
{
return mDx;
}
//! Check if indices are within bounds, otherwise error (should only be called when debugging)
inline void checkIndex(int i, int j, int k, int t) const;
//! Check if indices are within bounds, otherwise error (should only be called when debugging)
inline void checkIndex(IndexInt idx) const;
//! Check if index is within given boundaries
inline bool isInBounds(const Vec4i &p, int bnd) const;
//! Check if index is within given boundaries
inline bool isInBounds(const Vec4i &p) const;
//! Check if index is within given boundaries
inline bool isInBounds(const Vec4 &p, int bnd = 0) const
{
return isInBounds(toVec4i(p), bnd);
}
//! Check if linear index is in the range of the array
inline bool isInBounds(IndexInt idx) const;
//! Get the type of grid
inline Grid4dType getType() const
{
return mType;
}
//! Check dimensionality
inline bool is3D() const
{
return true;
}
static PyObject *_W_6(PyObject *_self, PyObject *_linargs, PyObject *_kwds)
{
try {
PbArgs _args(_linargs, _kwds);
Grid4dBase *pbo = dynamic_cast<Grid4dBase *>(Pb::objFromPy(_self));
bool noTiming = _args.getOpt<bool>("notiming", -1, 0);
pbPreparePlugin(pbo->getParent(), "Grid4dBase::is3D", !noTiming);
PyObject *_retval = nullptr;
{
ArgLocker _lock;
pbo->_args.copy(_args);
_retval = toPy(pbo->is3D());
pbo->_args.check();
}
pbFinalizePlugin(pbo->getParent(), "Grid4dBase::is3D", !noTiming);
return _retval;
}
catch (std::exception &e) {
pbSetError("Grid4dBase::is3D", e.what());
return 0;
}
}
inline bool is4D() const
{
return true;
}
static PyObject *_W_7(PyObject *_self, PyObject *_linargs, PyObject *_kwds)
{
try {
PbArgs _args(_linargs, _kwds);
Grid4dBase *pbo = dynamic_cast<Grid4dBase *>(Pb::objFromPy(_self));
bool noTiming = _args.getOpt<bool>("notiming", -1, 0);
pbPreparePlugin(pbo->getParent(), "Grid4dBase::is4D", !noTiming);
PyObject *_retval = nullptr;
{
ArgLocker _lock;
pbo->_args.copy(_args);
_retval = toPy(pbo->is4D());
pbo->_args.check();
}
pbFinalizePlugin(pbo->getParent(), "Grid4dBase::is4D", !noTiming);
return _retval;
}
catch (std::exception &e) {
pbSetError("Grid4dBase::is4D", e.what());
return 0;
}
}
//! 3d compatibility
inline bool isInBounds(int i, int j, int k, int t, int bnd) const
{
return isInBounds(Vec4i(i, j, k, t), bnd);
}
//! Get index into the data
inline IndexInt index(int i, int j, int k, int t) const
{
DEBUG_ONLY(checkIndex(i, j, k, t));
return (IndexInt)i + (IndexInt)mSize.x * j + (IndexInt)mStrideZ * k + (IndexInt)mStrideT * t;
}
//! Get index into the data
inline IndexInt index(const Vec4i &pos) const
{
DEBUG_ONLY(checkIndex(pos.x, pos.y, pos.z, pos.t));
return (IndexInt)pos.x + (IndexInt)mSize.x * pos.y + (IndexInt)mStrideZ * pos.z +
(IndexInt)mStrideT * pos.t;
}
protected:
Grid4dType mType;
Vec4i mSize;
Real mDx;
// precomputed Z,T shift: to ensure 2D compatibility, always use this instead of sx*sy !
IndexInt mStrideZ;
IndexInt mStrideT;
public:
PbArgs _args;
}
#define _C_Grid4dBase
;
//! Grid class
template<class T> class Grid4d : public Grid4dBase {
public:
//! init new grid, values are set to zero
Grid4d(FluidSolver *parent, bool show = true);
static int _W_8(PyObject *_self, PyObject *_linargs, PyObject *_kwds)
{
PbClass *obj = Pb::objFromPy(_self);
if (obj)
delete obj;
try {
PbArgs _args(_linargs, _kwds);
bool noTiming = _args.getOpt<bool>("notiming", -1, 0);
pbPreparePlugin(0, "Grid4d::Grid4d", !noTiming);
{
ArgLocker _lock;
FluidSolver *parent = _args.getPtr<FluidSolver>("parent", 0, &_lock);
bool show = _args.getOpt<bool>("show", 1, true, &_lock);
obj = new Grid4d(parent, show);
obj->registerObject(_self, &_args);
_args.check();
}
pbFinalizePlugin(obj->getParent(), "Grid4d::Grid4d", !noTiming);
return 0;
}
catch (std::exception &e) {
pbSetError("Grid4d::Grid4d", e.what());
return -1;
}
}
//! create new & copy content from another grid
Grid4d(const Grid4d<T> &a);
//! return memory to solver
virtual ~Grid4d();
typedef T BASETYPE;
typedef Grid4dBase BASETYPE_GRID;
int save(std::string name);
static PyObject *_W_9(PyObject *_self, PyObject *_linargs, PyObject *_kwds)
{
try {
PbArgs _args(_linargs, _kwds);
Grid4d *pbo = dynamic_cast<Grid4d *>(Pb::objFromPy(_self));
bool noTiming = _args.getOpt<bool>("notiming", -1, 0);
pbPreparePlugin(pbo->getParent(), "Grid4d::save", !noTiming);
PyObject *_retval = nullptr;
{
ArgLocker _lock;
std::string name = _args.get<std::string>("name", 0, &_lock);
pbo->_args.copy(_args);
_retval = toPy(pbo->save(name));
pbo->_args.check();
}
pbFinalizePlugin(pbo->getParent(), "Grid4d::save", !noTiming);
return _retval;
}
catch (std::exception &e) {
pbSetError("Grid4d::save", e.what());
return 0;
}
}
int load(std::string name);
static PyObject *_W_10(PyObject *_self, PyObject *_linargs, PyObject *_kwds)
{
try {
PbArgs _args(_linargs, _kwds);
Grid4d *pbo = dynamic_cast<Grid4d *>(Pb::objFromPy(_self));
bool noTiming = _args.getOpt<bool>("notiming", -1, 0);
pbPreparePlugin(pbo->getParent(), "Grid4d::load", !noTiming);
PyObject *_retval = nullptr;
{
ArgLocker _lock;
std::string name = _args.get<std::string>("name", 0, &_lock);
pbo->_args.copy(_args);
_retval = toPy(pbo->load(name));
pbo->_args.check();
}
pbFinalizePlugin(pbo->getParent(), "Grid4d::load", !noTiming);
return _retval;
}
catch (std::exception &e) {
pbSetError("Grid4d::load", e.what());
return 0;
}
}
//! set all cells to zero
void clear();
static PyObject *_W_11(PyObject *_self, PyObject *_linargs, PyObject *_kwds)
{
try {
PbArgs _args(_linargs, _kwds);
Grid4d *pbo = dynamic_cast<Grid4d *>(Pb::objFromPy(_self));
bool noTiming = _args.getOpt<bool>("notiming", -1, 0);
pbPreparePlugin(pbo->getParent(), "Grid4d::clear", !noTiming);
PyObject *_retval = nullptr;
{
ArgLocker _lock;
pbo->_args.copy(_args);
_retval = getPyNone();
pbo->clear();
pbo->_args.check();
}
pbFinalizePlugin(pbo->getParent(), "Grid4d::clear", !noTiming);
return _retval;
}
catch (std::exception &e) {
pbSetError("Grid4d::clear", e.what());
return 0;
}
}
//! all kinds of access functions, use grid(), grid[] or grid.get()
//! access data
inline T get(int i, int j, int k, int t) const
{
return mData[index(i, j, k, t)];
}
//! access data
inline T &get(int i, int j, int k, int t)
{
return mData[index(i, j, k, t)];
}
//! access data
inline T get(IndexInt idx) const
{
DEBUG_ONLY(checkIndex(idx));
return mData[idx];
}
//! access data
inline T get(const Vec4i &pos) const
{
return mData[index(pos)];
}
//! access data
inline T &operator()(int i, int j, int k, int t)
{
return mData[index(i, j, k, t)];
}
//! access data
inline T operator()(int i, int j, int k, int t) const
{
return mData[index(i, j, k, t)];
}
//! access data
inline T &operator()(IndexInt idx)
{
DEBUG_ONLY(checkIndex(idx));
return mData[idx];
}
//! access data
inline T operator()(IndexInt idx) const
{
DEBUG_ONLY(checkIndex(idx));
return mData[idx];
}
//! access data
inline T &operator()(const Vec4i &pos)
{
return mData[index(pos)];
}
//! access data
inline T operator()(const Vec4i &pos) const
{
return mData[index(pos)];
}
//! access data
inline T &operator[](IndexInt idx)
{
DEBUG_ONLY(checkIndex(idx));
return mData[idx];
}
//! access data
inline const T operator[](IndexInt idx) const
{
DEBUG_ONLY(checkIndex(idx));
return mData[idx];
}
// interpolated access
inline T getInterpolated(const Vec4 &pos) const
{
return interpol4d<T>(mData, mSize, mStrideZ, mStrideT, pos);
}
// assignment / copy
//! warning - do not use "=" for grids in python, this copies the reference! not the grid
//! content...
// Grid4d<T>& operator=(const Grid4d<T>& a);
//! copy content from other grid (use this one instead of operator= !)
Grid4d<T> ©From(const Grid4d<T> &a, bool copyType = true);
static PyObject *_W_12(PyObject *_self, PyObject *_linargs, PyObject *_kwds)
{
try {
PbArgs _args(_linargs, _kwds);
Grid4d *pbo = dynamic_cast<Grid4d *>(Pb::objFromPy(_self));
bool noTiming = _args.getOpt<bool>("notiming", -1, 0);
pbPreparePlugin(pbo->getParent(), "Grid4d::copyFrom", !noTiming);
PyObject *_retval = nullptr;
{
ArgLocker _lock;
const Grid4d<T> &a = *_args.getPtr<Grid4d<T>>("a", 0, &_lock);
bool copyType = _args.getOpt<bool>("copyType", 1, true, &_lock);
pbo->_args.copy(_args);
_retval = toPy(pbo->copyFrom(a, copyType));
pbo->_args.check();
}
pbFinalizePlugin(pbo->getParent(), "Grid4d::copyFrom", !noTiming);
return _retval;
}
catch (std::exception &e) {
pbSetError("Grid4d::copyFrom", e.what());
return 0;
}
}
// old: { *this = a; }
// helper functions to work with grids in scene files
//! add/subtract other grid
void add(const Grid4d<T> &a);
static PyObject *_W_13(PyObject *_self, PyObject *_linargs, PyObject *_kwds)
{
try {
PbArgs _args(_linargs, _kwds);
Grid4d *pbo = dynamic_cast<Grid4d *>(Pb::objFromPy(_self));
bool noTiming = _args.getOpt<bool>("notiming", -1, 0);
pbPreparePlugin(pbo->getParent(), "Grid4d::add", !noTiming);
PyObject *_retval = nullptr;
{
ArgLocker _lock;
const Grid4d<T> &a = *_args.getPtr<Grid4d<T>>("a", 0, &_lock);
pbo->_args.copy(_args);
_retval = getPyNone();
pbo->add(a);
pbo->_args.check();
}
pbFinalizePlugin(pbo->getParent(), "Grid4d::add", !noTiming);
return _retval;
}
catch (std::exception &e) {
pbSetError("Grid4d::add", e.what());
return 0;
}
}
void sub(const Grid4d<T> &a);
static PyObject *_W_14(PyObject *_self, PyObject *_linargs, PyObject *_kwds)
{
try {
PbArgs _args(_linargs, _kwds);
Grid4d *pbo = dynamic_cast<Grid4d *>(Pb::objFromPy(_self));
bool noTiming = _args.getOpt<bool>("notiming", -1, 0);
pbPreparePlugin(pbo->getParent(), "Grid4d::sub", !noTiming);
PyObject *_retval = nullptr;
{
ArgLocker _lock;
const Grid4d<T> &a = *_args.getPtr<Grid4d<T>>("a", 0, &_lock);
pbo->_args.copy(_args);
_retval = getPyNone();
pbo->sub(a);
pbo->_args.check();
}
pbFinalizePlugin(pbo->getParent(), "Grid4d::sub", !noTiming);
return _retval;
}
catch (std::exception &e) {
pbSetError("Grid4d::sub", e.what());
return 0;
}
}
//! set all cells to constant value
void setConst(T s);
static PyObject *_W_15(PyObject *_self, PyObject *_linargs, PyObject *_kwds)
{
try {
PbArgs _args(_linargs, _kwds);
Grid4d *pbo = dynamic_cast<Grid4d *>(Pb::objFromPy(_self));
bool noTiming = _args.getOpt<bool>("notiming", -1, 0);
pbPreparePlugin(pbo->getParent(), "Grid4d::setConst", !noTiming);
PyObject *_retval = nullptr;
{
ArgLocker _lock;
T s = _args.get<T>("s", 0, &_lock);
pbo->_args.copy(_args);
_retval = getPyNone();
pbo->setConst(s);
pbo->_args.check();
}
pbFinalizePlugin(pbo->getParent(), "Grid4d::setConst", !noTiming);
return _retval;
}
catch (std::exception &e) {
pbSetError("Grid4d::setConst", e.what());
return 0;
}
}
//! add constant to all grid cells
void addConst(T s);
static PyObject *_W_16(PyObject *_self, PyObject *_linargs, PyObject *_kwds)
{
try {
PbArgs _args(_linargs, _kwds);
Grid4d *pbo = dynamic_cast<Grid4d *>(Pb::objFromPy(_self));
bool noTiming = _args.getOpt<bool>("notiming", -1, 0);
pbPreparePlugin(pbo->getParent(), "Grid4d::addConst", !noTiming);
PyObject *_retval = nullptr;
{
ArgLocker _lock;
T s = _args.get<T>("s", 0, &_lock);
pbo->_args.copy(_args);
_retval = getPyNone();
pbo->addConst(s);
pbo->_args.check();
}
pbFinalizePlugin(pbo->getParent(), "Grid4d::addConst", !noTiming);
return _retval;
}
catch (std::exception &e) {
pbSetError("Grid4d::addConst", e.what());
return 0;
}
}
//! add scaled other grid to current one (note, only "Real" factor, "T" type not supported here!)
void addScaled(const Grid4d<T> &a, const T &factor);
static PyObject *_W_17(PyObject *_self, PyObject *_linargs, PyObject *_kwds)
{
try {
PbArgs _args(_linargs, _kwds);
Grid4d *pbo = dynamic_cast<Grid4d *>(Pb::objFromPy(_self));
bool noTiming = _args.getOpt<bool>("notiming", -1, 0);
pbPreparePlugin(pbo->getParent(), "Grid4d::addScaled", !noTiming);
PyObject *_retval = nullptr;
{
ArgLocker _lock;
const Grid4d<T> &a = *_args.getPtr<Grid4d<T>>("a", 0, &_lock);
const T &factor = *_args.getPtr<T>("factor", 1, &_lock);
pbo->_args.copy(_args);
_retval = getPyNone();
pbo->addScaled(a, factor);
pbo->_args.check();
}
pbFinalizePlugin(pbo->getParent(), "Grid4d::addScaled", !noTiming);
return _retval;
}
catch (std::exception &e) {
pbSetError("Grid4d::addScaled", e.what());
return 0;
}
}
//! multiply contents of grid
void mult(const Grid4d<T> &a);
static PyObject *_W_18(PyObject *_self, PyObject *_linargs, PyObject *_kwds)
{
try {
PbArgs _args(_linargs, _kwds);
Grid4d *pbo = dynamic_cast<Grid4d *>(Pb::objFromPy(_self));
bool noTiming = _args.getOpt<bool>("notiming", -1, 0);
pbPreparePlugin(pbo->getParent(), "Grid4d::mult", !noTiming);
PyObject *_retval = nullptr;
{
ArgLocker _lock;
const Grid4d<T> &a = *_args.getPtr<Grid4d<T>>("a", 0, &_lock);
pbo->_args.copy(_args);
_retval = getPyNone();
pbo->mult(a);
pbo->_args.check();
}
pbFinalizePlugin(pbo->getParent(), "Grid4d::mult", !noTiming);
return _retval;
}
catch (std::exception &e) {
pbSetError("Grid4d::mult", e.what());
return 0;
}
}
//! multiply each cell by a constant scalar value
void multConst(T s);
static PyObject *_W_19(PyObject *_self, PyObject *_linargs, PyObject *_kwds)
{
try {
PbArgs _args(_linargs, _kwds);
Grid4d *pbo = dynamic_cast<Grid4d *>(Pb::objFromPy(_self));
bool noTiming = _args.getOpt<bool>("notiming", -1, 0);
pbPreparePlugin(pbo->getParent(), "Grid4d::multConst", !noTiming);
PyObject *_retval = nullptr;
{
ArgLocker _lock;
T s = _args.get<T>("s", 0, &_lock);
pbo->_args.copy(_args);
_retval = getPyNone();
pbo->multConst(s);
pbo->_args.check();
}
pbFinalizePlugin(pbo->getParent(), "Grid4d::multConst", !noTiming);
return _retval;
}
catch (std::exception &e) {
pbSetError("Grid4d::multConst", e.what());
return 0;
}
}
//! clamp content to range (for vec3, clamps each component separately)
void clamp(Real min, Real max);
static PyObject *_W_20(PyObject *_self, PyObject *_linargs, PyObject *_kwds)
{
try {
PbArgs _args(_linargs, _kwds);
Grid4d *pbo = dynamic_cast<Grid4d *>(Pb::objFromPy(_self));
bool noTiming = _args.getOpt<bool>("notiming", -1, 0);
pbPreparePlugin(pbo->getParent(), "Grid4d::clamp", !noTiming);
PyObject *_retval = nullptr;
{
ArgLocker _lock;
Real min = _args.get<Real>("min", 0, &_lock);
Real max = _args.get<Real>("max", 1, &_lock);
pbo->_args.copy(_args);
_retval = getPyNone();
pbo->clamp(min, max);
pbo->_args.check();
}
pbFinalizePlugin(pbo->getParent(), "Grid4d::clamp", !noTiming);
return _retval;
}
catch (std::exception &e) {
pbSetError("Grid4d::clamp", e.what());
return 0;
}
}
// common compound operators
//! get absolute max value in grid
Real getMaxAbs();
static PyObject *_W_21(PyObject *_self, PyObject *_linargs, PyObject *_kwds)
{
try {
PbArgs _args(_linargs, _kwds);
Grid4d *pbo = dynamic_cast<Grid4d *>(Pb::objFromPy(_self));
bool noTiming = _args.getOpt<bool>("notiming", -1, 0);
pbPreparePlugin(pbo->getParent(), "Grid4d::getMaxAbs", !noTiming);
PyObject *_retval = nullptr;
{
ArgLocker _lock;
pbo->_args.copy(_args);
_retval = toPy(pbo->getMaxAbs());
pbo->_args.check();
}
pbFinalizePlugin(pbo->getParent(), "Grid4d::getMaxAbs", !noTiming);
return _retval;
}
catch (std::exception &e) {
pbSetError("Grid4d::getMaxAbs", e.what());
return 0;
}
}
//! get max value in grid
Real getMax();
static PyObject *_W_22(PyObject *_self, PyObject *_linargs, PyObject *_kwds)
{
try {
PbArgs _args(_linargs, _kwds);
Grid4d *pbo = dynamic_cast<Grid4d *>(Pb::objFromPy(_self));
bool noTiming = _args.getOpt<bool>("notiming", -1, 0);
pbPreparePlugin(pbo->getParent(), "Grid4d::getMax", !noTiming);
PyObject *_retval = nullptr;
{
ArgLocker _lock;
pbo->_args.copy(_args);
_retval = toPy(pbo->getMax());
pbo->_args.check();
}
pbFinalizePlugin(pbo->getParent(), "Grid4d::getMax", !noTiming);
return _retval;
}
catch (std::exception &e) {
pbSetError("Grid4d::getMax", e.what());
return 0;
}
}
//! get min value in grid
Real getMin();
static PyObject *_W_23(PyObject *_self, PyObject *_linargs, PyObject *_kwds)
{
try {
PbArgs _args(_linargs, _kwds);
Grid4d *pbo = dynamic_cast<Grid4d *>(Pb::objFromPy(_self));
bool noTiming = _args.getOpt<bool>("notiming", -1, 0);
pbPreparePlugin(pbo->getParent(), "Grid4d::getMin", !noTiming);
PyObject *_retval = nullptr;
{
ArgLocker _lock;
pbo->_args.copy(_args);
_retval = toPy(pbo->getMin());
pbo->_args.check();
}
pbFinalizePlugin(pbo->getParent(), "Grid4d::getMin", !noTiming);
return _retval;
}
catch (std::exception &e) {
pbSetError("Grid4d::getMin", e.what());
return 0;
}
}
//! set all boundary cells to constant value (Dirichlet)
void setBound(T value, int boundaryWidth = 1);
static PyObject *_W_24(PyObject *_self, PyObject *_linargs, PyObject *_kwds)
{
try {
PbArgs _args(_linargs, _kwds);
Grid4d *pbo = dynamic_cast<Grid4d *>(Pb::objFromPy(_self));
bool noTiming = _args.getOpt<bool>("notiming", -1, 0);
pbPreparePlugin(pbo->getParent(), "Grid4d::setBound", !noTiming);
PyObject *_retval = nullptr;
{
ArgLocker _lock;
T value = _args.get<T>("value", 0, &_lock);
int boundaryWidth = _args.getOpt<int>("boundaryWidth", 1, 1, &_lock);
pbo->_args.copy(_args);
_retval = getPyNone();
pbo->setBound(value, boundaryWidth);
pbo->_args.check();
}
pbFinalizePlugin(pbo->getParent(), "Grid4d::setBound", !noTiming);
return _retval;
}
catch (std::exception &e) {
pbSetError("Grid4d::setBound", e.what());
return 0;
}
}
//! set all boundary cells to last inner value (Neumann)
void setBoundNeumann(int boundaryWidth = 1);
static PyObject *_W_25(PyObject *_self, PyObject *_linargs, PyObject *_kwds)
{
try {
PbArgs _args(_linargs, _kwds);
Grid4d *pbo = dynamic_cast<Grid4d *>(Pb::objFromPy(_self));
bool noTiming = _args.getOpt<bool>("notiming", -1, 0);
pbPreparePlugin(pbo->getParent(), "Grid4d::setBoundNeumann", !noTiming);
PyObject *_retval = nullptr;
{
ArgLocker _lock;
int boundaryWidth = _args.getOpt<int>("boundaryWidth", 0, 1, &_lock);
pbo->_args.copy(_args);
_retval = getPyNone();
pbo->setBoundNeumann(boundaryWidth);
pbo->_args.check();
}
pbFinalizePlugin(pbo->getParent(), "Grid4d::setBoundNeumann", !noTiming);
return _retval;
}
catch (std::exception &e) {
pbSetError("Grid4d::setBoundNeumann", e.what());
return 0;
}
}
//! debugging helper, print grid from Python
void printGrid(int zSlice = -1, int tSlice = -1, bool printIndex = false, int bnd = 0);
static PyObject *_W_26(PyObject *_self, PyObject *_linargs, PyObject *_kwds)
{
try {
PbArgs _args(_linargs, _kwds);
Grid4d *pbo = dynamic_cast<Grid4d *>(Pb::objFromPy(_self));
bool noTiming = _args.getOpt<bool>("notiming", -1, 0);
pbPreparePlugin(pbo->getParent(), "Grid4d::printGrid", !noTiming);
PyObject *_retval = nullptr;
{
ArgLocker _lock;
int zSlice = _args.getOpt<int>("zSlice", 0, -1, &_lock);
int tSlice = _args.getOpt<int>("tSlice", 1, -1, &_lock);
bool printIndex = _args.getOpt<bool>("printIndex", 2, false, &_lock);
int bnd = _args.getOpt<int>("bnd", 3, 0, &_lock);
pbo->_args.copy(_args);
_retval = getPyNone();
pbo->printGrid(zSlice, tSlice, printIndex, bnd);
pbo->_args.check();
}
pbFinalizePlugin(pbo->getParent(), "Grid4d::printGrid", !noTiming);
return _retval;
}
catch (std::exception &e) {
pbSetError("Grid4d::printGrid", e.what());
return 0;
}
}
// c++ only operators
template<class S> Grid4d<T> &operator+=(const Grid4d<S> &a);
template<class S> Grid4d<T> &operator+=(const S &a);
template<class S> Grid4d<T> &operator-=(const Grid4d<S> &a);
template<class S> Grid4d<T> &operator-=(const S &a);
template<class S> Grid4d<T> &operator*=(const Grid4d<S> &a);
template<class S> Grid4d<T> &operator*=(const S &a);
template<class S> Grid4d<T> &operator/=(const Grid4d<S> &a);
template<class S> Grid4d<T> &operator/=(const S &a);
Grid4d<T> &safeDivide(const Grid4d<T> &a);
//! Swap data with another grid (no actual data is moved)
void swap(Grid4d<T> &other);
protected:
T *mData;
public:
PbArgs _args;
}
#define _C_Grid4d
;
// Python doesn't know about templates: explicit aliases needed
//! helper to compute grid conversion factor between local coordinates of two grids
inline Vec4 calcGridSizeFactor4d(Vec4i s1, Vec4i s2)
{
return Vec4(Real(s1[0]) / s2[0], Real(s1[1]) / s2[1], Real(s1[2]) / s2[2], Real(s1[3]) / s2[3]);
}
inline Vec4 calcGridSizeFactor4d(Vec4 s1, Vec4 s2)
{
return Vec4(s1[0] / s2[0], s1[1] / s2[1], s1[2] / s2[2], s1[3] / s2[3]);
}
// prototypes for grid plugins
void getComponent4d(const Grid4d<Vec4> &src, Grid4d<Real> &dst, int c);
void setComponent4d(const Grid4d<Real> &src, Grid4d<Vec4> &dst, int c);
//******************************************************************************
// Implementation of inline functions
inline void Grid4dBase::checkIndex(int i, int j, int k, int t) const
{
if (i < 0 || j < 0 || i >= mSize.x || j >= mSize.y || k < 0 || k >= mSize.z || t < 0 ||
t >= mSize.t) {
std::ostringstream s;
s << "Grid4d " << mName << " dim " << mSize << " : index " << i << "," << j << "," << k << ","
<< t << " out of bound ";
errMsg(s.str());
}
}
inline void Grid4dBase::checkIndex(IndexInt idx) const
{
if (idx < 0 || idx >= mSize.x * mSize.y * mSize.z * mSize.t) {
std::ostringstream s;
s << "Grid4d " << mName << " dim " << mSize << " : index " << idx << " out of bound ";
errMsg(s.str());
}
}
bool Grid4dBase::isInBounds(const Vec4i &p) const
{
return (p.x >= 0 && p.y >= 0 && p.z >= 0 && p.t >= 0 && p.x < mSize.x && p.y < mSize.y &&
p.z < mSize.z && p.t < mSize.t);
}
bool Grid4dBase::isInBounds(const Vec4i &p, int bnd) const
{
bool ret = (p.x >= bnd && p.y >= bnd && p.x < mSize.x - bnd && p.y < mSize.y - bnd);
ret &= (p.z >= bnd && p.z < mSize.z - bnd);
ret &= (p.t >= bnd && p.t < mSize.t - bnd);
return ret;
}
//! Check if linear index is in the range of the array
bool Grid4dBase::isInBounds(IndexInt idx) const
{
if (idx < 0 || idx >= mSize.x * mSize.y * mSize.z * mSize.t) {
return false;
}
return true;
}
// note - ugly, mostly copied from normal GRID!
template<class T, class S> struct Grid4dAdd : public KernelBase {
Grid4dAdd(Grid4d<T> &me, const Grid4d<S> &other) : KernelBase(&me, 0), me(me), other(other)
{
runMessage();
run();
}
inline void op(IndexInt idx, Grid4d<T> &me, const Grid4d<S> &other) const
{
me[idx] += other[idx];
}
inline Grid4d<T> &getArg0()
{
return me;
}
typedef Grid4d<T> type0;
inline const Grid4d<S> &getArg1()
{
return other;
}
typedef Grid4d<S> type1;
void runMessage()
{
debMsg("Executing kernel Grid4dAdd ", 3);
debMsg("Kernel range"
<< " x " << maxX << " y " << maxY << " z " << minZ << " - " << maxZ << " ",
4);
};
void operator()(const tbb::blocked_range<IndexInt> &__r) const
{
for (IndexInt idx = __r.begin(); idx != (IndexInt)__r.end(); idx++)
op(idx, me, other);
}
void run()
{
tbb::parallel_for(tbb::blocked_range<IndexInt>(0, size), *this);
}
Grid4d<T> &me;
const Grid4d<S> &other;
};
template<class T, class S> struct Grid4dSub : public KernelBase {
Grid4dSub(Grid4d<T> &me, const Grid4d<S> &other) : KernelBase(&me, 0), me(me), other(other)
{
runMessage();
run();
}
inline void op(IndexInt idx, Grid4d<T> &me, const Grid4d<S> &other) const
{
me[idx] -= other[idx];
}
inline Grid4d<T> &getArg0()
{
return me;
}
typedef Grid4d<T> type0;
inline const Grid4d<S> &getArg1()
{
return other;
}
typedef Grid4d<S> type1;
void runMessage()
{
debMsg("Executing kernel Grid4dSub ", 3);
debMsg("Kernel range"
<< " x " << maxX << " y " << maxY << " z " << minZ << " - " << maxZ << " ",
4);
};
void operator()(const tbb::blocked_range<IndexInt> &__r) const
{
for (IndexInt idx = __r.begin(); idx != (IndexInt)__r.end(); idx++)
op(idx, me, other);
}
void run()
{
tbb::parallel_for(tbb::blocked_range<IndexInt>(0, size), *this);
}
Grid4d<T> &me;
const Grid4d<S> &other;
};
template<class T, class S> struct Grid4dMult : public KernelBase {
Grid4dMult(Grid4d<T> &me, const Grid4d<S> &other) : KernelBase(&me, 0), me(me), other(other)
{
runMessage();
run();
}
inline void op(IndexInt idx, Grid4d<T> &me, const Grid4d<S> &other) const
{
me[idx] *= other[idx];
}
inline Grid4d<T> &getArg0()
{
return me;
}
typedef Grid4d<T> type0;
inline const Grid4d<S> &getArg1()
{
return other;
}
typedef Grid4d<S> type1;
void runMessage()
{
debMsg("Executing kernel Grid4dMult ", 3);
debMsg("Kernel range"
<< " x " << maxX << " y " << maxY << " z " << minZ << " - " << maxZ << " ",
4);
};
void operator()(const tbb::blocked_range<IndexInt> &__r) const
{
for (IndexInt idx = __r.begin(); idx != (IndexInt)__r.end(); idx++)
op(idx, me, other);
}
void run()
{
tbb::parallel_for(tbb::blocked_range<IndexInt>(0, size), *this);
}
Grid4d<T> &me;
const Grid4d<S> &other;
};
template<class T, class S> struct Grid4dDiv : public KernelBase {
Grid4dDiv(Grid4d<T> &me, const Grid4d<S> &other) : KernelBase(&me, 0), me(me), other(other)
{
runMessage();
run();
}
inline void op(IndexInt idx, Grid4d<T> &me, const Grid4d<S> &other) const
{
me[idx] /= other[idx];
}
inline Grid4d<T> &getArg0()
{
return me;
}
typedef Grid4d<T> type0;
inline const Grid4d<S> &getArg1()
{
return other;
}
typedef Grid4d<S> type1;
void runMessage()
{
debMsg("Executing kernel Grid4dDiv ", 3);
debMsg("Kernel range"
<< " x " << maxX << " y " << maxY << " z " << minZ << " - " << maxZ << " ",
4);
};
void operator()(const tbb::blocked_range<IndexInt> &__r) const
{
for (IndexInt idx = __r.begin(); idx != (IndexInt)__r.end(); idx++)
op(idx, me, other);
}
void run()
{
tbb::parallel_for(tbb::blocked_range<IndexInt>(0, size), *this);
}
Grid4d<T> &me;
const Grid4d<S> &other;
};
template<class T, class S> struct Grid4dAddScalar : public KernelBase {
Grid4dAddScalar(Grid4d<T> &me, const S &other) : KernelBase(&me, 0), me(me), other(other)
{
runMessage();
run();
}
inline void op(IndexInt idx, Grid4d<T> &me, const S &other) const
{
me[idx] += other;
}
inline Grid4d<T> &getArg0()
{
return me;
}
typedef Grid4d<T> type0;
inline const S &getArg1()
{
return other;
}
typedef S type1;
void runMessage()
{
debMsg("Executing kernel Grid4dAddScalar ", 3);
debMsg("Kernel range"
<< " x " << maxX << " y " << maxY << " z " << minZ << " - " << maxZ << " ",
4);
};
void operator()(const tbb::blocked_range<IndexInt> &__r) const
{
for (IndexInt idx = __r.begin(); idx != (IndexInt)__r.end(); idx++)
op(idx, me, other);
}
void run()
{
tbb::parallel_for(tbb::blocked_range<IndexInt>(0, size), *this);
}
Grid4d<T> &me;
const S &other;
};
template<class T, class S> struct Grid4dMultScalar : public KernelBase {
Grid4dMultScalar(Grid4d<T> &me, const S &other) : KernelBase(&me, 0), me(me), other(other)
{
runMessage();
run();
}
inline void op(IndexInt idx, Grid4d<T> &me, const S &other) const
{
me[idx] *= other;
}
inline Grid4d<T> &getArg0()
{
return me;
}
typedef Grid4d<T> type0;
inline const S &getArg1()
{
return other;
}
typedef S type1;
void runMessage()
{
debMsg("Executing kernel Grid4dMultScalar ", 3);
debMsg("Kernel range"
<< " x " << maxX << " y " << maxY << " z " << minZ << " - " << maxZ << " ",
4);
};
void operator()(const tbb::blocked_range<IndexInt> &__r) const
{
for (IndexInt idx = __r.begin(); idx != (IndexInt)__r.end(); idx++)
op(idx, me, other);
}
void run()
{
tbb::parallel_for(tbb::blocked_range<IndexInt>(0, size), *this);
}
Grid4d<T> &me;
const S &other;
};
template<class T, class S> struct Grid4dScaledAdd : public KernelBase {
Grid4dScaledAdd(Grid4d<T> &me, const Grid4d<T> &other, const S &factor)
: KernelBase(&me, 0), me(me), other(other), factor(factor)
{
runMessage();
run();
}
inline void op(IndexInt idx, Grid4d<T> &me, const Grid4d<T> &other, const S &factor) const
{
me[idx] += factor * other[idx];
}
inline Grid4d<T> &getArg0()
{
return me;
}
typedef Grid4d<T> type0;
inline const Grid4d<T> &getArg1()
{
return other;
}
typedef Grid4d<T> type1;
inline const S &getArg2()
{
return factor;
}
typedef S type2;
void runMessage()
{
debMsg("Executing kernel Grid4dScaledAdd ", 3);
debMsg("Kernel range"
<< " x " << maxX << " y " << maxY << " z " << minZ << " - " << maxZ << " ",
4);
};
void operator()(const tbb::blocked_range<IndexInt> &__r) const
{
for (IndexInt idx = __r.begin(); idx != (IndexInt)__r.end(); idx++)
op(idx, me, other, factor);
}
void run()
{
tbb::parallel_for(tbb::blocked_range<IndexInt>(0, size), *this);
}
Grid4d<T> &me;
const Grid4d<T> &other;
const S &factor;
};
template<class T> struct Grid4dSafeDiv : public KernelBase {
Grid4dSafeDiv(Grid4d<T> &me, const Grid4d<T> &other) : KernelBase(&me, 0), me(me), other(other)
{
runMessage();
run();
}
inline void op(IndexInt idx, Grid4d<T> &me, const Grid4d<T> &other) const
{
me[idx] = safeDivide(me[idx], other[idx]);
}
inline Grid4d<T> &getArg0()
{
return me;
}
typedef Grid4d<T> type0;
inline const Grid4d<T> &getArg1()
{
return other;
}
typedef Grid4d<T> type1;
void runMessage()
{
debMsg("Executing kernel Grid4dSafeDiv ", 3);
debMsg("Kernel range"
<< " x " << maxX << " y " << maxY << " z " << minZ << " - " << maxZ << " ",
4);
};
void operator()(const tbb::blocked_range<IndexInt> &__r) const
{
for (IndexInt idx = __r.begin(); idx != (IndexInt)__r.end(); idx++)
op(idx, me, other);
}
void run()
{
tbb::parallel_for(tbb::blocked_range<IndexInt>(0, size), *this);
}
Grid4d<T> &me;
const Grid4d<T> &other;
};
template<class T> struct Grid4dSetConst : public KernelBase {
Grid4dSetConst(Grid4d<T> &me, T value) : KernelBase(&me, 0), me(me), value(value)
{
runMessage();
run();
}
inline void op(IndexInt idx, Grid4d<T> &me, T value) const
{
me[idx] = value;
}
inline Grid4d<T> &getArg0()
{
return me;
}
typedef Grid4d<T> type0;
inline T &getArg1()
{
return value;
}
typedef T type1;
void runMessage()
{
debMsg("Executing kernel Grid4dSetConst ", 3);
debMsg("Kernel range"
<< " x " << maxX << " y " << maxY << " z " << minZ << " - " << maxZ << " ",
4);
};
void operator()(const tbb::blocked_range<IndexInt> &__r) const
{
for (IndexInt idx = __r.begin(); idx != (IndexInt)__r.end(); idx++)
op(idx, me, value);
}
void run()
{
tbb::parallel_for(tbb::blocked_range<IndexInt>(0, size), *this);
}
Grid4d<T> &me;
T value;
};
template<class T> template<class S> Grid4d<T> &Grid4d<T>::operator+=(const Grid4d<S> &a)
{
Grid4dAdd<T, S>(*this, a);
return *this;
}
template<class T> template<class S> Grid4d<T> &Grid4d<T>::operator+=(const S &a)
{
Grid4dAddScalar<T, S>(*this, a);
return *this;
}
template<class T> template<class S> Grid4d<T> &Grid4d<T>::operator-=(const Grid4d<S> &a)
{
Grid4dSub<T, S>(*this, a);
return *this;
}
template<class T> template<class S> Grid4d<T> &Grid4d<T>::operator-=(const S &a)
{
Grid4dAddScalar<T, S>(*this, -a);
return *this;
}
template<class T> template<class S> Grid4d<T> &Grid4d<T>::operator*=(const Grid4d<S> &a)
{
Grid4dMult<T, S>(*this, a);
return *this;
}
template<class T> template<class S> Grid4d<T> &Grid4d<T>::operator*=(const S &a)
{
Grid4dMultScalar<T, S>(*this, a);
return *this;
}
template<class T> template<class S> Grid4d<T> &Grid4d<T>::operator/=(const Grid4d<S> &a)
{
Grid4dDiv<T, S>(*this, a);
return *this;
}
template<class T> template<class S> Grid4d<T> &Grid4d<T>::operator/=(const S &a)
{
S rez((S)1.0 / a);
Grid4dMultScalar<T, S>(*this, rez);
return *this;
}
//******************************************************************************
// Other helper functions
inline Vec4 getGradient4d(const Grid4d<Real> &data, int i, int j, int k, int t)
{
Vec4 v;
if (i > data.getSizeX() - 2)
i = data.getSizeX() - 2;
if (j > data.getSizeY() - 2)
j = data.getSizeY() - 2;
if (k > data.getSizeZ() - 2)
k = data.getSizeZ() - 2;
if (t > data.getSizeT() - 2)
t = data.getSizeT() - 2;
if (i < 1)
i = 1;
if (j < 1)
j = 1;
if (k < 1)
k = 1;
if (t < 1)
t = 1;
v = Vec4(data(i + 1, j, k, t) - data(i - 1, j, k, t),
data(i, j + 1, k, t) - data(i, j - 1, k, t),
data(i, j, k + 1, t) - data(i, j, k - 1, t),
data(i, j, k, t + 1) - data(i, j, k, t - 1));
return v;
}
template<class S> struct KnInterpolateGrid4dTempl : public KernelBase {
KnInterpolateGrid4dTempl(Grid4d<S> &target,
Grid4d<S> &source,
const Vec4 &sourceFactor,
Vec4 offset)
: KernelBase(&target, 0),
target(target),
source(source),
sourceFactor(sourceFactor),
offset(offset)
{
runMessage();
run();
}
inline void op(int i,
int j,
int k,
int t,
Grid4d<S> &target,
Grid4d<S> &source,
const Vec4 &sourceFactor,
Vec4 offset) const
{
Vec4 pos = Vec4(i, j, k, t) * sourceFactor + offset;
if (!source.is3D())
pos[2] = 0.; // allow 2d -> 3d
if (!source.is4D())
pos[3] = 0.; // allow 3d -> 4d
target(i, j, k, t) = source.getInterpolated(pos);
}
inline Grid4d<S> &getArg0()
{
return target;
}
typedef Grid4d<S> type0;
inline Grid4d<S> &getArg1()
{
return source;
}
typedef Grid4d<S> type1;
inline const Vec4 &getArg2()
{
return sourceFactor;
}
typedef Vec4 type2;
inline Vec4 &getArg3()
{
return offset;
}
typedef Vec4 type3;
void runMessage()
{
debMsg("Executing kernel KnInterpolateGrid4dTempl ", 3);
debMsg("Kernel range"
<< " x " << maxX << " y " << maxY << " z " << minZ << " - " << maxZ
<< " "
" t "
<< minT << " - " << maxT,
4);
};
void operator()(const tbb::blocked_range<IndexInt> &__r) const
{
if (maxT > 1) {
for (int t = __r.begin(); t != (int)__r.end(); t++)
for (int k = 0; k < maxZ; k++)
for (int j = 0; j < maxY; j++)
for (int i = 0; i < maxX; i++)
op(i, j, k, t, target, source, sourceFactor, offset);
}
else if (maxZ > 1) {
const int t = 0;
for (int k = __r.begin(); k != (int)__r.end(); k++)
for (int j = 0; j < maxY; j++)
for (int i = 0; i < maxX; i++)
op(i, j, k, t, target, source, sourceFactor, offset);
}
else {
const int t = 0;
const int k = 0;
for (int j = __r.begin(); j != (int)__r.end(); j++)
for (int i = 0; i < maxX; i++)
op(i, j, k, t, target, source, sourceFactor, offset);
}
}
void run()
{
if (maxT > 1) {
tbb::parallel_for(tbb::blocked_range<IndexInt>(minT, maxT), *this);
}
else if (maxZ > 1) {
tbb::parallel_for(tbb::blocked_range<IndexInt>(minZ, maxZ), *this);
}
else {
tbb::parallel_for(tbb::blocked_range<IndexInt>(0, maxY), *this);
}
}
Grid4d<S> ⌖
Grid4d<S> &source;
const Vec4 &sourceFactor;
Vec4 offset;
};
} // namespace Manta
#endif
| 0 | 0.875446 | 1 | 0.875446 | game-dev | MEDIA | 0.267075 | game-dev | 0.813623 | 1 | 0.813623 |
Dzierzan/OpenSA | 3,991 | OpenRA.Mods.OpenSA/Warheads/SplitWarhead.cs | #region Copyright & License Information
/*
* Copyright The OpenSA Developers (see CREDITS)
* This file is part of OpenSA, which is free software. It is made
* available to you 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. For more
* information, see COPYING.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using OpenRA.GameRules;
using OpenRA.Mods.Common.Traits;
using OpenRA.Mods.Common.Warheads;
using OpenRA.Traits;
namespace OpenRA.Mods.OpenSA.Warheads
{
[Desc("A warhead that fires another weapon on impact.")]
public class SplitWarhead : Warhead, IRulesetLoaded<WeaponInfo>
{
[WeaponReference]
[FieldLoader.Require]
[Desc("Has to be defined in weapons.yaml as well.")]
public readonly string Weapon = null;
[WeaponReference]
[Desc("Fires when hitting invalid bounce terrain or an actor.")]
public readonly string ExplodeWeapon = null;
[Desc("Terrain where the projectile explodes instead of bouncing.")]
public readonly HashSet<string> InvalidBounceTerrain = new();
[Desc("Modify distance of each bounce by this percentage of previous distance.")]
public readonly int BounceRangeModifier = 100;
[Desc("At which angle to divide the split projectiles.")]
public readonly WAngle[] SplitAngles = { WAngle.FromDegrees(-45), WAngle.FromDegrees(45) };
WeaponInfo splitWeapon;
WeaponInfo explodeWeapon;
public void RulesetLoaded(Ruleset rules, WeaponInfo info)
{
if (!rules.Weapons.TryGetValue(Weapon.ToLowerInvariant(), out splitWeapon))
throw new YamlException($"Weapons Ruleset does not contain an entry '{Weapon.ToLowerInvariant()}'");
rules.Weapons.TryGetValue(Weapon.ToLowerInvariant(), out explodeWeapon);
}
public override void DoImpact(in Target target, WarheadArgs args)
{
var firedBy = args.SourceActor;
var world = firedBy.World;
var map = world.Map;
var position = args.ImpactPosition;
var source = args.Source.Value;
var cell = world.Map.CellContaining(position);
if (!world.Map.Contains(cell))
return;
if (InvalidBounceTerrain.Contains(world.Map.GetTerrainInfo(cell).Type)
|| world.ActorMap.AnyActorsAt(world.Map.CellContaining(position)))
{
if (explodeWeapon != null)
explodeWeapon.Impact(target, args);
return;
}
var targetPosition = target.CenterPosition;
foreach (var splitAngle in SplitAngles)
{
targetPosition += (position - source).Rotate(WRot.FromYaw(splitAngle)) * BounceRangeModifier / 100;
var dat = world.Map.DistanceAboveTerrain(targetPosition);
targetPosition += new WVec(0, 0, -dat.Length);
var newTarget = Target.FromPos(targetPosition);
var facing = (targetPosition - target.CenterPosition).Yaw;
var projectileArgs = new ProjectileArgs
{
Weapon = splitWeapon,
Facing = facing,
CurrentMuzzleFacing = () => facing,
DamageModifiers = args.DamageModifiers,
InaccuracyModifiers = !firedBy.IsDead ? firedBy.TraitsImplementing<IInaccuracyModifier>()
.Select(a => a.GetInaccuracyModifier()).ToArray() : Array.Empty<int>(),
RangeModifiers = !firedBy.IsDead ? firedBy.TraitsImplementing<IRangeModifier>()
.Select(a => a.GetRangeModifier()).ToArray() : Array.Empty<int>(),
Source = position,
CurrentSource = () => position,
SourceActor = firedBy,
GuidedTarget = newTarget,
PassiveTarget = targetPosition
};
if (projectileArgs.Weapon.Projectile != null)
{
var projectile = projectileArgs.Weapon.Projectile.Create(projectileArgs);
if (projectile != null)
firedBy.World.AddFrameEndTask(w => w.Add(projectile));
if (projectileArgs.Weapon.Report != null && projectileArgs.Weapon.Report.Any())
Game.Sound.Play(SoundType.World, projectileArgs.Weapon.Report.Random(firedBy.World.SharedRandom), target.CenterPosition);
}
}
}
}
}
| 0 | 0.961799 | 1 | 0.961799 | game-dev | MEDIA | 0.939489 | game-dev | 0.865478 | 1 | 0.865478 |
D4rkks/r.e.p.o-cheat | 43,409 | r.e.p.o cheat/Cheats/DebugCheats.cs | using System;
using UnityEngine;
using Photon.Pun;
using Photon.Realtime; // Necessário para ReceiverGroup e RaiseEventOptions
using ExitGames.Client.Photon; // Necessário para SendOptions
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
using System.Collections;
namespace r.e.p.o_cheat
{
static class DebugCheats
{
private static int frameCounter = 0;
public static List<Enemy> enemyList = new List<Enemy>();
public static List<object> valuableObjects = new List<object>();
private static List<object> playerList = new List<object>();
private static Camera cachedCamera;
private static float scaleX, scaleY;
public static Texture2D texture2;
private static float lastUpdateTime = 0f;
private static float lastExtractionUpdateTime = 0f;
private const float updateInterval = 1f;
private const float extractionUpdateInterval = 5f;
private static GameObject localPlayer;
private static List<ExtractionPointData> extractionPointList = new List<ExtractionPointData>();
public static bool drawEspBool = false;
public static bool drawItemEspBool = false;
public static bool drawPlayerEspBool = false;
public static bool draw3DItemEspBool = false;
public static bool draw3DPlayerEspBool = false;
public static bool drawExtractionPointEspBool = false;
public static GUIStyle nameStyle;
public static GUIStyle valueStyle;
public static GUIStyle enemyStyle;
public static GUIStyle healthStyle;
public static GUIStyle distanceStyle;
public static bool showEnemyNames = true;
public static bool showEnemyDistance = true;
public static bool showItemNames = true;
public static bool showItemValue = true;
public static bool showItemDistance = false;
public static bool showPlayerDeathHeads = true;
public static bool showExtractionNames = true;
public static bool showExtractionDistance = true;
public static bool showPlayerNames = true;
public static bool showPlayerDistance = true;
public static bool showPlayerHP = true;
private static List<PlayerData> playerDataList = new List<PlayerData>();
private static float lastPlayerUpdateTime = 0f;
private static float playerUpdateInterval = 1f;
private static Dictionary<int, int> playerHealthCache = new Dictionary<int, int>();
private const float maxEspDistance = 100f;
public class PlayerData
{
public object PlayerObject { get; }
public PhotonView PhotonView { get; }
public Transform Transform { get; }
public bool IsAlive { get; set; }
public string Name { get; set; }
public PlayerData(object player)
{
PlayerObject = player;
PhotonView = player.GetType().GetField("photonView", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)?.GetValue(player) as PhotonView;
Transform = player.GetType().GetProperty("transform", BindingFlags.Public | BindingFlags.Instance)?.GetValue(player) as Transform;
Name = (player as PlayerAvatar) != null ? (SemiFunc.PlayerGetName(player as PlayerAvatar) ?? "Unknown Player") : "Unknown Player";
IsAlive = true;
}
}
static DebugCheats()
{
cachedCamera = Camera.main;
if (cachedCamera != null)
{
scaleX = (float)Screen.width / cachedCamera.pixelWidth;
scaleY = (float)Screen.height / cachedCamera.pixelHeight;
}
UpdateLists();
UpdateLocalPlayer();
UpdateExtractionPointList();
UpdatePlayerDataList();
}
private static void UpdatePlayerDataList()
{
playerDataList.Clear();
playerHealthCache.Clear();
var players = SemiFunc.PlayerGetList();
if (players != null)
{
foreach (var player in players)
{
if (player != null)
{
var data = new PlayerData(player);
if (data.PhotonView != null && data.Transform != null)
{
playerDataList.Add(data);
int health = GetPlayerHealth(player);
playerHealthCache[data.PhotonView.ViewID] = health;
}
}
}
}
lastPlayerUpdateTime = Time.time;
Hax2.Log1($"Lista de dados de jogadores atualizada: {playerDataList.Count} jogadores.");
}
private static void UpdateExtractionPointList()
{
extractionPointList.Clear();
var extractionPoints = UnityEngine.Object.FindObjectsOfType(Type.GetType("ExtractionPoint, Assembly-CSharp"));
if (extractionPoints != null)
{
foreach (var ep in extractionPoints)
{
var extractionPoint = ep as ExtractionPoint;
if (extractionPoint != null && extractionPoint.gameObject.activeInHierarchy)
{
var currentStateField = extractionPoint.GetType().GetField("currentState", BindingFlags.NonPublic | BindingFlags.Instance);
string cachedState = "Unknown";
if (currentStateField != null)
{
var stateValue = currentStateField.GetValue(extractionPoint);
cachedState = stateValue?.ToString() ?? "Unknown";
}
Vector3 cachedPosition = extractionPoint.transform.position;
extractionPointList.Add(new ExtractionPointData(extractionPoint, cachedState, cachedPosition));
Hax2.Log1($"Extraction Point cacheado na posição: {cachedPosition}");
}
}
Hax2.Log1($"Lista de Extraction Points atualizada: {extractionPointList.Count} pontos encontrados.");
}
}
public class ExtractionPointData
{
public ExtractionPoint ExtractionPoint { get; }
public string CachedState { get; }
public Vector3 CachedPosition { get; }
public ExtractionPointData(ExtractionPoint ep, string state, Vector3 position)
{
ExtractionPoint = ep;
CachedState = state;
CachedPosition = position;
}
}
private static void UpdateLists()
{
UpdateExtractionPointList();
enemyList.Clear();
var enemyDirectorType = Type.GetType("EnemyDirector, Assembly-CSharp");
if (enemyDirectorType != null)
{
var enemyDirectorInstance = enemyDirectorType.GetField("instance", BindingFlags.Public | BindingFlags.Static)?.GetValue(null);
if (enemyDirectorInstance != null)
{
var enemiesSpawnedField = enemyDirectorType.GetField("enemiesSpawned", BindingFlags.Public | BindingFlags.Instance);
if (enemiesSpawnedField != null)
{
var enemies = enemiesSpawnedField.GetValue(enemyDirectorInstance) as IEnumerable<object>;
if (enemies != null)
{
foreach (var enemy in enemies)
{
if (enemy != null)
{
var enemyInstanceField = enemy.GetType().GetField("enemyInstance", BindingFlags.NonPublic | BindingFlags.Instance)
?? enemy.GetType().GetField("Enemy", BindingFlags.NonPublic | BindingFlags.Instance)
?? enemy.GetType().GetField("childEnemy", BindingFlags.NonPublic | BindingFlags.Instance);
if (enemyInstanceField != null)
{
var enemyInstance = enemyInstanceField.GetValue(enemy) as Enemy;
if (enemyInstance != null && enemyInstance.gameObject != null && enemyInstance.gameObject.activeInHierarchy)
{
enemyList.Add(enemyInstance);
}
}
}
}
}
}
}
}
playerList.Clear();
var players = SemiFunc.PlayerGetList();
if (players != null)
{
foreach (var player in players)
{
if (player != null)
{
playerList.Add(player);
}
}
}
lastUpdateTime = Time.time;
Hax2.Log1($"Listas atualizadas: {enemyList.Count} inimigos, {valuableObjects.Count} itens, {playerList.Count} jogadores.");
}
private static void UpdateLocalPlayer()
{
localPlayer = GetLocalPlayer();
if (localPlayer != null)
{
Hax2.Log1("Jogador local atualizado com sucesso: " + localPlayer.name);
}
else
{
Hax2.Log1("Falha ao atualizar jogador local!");
}
}
public static GameObject GetLocalPlayer()
{
if (PhotonNetwork.IsConnected)
{
var players = SemiFunc.PlayerGetList();
if (players != null)
{
foreach (var player in players)
{
var photonViewField = player.GetType().GetField("photonView", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
if (photonViewField != null)
{
var photonView = photonViewField.GetValue(player) as PhotonView;
if (photonView != null && photonView.IsMine)
{
var gameObjectProperty = player.GetType().GetProperty("gameObject", BindingFlags.Public | BindingFlags.Instance);
if (gameObjectProperty != null)
{
GameObject foundPlayer = gameObjectProperty.GetValue(player) as GameObject;
Hax2.Log1("Local player encontrado via Photon: " + foundPlayer.name);
return foundPlayer;
}
Hax2.Log1("Local player encontrado via PhotonView: " + photonView.gameObject.name);
return photonView.gameObject;
}
}
}
}
if (PhotonNetwork.LocalPlayer != null)
{
foreach (var photonView in UnityEngine.Object.FindObjectsOfType<PhotonView>())
{
if (photonView.Owner == PhotonNetwork.LocalPlayer && photonView.IsMine)
{
Hax2.Log1("Local player encontrado via Photon fallback: " + photonView.gameObject.name);
return photonView.gameObject;
}
}
}
}
else
{
var players = SemiFunc.PlayerGetList();
if (players != null && players.Count > 0)
{
var player = players[0];
var gameObjectProperty = player.GetType().GetProperty("gameObject", BindingFlags.Public | BindingFlags.Instance);
if (gameObjectProperty != null)
{
GameObject foundPlayer = gameObjectProperty.GetValue(player) as GameObject;
Hax2.Log1("Local player encontrado em singleplayer via PlayerGetList: " + foundPlayer.name);
return foundPlayer;
}
}
var playerAvatarType = Type.GetType("PlayerAvatar, Assembly-CSharp");
if (playerAvatarType != null)
{
var playerAvatar = UnityEngine.Object.FindObjectOfType(playerAvatarType) as MonoBehaviour;
if (playerAvatar != null)
{
Hax2.Log1("Local player encontrado em singleplayer via PlayerAvatar: " + playerAvatar.gameObject.name);
return playerAvatar.gameObject;
}
}
var playerByTag = GameObject.FindWithTag("Player");
if (playerByTag != null)
{
Hax2.Log1("Local player encontrado em singleplayer via tag 'Player': " + playerByTag.name);
return playerByTag;
}
var allObjects = UnityEngine.Object.FindObjectsOfType<GameObject>();
foreach (var obj in allObjects)
{
if (obj.name.Contains("Player") && obj.activeInHierarchy)
{
Hax2.Log1("Local player encontrado em singleplayer via nome genérico: " + obj.name);
return obj;
}
}
Hax2.Log1("Nenhum jogador local encontrado no singleplayer após todas as tentativas!");
return null;
}
Hax2.Log1("Nenhum jogador local encontrado!");
return null;
}
public static void UpdateEnemyList()
{
enemyList.Clear();
var enemyDirectorType = Type.GetType("EnemyDirector, Assembly-CSharp");
if (enemyDirectorType != null)
{
var enemyDirectorInstance = enemyDirectorType.GetField("instance", BindingFlags.Public | BindingFlags.Static)?.GetValue(null);
if (enemyDirectorInstance != null)
{
var enemiesSpawnedField = enemyDirectorType.GetField("enemiesSpawned", BindingFlags.Public | BindingFlags.Instance);
if (enemiesSpawnedField != null)
{
var enemies = enemiesSpawnedField.GetValue(enemyDirectorInstance) as IEnumerable<object>;
if (enemies != null)
{
foreach (var enemy in enemies)
{
if (enemy != null)
{
var enemyInstanceField = enemy.GetType().GetField("enemyInstance", BindingFlags.NonPublic | BindingFlags.Instance)
?? enemy.GetType().GetField("Enemy", BindingFlags.NonPublic | BindingFlags.Instance)
?? enemy.GetType().GetField("childEnemy", BindingFlags.NonPublic | BindingFlags.Instance);
if (enemyInstanceField != null)
{
var enemyInstance = enemyInstanceField.GetValue(enemy) as Enemy;
if (enemyInstance != null && enemyInstance.gameObject != null && enemyInstance.gameObject.activeInHierarchy)
{
enemyList.Add(enemyInstance);
}
}
}
}
}
else
{
Hax2.Log1("Nenhum inimigo encontrado em enemiesSpawned");
}
}
else
{
Hax2.Log1("Campo 'enemiesSpawned' não encontrado");
}
}
else
{
Hax2.Log1("Instância de EnemyDirector é nula");
}
}
else
{
Hax2.Log1("EnemyDirector não encontrado");
}
}
public static void RectFilled(float x, float y, float width, float height, Texture2D text)
{
GUI.DrawTexture(new Rect(x, y, width, height), text);
}
public static void RectOutlined(float x, float y, float width, float height, Texture2D text, float thickness = 1f)
{
RectFilled(x, y, thickness, height, text);
RectFilled(x + width - thickness, y, thickness, height, text);
RectFilled(x + thickness, y, width - thickness * 2f, thickness, text);
RectFilled(x + thickness, y + height - thickness, width - thickness * 2f, thickness, text);
}
public static void Box(float x, float y, float width, float height, Texture2D text, float thickness = 2f)
{
RectOutlined(x - width / 2f, y - height, width, height, text, thickness);
}
public static void InitializeStyles()
{
if (nameStyle == null)
{
nameStyle = new GUIStyle(GUI.skin.label)
{
normal = { textColor = Color.yellow },
alignment = TextAnchor.MiddleCenter,
fontSize = 14,
fontStyle = FontStyle.Bold,
wordWrap = true,
border = new RectOffset(1, 1, 1, 1)
};
}
if (valueStyle == null)
{
valueStyle = new GUIStyle(GUI.skin.label)
{
normal = { textColor = Color.green },
alignment = TextAnchor.MiddleCenter,
fontSize = 12,
fontStyle = FontStyle.Bold
};
}
if (enemyStyle == null)
{
enemyStyle = new GUIStyle(GUI.skin.label)
{
alignment = TextAnchor.MiddleCenter,
wordWrap = true,
fontSize = 12,
fontStyle = FontStyle.Bold
};
}
if (healthStyle == null)
{
healthStyle = new GUIStyle(GUI.skin.label)
{
normal = { textColor = Color.green },
alignment = TextAnchor.MiddleCenter,
fontSize = 12,
fontStyle = FontStyle.Bold
};
}
if (distanceStyle == null)
{
distanceStyle = new GUIStyle(GUI.skin.label)
{
normal = { textColor = Color.yellow },
alignment = TextAnchor.MiddleCenter,
fontSize = 12,
fontStyle = FontStyle.Bold
};
}
}
private static void CreateBoundsEdges(Bounds bounds, Color color)
{
Vector3[] vertices = new Vector3[8];
Vector3 min = bounds.min;
Vector3 max = bounds.max;
vertices[0] = new Vector3(min.x, min.y, min.z);
vertices[1] = new Vector3(max.x, min.y, min.z);
vertices[2] = new Vector3(max.x, min.y, max.z);
vertices[3] = new Vector3(min.x, min.y, max.z);
vertices[4] = new Vector3(min.x, max.y, min.z);
vertices[5] = new Vector3(max.x, max.y, min.z);
vertices[6] = new Vector3(max.x, max.y, max.z);
vertices[7] = new Vector3(min.x, max.y, max.z);
Vector2[] screenVertices = new Vector2[8];
bool isVisible = false;
for (int i = 0; i < 8; i++)
{
Vector3 screenPos = cachedCamera.WorldToScreenPoint(vertices[i]);
if (screenPos.z > 0) isVisible = true;
screenVertices[i] = new Vector2(screenPos.x * scaleX, Screen.height - (screenPos.y * scaleY));
}
if (!isVisible) return;
DrawLine(screenVertices[0], screenVertices[1], color);
DrawLine(screenVertices[1], screenVertices[2], color);
DrawLine(screenVertices[2], screenVertices[3], color);
DrawLine(screenVertices[3], screenVertices[0], color);
DrawLine(screenVertices[4], screenVertices[5], color);
DrawLine(screenVertices[5], screenVertices[6], color);
DrawLine(screenVertices[6], screenVertices[7], color);
DrawLine(screenVertices[7], screenVertices[4], color);
DrawLine(screenVertices[0], screenVertices[4], color);
DrawLine(screenVertices[1], screenVertices[5], color);
DrawLine(screenVertices[2], screenVertices[6], color);
DrawLine(screenVertices[3], screenVertices[7], color);
}
private static void DrawLine(Vector2 start, Vector2 end, Color color)
{
if (texture2 == null) return;
float distance = Vector2.Distance(start, end);
float angle = Mathf.Atan2(end.y - start.y, end.x - start.x) * Mathf.Rad2Deg;
GUI.color = color;
Matrix4x4 originalMatrix = GUI.matrix;
GUIUtility.RotateAroundPivot(angle, start);
GUI.DrawTexture(new Rect(start.x, start.y, distance, 1f), texture2);
GUI.matrix = originalMatrix;
GUI.color = Color.white;
}
private static Bounds GetActiveColliderBounds(GameObject obj)
{
Collider[] colliders = obj.GetComponentsInChildren<Collider>(true);
List<Collider> activeColliders = new List<Collider>();
foreach (Collider col in colliders)
{
if (col.enabled && col.gameObject.activeInHierarchy)
activeColliders.Add(col);
}
if (activeColliders.Count == 0)
{
Renderer[] renderers = obj.GetComponentsInChildren<Renderer>(true);
if (renderers.Length > 0)
{
Bounds bounds = renderers[0].bounds;
for (int i = 1; i < renderers.Length; i++)
{
if (renderers[i].enabled && renderers[i].gameObject.activeInHierarchy)
bounds.Encapsulate(renderers[i].bounds);
}
return bounds;
}
return new Bounds(obj.transform.position, Vector3.one * 0.5f);
}
Bounds resultBounds = activeColliders[0].bounds;
for (int i = 1; i < activeColliders.Count; i++)
{
resultBounds.Encapsulate(activeColliders[i].bounds);
}
resultBounds.Expand(0.1f);
return resultBounds;
}
public static void DrawESP()
{
InitializeStyles();
if (!drawEspBool && !drawItemEspBool && !drawExtractionPointEspBool && !drawPlayerEspBool && !draw3DPlayerEspBool && !draw3DItemEspBool) return;
if (localPlayer == null)
{
UpdateLocalPlayer();
}
if (Time.time - lastUpdateTime > updateInterval)
{
UpdatePlayerDataList();
if (drawEspBool || drawItemEspBool || drawExtractionPointEspBool || drawPlayerEspBool || draw3DPlayerEspBool || draw3DItemEspBool)
{
UpdateLists();
}
UpdateLocalPlayer();
}
frameCounter++;
if (frameCounter % 2 != 0) return;
if (cachedCamera == null || cachedCamera != Camera.main)
{
cachedCamera = Camera.main;
if (cachedCamera == null)
{
Hax2.Log1("Camera.main não encontrada!");
return;
}
}
scaleX = (float)Screen.width / cachedCamera.pixelWidth;
scaleY = (float)Screen.height / cachedCamera.pixelHeight;
if (drawEspBool)
{
foreach (var enemyInstance in enemyList)
{
if (enemyInstance == null || !enemyInstance.gameObject.activeInHierarchy || enemyInstance.CenterTransform == null) continue;
Vector3 footPosition = enemyInstance.transform.position;
float enemyHeightEstimate = 2f;
Vector3 headPosition = enemyInstance.transform.position + Vector3.up * enemyHeightEstimate;
Vector3 screenFootPos = cachedCamera.WorldToScreenPoint(footPosition);
Vector3 screenHeadPos = cachedCamera.WorldToScreenPoint(headPosition);
if (screenFootPos.z > 0 && screenHeadPos.z > 0)
{
float footX = screenFootPos.x * scaleX;
float footY = Screen.height - (screenFootPos.y * scaleY);
float headY = Screen.height - (screenHeadPos.y * scaleY);
float height = Mathf.Abs(footY - headY);
float enemyScale = enemyInstance.transform.localScale.y;
float baseWidth = enemyScale * 200f;
float distance = screenFootPos.z;
float width = (baseWidth / distance) * scaleX;
width = Mathf.Clamp(width, 30f, height * 1.2f);
height = Mathf.Clamp(height, 40f, 400f);
float x = footX;
float y = footY;
Box(x, y, width, height, texture2, 1f);
float labelWidth = 100f;
float labelX = x - labelWidth / 2f;
var enemyParent = enemyInstance.GetComponentInParent(Type.GetType("EnemyParent, Assembly-CSharp"));
string enemyName = "Enemy";
if (enemyParent != null)
{
var nameField = enemyParent.GetType().GetField("enemyName", BindingFlags.Public | BindingFlags.Instance);
enemyName = nameField?.GetValue(enemyParent) as string ?? "Enemy";
}
string distanceText = "";
if (showEnemyDistance && localPlayer != null)
{
float distance2 = Vector3.Distance(localPlayer.transform.position, enemyInstance.transform.position);
distanceText = $" [{distance2:F1}m]";
}
string fullText = "";
if (showEnemyNames) fullText = enemyName;
if (showEnemyDistance) fullText += distanceText;
float labelHeight = enemyStyle.CalcHeight(new GUIContent(fullText), labelWidth);
float labelY = y - height - labelHeight;
GUI.Label(new Rect(labelX, labelY, labelWidth, labelHeight), fullText, enemyStyle);
}
}
}
if (drawItemEspBool)
{
foreach (var valuableObject in valuableObjects)
{
if (valuableObject == null) continue;
bool isPlayerDeathHead = valuableObject.GetType().Name == "PlayerDeathHead";
if (!DebugCheats.showPlayerDeathHeads && isPlayerDeathHead) continue;
var transform = valuableObject.GetType().GetProperty("transform", BindingFlags.Public | BindingFlags.Instance)?.GetValue(valuableObject) as Transform;
if (transform == null || !transform.gameObject.activeInHierarchy) continue;
Vector3 itemPosition = transform.position;
Vector3 screenPos = cachedCamera.WorldToScreenPoint(itemPosition);
if (screenPos.z > 0 && screenPos.x > 0 && screenPos.x < Screen.width && screenPos.y > 0 && screenPos.y < Screen.height)
{
float x = screenPos.x * scaleX;
float y = Screen.height - (screenPos.y * scaleY);
string itemName;
Color originalColor = nameStyle.normal.textColor;
if (isPlayerDeathHead)
{
itemName = "Dead Player Head";
nameStyle.normal.textColor = Color.red;
}
else
{
nameStyle.normal.textColor = Color.yellow;
try
{
itemName = valuableObject.GetType().GetProperty("name", BindingFlags.Public | BindingFlags.Instance)?.GetValue(valuableObject) as string;
if (string.IsNullOrEmpty(itemName))
{
itemName = (valuableObject as UnityEngine.Object)?.name ?? "Unknown";
}
}
catch (Exception e)
{
itemName = (valuableObject as UnityEngine.Object)?.name ?? "Unknown";
Hax2.Log1($"Erro ao acessar 'name' do item: {e.Message}. Usando nome do GameObject: {itemName}");
}
if (itemName.StartsWith("Valuable", StringComparison.OrdinalIgnoreCase))
{
itemName = itemName.Substring("Valuable".Length).Trim();
}
if (itemName.EndsWith("(Clone)", StringComparison.OrdinalIgnoreCase))
{
itemName = itemName.Substring(0, itemName.Length - "(Clone)".Length).Trim();
}
}
int itemValue = 0;
if (!isPlayerDeathHead)
{
var valueField = valuableObject.GetType().GetField("dollarValueCurrent", BindingFlags.Public | BindingFlags.Instance);
if (valueField != null)
{
try
{
itemValue = Convert.ToInt32(valueField.GetValue(valuableObject));
}
catch (Exception e)
{
Hax2.Log1($"Error reading 'dollarValueCurrent' for '{itemName}': {e.Message}. Defaulting to 0.");
}
}
}
// Set distance color
Color distanceColor = isPlayerDeathHead ? Color.red : Color.yellow;
nameStyle.normal.textColor = distanceColor;
string distanceText = "";
if (showItemDistance && localPlayer != null)
{
float distance = Vector3.Distance(localPlayer.transform.position, itemPosition);
distanceText = $" [{distance:F1}m]";
}
string nameText = showItemNames ? itemName : "";
if (showItemDistance) nameText += distanceText;
float labelWidth = 150f;
float valueLabelHeight = valueStyle.CalcHeight(new GUIContent(itemValue.ToString() + "$"), labelWidth);
float nameLabelHeight = nameStyle.CalcHeight(new GUIContent(nameText), labelWidth);
float totalHeight = nameLabelHeight + valueLabelHeight + 5f;
float labelX = x - labelWidth / 2f;
float labelY = y - totalHeight - 5f;
// Draw Name (with distance included in the same label)
if (!string.IsNullOrEmpty(nameText))
{
GUI.Label(new Rect(labelX, labelY, labelWidth, nameLabelHeight), nameText, nameStyle);
}
// Draw Item Value (if not DeadPlayerHead)
if (showItemValue && !isPlayerDeathHead)
{
GUI.Label(new Rect(labelX, labelY + nameLabelHeight + 2f, labelWidth, valueLabelHeight), itemValue.ToString() + "$", valueStyle);
}
// Draw 3D Item ESP if enabled
if (draw3DItemEspBool)
{
Bounds bounds = GetActiveColliderBounds(transform.gameObject);
CreateBoundsEdges(bounds, Color.yellow);
}
nameStyle.normal.textColor = originalColor;
}
}
}
if (drawExtractionPointEspBool)
{
foreach (var epData in extractionPointList)
{
if (epData.ExtractionPoint == null || !epData.ExtractionPoint.gameObject.activeInHierarchy) continue;
Vector3 screenPos = cachedCamera.WorldToScreenPoint(epData.CachedPosition);
if (screenPos.z > 0 && screenPos.x > 0 && screenPos.x < Screen.width && screenPos.y > 0 && screenPos.y < Screen.height)
{
float x = screenPos.x * scaleX;
float y = Screen.height - (screenPos.y * scaleY);
string pointName = "Extraction Point";
string stateText = $" ({epData.CachedState})";
string distanceText = showExtractionDistance && localPlayer != null ? $"{Vector3.Distance(localPlayer.transform.position, epData.CachedPosition):F1}m" : "";
Color originalColor = nameStyle.normal.textColor;
nameStyle.normal.textColor = epData.CachedState == "Active" ? Color.green : (epData.CachedState == "Idle" ? Color.red : Color.cyan);
string nameFullText = showExtractionNames ? pointName + stateText : "";
if (showExtractionDistance) nameFullText += " " + distanceText;
float labelWidth = 150f;
float nameLabelHeight = nameStyle.CalcHeight(new GUIContent(nameFullText), labelWidth);
float totalHeight = nameLabelHeight;
float labelX = x - labelWidth / 2f;
float labelY = y - totalHeight - 5f;
if (!string.IsNullOrEmpty(nameFullText))
{
GUI.Label(new Rect(labelX, labelY, labelWidth, nameLabelHeight), nameFullText, nameStyle);
}
nameStyle.normal.textColor = originalColor;
}
}
}
if (drawPlayerEspBool || draw3DPlayerEspBool)
{
foreach (var playerData in playerDataList)
{
bool isLocalPlayer = false;
if (!PhotonNetwork.IsConnected && localPlayer != null && playerData.Transform.gameObject == localPlayer)
{
isLocalPlayer = true;
}
if (playerData.PhotonView == null || (playerData.PhotonView.IsMine && PhotonNetwork.IsConnected) || isLocalPlayer || !playerData.Transform.gameObject.activeInHierarchy) continue;
Vector3 playerPos = playerData.Transform.position;
float distanceToPlayer = localPlayer != null ? Vector3.Distance(localPlayer.transform.position, playerPos) : float.MaxValue;
if (distanceToPlayer > maxEspDistance) continue;
Vector3 footPosition = playerPos;
float playerHeightEstimate = 2f;
Vector3 headPosition = playerPos + Vector3.up * playerHeightEstimate;
Vector3 screenFootPos = cachedCamera.WorldToScreenPoint(footPosition);
Vector3 screenHeadPos = cachedCamera.WorldToScreenPoint(headPosition);
bool isInFront = screenFootPos.z > 0 && screenHeadPos.z > 0;
if (!isInFront) continue;
float footX = screenFootPos.x * scaleX;
float footY = Screen.height - (screenFootPos.y * scaleY);
float headY = Screen.height - (screenHeadPos.y * scaleY);
float height = Mathf.Abs(footY - headY);
float playerScale = playerData.Transform.localScale.y;
float baseWidth = playerScale * 200f;
float width = (baseWidth / (distanceToPlayer + 1f)) * scaleX;
width = Mathf.Clamp(width, 30f, height * 1.2f);
height = Mathf.Clamp(height, 40f, 400f);
float x = footX;
float y = footY;
if (draw3DPlayerEspBool)
{
Bounds bounds = GetActiveColliderBounds(playerData.Transform.gameObject);
CreateBoundsEdges(bounds, Color.red);
}
if (drawPlayerEspBool)
{
Box(x, y, width, height, texture2, 2f);
}
Color originalNameColor = nameStyle.normal.textColor;
nameStyle.normal.textColor = Color.white;
int health = playerHealthCache.ContainsKey(playerData.PhotonView.ViewID) ? playerHealthCache[playerData.PhotonView.ViewID] : 100;
string healthText = $"HP: {health}";
string distanceText = showPlayerDistance && localPlayer != null ? $"{distanceToPlayer:F1}m" : "";
string nameFullText = showPlayerNames ? playerData.Name : "";
if (showPlayerDistance) nameFullText += " " + distanceText;
float labelWidth = 150f;
float nameHeight = nameStyle.CalcHeight(new GUIContent(nameFullText), labelWidth);
float healthHeight = healthStyle.CalcHeight(new GUIContent(healthText), labelWidth);
float totalHeight = nameHeight + (showPlayerHP ? healthHeight + 2f : 0f);
float labelX = footX - labelWidth / 2f;
float labelY = footY - height - totalHeight - 10f;
if (!string.IsNullOrEmpty(nameFullText))
{
GUI.Label(new Rect(labelX, labelY, labelWidth, nameHeight), nameFullText, nameStyle);
}
if (showPlayerHP)
{
GUI.Label(new Rect(labelX, labelY + nameHeight + 2f, labelWidth, healthHeight), healthText, healthStyle);
}
nameStyle.normal.textColor = originalNameColor;
}
}
}
private static int GetPlayerHealth(object player)
{
try
{
var playerHealthField = player.GetType().GetField("playerHealth", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
if (playerHealthField == null) return 100;
var playerHealthInstance = playerHealthField.GetValue(player);
if (playerHealthInstance == null) return 100;
var healthField = playerHealthInstance.GetType().GetField("health", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
if (healthField == null) return 100;
return (int)healthField.GetValue(playerHealthInstance);
}
catch (Exception e)
{
Hax2.Log1($"Erro ao obter vida do jogador: {e.Message}");
return 100;
}
}
public static void KillAllEnemies()
{
Hax2.Log1("Tentando matar todos os inimigos");
foreach (var enemyInstance in enemyList)
{
if (enemyInstance == null) continue;
try
{
var healthField = enemyInstance.GetType().GetField("Health", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
if (healthField != null)
{
var healthComponent = healthField.GetValue(enemyInstance);
if (healthComponent != null)
{
var healthType = healthComponent.GetType();
var hurtMethod = healthType.GetMethod("Hurt", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
if (hurtMethod != null)
{
hurtMethod.Invoke(healthComponent, new object[] { 9999, Vector3.zero });
Hax2.Log1($"Inimigo ferido com 9999 de dano via Hurt");
}
else
Hax2.Log1("Método 'Hurt' não encontrado em EnemyHealth");
}
else
Hax2.Log1("Componente EnemyHealth é nulo");
}
else
Hax2.Log1("Campo 'Health' não encontrado em Enemy");
}
catch (Exception e)
{
Hax2.Log1($"Erro ao matar inimigo: {e.Message}");
}
}
UpdateEnemyList();
}
}
}
| 0 | 0.918985 | 1 | 0.918985 | game-dev | MEDIA | 0.935422 | game-dev | 0.980413 | 1 | 0.980413 |
Open-RSC/Core-Framework | 2,496 | server/plugins/com/openrsc/server/plugins/authentic/quests/members/watchtower/WatchTowerGorad.java | package com.openrsc.server.plugins.authentic.quests.members.watchtower;
import com.openrsc.server.constants.Quests;
import com.openrsc.server.constants.ItemId;
import com.openrsc.server.constants.NpcId;
import com.openrsc.server.model.entity.npc.Npc;
import com.openrsc.server.model.entity.player.Player;
import com.openrsc.server.plugins.triggers.AttackNpcTrigger;
import com.openrsc.server.plugins.triggers.KillNpcTrigger;
import com.openrsc.server.plugins.triggers.TalkNpcTrigger;
import static com.openrsc.server.plugins.Functions.*;
public class WatchTowerGorad implements TalkNpcTrigger,
KillNpcTrigger, AttackNpcTrigger {
@Override
public boolean blockKillNpc(Player player, Npc n) {
return n.getID() == NpcId.GORAD.id();
}
@Override
public void onKillNpc(Player player, Npc n) {
if (n.getID() == NpcId.GORAD.id()) {
player.message("Gorad has gone");
player.message("He's dropped a tooth, I'll keep that!");
give(player, ItemId.OGRE_TOOTH.id(), 1);
}
}
@Override
public boolean blockTalkNpc(Player player, Npc n) {
return n.getID() == NpcId.GORAD.id();
}
@Override
public void onTalkNpc(Player player, Npc n) {
if (n.getID() == NpcId.GORAD.id()) {
if (player.getCache().hasKey("ogre_grew")) {
say(player, n, "I've come to knock your teeth out!");
npcsay(player, n, "How dare you utter that foul language in my prescence!",
"You shall die quickly vermin");
n.startCombat(player);
} else if (player.getCache().hasKey("ogre_grew_p1") || player.getQuestStage(Quests.WATCHTOWER) > 0) {
say(player, n, "Hello");
npcsay(player, n, "Do you know who you are talking to ?");
int menu = multi(player, n,
"A big ugly brown creature...",
"I don't know who you are");
if (menu == 0) {
npcsay(player, n, "The impudence! take that...");
player.damage(16);
say(player, n, "Ouch!");
player.message("The ogre punched you hard in the face!");
} else if (menu == 1) {
npcsay(player, n, "I am Gorad - who you are dosen't matter",
"Go now and you may live another day!");
}
} else {
player.message("Gorad is busy, try again later");
}
}
}
@Override
public boolean blockAttackNpc(Player player, Npc n) {
return n.getID() == NpcId.GORAD.id();
}
@Override
public void onAttackNpc(Player player, Npc affectedmob) {
if (affectedmob.getID() == NpcId.GORAD.id()) {
npcsay(player, affectedmob, "Ho Ho! why would I want to fight a worm ?",
"Get lost!");
}
}
}
| 0 | 0.908938 | 1 | 0.908938 | game-dev | MEDIA | 0.938554 | game-dev | 0.911022 | 1 | 0.911022 |
shit-ware/IW4 | 5,123 | ui_mp/profile_create_fail_popmenu.menu | {
menuDef
{
name "profile_create_fail_popmenu"
rect -150 -124 300 124 2 2
popup
legacySplitScreenScale
visible 1
style 1
forecolor 1 1 1 1
backcolor 1 1 1 1
background "white"
focuscolor 1 1 1 1
fadeCycle 1
fadeClamp 1
fadeAmount 0.1
onOpen
{
setLocalVarInt "ui_centerPopup" ( 1 );
setfocus "ok";
}
onClose
{
setLocalVarInt "ui_centerPopup" ( 0 );
}
onEsc
{
close self;
}
itemDef
{
rect -854 -480 1708 960 0 0
decoration
visible 1
style 1
forecolor 1 1 1 1
backcolor 0 0 0 0.35
background "white"
textscale 0.55
}
itemDef
{
rect -854 -480 1708 960 0 0
decoration
visible 1
style 1
forecolor 1 1 1 1
backcolor 1 1 1 1
background "xpbar_stencilbase"
textscale 0.55
}
itemDef
{
rect 0 0 300 124 0 0
decoration
visible 1
style 1
forecolor 1 1 1 1
backcolor 0.5 0.5 0.5 1
background "white"
textscale 0.55
}
itemDef
{
rect 0 0 1708 480 0 0
decoration
visible 1
style 3
forecolor 1 1 1 0.75
background "mw2_popup_bg_fogstencil"
textscale 0.55
exp rect x ( 0 - ( ( float( milliseconds( ) % 60000 ) / 60000 ) * ( 854 ) ) )
}
itemDef
{
rect 0 0 -1708 -480 0 0
decoration
visible 1
style 3
forecolor 0.85 0.85 0.85 1
background "mw2_popup_bg_fogscroll"
textscale 0.55
exp rect x ( 0 - ( ( float( milliseconds( ) % 60000 ) / 60000 ) * ( 854 ) ) )
}
itemDef
{
rect 0 0 300 0 0 0
decoration
visible 1
style 3
forecolor 1 1 1 1
background "mockup_popup_bg_stencilfill"
textscale 0.55
exp rect h ( ( 24 + 5 * 20 ) )
}
itemDef
{
rect 0 0 -1708 -480 0 0
decoration
visible 1
style 3
forecolor 1 1 1 0.75
background "mw2_popup_bg_fogstencil"
textscale 0.55
exp rect x ( ( - 854 ) + ( ( float( milliseconds( ) % 50000 ) / 50000 ) * ( 854 ) ) )
}
itemDef
{
rect 0 0 -1708 -480 0 0
decoration
visible 1
style 3
forecolor 0.85 0.85 0.85 1
background "mw2_popup_bg_fogscroll"
textscale 0.55
exp rect x ( ( - 854 ) + ( ( float( milliseconds( ) % 50000 ) / 50000 ) * ( 854 ) ) )
}
itemDef
{
rect 0 0 300 0 1 1
decoration
visible 1
style 3
forecolor 1 1 1 0
background "small_box_lightfx"
textscale 0.55
exp rect h ( ( 24 + 5 * 20 ) )
}
itemDef
{
rect -64 -64 64 64 0 0
decoration
visible 1
style 3
forecolor 0 0 0 1
background "drop_shadow_tl"
textscale 0.55
visible when ( 1 )
}
itemDef
{
rect 0 -64 300 64 0 0
decoration
visible 1
style 3
forecolor 0 0 0 1
background "drop_shadow_t"
textscale 0.55
visible when ( 1 )
}
itemDef
{
rect 300 -64 64 64 0 0
decoration
visible 1
style 3
forecolor 0 0 0 1
background "drop_shadow_tr"
textscale 0.55
visible when ( 1 )
}
itemDef
{
rect 300 0 64 0 0 0
decoration
visible 1
style 3
forecolor 0 0 0 1
background "drop_shadow_r"
textscale 0.55
exp rect h ( ( 24 + 5 * 20 ) )
visible when ( 1 )
}
itemDef
{
rect 300 0 64 64 0 0
decoration
visible 1
style 3
forecolor 0 0 0 1
background "drop_shadow_br"
textscale 0.55
exp rect y ( ( 0 - 0 ) + ( ( 24 + 5 * 20 ) ) )
visible when ( 1 )
}
itemDef
{
rect 0 0 300 64 0 0
decoration
visible 1
style 3
forecolor 0 0 0 1
background "drop_shadow_b"
textscale 0.55
exp rect y ( ( 0 - 0 ) + ( ( 24 + 5 * 20 ) ) )
visible when ( 1 )
}
itemDef
{
rect -64 0 64 64 0 0
decoration
visible 1
style 3
forecolor 0 0 0 1
background "drop_shadow_bl"
textscale 0.55
exp rect y ( ( 0 - 0 ) + ( ( 24 + 5 * 20 ) ) )
visible when ( 1 )
}
itemDef
{
rect -64 0 64 0 0 0
decoration
visible 1
style 3
forecolor 0 0 0 1
background "drop_shadow_l"
textscale 0.55
exp rect h ( ( 24 + 5 * 20 ) )
visible when ( 1 )
}
itemDef
{
rect 0 0 300 24 0 0
decoration
visible 1
style 1
forecolor 1 1 1 1
background "gradient_fadein"
textfont 9
textalign 5
textalignx -4
textscale 0.375
text "@MENU_NOTICE"
}
itemDef
{
rect 4 20 292 42 0 0
decoration
autowrapped
visible 1
style 1
forecolor 1 1 1 1
textfont 3
textalign 5
textscale 0.375
visible when ( 1 )
exp text ( "@MENU_PROFILE_CREATION_FAILED" )
}
itemDef
{
name "ok"
rect 4 104 292 20 0 0
visible 1
group "mw2_popup_button"
style 1
forecolor 1 1 1 1
disablecolor 0.6 0.55 0.55 1
background "popup_button_selection_bar"
type 1
textfont 3
textalign 6
textalignx -24
textscale 0.375
text "@MENU_OK"
visible when ( 1 )
action
{
play "mouse_click";
close self;
}
onFocus
{
play "mouse_over";
if ( dvarstring( "gameMode" ) != "mp" )
{
setItemColor "mw2_popup_button" backcolor 0 0 0 0;
}
setItemColor self backcolor 0 0 0 1;
setLocalVarBool "ui_popupAButton" ( 1 );
}
leaveFocus
{
setItemColor self backcolor 1 1 1 0;
setLocalVarBool "ui_popupAButton" ( 0 );
}
}
}
}
| 0 | 0.700372 | 1 | 0.700372 | game-dev | MEDIA | 0.685662 | game-dev,desktop-app | 0.885415 | 1 | 0.885415 |
tado/ofxLiquidFun | 1,512 | libs/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h | /*
* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#ifndef B2_POLYGON_AND_CIRCLE_CONTACT_H
#define B2_POLYGON_AND_CIRCLE_CONTACT_H
#include <Box2D/Dynamics/Contacts/b2Contact.h>
class b2BlockAllocator;
class b2PolygonAndCircleContact : public b2Contact
{
public:
static b2Contact* Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator);
static void Destroy(b2Contact* contact, b2BlockAllocator* allocator);
b2PolygonAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB);
~b2PolygonAndCircleContact() {}
void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB);
};
#endif
| 0 | 0.530631 | 1 | 0.530631 | game-dev | MEDIA | 0.89806 | game-dev | 0.634085 | 1 | 0.634085 |
MegaMek/mekhq | 6,378 | MekHQ/src/mekhq/campaign/personnel/BodyLocation.java | /*
* Copyright (C) 2016-2025 The MegaMek Team. All Rights Reserved.
*
* This file is part of MekHQ.
*
* MekHQ is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License (GPL),
* version 3 or (at your option) any later version,
* as published by the Free Software Foundation.
*
* MekHQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* A copy of the GPL should have been included with this project;
* if not, see <https://www.gnu.org/licenses/>.
*
* NOTICE: The MegaMek organization is a non-profit group of volunteers
* creating free software for the BattleTech community.
*
* MechWarrior, BattleMech, `Mech and AeroTech are registered trademarks
* of The Topps Company, Inc. All Rights Reserved.
*
* Catalyst Game Labs and the Catalyst Game Labs logo are trademarks of
* InMediaRes Productions, LLC.
*
* MechWarrior Copyright Microsoft Corporation. MekHQ was created under
* Microsoft's "Game Content Usage Rules"
* <https://www.xbox.com/en-US/developers/rules> and it is not endorsed by or
* affiliated with Microsoft.
*/
package mekhq.campaign.personnel;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.Set;
import jakarta.xml.bind.annotation.adapters.XmlAdapter;
import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import mekhq.MekHQ;
import mekhq.campaign.personnel.BodyLocation.XMLAdapter;
@XmlJavaTypeAdapter(value = XMLAdapter.class)
public enum BodyLocation {
//region Enum Declarations
HEAD(0, "BodyLocation.HEAD.text"),
CHEST(3, "BodyLocation.CHEST.text"),
ABDOMEN(4, "BodyLocation.ABDOMEN.text"),
RIGHT_ARM(5, "BodyLocation.RIGHT_ARM.text", true),
LEFT_ARM(2, "BodyLocation.LEFT_ARM.text", true),
RIGHT_LEG(6, "BodyLocation.RIGHT_LEG.text", true),
LEFT_LEG(1, "BodyLocation.LEFT_LEG.text", true),
RIGHT_HAND(9, "BodyLocation.RIGHT_HAND.text", true, RIGHT_ARM),
LEFT_HAND(8, "BodyLocation.LEFT_HAND.text", true, LEFT_ARM),
RIGHT_FOOT(11, "BodyLocation.RIGHT_FOOT.text", true, RIGHT_LEG),
LEFT_FOOT(10, "BodyLocation.LEFT_FOOT.text", true, LEFT_LEG),
INTERNAL(7, "BodyLocation.INTERNAL.text"),
GENERIC(-1, "BodyLocation.GENERIC.text");
//endregion Enum Declarations
//region Variable Declarations
private final int id;
private final boolean limb; // Includes everything attached to a limb
private final String locationName;
private final BodyLocation parent;
/**
* We can't use an EnumSet here because it requires the whole enum to be initialised. We fix it later, in the static
* code block.
*/
private Set<BodyLocation> children = new HashSet<>();
//endregion Variable Declarations
//region Static Initialization
// Initialize by-id array lookup table
private static final BodyLocation[] idMap;
static {
int maxId = 0;
for (BodyLocation workTime : values()) {
maxId = Math.max(maxId, workTime.id);
}
idMap = new BodyLocation[maxId + 1];
Arrays.fill(idMap, GENERIC);
for (BodyLocation workTime : values()) {
if (workTime.id > 0) {
idMap[workTime.id] = workTime;
}
// Optimise the children sets (we can't do that in the constructor, since
// the EnumSet static methods require this enum to be fully initialized first).
if (workTime.children.isEmpty()) {
workTime.children = EnumSet.noneOf(BodyLocation.class);
} else {
workTime.children = EnumSet.copyOf(workTime.children);
}
}
}
//endregion Static Initialization
//region Constructors
BodyLocation(int id, String localizationString) {
this(id, localizationString, false, null);
}
BodyLocation(int id, String localizationString, boolean limb) {
this(id, localizationString, limb, null);
}
BodyLocation(int id, String localizationString, boolean limb, BodyLocation parent) {
final ResourceBundle resources = ResourceBundle.getBundle("mekhq.resources.Personnel",
MekHQ.getMHQOptions().getLocale());
this.id = id;
this.locationName = resources.getString(localizationString);
this.limb = limb;
this.parent = parent;
if (parent != null) {
parent.addChildLocation(this);
}
}
//endregion Constructors
//region Getters
public boolean isLimb() {
return limb;
}
public String locationName() {
return locationName;
}
public BodyLocation Parent() {
return parent;
}
//endregion Getters
/**
* @return the body location corresponding to the (old) ID
*/
public static BodyLocation of(int id) {
return ((id > 0) && (id < idMap.length)) ? idMap[id] : GENERIC;
}
/**
* @return the body location corresponding to the given string
*/
public static BodyLocation of(String str) {
try {
return of(Integer.parseInt(str));
} catch (NumberFormatException ignored) {
return valueOf(str.toUpperCase(Locale.ROOT));
}
}
private void addChildLocation(BodyLocation child) {
children.add(child);
}
public boolean isParentOf(BodyLocation child) {
if (children.contains(child)) {
return true;
}
for (BodyLocation myChild : children) {
if (myChild.isParentOf(child)) {
return true;
}
}
return false;
}
public boolean isChildOf(BodyLocation parent) {
return ((null != this.parent) && ((this.parent == parent) || this.parent.isChildOf(parent)));
}
public static final class XMLAdapter extends XmlAdapter<String, BodyLocation> {
@Override
public BodyLocation unmarshal(String v) {
return (null == v) ? null : BodyLocation.of(v);
}
@Override
public String marshal(BodyLocation v) {
return (null == v) ? null : v.toString();
}
}
}
| 0 | 0.691356 | 1 | 0.691356 | game-dev | MEDIA | 0.391362 | game-dev | 0.920506 | 1 | 0.920506 |
InfernumTeam/InfernumMode | 1,821 | Content/BehaviorOverrides/BossAIs/Perforators/FallingIchor.cs | using CalamityMod.NPCs.Perforator;
using Microsoft.Xna.Framework;
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
namespace InfernumMode.Content.BehaviorOverrides.BossAIs.Perforators
{
public class FallingIchor : ModProjectile
{
internal const float Gravity = 0.25f;
// public override void SetStaticDefaults() => DisplayName.SetDefault("Ichor");
public override void SetDefaults()
{
Projectile.width = Projectile.height = 12;
Projectile.hostile = true;
Projectile.tileCollide = false;
Projectile.timeLeft = 420;
Projectile.penetrate = -1;
}
public override void AI()
{
Projectile.tileCollide = Projectile.timeLeft < 300;
bool smallWormIsPresent = NPC.AnyNPCs(ModContent.NPCType<PerforatorHeadSmall>());
if (smallWormIsPresent)
Projectile.tileCollide = false;
Projectile.rotation = Projectile.velocity.ToRotation() + PiOver2;
bool shouldDie = Collision.SolidCollision(Projectile.position, Projectile.width, Projectile.height);
shouldDie &= !TileID.Sets.Platforms[Framing.GetTileSafely((int)Projectile.Center.X / 16, (int)Projectile.Center.Y / 16).TileType];
if (shouldDie && Projectile.tileCollide)
Projectile.Kill();
// Release blood idly.
Dust blood = Dust.NewDustDirect(Projectile.position, Projectile.width, Projectile.height, DustID.Blood, 0f, 0f, 100, default, 0.5f);
blood.velocity = Vector2.Zero;
blood.noGravity = true;
Projectile.velocity.Y += Gravity;
}
public override Color? GetAlpha(Color lightColor) => new Color(246, 195, 80, Projectile.alpha);
}
}
| 0 | 0.875902 | 1 | 0.875902 | game-dev | MEDIA | 0.988661 | game-dev | 0.937978 | 1 | 0.937978 |
QuestionableM/SM-ProximityVoiceChat | 2,807 | Dependencies/bullet3/BulletCollision/CollisionShapes/btTriangleMeshShape.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_TRIANGLE_MESH_SHAPE_H
#define BT_TRIANGLE_MESH_SHAPE_H
#include "btConcaveShape.h"
#include "btStridingMeshInterface.h"
///The btTriangleMeshShape is an internal concave triangle mesh interface. Don't use this class directly, use btBvhTriangleMeshShape instead.
ATTRIBUTE_ALIGNED16(class)
btTriangleMeshShape : public btConcaveShape
{
protected:
btVector3 m_localAabbMin;
btVector3 m_localAabbMax;
btStridingMeshInterface* m_meshInterface;
///btTriangleMeshShape constructor has been disabled/protected, so that users will not mistakenly use this class.
///Don't use btTriangleMeshShape but use btBvhTriangleMeshShape instead!
btTriangleMeshShape(btStridingMeshInterface * meshInterface);
public:
BT_DECLARE_ALIGNED_ALLOCATOR();
virtual ~btTriangleMeshShape();
virtual btVector3 localGetSupportingVertex(const btVector3& vec) const;
virtual btVector3 localGetSupportingVertexWithoutMargin(const btVector3& vec) const
{
btAssert(0);
return localGetSupportingVertex(vec);
}
void recalcLocalAabb();
virtual void getAabb(const btTransform& t, btVector3& aabbMin, btVector3& aabbMax) const;
virtual void processAllTriangles(btTriangleCallback * callback, const btVector3& aabbMin, const btVector3& aabbMax) const;
virtual void calculateLocalInertia(btScalar mass, btVector3 & inertia) const;
virtual void setLocalScaling(const btVector3& scaling);
virtual const btVector3& getLocalScaling() const;
btStridingMeshInterface* getMeshInterface()
{
return m_meshInterface;
}
const btStridingMeshInterface* getMeshInterface() const
{
return m_meshInterface;
}
const btVector3& getLocalAabbMin() const
{
return m_localAabbMin;
}
const btVector3& getLocalAabbMax() const
{
return m_localAabbMax;
}
//debugging
virtual const char* getName() const { return "TRIANGLEMESH"; }
};
#endif //BT_TRIANGLE_MESH_SHAPE_H
| 0 | 0.909474 | 1 | 0.909474 | game-dev | MEDIA | 0.991165 | game-dev | 0.814451 | 1 | 0.814451 |
swganh/mmoserver | 4,345 | src/ZoneServer/HouseObject.cpp |
/*
---------------------------------------------------------------------------------------
This source file is part of SWG:ANH (Star Wars Galaxies - A New Hope - Server Emulator)
For more information, visit http://www.swganh.com
Copyright (c) 2006 - 2010 The SWG:ANH Team
---------------------------------------------------------------------------------------
Use of this source code is governed by the GPL v3 license that can be found
in the COPYING file or at http://www.gnu.org/licenses/gpl-3.0.html
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
---------------------------------------------------------------------------------------
*/
#include "ObjectFactory.h"
#include "HouseObject.h"
#include "PlayerObject.h"
#include "Inventory.h"
#include "CellObject.h"
#include "ResourceContainer.h"
#include "StructureManager.h"
#include "UIManager.h"
#include "MessageLib/MessageLib.h"
#include "DatabaseManager/Database.h"
#include "DatabaseManager/DatabaseResult.h"
#include "DatabaseManager/DataBinding.h"
#include <cassert>
//=============================================================================
HouseObject::HouseObject() : BuildingObject()
{
mType = ObjType_Building;
setWidth(64);
setHeight(64);
}
//=============================================================================
HouseObject::~HouseObject()
{
}
void HouseObject::checkCellPermission(PlayerObject* player)
{
if(this->getPublic())
{
//structure is public - are we banned ?
StructureAsyncCommand command;
command.Command = Structure_Command_CellEnterDenial;
command.PlayerId = player->getId();
command.StructureId = this->getId();
gStructureManager->checkNameOnPermissionList(this->getId(),player->getId(),player->getFirstName().getAnsi(),"BAN",command);
}
else
{
//structure is private - do we have access ?
StructureAsyncCommand command;
command.Command = Structure_Command_CellEnter;
command.PlayerId = player->getId();
command.StructureId = this->getId();
gStructureManager->checkNameOnPermissionList(this->getId(),player->getId(),player->getFirstName().getAnsi(),"ENTRY",command);
}
}
//========================================================================0
//
//
void HouseObject::handleObjectReady(Object* object,DispatchClient* client, uint64 hopper)
{
Item* item = dynamic_cast<Item*>(gWorldManager->getObjectById(hopper));
if(!item)
{
assert(false && "HouseObject::handleObjectReady could not find hopper");
}
}
//=============================================================================
//handles the radial selection
void HouseObject::handleObjectMenuSelect(uint8 messageType,Object* srcObject)
{
PlayerObject* player = dynamic_cast<PlayerObject*>(srcObject);
if(!player)
{
return;
}
}
//=============================================================================
// not needed - this is handled over the structures terminal
void HouseObject::prepareCustomRadialMenu(CreatureObject* creatureObject, uint8 itemCount)
{
}
void HouseObject::handleDatabaseJobComplete(void* ref,DatabaseResult* result)
{
StructureManagerAsyncContainer* asynContainer = (StructureManagerAsyncContainer*)ref;
// switch(asynContainer->mQueryType)
// {
// default:break;
// }
SAFE_DELETE(asynContainer);
}
bool HouseObject::hasAdmin(uint64 id)
{
ObjectIDList adminList = getHousingList();
ObjectIDList::iterator it = adminList.begin();
while (it != adminList.end())
{
if( id == (*it))
return true;
it++;
}
return false;
}
| 0 | 0.75963 | 1 | 0.75963 | game-dev | MEDIA | 0.725168 | game-dev | 0.736441 | 1 | 0.736441 |
Deadrik/TFCraft | 4,749 | src/Common/com/bioxx/tfc/Blocks/Terrain/BlockSand.java | package com.bioxx.tfc.Blocks.Terrain;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import com.bioxx.tfc.Reference;
import com.bioxx.tfc.Blocks.BlockTerra;
import com.bioxx.tfc.Core.TFCTabs;
import com.bioxx.tfc.api.Constant.Global;
public class BlockSand extends BlockTerra
{
protected IIcon[] icons = new IIcon[Global.STONE_ALL.length];
protected int textureOffset;
public BlockSand(int texOff)
{
super(Material.sand);
this.setCreativeTab(TFCTabs.TFC_BUILDING);
textureOffset = texOff;
}
@SideOnly(Side.CLIENT)
@Override
/**
* returns a list of blocks with the same ID, but different meta (eg: wood returns 4 blocks)
*/
public void getSubBlocks(Item item, CreativeTabs tabs, List list)
{
// Change to false if this block should not be added to the creative tab
Boolean addToCreative = true;
if(addToCreative)
{
int count;
if(textureOffset == 0) count = 16;
else count = Global.STONE_ALL.length - 16;
for(int i = 0; i < count; i++)
list.add(new ItemStack(item, 1, i));
}
}
@Override
public int damageDropped(int dmg)
{
return dmg;
}
/**
* Retrieves the block texture to use based on the display side. Args: iBlockAccess, x, y, z, side
*/
@Override
public IIcon getIcon(IBlockAccess bAccess, int x, int y, int z, int side)
{
int meta = bAccess.getBlockMetadata(x, y, z);
if(meta >= icons.length) return icons[icons.length - 1];
return icons[meta];
}
/**
* From the specified side and block metadata retrieves the blocks texture. Args: side, metadata
*/
@Override
public IIcon getIcon(int side, int meta)
{
if(meta >= icons.length) return icons[icons.length - 1];
return icons[meta];
}
@Override
public void registerBlockIcons(IIconRegister registerer)
{
int count = (textureOffset == 0 ? 16 : Global.STONE_ALL.length - 16);
icons = new IIcon[count];
for(int i = 0; i < count; i++)
icons[i] = registerer.registerIcon(Reference.MOD_ID + ":" + "sand/Sand " + Global.STONE_ALL[i + textureOffset]);
}
@Override
public void onBlockAdded(World world, int x, int y, int z)
{
world.scheduleBlockUpdate(x, y, z, this, tickRate(world));
}
@Override
public void updateTick(World world, int x, int y, int z, Random random)
{
if (!world.isRemote && world.doChunksNearChunkExist(x, y, z, 1))
{
int meta = world.getBlockMetadata(x, y, z);
boolean canFallOneBelow = BlockCollapsible.canFallBelow(world, x, y - 1, z);
byte count = 0;
List<Integer> sides = new ArrayList<Integer>();
if (world.isAirBlock(x + 1, y, z))
{
count++;
if (BlockCollapsible.canFallBelow(world, x + 1, y - 1, z))
sides.add(0);
}
if (world.isAirBlock(x, y, z + 1))
{
count++;
if (BlockCollapsible.canFallBelow(world, x, y - 1, z + 1))
sides.add(1);
}
if (world.isAirBlock(x - 1, y, z))
{
count++;
if (BlockCollapsible.canFallBelow(world, x - 1, y - 1, z))
sides.add(2);
}
if (world.isAirBlock(x, y, z - 1))
{
count++;
if (BlockCollapsible.canFallBelow(world, x, y - 1, z - 1))
sides.add(3);
}
if (!canFallOneBelow && count > 2 && !sides.isEmpty())
{
switch (sides.get(random.nextInt(sides.size())))
{
case 0:
{
world.setBlockToAir(x, y, z);
world.setBlock(x + 1, y, z, this, meta, 0x2);
BlockCollapsible.tryToFall(world, x + 1, y, z, this);
break;
}
case 1:
{
world.setBlockToAir(x, y, z);
world.setBlock(x, y, z + 1, this, meta, 0x2);
BlockCollapsible.tryToFall(world, x, y, z + 1, this);
break;
}
case 2:
{
world.setBlockToAir(x, y, z);
world.setBlock(x - 1, y, z, this, meta, 0x2);
BlockCollapsible.tryToFall(world, x - 1, y, z, this);
break;
}
case 3:
{
world.setBlockToAir(x, y, z);
world.setBlock(x, y, z - 1, this, meta, 0x2);
BlockCollapsible.tryToFall(world, x, y, z - 1, this);
break;
}
}
}
else if (canFallOneBelow)
{
BlockCollapsible.tryToFall(world, x, y, z, this);
}
}
}
@Override
public void onNeighborBlockChange(World world, int x, int y, int z, Block block)
{
if(!world.isRemote)
{
BlockCollapsible.tryToFall(world, x, y, z, this);
world.scheduleBlockUpdate(x, y, z, this, tickRate(world));
}
}
}
| 0 | 0.661206 | 1 | 0.661206 | game-dev | MEDIA | 0.991033 | game-dev | 0.885818 | 1 | 0.885818 |
SkyblockerMod/Skyblocker | 2,163 | src/main/java/de/hysky/skyblocker/skyblock/tabhud/widget/CommsWidget.java | package de.hysky.skyblocker.skyblock.tabhud.widget;
import de.hysky.skyblocker.annotations.RegisterWidget;
import de.hysky.skyblocker.skyblock.tabhud.util.Ico;
import de.hysky.skyblocker.skyblock.tabhud.widget.component.Component;
import de.hysky.skyblocker.skyblock.tabhud.widget.component.Components;
import net.minecraft.text.MutableText;
import net.minecraft.text.Text;
import net.minecraft.util.Formatting;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import com.mojang.logging.LogUtils;
// this widget shows the status of the king's commissions.
// (dwarven mines and crystal hollows)
@RegisterWidget
public class CommsWidget extends TabHudWidget {
private static final Logger LOGGER = LogUtils.getLogger();
public static final String ID = "commissions";
private static final MutableText TITLE = Text.literal("Commissions").formatted(Formatting.DARK_AQUA,
Formatting.BOLD);
// match a comm
// group 1: comm name
// group 2: comm progress (without "%" for comms that show a percentage)
public static final Pattern COMM_PATTERN = Pattern.compile("(?<name>.*): (?<progress>.*)%?");
public CommsWidget() {
super("Commissions", TITLE, Formatting.DARK_AQUA.getColorValue());
}
@Override
public void updateContent(List<Text> lines) {
if (lines.isEmpty()) {
this.addComponent(Components.iconTextComponent());
return;
}
for (Text line : lines) {
Matcher m = COMM_PATTERN.matcher(line.getString());
if (m.matches()) {
Component component;
String name = m.group("name");
String progress = m.group("progress");
if (progress.equals("DONE")) {
component = Components.progressComponent(Ico.BOOK, Text.of(name), Text.of(progress), 100f);
} else {
float percent;
try {
percent = Float.parseFloat(progress.substring(0, progress.length() - 1));
} catch (NumberFormatException e) {
LOGGER.error("[Skyblocker Comms Widget] Failed to parse number.", e);
percent = 0;
}
component = Components.progressComponent(Ico.BOOK, Text.of(name), percent);
}
this.addComponent(component);
}
}
}
}
| 0 | 0.820526 | 1 | 0.820526 | game-dev | MEDIA | 0.462119 | game-dev | 0.968428 | 1 | 0.968428 |
Better-Politics-Mod/Better-Politics-Mod-Vic-3 | 3,420 | better-politics-mod/localization/japanese/replace/zz_bpm_content_204_l_japanese.yml | l_japanese:
je_south_american_national_identity_emergence_reason: "The independence of [ROOT.GetCountry.GetName] from Spain has given rise to rumblings of nationalism across the nation. As our nation advances into the future, our intellectuals seek to formulate a new identity, one that is distinctly and solely [SCOPE.sCulture('new_national_culture').GetName].\n\nThe following conditions will benefit the process of developing our #bold national identity#!:\n• Pro [GetLawType('law_repeatable_culture_promote_patriotic_values').GetName] [Concept('concept_interest_group','$concept_interest_groups$')] that are [concept_in_government] or have high [concept_clout]\n• Ongoing [Concept('concept_war','$concept_wars$')] with high [concept_war_support]\n• [GetBuildingType('building_university').GetName], [GetBuildingType('building_arts_academy').GetName], and [GetBuildingType('building_government_administration').GetName] buildings with high [concept_occupancy]\n• High national [concept_prestige]\n• Not owning non-[SCOPE.sCulture('old_national_culture').GetName] [Concept('concept_homeland','$concept_homelands$')]\n• Enacting [GetLawType('law_repeatable_culture_promote_patriotic_values').GetName]\n\nThe progress of this #bold national awakening#! is expected to progress by #tooltippable;tooltip:[Country.GetTooltipTag],je_south_american_national_identity_emergence_special_tooltip [Country.MakeScope.Var('national_identity_progress_var_next').GetValue|+=]#! next month.\n\n@warning! Completing this [concept_journal_entry] will exclude [ROOT.GetCountry.GetName] from pursuing #bold greater pan-national ambitions#!"
je_south_american_national_identity_emergence_special_tooltip: "This rate is determined by the following:\n#variable [Country.MakeScope.Var('national_identity_progress_from_igs').GetValue|+=]#! from [concept_clout] of Pro [GetLawType('law_repeatable_culture_promote_patriotic_values').GetName] [Concept('concept_interest_group','$concept_interest_groups$')]\n#variable [Country.MakeScope.Var('national_identity_progress_from_wars').GetValue|+=]#! from ongoing [Concept('concept_war','$concept_wars$')]\n#variable [Country.MakeScope.Var('national_identity_progress_from_universities').GetValue|+=]#! from [GetBuildingType('building_university').GetName], [GetBuildingType('building_arts_academy').GetName], and [GetBuildingType('building_government_administration').GetName] buildings\n#variable [Country.MakeScope.Var('national_identity_progress_from_prestige').GetValue|+=]#! from [concept_prestige]\n#variable [Country.MakeScope.Var('national_identity_progress_from_homelands').GetValue|+=]#! from owning non-[Concept('concept_primary_cultures','$concept_primary_culture$')] [Concept('concept_homeland','$concept_homelands$')]\n#variable [Country.MakeScope.Var('national_identity_progress_from_law').GetValue|+=]#! from [GetLawType('law_repeatable_culture_promote_patriotic_values').GetName]\n#variable [Country.MakeScope.Var('national_identity_progress_var_add').GetValue|+=]#! from other effects"
TRIGGER_POLITICAL_MOVEMENT_SUPPORT: "Support is $COMPARATOR$ #variable $NUM|%0$#!"
TRIGGER_POLITICAL_MOVEMENT_SUPPORT_NOT: "Support is #bold not #!$COMPARATOR$ #variable $NUM|%0$#!"
TRIGGER_POLITICAL_MOVEMENT_RADICALISM: "Radicalism is $COMPARATOR$ #variable $NUM|%0$#!"
TRIGGER_POLITICAL_MOVEMENT_RADICALISM_NOT: "Radicalism is #bold not #!$COMPARATOR$ #variable $NUM|%0$#!"
| 0 | 0.650098 | 1 | 0.650098 | game-dev | MEDIA | 0.455247 | game-dev | 0.505175 | 1 | 0.505175 |
AscEmu/AscEmu | 28,433 | src/world/Server/Packets/Handlers/TradeHandler.cpp | /*
Copyright (c) 2014-2025 AscEmu Team <http://www.ascemu.org>
This file is released under the MIT license. See README-MIT for more information.
*/
#include "Server/Packets/CmsgClearTradeItem.h"
#include "Server/Packets/CmsgInitiateTrade.h"
#include "Server/Packets/SmsgTradeStatus.h"
#include "Server/Packets/CmsgSetTradeGold.h"
#include "Server/Packets/CmsgSetTradeItem.h"
#include "Server/World.h"
#include "Server/WorldSession.h"
#include "Spell/Definitions/SpellCastTargetFlags.hpp"
#include "Objects/Units/Players/Player.hpp"
#include "Objects/Units/Players/PlayerDefines.hpp"
#include "Objects/Units/UnitDefines.hpp"
#include "Map/Management/MapMgr.hpp"
#include "Objects/Container.hpp"
#include "Management/ItemInterface.h"
#include "Objects/Units/Players/TradeData.hpp"
#include "Server/WorldSessionLog.hpp"
#include "Spell/Spell.hpp"
#include "Spell/SpellMgr.hpp"
using namespace AscEmu::Packets;
void WorldSession::handleInitiateTradeOpcode(WorldPacket& recvPacket)
{
#if VERSION_STRING < Cata
CmsgInitiateTrade srlPacket;
if (!srlPacket.deserialise(recvPacket))
return;
const auto playerTarget = _player->getWorldMapPlayer(srlPacket.guid.getGuidLow());
#else
ObjectGuid targetGuid;
targetGuid[0] = recvPacket.readBit();
targetGuid[3] = recvPacket.readBit();
targetGuid[5] = recvPacket.readBit();
targetGuid[1] = recvPacket.readBit();
targetGuid[4] = recvPacket.readBit();
targetGuid[6] = recvPacket.readBit();
targetGuid[7] = recvPacket.readBit();
targetGuid[2] = recvPacket.readBit();
recvPacket.ReadByteSeq(targetGuid[7]);
recvPacket.ReadByteSeq(targetGuid[4]);
recvPacket.ReadByteSeq(targetGuid[3]);
recvPacket.ReadByteSeq(targetGuid[5]);
recvPacket.ReadByteSeq(targetGuid[1]);
recvPacket.ReadByteSeq(targetGuid[2]);
recvPacket.ReadByteSeq(targetGuid[6]);
recvPacket.ReadByteSeq(targetGuid[0]);
const auto playerTarget = _player->getWorldMapPlayer(static_cast<uint32_t>(targetGuid));
#endif
if (_player->m_TradeData != nullptr)
{
sendTradeResult(TRADE_STATUS_ALREADY_TRADING);
return;
}
if (playerTarget == nullptr || playerTarget == _player)
{
sendTradeResult(TRADE_STATUS_PLAYER_NOT_FOUND);
return;
}
if (playerTarget->CalcDistance(_player) > 10.0f)
{
sendTradeResult(TRADE_STATUS_TOO_FAR_AWAY);
return;
}
if (playerTarget->m_TradeData != nullptr)
{
sendTradeResult(TRADE_STATUS_PLAYER_BUSY);
return;
}
if (_player->hasUnitStateFlag(UNIT_STATE_STUNNED))
{
sendTradeResult(TRADE_STATUS_YOU_STUNNED);
return;
}
if (playerTarget->hasUnitStateFlag(UNIT_STATE_STUNNED))
{
sendTradeResult(TRADE_STATUS_TARGET_STUNNED);
return;
}
if (!_player->isAlive())
{
sendTradeResult(TRADE_STATUS_YOU_DEAD);
return;
}
if (!playerTarget->isAlive())
{
sendTradeResult(TRADE_STATUS_TARGET_DEAD);
return;
}
if (LoggingOut)
{
sendTradeResult(TRADE_STATUS_YOU_LOGOUT);
return;
}
if (playerTarget->getSession()->LoggingOut)
{
sendTradeResult(TRADE_STATUS_TARGET_LOGOUT);
return;
}
if (playerTarget->getTeam() != _player->getTeam() && !hasPermissions() && !worldConfig.player.isInterfactionTradeEnabled)
{
sendTradeResult(TRADE_STATUS_WRONG_FACTION);
return;
}
_player->m_TradeData = std::make_unique<TradeData>(_player, playerTarget);
playerTarget->m_TradeData = std::make_unique<TradeData>(playerTarget, _player);
#if VERSION_STRING < Cata
playerTarget->m_session->sendTradeResult(TRADE_STATUS_PROPOSED, _player->getGuid());
#else
WorldPacket data(SMSG_TRADE_STATUS, 12);
data.writeBit(false);
data.writeBits(TRADE_STATUS_PROPOSED, 5);
ObjectGuid source_guid = _player->getGuid();
data.WriteByteMask(source_guid[2]);
data.WriteByteMask(source_guid[4]);
data.WriteByteMask(source_guid[6]);
data.WriteByteMask(source_guid[0]);
data.WriteByteMask(source_guid[1]);
data.WriteByteMask(source_guid[3]);
data.WriteByteMask(source_guid[7]);
data.WriteByteMask(source_guid[5]);
data.WriteByteSeq(source_guid[4]);
data.WriteByteSeq(source_guid[1]);
data.WriteByteSeq(source_guid[2]);
data.WriteByteSeq(source_guid[3]);
data.WriteByteSeq(source_guid[0]);
data.WriteByteSeq(source_guid[7]);
data.WriteByteSeq(source_guid[6]);
data.WriteByteSeq(source_guid[5]);
data << uint32_t(0); // unk
playerTarget->getSession()->SendPacket(&data);
#endif
}
void WorldSession::handleBeginTradeOpcode(WorldPacket& /*recvPacket*/)
{
const auto tradeData = _player->getTradeData();
if (tradeData == nullptr)
{
sendTradeResult(TRADE_STATUS_PLAYER_NOT_FOUND);
return;
}
if (_player->CalcDistance(tradeData->getTradeTarget()) > 10.0f)
{
sendTradeResult(TRADE_STATUS_TOO_FAR_AWAY);
return;
}
sendTradeResult(TRADE_STATUS_INITIATED);
tradeData->getTradeTarget()->getSession()->sendTradeResult(TRADE_STATUS_INITIATED);
}
void WorldSession::handleSetTradeGold(WorldPacket& recvPacket)
{
#if VERSION_STRING < Cata
CmsgSetTradeGold srlPacket;
if (!srlPacket.deserialise(recvPacket))
return;
const auto tradeMoney = srlPacket.tradeGoldAmount;
#else
uint64_t tradeMoney;
recvPacket >> tradeMoney;
#endif
const auto tradeData = _player->getTradeData();
if (tradeData == nullptr)
return;
tradeData->setTradeMoney(tradeMoney);
}
void WorldSession::handleAcceptTrade(WorldPacket& /*recvPacket*/)
{
const auto tradeData = _player->getTradeData();
if (tradeData == nullptr)
return;
const auto tradeTarget = tradeData->getTradeTarget();
if (tradeTarget == nullptr)
return;
const auto targetTradeData = tradeTarget->getTradeData();
if (targetTradeData == nullptr)
return;
tradeData->setTradeAccepted(true);
if (tradeData->getTradeMoney() > _player->getCoinage())
{
tradeData->setTradeAccepted(false, true);
return;
}
if (targetTradeData->getTradeMoney() > tradeTarget->getCoinage())
{
targetTradeData->setTradeAccepted(false, true);
return;
}
if (targetTradeData->getTradeMoney() > 0)
{
// Check for gold cap
if (worldConfig.player.isGoldCapEnabled && ((_player->getCoinage() + targetTradeData->getTradeMoney()) > worldConfig.player.limitGoldAmount))
{
_player->getItemInterface()->buildInventoryChangeError(nullptr, nullptr, INV_ERR_TOO_MUCH_GOLD);
tradeData->setTradeAccepted(false, true);
return;
}
}
if (tradeData->getTradeMoney() > 0)
{
// Check for gold cap
if (worldConfig.player.isGoldCapEnabled && (tradeTarget->getCoinage() + tradeData->getTradeMoney()) > worldConfig.player.limitGoldAmount)
{
tradeTarget->getItemInterface()->buildInventoryChangeError(nullptr, nullptr, INV_ERR_TOO_MUCH_GOLD);
targetTradeData->setTradeAccepted(false, true);
return;
}
}
uint32_t itemCount = 0, targetItemCount = 0;
for (uint8_t i = 0; i < TRADE_SLOT_TRADED_COUNT; ++i)
{
Item* tradeItem = tradeData->getTradeItem(TradeSlots(i));
if (tradeItem != nullptr)
{
if (tradeItem->isContainer())
{
const auto container = dynamic_cast<Container*>(tradeItem);
if (container != nullptr && container->hasItems())
{
_player->cancelTrade(true);
return;
}
}
if (!tradeItem->isTradeableWith(tradeTarget))
{
_player->cancelTrade(true);
return;
}
++itemCount;
}
tradeItem = targetTradeData->getTradeItem(TradeSlots(i));
if (tradeItem != nullptr)
{
if (tradeItem->isContainer())
{
const auto container = dynamic_cast<Container*>(tradeItem);
if (container != nullptr && container->hasItems())
{
tradeTarget->cancelTrade(true);
return;
}
}
if (!tradeItem->isTradeableWith(tradeTarget))
{
tradeTarget->cancelTrade(true);
return;
}
++targetItemCount;
}
}
// Check if player has enough free slots
if ((_player->getItemInterface()->CalculateFreeSlots(nullptr) + itemCount) < targetItemCount)
{
_player->getItemInterface()->buildInventoryChangeError(nullptr, nullptr, INV_ERR_INVENTORY_FULL);
tradeData->setTradeAccepted(false, true);
return;
}
// If trade target has not accepted, do not proceed
if (!targetTradeData->isTradeAccepted())
{
tradeTarget->getSession()->sendTradeResult(TRADE_STATUS_ACCEPTED);
return;
}
// Both parties have accepted, proceed
tradeTarget->getSession()->sendTradeResult(TRADE_STATUS_ACCEPTED);
// Check player's spell on the lowest item
Spell* playerSpell = nullptr;
SpellCastTargets playerSpellTargets;
if (tradeData->getSpell() != 0)
{
const auto spellInfo = sSpellMgr.getSpellInfo(tradeData->getSpell());
const auto castedFromItem = tradeData->getSpellCastItem();
// Check if the spell is valid and target item exists
if (spellInfo == nullptr || (castedFromItem == nullptr && tradeData->hasSpellCastItem()) || targetTradeData->getTradeItem(TRADE_SLOT_NONTRADED) == nullptr)
{
tradeData->setTradeSpell(0);
return;
}
// Generate spell target
playerSpellTargets.setItemTarget(TRADE_SLOT_NONTRADED);
playerSpellTargets.addTargetMask(TARGET_FLAG_TRADE_ITEM);
// Create spell
playerSpell = sSpellMgr.newSpell(_player, spellInfo, true, nullptr);
playerSpell->setItemCaster(castedFromItem);
playerSpell->m_targets = playerSpellTargets;
// Check if player is able to cast the spell
const auto castResult = playerSpell->canCast(true, 0, 0);
if (castResult != SPELL_CAST_SUCCESS)
{
playerSpell->sendCastResult(castResult);
tradeData->setTradeSpell(0);
delete playerSpell;
return;
}
}
// Check trader's spell on the lowest item
Spell* traderSpell = nullptr;
SpellCastTargets traderSpellTargets;
if (targetTradeData->getSpell() != 0)
{
const auto spellInfo = sSpellMgr.getSpellInfo(targetTradeData->getSpell());
const auto castedFromItem = targetTradeData->getSpellCastItem();
// Check if the spell is valid and target item exists
if (spellInfo == nullptr || (castedFromItem == nullptr && targetTradeData->hasSpellCastItem()) || tradeData->getTradeItem(TRADE_SLOT_NONTRADED) == nullptr)
{
targetTradeData->setTradeSpell(0);
return;
}
// Generate spell target
traderSpellTargets.setItemTarget(TRADE_SLOT_NONTRADED);
traderSpellTargets.addTargetMask(TARGET_FLAG_TRADE_ITEM);
// Create spell
traderSpell = sSpellMgr.newSpell(tradeData->getTradeTarget(), spellInfo, true, nullptr);
traderSpell->setItemCaster(castedFromItem);
traderSpell->m_targets = traderSpellTargets;
// Check if trader is able to cast the spell
const auto castResult = traderSpell->canCast(true, 0, 0);
if (castResult != SPELL_CAST_SUCCESS)
{
traderSpell->sendCastResult(castResult);
targetTradeData->setTradeSpell(0);
delete traderSpell;
return;
}
}
std::array<std::unique_ptr<Item>, TRADE_SLOT_TRADED_COUNT> tradeItems = { nullptr };
std::array<std::unique_ptr<Item>, TRADE_SLOT_TRADED_COUNT> targetTradeItems = { nullptr };
// Remove items
for (uint8_t i = 0; i < TRADE_SLOT_TRADED_COUNT; ++i)
{
if (auto* const tradeItem = tradeData->getTradeItem(static_cast<TradeSlots>(i)))
{
tradeItem->setGiftCreatorGuid(_player->getGuid());
// TODO: what about temp enchantments and refundable items since old owner has pointers to the item
#if VERSION_STRING >= WotLK
if (tradeItem->hasFlags(ITEM_FLAG_BOP_TRADEABLE))
_player->getItemInterface()->removeTradeableItem(tradeItem);
#endif
tradeItems[i] = _player->getItemInterface()->SafeRemoveAndRetreiveItemByGuid(tradeItem->getGuid(), true);
}
if (auto* const targetTradeItem = targetTradeData->getTradeItem(static_cast<TradeSlots>(i)))
{
targetTradeItem->setGiftCreatorGuid(tradeTarget->getGuid());
#if VERSION_STRING >= WotLK
if (targetTradeItem->hasFlags(ITEM_FLAG_BOP_TRADEABLE))
tradeTarget->getItemInterface()->removeTradeableItem(targetTradeItem);
#endif
targetTradeItems[i] = tradeTarget->getItemInterface()->SafeRemoveAndRetreiveItemByGuid(targetTradeItem->getGuid(), true);
}
}
// Add items
for (uint8_t i = 0; i < TRADE_SLOT_TRADED_COUNT; ++i)
{
if (tradeItems[i] != nullptr)
{
tradeItems[i]->setOwner(tradeTarget);
#if VERSION_STRING >= WotLK
if (tradeItems[i]->hasFlags(ITEM_FLAG_BOP_TRADEABLE))
tradeTarget->getItemInterface()->addTradeableItem(tradeItems[i].get());
#endif
tradeTarget->getItemInterface()->AddItemToFreeSlot(std::move(tradeItems[i]));
}
if (targetTradeItems[i] != nullptr)
{
targetTradeItems[i]->setOwner(_player);
#if VERSION_STRING >= WotLK
if (targetTradeItems[i]->hasFlags(ITEM_FLAG_BOP_TRADEABLE))
_player->getItemInterface()->addTradeableItem(targetTradeItems[i].get());
#endif
_player->getItemInterface()->AddItemToFreeSlot(std::move(targetTradeItems[i]));
}
}
// Trade money
if (targetTradeData->getTradeMoney() > 0)
{
#if VERSION_STRING < Cata
_player->modCoinage((int32_t)targetTradeData->getTradeMoney());
tradeTarget->modCoinage(-(int32_t)targetTradeData->getTradeMoney());
#else
_player->modCoinage((int64_t)targetTradeData->getTradeMoney());
tradeTarget->modCoinage(-(int64_t)targetTradeData->getTradeMoney());
#endif
}
if (tradeData->getTradeMoney() > 0)
{
#if VERSION_STRING < Cata
tradeTarget->modCoinage((int32_t)tradeData->getTradeMoney());
_player->modCoinage(-(int32_t)tradeData->getTradeMoney());
#else
tradeTarget->modCoinage((int64_t)tradeData->getTradeMoney());
_player->modCoinage(-(int64_t)tradeData->getTradeMoney());
#endif
}
// Cast spells
if (playerSpell != nullptr)
playerSpell->prepare(&playerSpellTargets);
if (traderSpell != nullptr)
traderSpell->prepare(&traderSpellTargets);
_player->m_TradeData = nullptr;
tradeTarget->m_TradeData = nullptr;
_player->getSession()->sendTradeResult(TRADE_STATUS_COMPLETE);
tradeTarget->getSession()->sendTradeResult(TRADE_STATUS_COMPLETE);
_player->saveToDB(false);
tradeTarget->saveToDB(false);
}
void WorldSession::handleCancelTrade(WorldPacket& /*recvPacket*/)
{
if (_player != nullptr)
_player->cancelTrade(true);
}
void WorldSession::handleSetTradeItem(WorldPacket& recvPacket)
{
CmsgSetTradeItem srlPacket;
if (!srlPacket.deserialise(recvPacket))
return;
const auto tradeData = _player->getTradeData();
if (tradeData == nullptr)
return;
if (srlPacket.tradeSlot >= TRADE_SLOT_COUNT)
return;
const auto playerTarget = tradeData->getTradeTarget();
if (playerTarget == nullptr)
return;
const auto tradeItem = _player->getItemInterface()->GetInventoryItem(srlPacket.sourceBag, srlPacket.sourceSlot);
if (tradeItem == nullptr)
return;
if (srlPacket.tradeSlot < TRADE_SLOT_NONTRADED)
{
if (tradeItem->isAccountbound())
return;
if (!tradeItem->isTradeableWith(tradeData->getTradeTarget()))
{
sCheatLog.writefromsession(this, "tried to cheat trade a soulbound item");
// not a good idea since we can trade soulbound items if item flag is set.
// Would Disconnect the Trader when the Trader is not on the allowedGuids list.
//Disconnect();
return;
}
}
if (tradeItem->isContainer())
{
const auto container = dynamic_cast<Container*>(tradeItem);
if (container != nullptr && container->hasItems())
{
_player->getItemInterface()->buildInventoryChangeError(tradeItem, nullptr, INV_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS);
return;
}
}
for (uint8_t i = 0; i < TRADE_SLOT_COUNT; ++i)
{
if (tradeData->getTradeItem(TradeSlots(i)) == tradeItem || playerTarget->getTradeData()->getTradeItem(TradeSlots(i)) == tradeItem)
{
sCheatLog.writefromsession(this, "tried to dupe an item through trade");
Disconnect();
return;
}
}
if (srlPacket.sourceSlot >= INVENTORY_SLOT_BAG_START && srlPacket.sourceSlot < INVENTORY_SLOT_BAG_END)
{
const auto item = _player->getItemInterface()->GetInventoryItem(srlPacket.sourceBag);
if (item == nullptr || srlPacket.sourceSlot >= item->getItemProperties()->ContainerSlots)
{
sCheatLog.writefromsession(this, "tried to cheat trade a soulbound item");
Disconnect();
}
}
tradeData->setTradeItem(TradeSlots(srlPacket.tradeSlot), tradeItem);
}
void WorldSession::handleClearTradeItem(WorldPacket& recvPacket)
{
CmsgClearTradeItem srlPacket;
if (!srlPacket.deserialise(recvPacket))
return;
const auto tradeData = _player->getTradeData();
if (tradeData == nullptr)
return;
if (srlPacket.tradeSlot >= TRADE_SLOT_COUNT)
return;
tradeData->setTradeItem(TradeSlots(srlPacket.tradeSlot), nullptr);
}
void WorldSession::handleBusyTrade(WorldPacket& /*recvPacket*/)
{
#if VERSION_STRING < Cata
const auto tradeData = _player->getTradeData();
if (tradeData == nullptr)
{
_player->getSession()->sendTradeResult(TRADE_STATUS_PLAYER_NOT_FOUND);
return;
}
_player->getSession()->sendTradeResult(TRADE_STATUS_PLAYER_BUSY);
tradeData->getTradeTarget()->getSession()->sendTradeResult(TRADE_STATUS_PLAYER_BUSY);
_player->cancelTrade(false, true);
#endif
}
void WorldSession::handleIgnoreTrade(WorldPacket& /*recvPacket*/)
{
#if VERSION_STRING < Cata
const auto tradeData = _player->getTradeData();
if (tradeData == nullptr)
{
_player->getSession()->sendTradeResult(TRADE_STATUS_PLAYER_NOT_FOUND);
return;
}
_player->getSession()->sendTradeResult(TRADE_STATUS_IGNORES_YOU);
tradeData->getTradeTarget()->getSession()->sendTradeResult(TRADE_STATUS_IGNORES_YOU);
// Client sends this opcode after trade is created so TradeData must be cleaned
_player->cancelTrade(false, true);
#endif
}
void WorldSession::handleUnacceptTrade(WorldPacket& /*recvPacket*/)
{
#if VERSION_STRING < Cata
const auto tradeData = _player->getTradeData();
if (tradeData == nullptr)
return;
_player->getSession()->sendTradeResult(TRADE_STATUS_UNACCEPTED);
tradeData->getTradeTarget()->getSession()->sendTradeResult(TRADE_STATUS_UNACCEPTED);
_player->getTradeData()->setTradeAccepted(false, true);
#endif
}
#if VERSION_STRING < Cata
void WorldSession::sendTradeResult(TradeStatus result, uint64_t guid /*= 0*/)
{
SendPacket(SmsgTradeStatus(result, guid).serialise().get());
}
#else
void WorldSession::sendTradeResult(TradeStatus result, uint64_t /*guid = 0*/)
{
WorldPacket data(SMSG_TRADE_STATUS, 4 + 8);
data.writeBit(false);
data.writeBits(result, 5);
switch (result)
{
case TRADE_STATUS_PROPOSED:
{
ObjectGuid guid;
data.writeBit(guid[2]);
data.writeBit(guid[4]);
data.writeBit(guid[6]);
data.writeBit(guid[0]);
data.writeBit(guid[1]);
data.writeBit(guid[3]);
data.writeBit(guid[7]);
data.writeBit(guid[5]);
data.flushBits();
data.WriteByteSeq(guid[4]);
data.WriteByteSeq(guid[1]);
data.WriteByteSeq(guid[2]);
data.WriteByteSeq(guid[3]);
data.WriteByteSeq(guid[0]);
data.WriteByteSeq(guid[7]);
data.WriteByteSeq(guid[6]);
data.WriteByteSeq(guid[5]);
break;
}
case TRADE_STATUS_INITIATED:
{
data.flushBits();
data << uint32_t(0);
break;
}
case TRADE_STATUS_FAILED:
{
data.writeBit(false);
data.flushBits();
data << uint32_t(0);
data << uint32_t(0);
break;
}
case TRADE_STATUS_LOOT_ITEM:
case TRADE_STATUS_ONLY_CONJURED:
{
data.flushBits();
data << uint8_t(0);
break;
}
case TRADE_STATUS_CURRENCY_NOT_TRADEABLE:
case TRADE_STATUS_CURRENCY:
{
data.flushBits();
data << uint32_t(0);
data << uint32_t(0);
}
default:
data.flushBits();
break;
}
SendPacket(&data);
}
#endif
void WorldSession::sendTradeUpdate(bool tradeState /*= true*/)
{
TradeData* tradeData = tradeState ? _player->getTradeData()->getTargetTradeData() : _player->getTradeData();
WorldPacket data(SMSG_TRADE_STATUS_EXTENDED, 21 + (TRADE_SLOT_COUNT * 73));
#if VERSION_STRING < Cata
data << uint8_t(tradeState ? 1 : 0);
data << uint32_t(0); // unk
data << uint32_t(TRADE_SLOT_COUNT);
data << uint32_t(TRADE_SLOT_COUNT);
data << uint32_t(tradeData->getTradeMoney());
data << uint32_t(tradeData->getSpell()); // This is the spell which is casted on the lowest item
uint8_t itemCount = 0;
for (uint8_t i = 0; i < TRADE_SLOT_COUNT; ++i)
{
data << uint8_t(i);
const auto item = tradeData->getTradeItem(TradeSlots(i));
if (item == nullptr)
{
// Need to send empty fields, otherwise slots get messed up
data << uint32_t(0);
data << uint32_t(0);
data << uint32_t(0);
data << uint32_t(0);
data << uint64_t(0);
data << uint32_t(0);
for (uint8_t ench = SOCK_ENCHANTMENT_SLOT1; ench < BONUS_ENCHANTMENT_SLOT; ++ench)
data << uint32_t(0);
data << uint64_t(0);
data << uint32_t(0);
data << uint32_t(0);
data << uint32_t(0);
data << uint32_t(0);
data << uint32_t(0);
data << uint32_t(0);
continue;
}
++itemCount;
if (const auto itemProperties = item->getItemProperties())
{
data << uint32_t(itemProperties->ItemId);
data << uint32_t(itemProperties->DisplayInfoID);
data << uint32_t(item->getStackCount());
data << uint32_t(item->hasFlags(ITEM_FLAG_WRAPPED) ? 1 : 0);
// Enchantment stuff
data << uint64_t(item->getGiftCreatorGuid());
data << uint32_t(item->getEnchantmentId(PERM_ENCHANTMENT_SLOT));
for (uint8_t ench = SOCK_ENCHANTMENT_SLOT1; ench < BONUS_ENCHANTMENT_SLOT; ++ench)
data << uint32_t(item->getEnchantmentId(ench));
data << uint64_t(item->getCreatorGuid()); // Item creator
data << uint32_t(item->getSpellCharges(0)); // Spell charges
data << uint32_t(item->getPropertySeed());
data << uint32_t(item->getRandomPropertiesId());
data << uint32_t(itemProperties->LockId);
data << uint32_t(item->getMaxDurability());
data << uint32_t(item->getDurability());
}
}
#else
data << uint32_t(0); // unk
data << uint32_t(0); // unk
data << uint64_t(tradeData->getTradeMoney());
data << uint32_t(tradeData->getSpell());
data << uint32_t(TRADE_SLOT_COUNT);
data << uint32_t(0); // unk
data << uint8_t(tradeState ? 1 : 0);
data << uint32_t(TRADE_SLOT_COUNT);
uint8_t count = 0;
for (uint8_t i = 0; i < TRADE_SLOT_COUNT; ++i)
{
if (Item* item = tradeData->getTradeItem(TradeSlots(i)))
++count;
}
data.writeBits(count, 22);
for (uint8_t i = 0; i < TRADE_SLOT_COUNT; ++i)
{
if (Item* item = tradeData->getTradeItem(TradeSlots(i)))
{
ObjectGuid creatorGuid = item->getCreatorGuid();
ObjectGuid giftCreatorGuid = item->getGiftCreatorGuid();
data.writeBit(giftCreatorGuid[7]);
data.writeBit(giftCreatorGuid[1]);
bool notWrapped = data.writeBit(!item->hasFlags(ITEM_FLAG_WRAPPED)); //wrapped
data.writeBit(giftCreatorGuid[3]);
if (notWrapped)
{
data.writeBit(creatorGuid[7]);
data.writeBit(creatorGuid[1]);
data.writeBit(creatorGuid[4]);
data.writeBit(creatorGuid[6]);
data.writeBit(creatorGuid[2]);
data.writeBit(creatorGuid[3]);
data.writeBit(creatorGuid[5]);
data.writeBit(item->getItemProperties()->LockId != 0);
data.writeBit(creatorGuid[0]);
}
data.writeBit(giftCreatorGuid[6]);
data.writeBit(giftCreatorGuid[4]);
data.writeBit(giftCreatorGuid[2]);
data.writeBit(giftCreatorGuid[0]);
data.writeBit(giftCreatorGuid[5]);
}
}
data.flushBits();
for (uint8_t i = 0; i < TRADE_SLOT_COUNT; ++i)
{
if (Item* item = tradeData->getTradeItem(TradeSlots(i)))
{
ObjectGuid creatorGuid = item->getCreatorGuid();
ObjectGuid giftCreatorGuid = item->getGiftCreatorGuid();
if (!item->hasFlags(ITEM_FLAG_WRAPPED))
{
data.WriteByteSeq(creatorGuid[1]);
data << uint32_t(item->getEnchantmentId(PERM_ENCHANTMENT_SLOT));
for (uint8_t enchant_slot = SOCK_ENCHANTMENT_SLOT1; enchant_slot < BONUS_ENCHANTMENT_SLOT; ++enchant_slot)
{
data << uint32_t(item->getEnchantmentId(enchant_slot));
}
data << uint32_t(item->getMaxDurability());
data.WriteByteSeq(creatorGuid[6]);
data.WriteByteSeq(creatorGuid[2]);
data.WriteByteSeq(creatorGuid[7]);
data.WriteByteSeq(creatorGuid[4]);
data << uint32_t(item->getEnchantmentId(REFORGE_ENCHANTMENT_SLOT));
data << uint32_t(item->getDurability());
data << uint32_t(item->getRandomPropertiesId());
data.WriteByteSeq(creatorGuid[3]);
data << uint32_t(0); // unk
data.WriteByteSeq(creatorGuid[0]);
data << uint32_t(item->getSpellCharges(0));
data << uint32_t(item->getPropertySeed());
data.WriteByteSeq(creatorGuid[5]);
}
data.WriteByteSeq(giftCreatorGuid[6]);
data.WriteByteSeq(giftCreatorGuid[1]);
data.WriteByteSeq(giftCreatorGuid[7]);
data.WriteByteSeq(giftCreatorGuid[4]);
data << uint32_t(item->getItemProperties()->ItemId);
data.WriteByteSeq(giftCreatorGuid[0]);
data << uint32_t(item->getStackCount());
data.WriteByteSeq(giftCreatorGuid[5]);
data << uint8_t(i); // slot
data.WriteByteSeq(giftCreatorGuid[2]);
data.WriteByteSeq(giftCreatorGuid[3]);
}
}
#endif
SendPacket(&data);
}
| 0 | 0.90843 | 1 | 0.90843 | game-dev | MEDIA | 0.620995 | game-dev,networking | 0.904992 | 1 | 0.904992 |
moja-global/FLINT | 3,149 | Source/moja.flint.configuration/include/moja/flint/configuration/localdomain.h | #ifndef MOJA_FLINT_CONFIGURATION_LOCALDOMAIN_H_
#define MOJA_FLINT_CONFIGURATION_LOCALDOMAIN_H_
#include "moja/flint/configuration/_configuration_exports.h"
#include "moja/flint/configuration/iterationbase.h"
#include "moja/flint/configuration/itiming.h"
#include "moja/flint/configuration/landscape.h"
#include "moja/flint/configuration/operationmanager.h"
#include <moja/dynamic.h>
#include <string>
namespace moja {
namespace flint {
namespace configuration {
enum class LocalDomainType {
SpatialTiled,
SpatiallyReferencedSQL,
SpatiallyReferencedNoSQL,
ThreadedSpatiallyReferencedNoSQL,
Point
};
class CONFIGURATION_API LocalDomain {
public:
LocalDomain(LocalDomainType type, LocalDomainIterationType iterationType, bool doLogging, int numThreads,
const std::string& sequencerLibrary, const std::string& sequencer, const std::string& simulateLandUnit,
const std::string& landUnitBuildSuccess, DynamicObject settings,
TimeStepping timeStepping = TimeStepping::Monthly);
virtual ~LocalDomain() {}
virtual LocalDomainType type() const { return _type; }
virtual LocalDomainIterationType iterationType() const { return _iterationType; }
virtual bool doLogging() const { return _doLogging; }
virtual int numThreads() const { return _numThreads; }
virtual const std::string& sequencerLibrary() const { return _sequencerLibrary; }
virtual const std::string& sequencer() const { return _sequencer; }
virtual const std::string& simulateLandUnit() const { return _simulateLandUnit; }
virtual const std::string& landUnitBuildSuccess() const { return _landUnitBuildSuccess; }
virtual const DynamicObject& settings() const { return _settings; }
virtual DynamicObject& settings() { return _settings; }
virtual TimeStepping timeStepping() const { return _timeStepping; }
virtual void set_iterationType(LocalDomainIterationType value) { _iterationType = value; }
virtual void set_doLogging(bool value) { _doLogging = value; }
virtual void set_settings(DynamicObject& value) { _settings = value; }
virtual const Landscape* landscapeObject() const { return _landscapeObject.get(); }
virtual Landscape* landscapeObject() { return _landscapeObject.get(); }
void setLandscapeObject(const std::string& providerName, LocalDomainIterationType iterationType);
virtual const OperationManager* operationManagerObject() const { return &_operationManager; }
virtual OperationManager* operationManagerObject() { return &_operationManager; }
static std::string localDomainTypeToStr(LocalDomainType type);
private:
LocalDomainType _type;
LocalDomainIterationType _iterationType;
bool _doLogging;
int _numThreads;
std::string _sequencerLibrary;
std::string _sequencer;
std::string _simulateLandUnit;
std::string _landUnitBuildSuccess;
TimeStepping _timeStepping;
DynamicObject _settings;
std::shared_ptr<Landscape> _landscapeObject;
OperationManager _operationManager;
};
} // namespace configuration
} // namespace flint
} // namespace moja
#endif // MOJA_FLINT_CONFIGURATION_LOCALDOMAIN_H_
| 0 | 0.887877 | 1 | 0.887877 | game-dev | MEDIA | 0.307488 | game-dev | 0.698415 | 1 | 0.698415 |
dr-matt-smith/unity-5-cookbook-codes | 1,358 | 1362_01_UI/1362_01_UI_codes/1362_01_12_fungus_hello/unityProject_fungusVisualDialogs/Assets/Fungus/Flowchart/Scripts/VariableTypes/FloatVariable.cs | using UnityEngine;
using System.Collections;
namespace Fungus
{
[VariableInfo("", "Float")]
[AddComponentMenu("")]
public class FloatVariable : VariableBase<float>
{
public virtual bool Evaluate(CompareOperator compareOperator, float floatValue)
{
float lhs = value;
float rhs = floatValue;
bool condition = false;
switch (compareOperator)
{
case CompareOperator.Equals:
condition = lhs == rhs;
break;
case CompareOperator.NotEquals:
condition = lhs != rhs;
break;
case CompareOperator.LessThan:
condition = lhs < rhs;
break;
case CompareOperator.GreaterThan:
condition = lhs > rhs;
break;
case CompareOperator.LessThanOrEquals:
condition = lhs <= rhs;
break;
case CompareOperator.GreaterThanOrEquals:
condition = lhs >= rhs;
break;
}
return condition;
}
}
[System.Serializable]
public struct FloatData
{
[SerializeField]
public FloatVariable floatRef;
[SerializeField]
public float floatVal;
public float Value
{
get { return (floatRef == null) ? floatVal : floatRef.value; }
set { if (floatRef == null) { floatVal = value; } else { floatRef.value = value; } }
}
public string GetDescription()
{
if (floatRef == null)
{
return floatVal.ToString();
}
else
{
return floatRef.key;
}
}
}
} | 0 | 0.654059 | 1 | 0.654059 | game-dev | MEDIA | 0.739795 | game-dev | 0.84309 | 1 | 0.84309 |
iortcw/iortcw | 28,520 | SP/code/game/ai_cast.h | /*
===========================================================================
Return to Castle Wolfenstein single player GPL Source Code
Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company.
This file is part of the Return to Castle Wolfenstein single player GPL Source Code (RTCW SP Source Code).
RTCW SP Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
RTCW SP Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with RTCW SP Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the RTCW SP Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the RTCW SP Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
//===========================================================================
//
// Name: ai_cast.h
// Function: Wolfenstein AI Character Routines
// Programmer: Ridah
// Tab Size: 4 (real tabs)
//===========================================================================
#include "ai_main.h" // just so we can use the structures
#include "ai_dmq3.h" // just so we can use the structures
#include "ai_cast_fight.h"
//
// constants/defines
//
#define MAX_AIFUNCS 15 // if we go over this per frame, likely to have an infinite loop
//
#define SIGHT_PER_SEC 50 // do this many sight iterations per second
//
// Cast AI specific action flags (get translated into ucmd's
#define CASTACTION_WALK 1
//
#define MAX_SCRIPT_ACCUM_BUFFERS 8
//
#define AICAST_PRT_ALWAYS 0
#define AICAST_PRT_DEBUG 1
//
#define DEBUG_FOLLOW_DIST 96
//
#define MAX_LEADER_DIST 256
//
#define AASWORLD_STANDARD 0
#define AASWORLD_LARGE 1
//
// use this for returning the length of an anim
#define ANIMLENGTH( frames,fps ) ( ( frames * 1000 ) / fps )
//
#define AICAST_TFL_DEFAULT TFL_DEFAULT & ~( TFL_JUMPPAD | TFL_ROCKETJUMP | TFL_BFGJUMP | TFL_GRAPPLEHOOK | TFL_DOUBLEJUMP | TFL_RAMPJUMP | TFL_STRAFEJUMP | TFL_LAVA ) //----(SA) modified since slime is no longer deadly
//#define AICAST_TFL_DEFAULT TFL_DEFAULT & ~(TFL_JUMPPAD|TFL_ROCKETJUMP|TFL_BFGJUMP|TFL_GRAPPLEHOOK|TFL_DOUBLEJUMP|TFL_RAMPJUMP|TFL_STRAFEJUMP|TFL_SLIME|TFL_LAVA)
//
// AI flags
#define AIFL_CATCH_GRENADE 0x1
#define AIFL_NO_FLAME_DAMAGE 0x2
#define AIFL_FIRED 0x4
#define AIFL_LAND_ANIM_PLAYED 0x8
#define AIFL_ROLL_ANIM 0x10
#define AIFL_FLIP_ANIM 0x20
#define AIFL_STAND_IDLE2 0x40
#define AIFL_NOAVOID 0x80 // if set, this AI will ignore requests for us to move out the way
#define AIFL_NOPAIN 0x100 // don't stop for pain anims
#define AIFL_WALKFORWARD 0x200 // only walk forward
#define AIFL_DENYACTION 0x400 // used by scripting to prevent dynamic code from executing certain behaviour
#define AIFL_VIEWLOCKED 0x800 // prevent anything outside movement routines from changing view
#define AIFL_CORPSESIGHTING 0x1000 // share information through friendly corpses
#define AIFL_WAITINGTOSPAWN 0x2000 // waiting until space is clear to spawn in to the game
#define AIFL_JUST_SPAWNED 0x4000
#define AIFL_NO_RELOAD 0x8000 // this character doesn't need to reload
#define AIFL_TALKING 0x10000
#define AIFL_NO_HEADLOOK 0x20000
#define AIFL_ATTACK_CROUCH 0x40000
#define AIFL_MISCFLAG1 0x80000 // used various bits of code, temporarily
#define AIFL_MISCFLAG2 0x100000 // used various bits of code, temporarily
#define AIFL_ZOOMING 0x200000
#define AIFL_NO_HEADSHOT_DMG 0x400000
#define AIFL_DIVE_ANIM 0x800000 // able to dive to cover
#define AIFL_NO_TESLA_DAMAGE 0x1000000
#define AIFL_EXPLICIT_ROUTING 0x2000000 // direct routing towards ai_markers, rather than using AAS
#define AIFL_DISMOUNTING 0x4000000
#define AIFL_SPECIAL_FUNC 0x8000000 // prevent external interuption of current think func
//
// predict events
typedef enum
{
PREDICTSTOP_NONE,
PREDICTSTOP_HITENT,
PREDICTSTOP_HITCLIENT
} predictStop_t;
//
typedef enum
{
AITEAM_NAZI,
AITEAM_ALLIES,
AITEAM_MONSTER,
AITEAM_SPARE1,
AITEAM_SPARE2,
AITEAM_SPARE3,
AITEAM_SPARE4,
AITEAM_NEUTRAL
} AITeam_t;
//
typedef enum
{
BBOX_SMALL,
BBOX_LARGE
} BBoxType_t;
//
// attributes
// !!! NOTE: any changes to this must be reflected in the attributeStrings in ai_cast.c
typedef enum
{
RUNNING_SPEED, // max = 300 (running speed)
WALKING_SPEED, // max = 300 (walking speed)
CROUCHING_SPEED, // max = 300 (crouching speed)
FOV, // max = 360 (field of view)
YAW_SPEED, // max = 300 (yaw speed, so we can make zombie's turn slowly)
LEADER, // max = 1.0 (ability to lead an AI squadron)
AIM_SKILL, // max = 1.0 (skill while aiming)
AIM_ACCURACY, // max = 1.0 (accuracy of firing)
ATTACK_SKILL, // max = 1.0 (ability to attack and do other things, like retreat)
REACTION_TIME, // max = 1.0 (upon seeing enemy, wait this long before reaction)
ATTACK_CROUCH, // max = 1.0 (likely to crouch while firing)
IDLE_CROUCH, // max = 1.0 (likely to crouch while idling)
AGGRESSION, // max = 1.0 (willingness to fight till the death)
TACTICAL, // max = 1.0 (ability to use strategy to their advantage, also behaviour whilst hunting enemy, more likely to creep around)
CAMPER, // max = 1.0 (set this to make them stay in the spot they are spawned)
ALERTNESS, // max = 1.0 (ability to notice enemies at long range)
STARTING_HEALTH, // MAX = 999 (starting health)
HEARING_SCALE, // max = 999 (multiply default hearing ranges by this)
HEARING_SCALE_NOT_PVS, // max = 999 (multiply hearing range by this if outside PVS)
INNER_DETECTION_RADIUS, // default = 512 (enemies within this range trigger immediate combat mode
PAIN_THRESHOLD_SCALE, // default = 1.0
AICAST_MAX_ATTRIBUTES
} castAttributes_t;
//
typedef enum
{
SIGHTSOUNDSCRIPT,
ATTACKSOUNDSCRIPT,
ORDERSSOUNDSCRIPT,
DEATHSOUNDSCRIPT,
QUIETDEATHSOUNDSCRIPT, //----(SA) ADDED FOR SILENT DEATHS (SNIPER/KNIFE)
FLAMEDEATHSOUNDSCRIPT, //----(SA) ADDED FOR FLAMING
PAINSOUNDSCRIPT,
STAYSOUNDSCRIPT,
FOLLOWSOUNDSCRIPT,
ORDERSDENYSOUNDSCRIPT,
MISC1SOUNDSCRIPT,
MAX_AI_EVENT_SOUNDS
} AIEventSounds_t;
//
typedef struct {
char *name;
float attributes[AICAST_MAX_ATTRIBUTES];
char *soundScripts[MAX_AI_EVENT_SOUNDS];
int aiTeam;
char *skin;
int weapons[8];
int bboxType;
vec2_t crouchstandZ;
int aiFlags;
char *( *aifuncAttack1 )( struct cast_state_s *cs ); //use this battle aifunc for monster_attack1
char *( *aifuncAttack2 )( struct cast_state_s *cs ); //use this battle aifunc for monster_attack2
char *( *aifuncAttack3 )( struct cast_state_s *cs ); //use this battle aifunc for monster_attack2
char *loopingSound; // play this sound constantly while alive
aistateEnum_t aiState;
} AICharacterDefaults_t;
//
// script flags
#define SFL_NOCHANGEWEAPON 0x1
#define SFL_NOAIDAMAGE 0x2
#define SFL_FRIENDLYSIGHTCORPSE_TRIGGERED 0x4
#define SFL_WAITING_RESTORE 0x8
#define SFL_FIRST_CALL 0x10
//
// attributes strings (used for per-entity attribute definitions)
// NOTE: these must match the attributes above)
extern char *castAttributeStrings[];
extern AICharacterDefaults_t aiDefaults[NUM_CHARACTERS];
//
// structure defines
//
#define AIVIS_ENEMY 1
#define AIVIS_INSPECTED 2 // we have inspected them once already
#define AIVIS_INSPECT 4 // we should inspect them when we get a chance
#define AIVIS_PROCESS_SIGHTING 8 // so we know if we have or haven't processed the sighting since they were last seen
#define AIVIS_SIGHT_SCRIPT_CALLED 0x10 // set once sight script has been called.. only call once
//
// share range
#define AIVIS_SHARE_RANGE 384 // if we are within this range of a friendly, share their vis info
//
#define MAX_CHASE_MARKERS 3
#define CHASE_MARKER_INTERVAL 1000
//
#define COMBAT_TIMEOUT 8000
// sight info
typedef struct
{
int flags;
int lastcheck_timestamp;
int real_visible_timestamp;
int real_update_timestamp;
int real_notvisible_timestamp;
int visible_timestamp; // time we last recorded a sighting
vec3_t visible_pos; // position we last knew of them being at (could be hearing, etc)
vec3_t real_visible_pos; // position we last physically saw them
vec3_t visible_vel; // velocity during last sighting
int notvisible_timestamp; // last time we didn't see the entity (used for reaction delay)
vec3_t chase_marker[MAX_CHASE_MARKERS];
int chase_marker_count;
int lastcheck_health;
} cast_visibility_t;
//
// starting weapons, ammo, etc
typedef struct
{
int startingWeapons[MAX_WEAPONS / ( sizeof( int ) * 8 )];
int startingAmmo[MAX_WEAPONS]; // starting ammo values for each weapon (set to 999 for unlimited)
} cast_weapon_info_t;
//
// scripting
typedef struct
{
char *actionString;
qboolean ( *actionFunc )( struct cast_state_s *cs, char *params );
} cast_script_stack_action_t;
//
typedef struct
{
//
// set during script parsing
cast_script_stack_action_t *action; // points to an action to perform
char *params;
} cast_script_stack_item_t;
//
#define AICAST_MAX_SCRIPT_STACK_ITEMS 64
//
typedef struct
{
cast_script_stack_item_t items[AICAST_MAX_SCRIPT_STACK_ITEMS];
int numItems;
} cast_script_stack_t;
//
typedef struct
{
int eventNum; // index in scriptEvents[]
char *params; // trigger targetname, etc
cast_script_stack_t stack;
} cast_script_event_t;
//
typedef struct
{
char *eventStr;
qboolean ( *eventMatch )( cast_script_event_t *event, char *eventParm );
} cast_script_event_define_t;
//
typedef struct
{
int castScriptStackHead, castScriptStackChangeTime;
int castScriptEventIndex; // current event containing stack of actions to perform
// scripting system AI variables (set by scripting system, used directly by AI)
int scriptId; // incremented each time the script changes
int scriptFlags;
int scriptNoAttackTime;
int scriptNoMoveTime;
int playAnimViewlockTime;
int scriptGotoEnt; // just goto them, then resume normal behaviour (don't follow)
int scriptGotoId;
vec3_t scriptWaitPos;
int scriptWaitMovetime;
vec3_t scriptWaitHidePos;
int scriptWaitHideTime;
int scriptNoSightTime;
int scriptAttackEnt; // we should always attack this AI if they are alive
vec3_t playanim_viewangles;
} cast_script_status_t;
//
typedef struct
{
aistateEnum_t currentState;
aistateEnum_t nextState;
int nextStateTimer; // time left until "newState" is reached
} aistate_t;
//
typedef enum
{
MS_DEFAULT,
MS_WALK,
MS_RUN,
MS_CROUCH
} movestate_t;
//
typedef enum
{
MSTYPE_NONE,
MSTYPE_TEMPORARY,
MSTYPE_PERMANENT
} movestateType_t;
//
//
typedef struct aicast_checkattack_cache_s
{
int enemy;
qboolean allowHitWorld;
int time;
int weapon;
qboolean result;
} aicast_checkattack_cache_t;
//
// --------------------------------------------------------------------------------
// the main cast structure
typedef struct cast_state_s
{
bot_state_t *bs;
int entityNum;
int aasWorldIndex; // set this according to our bounding box type
// Cast specific information follows. Add to this as needed, this way the bot_state_t structure
// remains untouched.
int aiCharacter;
int aiFlags;
int lastThink; // time they last thinked, so we can vary the think times
int actionFlags; // cast AI specific movement flags
int lastPain, lastPainDamage;
int travelflags;
int thinkFuncChangeTime;
aistateEnum_t aiState;
movestate_t movestate; // walk, run, crouch etc (can be specified in a script)
movestateType_t movestateType; // temporary, permanent, etc
float attributes[AICAST_MAX_ATTRIBUTES];
// these define the abilities of each cast AI
// scripting system
int numCastScriptEvents;
cast_script_event_t *castScriptEvents; // contains a list of actions to perform for each event type
cast_script_status_t castScriptStatus; // current status of scripting
cast_script_status_t castScriptStatusCurrent; // scripting status to use for backups
cast_script_status_t castScriptStatusBackup; // perm backup of status of scripting, only used by backup and restore commands
int scriptCallIndex; // inc'd each time a script is called
int scriptAnimTime, scriptAnimNum; // last time an anim was played using scripting
// the accumulation buffer
int scriptAccumBuffer[MAX_SCRIPT_ACCUM_BUFFERS];
//
cast_weapon_info_t *weaponInfo; // FIXME: make this a list, so they can have multiple weapons?
cast_visibility_t vislist[MAX_CLIENTS]; // array of all other client entities, allocated at level start-up
int weaponFireTimes[MAX_WEAPONS];
char *( *aifunc )( struct cast_state_s *cs ); //current AI function
char *( *oldAifunc )( struct cast_state_s *cs ); // just so we can restore the last aiFunc if required
char *( *aifuncAttack1 )( struct cast_state_s *cs ); //use this battle aifunc for monster_attack1
char *( *aifuncAttack2 )( struct cast_state_s *cs ); //use this battle aifunc for monster_attack2
char *( *aifuncAttack3 )( struct cast_state_s *cs ); //use this battle aifunc for monster_attack2
void ( *painfunc )( gentity_t *ent, gentity_t *attacker, int damage, vec3_t point );
void ( *deathfunc )( gentity_t *ent, gentity_t *attacker, int damage, int mod ); //----(SA) added mod
void ( *sightfunc )( gentity_t *ent, gentity_t *other, int lastSight );
//int (*getDeathAnim)(gentity_t *ent, gentity_t *attacker, int damage);
void ( *sightEnemy )( gentity_t *ent, gentity_t *other );
void ( *sightFriend )( gentity_t *ent, gentity_t *other );
void ( *activate )( int entNum, int activatorNum );
//
// !!! NOTE: make sure any entityNum type variables get initialized
// to -1 in AICast_CreateCharacter(), or they'll be defaulting to
// the player (index 0)
//
// goal/AI stuff
int followEntity;
float followDist;
qboolean followIsGoto; // we are really just going to the entity, but should wait until scripting tells us we can stop
int followTime; // if this runs out, the scripting has probably been interupted
qboolean followSlowApproach;
int leaderNum; // entnum of player we are following
float speedScale; // so we can vary movement speed
float combatGoalTime;
vec3_t combatGoalOrigin;
int lastGetHidePos;
int startAttackCount; // incremented each time we start a standing attack
// used to make sure we only find a combat spot once per attack
int combatSpotAttackCount;
int combatSpotDelayTime;
int startBattleChaseTime;
int blockedTime; // time they were last blocked by a solid entity
int obstructingTime; // time that we should move so we are not obstructing someone else
vec3_t obstructingPos;
int blockedAvoidTime;
float blockedAvoidYaw;
int deathTime;
int rebirthTime, revivingTime;
// battle values
int enemyHeight;
int enemyDist;
vec3_t takeCoverPos, takeCoverEnemyPos;
int takeCoverTime;
int attackSpotTime;
int triggerReleaseTime;
int lastWeaponFired; // set each time a weapon is fired. used to detect when a weapon has been fired from within scripting
vec3_t lastWeaponFiredPos;
int lastWeaponFiredWeaponNum;
// idle behaviour stuff
int lastEnemy, nextIdleAngleChange;
float idleYawChange, idleYaw;
qboolean crouchHideFlag;
int doorMarker, doorEntNum;
// Rafael
int attackSNDtime;
int attacksnd;
int painSoundTime;
int firstSightTime;
qboolean secondDeadTime;
// done
int startGrenadeFlushTime;
int lockViewAnglesTime;
int grenadeFlushEndTime;
int grenadeFlushFiring;
int dangerEntity;
int dangerEntityValidTime; // dangerEntity is valid until this time expires
vec3_t dangerEntityPos; // dangerEntity is predicted to end up here
int dangerEntityTimestamp; // time this danger was recorded
float dangerDist;
int mountedEntity; // mg42, etc that we have mounted
int inspectBodyTime;
vec3_t startOrigin;
int damageQuota;
int damageQuotaTime;
int dangerLastGetAvoid;
int lastAvoid;
int doorMarkerTime, doorMarkerNum, doorMarkerDoor;
int pauseTime; // absolutely don't move move while this is > level.time
aicast_checkattack_cache_t checkAttackCache;
int secretsFound;
int attempts;
qboolean grenadeGrabFlag; // if this is set, we need to play the anim before we can grab it
vec3_t lastMoveToPosGoalOrg; // if this changes, we should reset the Bot Avoid Reach
int noAttackTime; // used by dynamic AI to stop attacking for set time
int lastRollMove;
int lastFlipMove;
vec3_t stimFlyAttackPos;
int lastDodgeRoll; // last time we rolled to get out of our enemies direct aim
int battleRollTime;
vec3_t viewlock_viewangles;
int grenadeKickWeapon;
int animHitCount; // for stepping through the frames on which to inflict damage
int totalPlayTime, lastLoadTime;
int queryStartTime, queryCountValidTime, queryCount, queryAlertSightTime;
int lastScriptSound;
int inspectNum;
int scriptPauseTime;
int bulletImpactEntity;
int bulletImpactTime; // last time we heard/saw a bullet impact
int bulletImpactIgnoreTime;
vec3_t bulletImpactStart, bulletImpactEnd;
int audibleEventTime;
vec3_t audibleEventOrg;
int audibleEventEnt;
int battleChaseMarker, battleChaseMarkerDir;
int lastBattleHunted; // last time an enemy decided to hunt us
int battleHuntPauseTime, battleHuntViewTime;
int lastAttackCrouch;
int lastMoveThink; // last time we ran our ClientThink()
int numEnemies; // last count of enemies that are currently pursuing us
int noReloadTime; // dont reload prematurely until this time has expired
int lastValidAreaNum[2]; // last valid area within each AAS world
int lastValidAreaTime[2]; // time we last got the area
int weaponNum; // our current weapon
int enemyNum; // our current enemy
vec3_t ideal_viewangles, viewangles;
usercmd_t lastucmd;
int attackcrouch_time;
int bFlags;
int deadSinkStartTime;
int lastActivate;
vec3_t loperLeapVel;
// -------------------------------------------------------------------------------------------
// if working on a post release patch, new variables should ONLY be inserted after this point
// -------------------------------------------------------------------------------------------
} cast_state_t;
//
#define CSFOFS( x ) ( (size_t)&( ( (cast_state_t *)0 )->x ) )
//
typedef struct aicast_predictmove_s
{
vec3_t endpos; //position at the end of movement prediction
vec3_t velocity; //velocity at the end of movement prediction
int presencetype; //presence type at end of movement prediction
int stopevent; //event that made the prediction stop
float time; //time predicted ahead
int frames; //number of frames predicted ahead
int numtouch;
int touchents[MAXTOUCH];
int groundEntityNum;
} aicast_predictmove_t;
//
// variables/globals
//
//cast states
extern cast_state_t *caststates;
//number of characters
extern int numcast;
//
// minimum time between thinks (maximum is double this)
extern int aicast_thinktime;
// maximum number of character thinks at once
extern int aicast_maxthink;
// maximum clients
extern int aicast_maxclients;
// skill scale
extern float aicast_skillscale;
//
// cvar to enable aicast debugging, set higher for more levels of debugging
extern vmCvar_t aicast_debug;
extern vmCvar_t aicast_debugname;
extern vmCvar_t aicast_scripts;
//
//
// procedure defines
//
// ai_cast.c
void AIChar_SetBBox( gentity_t *ent, cast_state_t *cs, qboolean useHeadTag );
void AICast_Printf( int type, const char *fmt, ... ) __attribute__ ((format (printf, 2, 3)));
gentity_t *AICast_CreateCharacter( gentity_t *ent, float *attributes, cast_weapon_info_t *weaponInfo, char *castname, char *model, char *head, char *sex, char *color, char *handicap );
void AICast_Init( void );
void AICast_DelayedSpawnCast( gentity_t *ent, int castType );
qboolean AICast_SolidsInBBox( vec3_t pos, vec3_t mins, vec3_t maxs, int entnum, int mask );
void AICast_CheckLevelAttributes( cast_state_t *cs, gentity_t *ent, char **ppStr );
//
// ai_cast_sight.c
void AICast_SightUpdate( int numchecks );
qboolean AICast_VisibleFromPos( vec3_t srcpos, int srcnum,
vec3_t destpos, int destnum, qboolean updateVisPos );
void AICast_UpdateVisibility( gentity_t *srcent, gentity_t *destent, qboolean shareVis, qboolean directview );
qboolean AICast_CheckVisibility( gentity_t *srcent, gentity_t *destent );
//
// ai_cast_debug.c
void AICast_DBG_InitAIFuncs( void );
void AICast_DBG_AddAIFunc( cast_state_t *cs, char *funcname );
void AICast_DBG_ListAIFuncs( cast_state_t *cs, int numprint );
void AICast_DBG_RouteTable_f( vec3_t org, char *param );
int Sys_MilliSeconds( void );
void AICast_DebugFrame( cast_state_t *cs );
//
// ai_cast_funcs.c
void AICast_SpecialFunc( cast_state_t *cs );
bot_moveresult_t *AICast_MoveToPos( cast_state_t *cs, vec3_t pos, int entnum );
float AICast_SpeedScaleForDistance( cast_state_t *cs, float startdist, float idealDist );
char *AIFunc_DefaultStart( cast_state_t *cs );
char *AIFunc_IdleStart( cast_state_t *cs );
char *AIFunc_ChaseGoalIdleStart( cast_state_t *cs, int entitynum, float reachdist );
char *AIFunc_ChaseGoalStart( cast_state_t *cs, int entitynum, float reachdist, qboolean slowApproach );
char *AIFunc_BattleChaseStart( cast_state_t *cs );
char *AIFunc_BattleStart( cast_state_t *cs );
char *AIFunc_DoorMarkerStart( cast_state_t *cs, int doornum, int markernum );
char *AIFunc_DoorMarker( cast_state_t *cs );
char *AIFunc_BattleTakeCoverStart( cast_state_t *cs );
char *AIFunc_GrenadeFlushStart( cast_state_t *cs );
char *AIFunc_AvoidDangerStart( cast_state_t *cs );
char *AIFunc_BattleMG42Start( cast_state_t *cs );
char *AIFunc_InspectBodyStart( cast_state_t *cs );
char *AIFunc_GrenadeKickStart( cast_state_t *cs );
char *AIFunc_InspectFriendlyStart( cast_state_t *cs, int entnum );
char *AIFunc_InspectBulletImpactStart( cast_state_t *cs );
char *AIFunc_InspectAudibleEventStart( cast_state_t *cs, int entnum );
char *AIFunc_BattleAmbushStart( cast_state_t *cs );
char *AIFunc_BattleHuntStart( cast_state_t *cs );
//
// ai_cast_func_attack.c
char *AIFunc_ZombieFlameAttackStart( cast_state_t *cs );
char *AIFunc_ZombieAttack2Start( cast_state_t *cs );
char *AIFunc_ZombieMeleeStart( cast_state_t *cs );
char *AIFunc_LoperAttack1Start( cast_state_t *cs );
char *AIFunc_LoperAttack2Start( cast_state_t *cs );
char *AIFunc_LoperAttack3Start( cast_state_t *cs );
char *AIFunc_StimSoldierAttack1Start( cast_state_t *cs );
char *AIFunc_StimSoldierAttack2Start( cast_state_t *cs );
char *AIFunc_BlackGuardAttack1Start( cast_state_t *cs );
char *AIFunc_RejectAttack1Start( cast_state_t *cs ); //----(SA)
char *AIFunc_WarriorZombieMeleeStart( cast_state_t *cs );
char *AIFunc_WarriorZombieSightStart( cast_state_t *cs );
char *AIFunc_WarriorZombieDefenseStart( cast_state_t *cs );
//
// ai_cast_func_boss1.c
char *AIFunc_Helga_SpiritAttack_Start( cast_state_t *cs );
char *AIFunc_Helga_MeleeStart( cast_state_t *cs );
char *AIFunc_FlameZombie_PortalStart( cast_state_t *cs );
char *AIFunc_Heinrich_MeleeStart( cast_state_t *cs );
char *AIFunc_Heinrich_RaiseDeadStart( cast_state_t *cs );
char *AIFunc_Heinrich_SpawnSpiritsStart( cast_state_t *cs );
void AICast_Heinrich_SoundPrecache( void );
//
// ai_cast_fight.c
qboolean AICast_StateChange( cast_state_t *cs, aistateEnum_t newaistate );
void AICast_WeaponSway( cast_state_t *cs, vec3_t ofs );
int AICast_ScanForEnemies( cast_state_t *cs, int *enemies );
void AICast_UpdateBattleInventory( cast_state_t *cs, int enemy );
float AICast_Aggression( cast_state_t *cs );
int AICast_WantsToChase( cast_state_t *cs );
int AICast_WantsToTakeCover( cast_state_t *cs, qboolean attacking );
qboolean AICast_EntityVisible( cast_state_t *cs, int enemynum, qboolean directview );
bot_moveresult_t AICast_CombatMove( cast_state_t *cs, int tfl );
qboolean AICast_AimAtEnemy( cast_state_t *cs );
qboolean AICast_CheckAttackAtPos( int entnum, int enemy, vec3_t pos, qboolean ducking, qboolean allowHitWorld );
qboolean AICast_CheckAttack( cast_state_t *cs, int enemy, qboolean allowHitWorld );
void AICast_ProcessAttack( cast_state_t *cs );
void AICast_ChooseWeapon( cast_state_t *cs, qboolean battleFunc );
qboolean AICast_GetTakeCoverPos( cast_state_t *cs, int enemyNum, vec3_t enemyPos, vec3_t returnPos );
qboolean AICast_CanMoveWhileFiringWeapon( int weaponnum );
float AICast_GetWeaponSoundRange( int weapon );
qboolean AICast_StopAndAttack( cast_state_t *cs );
qboolean AICast_WantToRetreat( cast_state_t *cs );
int AICast_SafeMissileFire( gentity_t *ent, int duration, int enemyNum, vec3_t enemyPos, int selfNum, vec3_t endPos );
void AIChar_AttackSound( cast_state_t *cs );
qboolean AICast_GotEnoughAmmoForWeapon( cast_state_t *cs, int weapon );
qboolean AICast_HostileEnemy( cast_state_t *cs, int enemynum );
qboolean AICast_QueryEnemy( cast_state_t *cs, int enemynum );
void AICast_AudibleEvent( int srcnum, vec3_t pos, float range );
qboolean AICast_WeaponUsable( cast_state_t *cs, int weaponNum );
float AICast_WeaponRange( cast_state_t *cs, int weaponnum );
//
// ai_cast_events.c
void AICast_Pain( gentity_t *targ, gentity_t *attacker, int damage, vec3_t point );
void AICast_Die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int meansOfDeath );
void AICast_Sight( gentity_t *ent, gentity_t *other, int lastSight );
void AICast_EndChase( cast_state_t *cs );
void AICast_ProcessActivate( int entNum, int activatorNum );
//
// ai_cast_think.c
void AICast_Think( int client, float thinktime );
void AICast_UpdateInput( cast_state_t *cs, int time );
void AICast_InputToUserCommand( cast_state_t * cs, bot_input_t * bi, usercmd_t * ucmd, int delta_angles[3] );
void AICast_PredictMovement( cast_state_t *cs, int numframes, float frametime, aicast_predictmove_t *move, usercmd_t *ucmd, int checkHitEnt );
void AICast_Blocked( cast_state_t *cs, bot_moveresult_t *moveresult, int activate, bot_goal_t *goal );
qboolean AICast_RequestCrouchAttack( cast_state_t *cs, vec3_t org, float time );
qboolean AICast_GetAvoid( cast_state_t *cs, bot_goal_t *goal, vec3_t outpos, qboolean reverse, int blockEnt );
void AICast_QueryThink( cast_state_t *cs );
void AICast_DeadClipWalls( cast_state_t *cs );
void AICast_IdleReload( cast_state_t *cs );
//
// ai_cast_script.c
qboolean AICast_ScriptRun( cast_state_t *cs, qboolean force );
//
// ai_cast_soldier.c
void AIChar_spawn( gentity_t *ent );
//
// other/external defines
void BotCheckAir( bot_state_t *bs );
void BotUpdateInput( bot_state_t *bs, int time );
float AngleDifference( float ang1, float ang2 );
float BotChangeViewAngle( float angle, float ideal_angle, float speed );
void BotInputToUserCommand( bot_input_t * bi, usercmd_t * ucmd, int delta_angles[3] );
void GibEntity( gentity_t *self, int killer );
void GibHead( gentity_t *self, int killer );
//
extern bot_state_t *botstates[MAX_CLIENTS];
| 0 | 0.922137 | 1 | 0.922137 | game-dev | MEDIA | 0.994754 | game-dev | 0.625547 | 1 | 0.625547 |
D-Programming-GDC/gcc | 4,742 | gcc/testsuite/gfortran.dg/minlocval_2.f90 | ! { dg-do run }
integer :: a(3), h
integer, allocatable :: c(:)
logical :: l
logical :: l2(3)
h = -huge(h)
h = h - 1
allocate (c(3))
a(:) = 5
if (minloc (a, dim = 1).ne.1) STOP 1
if (minval (a, dim = 1).ne.5) STOP 2
a(2) = h
if (minloc (a, dim = 1).ne.2) STOP 3
if (minval (a, dim = 1).ne.h) STOP 4
a(:) = huge(h)
if (minloc (a, dim = 1).ne.1) STOP 5
if (minval (a, dim = 1).ne.huge(h)) STOP 6
a(3) = huge(h) - 1
if (minloc (a, dim = 1).ne.3) STOP 7
if (minval (a, dim = 1).ne.huge(h)-1) STOP 8
c(:) = 5
if (minloc (c, dim = 1).ne.1) STOP 9
if (minval (c, dim = 1).ne.5) STOP 10
c(2) = h
if (minloc (c, dim = 1).ne.2) STOP 11
if (minval (c, dim = 1).ne.h) STOP 12
c(:) = huge(h)
if (minloc (c, dim = 1).ne.1) STOP 13
if (minval (c, dim = 1).ne.huge(h)) STOP 14
c(3) = huge(h) - 1
if (minloc (c, dim = 1).ne.3) STOP 15
if (minval (c, dim = 1).ne.huge(h)-1) STOP 16
l = .false.
l2(:) = .false.
a(:) = 5
if (minloc (a, dim = 1, mask = l).ne.0) STOP 17
if (minval (a, dim = 1, mask = l).ne.huge(h)) STOP 18
if (minloc (a, dim = 1, mask = l2).ne.0) STOP 19
if (minval (a, dim = 1, mask = l2).ne.huge(h)) STOP 20
a(2) = h
if (minloc (a, dim = 1, mask = l).ne.0) STOP 21
if (minval (a, dim = 1, mask = l).ne.huge(h)) STOP 22
if (minloc (a, dim = 1, mask = l2).ne.0) STOP 23
if (minval (a, dim = 1, mask = l2).ne.huge(h)) STOP 24
a(:) = huge(h)
if (minloc (a, dim = 1, mask = l).ne.0) STOP 25
if (minval (a, dim = 1, mask = l).ne.huge(h)) STOP 26
if (minloc (a, dim = 1, mask = l2).ne.0) STOP 27
if (minval (a, dim = 1, mask = l2).ne.huge(h)) STOP 28
a(3) = huge(h) - 1
if (minloc (a, dim = 1, mask = l).ne.0) STOP 29
if (minval (a, dim = 1, mask = l).ne.huge(h)) STOP 30
if (minloc (a, dim = 1, mask = l2).ne.0) STOP 31
if (minval (a, dim = 1, mask = l2).ne.huge(h)) STOP 32
c(:) = 5
if (minloc (c, dim = 1, mask = l).ne.0) STOP 33
if (minval (c, dim = 1, mask = l).ne.huge(h)) STOP 34
if (minloc (c, dim = 1, mask = l2).ne.0) STOP 35
if (minval (c, dim = 1, mask = l2).ne.huge(h)) STOP 36
c(2) = h
if (minloc (c, dim = 1, mask = l).ne.0) STOP 37
if (minval (c, dim = 1, mask = l).ne.huge(h)) STOP 38
if (minloc (c, dim = 1, mask = l2).ne.0) STOP 39
if (minval (c, dim = 1, mask = l2).ne.huge(h)) STOP 40
c(:) = huge(h)
if (minloc (c, dim = 1, mask = l).ne.0) STOP 41
if (minval (c, dim = 1, mask = l).ne.huge(h)) STOP 42
if (minloc (c, dim = 1, mask = l2).ne.0) STOP 43
if (minval (c, dim = 1, mask = l2).ne.huge(h)) STOP 44
c(3) = huge(h) - 1
if (minloc (c, dim = 1, mask = l).ne.0) STOP 45
if (minval (c, dim = 1, mask = l).ne.huge(h)) STOP 46
if (minloc (c, dim = 1, mask = l2).ne.0) STOP 47
if (minval (c, dim = 1, mask = l2).ne.huge(h)) STOP 48
l = .true.
l2(:) = .true.
a(:) = 5
if (minloc (a, dim = 1, mask = l).ne.1) STOP 49
if (minval (a, dim = 1, mask = l).ne.5) STOP 50
if (minloc (a, dim = 1, mask = l2).ne.1) STOP 51
if (minval (a, dim = 1, mask = l2).ne.5) STOP 52
a(2) = h
if (minloc (a, dim = 1, mask = l).ne.2) STOP 53
if (minval (a, dim = 1, mask = l).ne.h) STOP 54
if (minloc (a, dim = 1, mask = l2).ne.2) STOP 55
if (minval (a, dim = 1, mask = l2).ne.h) STOP 56
a(:) = huge(h)
if (minloc (a, dim = 1, mask = l).ne.1) STOP 57
if (minval (a, dim = 1, mask = l).ne.huge(h)) STOP 58
if (minloc (a, dim = 1, mask = l2).ne.1) STOP 59
if (minval (a, dim = 1, mask = l2).ne.huge(h)) STOP 60
a(3) = huge(h) - 1
if (minloc (a, dim = 1, mask = l).ne.3) STOP 61
if (minval (a, dim = 1, mask = l).ne.huge(h)-1) STOP 62
if (minloc (a, dim = 1, mask = l2).ne.3) STOP 63
if (minval (a, dim = 1, mask = l2).ne.huge(h)-1) STOP 64
c(:) = 5
if (minloc (c, dim = 1, mask = l).ne.1) STOP 65
if (minval (c, dim = 1, mask = l).ne.5) STOP 66
if (minloc (c, dim = 1, mask = l2).ne.1) STOP 67
if (minval (c, dim = 1, mask = l2).ne.5) STOP 68
c(2) = h
if (minloc (c, dim = 1, mask = l).ne.2) STOP 69
if (minval (c, dim = 1, mask = l).ne.h) STOP 70
if (minloc (c, dim = 1, mask = l2).ne.2) STOP 71
if (minval (c, dim = 1, mask = l2).ne.h) STOP 72
c(:) = huge(h)
if (minloc (c, dim = 1, mask = l).ne.1) STOP 73
if (minval (c, dim = 1, mask = l).ne.huge(h)) STOP 74
if (minloc (c, dim = 1, mask = l2).ne.1) STOP 75
if (minval (c, dim = 1, mask = l2).ne.huge(h)) STOP 76
c(3) = huge(h) - 1
if (minloc (c, dim = 1, mask = l).ne.3) STOP 77
if (minval (c, dim = 1, mask = l).ne.huge(h)-1) STOP 78
if (minloc (c, dim = 1, mask = l2).ne.3) STOP 79
if (minval (c, dim = 1, mask = l2).ne.huge(h)-1) STOP 80
deallocate (c)
allocate (c(-2:-3))
if (minloc (c, dim = 1).ne.0) STOP 81
if (minval (c, dim = 1).ne.huge(h)) STOP 82
end
| 0 | 0.503937 | 1 | 0.503937 | game-dev | MEDIA | 0.538418 | game-dev | 0.663422 | 1 | 0.663422 |
FyroxEngine/Fyrox | 2,820 | editor/src/export/asset.rs | // Copyright (c) 2019-present Dmitry Stepanov and Fyrox Engine contributors.
//
// 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.
//! Asset processing module.
use crate::export::utils;
use fyrox::{
asset::manager::ResourceManager,
core::{
futures::executor, futures::future::join_all, log::Log, platform::TargetPlatform, SafeLock,
},
};
use std::{fs, io, path::Path};
pub fn copy_and_convert_assets(
src_folder: impl AsRef<Path>,
dst_folder: impl AsRef<Path>,
target_platform: TargetPlatform,
filter: &dyn Fn(&Path) -> bool,
resource_manager: &ResourceManager,
convert: bool,
) -> io::Result<()> {
if convert {
let rm = resource_manager.state();
let io = rm.resource_io.clone();
let loaders = rm.loaders.safe_lock();
let mut tasks = Vec::new();
// Iterate over the file system and try to convert all the supported resources.
utils::copy_dir_ex(
src_folder,
dst_folder,
&filter,
&mut |src_file, dst_file| {
if let Some(loader) = loaders.loader_for(src_file) {
tasks.push(loader.convert(
src_file.to_path_buf(),
dst_file.to_path_buf(),
target_platform,
io.clone(),
));
Ok(())
} else {
fs::copy(src_file, dst_file)?;
Ok(())
}
},
)?;
// Wait until everything is converted and copied.
for result in executor::block_on(join_all(tasks)) {
Log::verify(result);
}
Ok(())
} else {
utils::copy_dir(src_folder, dst_folder, &filter)
}
}
| 0 | 0.961253 | 1 | 0.961253 | game-dev | MEDIA | 0.326791 | game-dev | 0.906092 | 1 | 0.906092 |
EarthSalamander42/dota_imba | 49,021 | game/scripts/vscripts/components/abilities/heroes/hero_lina.lua | -- Editors:
-- Firetoad
-- AtroCty, 23.03.2017
-- naowin, 20.05.2018
-------------------------------------------
-- #8 Talent - Blazing strike
-------------------------------------------
LinkLuaModifier("modifier_special_bonus_imba_lina_8", "components/abilities/heroes/hero_lina.lua", LUA_MODIFIER_MOTION_NONE)
modifier_special_bonus_imba_lina_8 = modifier_special_bonus_imba_lina_8 or class({})
function modifier_special_bonus_imba_lina_8:IsHidden() return true end
function modifier_special_bonus_imba_lina_8:RemoveOnDeath() return false end
function modifier_special_bonus_imba_lina_8:DeclareFunctions()
return {
MODIFIER_EVENT_ON_ATTACK_LANDED
}
end
function modifier_special_bonus_imba_lina_8:OnAttackLanded( params )
if IsServer() then
local parent = self:GetParent()
local target = params.target
if parent == params.attacker and target:GetTeamNumber() ~= parent:GetTeamNumber() and (target.IsCreep or target.IsHero) then
local int = parent:GetIntellect()
local ticks = parent:FindTalentValue("special_bonus_imba_lina_8", "ticks_amount")
local duration = parent:FindTalentValue("special_bonus_imba_lina_8", "duration")
local dmg_int_pct = parent:FindTalentValue("special_bonus_imba_lina_8", "dmg_int_pct")
local dmg_per_tick = ( int * dmg_int_pct / 100) / (duration / ticks)
local tick_duration = duration / ticks
target:AddNewModifier(parent, nil, "modifier_imba_blazing_fire", {duration = duration * (1 - target:GetStatusResistance()), dmg_per_tick = dmg_per_tick, tick_duration = tick_duration})
end
end
end
LinkLuaModifier("modifier_imba_blazing_fire", "components/abilities/heroes/hero_lina", LUA_MODIFIER_MOTION_NONE)
modifier_imba_blazing_fire = class({})
function modifier_imba_blazing_fire:OnCreated( params )
if IsServer() then
self.dmg_per_tick = params.dmg_per_tick
self.counter = 10
local parent = self:GetParent()
self:StartIntervalThink(params.tick_duration)
self.particle_fx = ParticleManager:CreateParticle("particles/units/heroes/hero_lina/lina_fiery_soul.vpcf", PATTACH_CUSTOMORIGIN_FOLLOW, self:GetCaster(), self:GetCaster())
ParticleManager:SetParticleControlEnt(self.particle_fx, 0, parent, PATTACH_POINT_FOLLOW, "attach_hitloc", parent:GetAbsOrigin(), true)
ParticleManager:SetParticleControl(self.particle_fx, 1, Vector(1,0,0))
end
end
function modifier_imba_blazing_fire:OnRefresh( params )
if IsServer() then
self.dmg_per_tick = params.dmg_per_tick
self.counter = 10
end
end
function modifier_imba_blazing_fire:OnIntervalThink( )
if IsServer() then
ApplyDamage({victim = self:GetParent(), attacker = self:GetCaster(), ability = nil, damage = self.dmg_per_tick, damage_type = DAMAGE_TYPE_MAGICAL})
self.counter = self.counter - 1
end
end
function modifier_imba_blazing_fire:OnDestroy( params )
if IsServer() then
ApplyDamage({victim = self:GetParent(), attacker = self:GetCaster(), ability = nil, damage = (self.dmg_per_tick * self.counter), damage_type = DAMAGE_TYPE_MAGICAL})
ParticleManager:DestroyParticle(self.particle_fx, false)
ParticleManager:ReleaseParticleIndex(self.particle_fx)
end
end
function modifier_imba_blazing_fire:IsDebuff()
return true
end
function modifier_imba_blazing_fire:IsHidden()
return false
end
function modifier_imba_blazing_fire:GetTexture()
return "lina_fiery_soul"
end
-------------------------------------------
-- DRAGON SLAVE
-------------------------------------------
imba_lina_dragon_slave = class({})
function imba_lina_dragon_slave:GetCooldown(level)
return self.BaseClass.GetCooldown(self, level) - self:GetCaster():FindTalentValue("special_bonus_imba_lina_10")
end
function imba_lina_dragon_slave:OnUpgrade()
self.cast_point = self.cast_point or self:GetCastPoint()
end
function imba_lina_dragon_slave:OnSpellStart()
if IsServer() then
-- Preventing projectiles getting stuck in one spot due to potential 0 length vector
if self:GetCursorPosition() == self:GetCaster():GetAbsOrigin() then
self:GetCaster():SetCursorPosition(self:GetCursorPosition() + self:GetCaster():GetForwardVector())
end
local caster = self:GetCaster()
local target_loc = self:GetCursorPosition()
local caster_loc = caster:GetAbsOrigin()
-- Parameters
local primary_damage = self:GetSpecialValueFor("primary_damage")
local secondary_damage = self:GetSpecialValueFor("secondary_damage")
local spread_angle = self:GetSpecialValueFor("spread_angle")
local secondary_amount = self:GetTalentSpecialValueFor("secondary_amount")
local speed = self:GetSpecialValueFor("speed")
local width_initial = self:GetSpecialValueFor("width_initial")
local width_end = self:GetSpecialValueFor("width_end")
local primary_distance = self:GetCastRange(caster_loc,caster) + GetCastRangeIncrease(caster)
local secondary_distance = self:GetSpecialValueFor("secondary_distance")
local split_delay = self:GetSpecialValueFor("split_delay")
local secondary_width_initial = self:GetSpecialValueFor("secondary_width_initial")
local secondary_width_end = self:GetSpecialValueFor("secondary_width_end")
local cdr_hero = self:GetSpecialValueFor("cdr_hero")
local cdr_units = self:GetSpecialValueFor("cdr_units")
-- Distances
local direction = (target_loc - caster_loc):Normalized()
local primary_direction = (target_loc - caster_loc):Normalized()
local split_timer = (CalculateDistance(caster_loc,target_loc) / speed)
local velocity = direction * speed
local primary_velocity = primary_direction * speed
local projectile =
{
Ability = self,
EffectName = "particles/units/heroes/hero_lina/lina_spell_dragon_slave.vpcf",
vSpawnOrigin = caster_loc,
fDistance = primary_distance,
fStartRadius = width_initial,
fEndRadius = width_end,
Source = caster,
bHasFrontalCone = true,
bReplaceExisting = false,
iUnitTargetTeam = DOTA_UNIT_TARGET_TEAM_ENEMY,
iUnitTargetFlags = DOTA_UNIT_TARGET_FLAG_NONE,
iUnitTargetType = DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC,
fExpireTime = GameRules:GetGameTime() + 10.0,
bDeleteOnHit = false,
vVelocity = Vector(velocity.x,velocity.y,0),
bProvidesVision = false,
ExtraData = {damage = primary_damage, cdr_hero = cdr_hero, cdr_units = cdr_units}
}
ProjectileManager:CreateLinearProjectile(projectile)
if secondary_amount == 0 then
return true
end
caster:EmitSound("Hero_Lina.DragonSlave")
Timers:CreateTimer(split_timer - 0.1, function()
local particle_fx = ParticleManager:CreateParticle("particles/hero/lina/dragon_slave_delay.vpcf", PATTACH_ABSORIGIN, caster)
ParticleManager:SetParticleControl(particle_fx, 0, (target_loc + Vector(0,0,50)))
ParticleManager:SetParticleControl(particle_fx, 1, (target_loc + Vector(0,0,50)))
ParticleManager:SetParticleControl(particle_fx, 3, (target_loc + Vector(0,0,50)))
Timers:CreateTimer(split_delay + 0.1, function()
ParticleManager:DestroyParticle(particle_fx, false)
ParticleManager:ReleaseParticleIndex(particle_fx)
local particle_fx2 = ParticleManager:CreateParticle("particles/econ/items/shadow_fiend/sf_fire_arcana/sf_fire_arcana_loadout.vpcf", PATTACH_ABSORIGIN, caster)
ParticleManager:SetParticleControl(particle_fx2, 0, target_loc)
Timers:CreateTimer(1, function()
ParticleManager:DestroyParticle(particle_fx2, false)
ParticleManager:ReleaseParticleIndex(particle_fx2)
end)
end)
end)
Timers:CreateTimer((split_timer + split_delay), function()
EmitSoundOnLocationWithCaster( target_loc, "Hero_Lina.DragonSlave", caster )
local start_angle
local interval_angle = 0
if secondary_amount == 1 then
start_angle = 0
else
start_angle = spread_angle * (-1)
interval_angle = spread_angle * 2 / (secondary_amount - 1)
end
for i = 1, secondary_amount, 1 do
local angle = start_angle + (i-1) * interval_angle
velocity = RotateVector2D(direction,angle,true) * speed
local projectile =
{
Ability = self,
EffectName = "particles/units/heroes/hero_lina/lina_spell_dragon_slave.vpcf",
vSpawnOrigin = target_loc,
fDistance = secondary_distance,
fStartRadius = secondary_width_initial,
fEndRadius = secondary_width_end,
Source = caster,
bHasFrontalCone = true,
bReplaceExisting = false,
iUnitTargetTeam = DOTA_UNIT_TARGET_TEAM_ENEMY,
iUnitTargetFlags = DOTA_UNIT_TARGET_FLAG_NONE,
iUnitTargetType = DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC,
fExpireTime = GameRules:GetGameTime() + 10.0,
bDeleteOnHit = false,
vVelocity = Vector(velocity.x,velocity.y,0),
bProvidesVision = false,
ExtraData = {damage = secondary_damage, cdr_hero = cdr_hero, cdr_units = cdr_units}
}
ProjectileManager:CreateLinearProjectile(projectile)
end
end)
if caster:HasTalent("special_bonus_imba_lina_2") then
local new_loc = target_loc + primary_direction * secondary_distance
local new_timer = (CalculateDistance(caster_loc,new_loc) / speed)
Timers:CreateTimer((new_timer + split_delay), function()
EmitSoundOnLocationWithCaster( new_loc, "Hero_Lina.DragonSlave", caster )
local projectile =
{
Ability = self,
EffectName = "particles/units/heroes/hero_lina/lina_spell_dragon_slave.vpcf",
vSpawnOrigin = new_loc,
fDistance = primary_distance,
fStartRadius = width_initial,
fEndRadius = width_end,
Source = caster,
bHasFrontalCone = true,
bReplaceExisting = false,
iUnitTargetTeam = DOTA_UNIT_TARGET_TEAM_ENEMY,
iUnitTargetFlags = DOTA_UNIT_TARGET_FLAG_NONE,
iUnitTargetType = DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC,
fExpireTime = GameRules:GetGameTime() + 10.0,
bDeleteOnHit = false,
vVelocity = Vector(primary_velocity.x,primary_velocity.y,0),
bProvidesVision = false,
ExtraData = {damage = primary_damage, cdr_hero = cdr_hero, cdr_units = cdr_units}
}
ProjectileManager:CreateLinearProjectile(projectile)
end)
end
end
end
function imba_lina_dragon_slave:OnProjectileHit_ExtraData(target, location, ExtraData)
if target then
local caster = self:GetCaster()
local ability_laguna = caster:FindAbilityByName("imba_lina_laguna_blade")
local pfx = ParticleManager:CreateParticle("particles/units/heroes/hero_lina/lina_spell_dragon_slave_impact.vpcf", PATTACH_ABSORIGIN_FOLLOW, caster, caster)
ParticleManager:SetParticleControl(pfx, 0, target:GetAbsOrigin())
ParticleManager:SetParticleControl(pfx, 1, target:GetAbsOrigin())
ApplyDamage({victim = target, attacker = caster, ability = self, damage = ExtraData.damage, damage_type = self:GetAbilityDamageType()})
-- #5 Talent: Lina's Spells causes DoT based on Fiery Soul stacks
if caster:HasTalent("special_bonus_imba_lina_5") then
local blaze_burn = target:FindModifierByName("modifier_imba_fiery_soul_blaze_burn")
if blaze_burn then
blaze_burn:ForceRefresh()
else
local fiery_soul = caster:FindAbilityByName("imba_lina_fiery_soul")
if fiery_soul:GetLevel() > 0 then
target:AddNewModifier(caster, fiery_soul, "modifier_imba_fiery_soul_blaze_burn", {duration = caster:FindTalentValue("special_bonus_imba_lina_5","duration") * (1 - target:GetStatusResistance())})
end
end
end
target:RemoveModifierByName("modifier_imba_blazing_fire")
if ability_laguna and not ability_laguna:IsCooldownReady() then
local cdr
if target:IsHero() and not target:IsIllusion() then
cdr = ExtraData.cdr_hero
else
cdr = ExtraData.cdr_units
end
local current_cooldown = ability_laguna:GetCooldownTimeRemaining()
ability_laguna:EndCooldown()
ability_laguna:StartCooldown(current_cooldown - cdr)
end
end
return false
end
function imba_lina_dragon_slave:IsStealable()
return true
end
function imba_lina_dragon_slave:IsHiddenWhenStolen()
return false
end
-------------------------------------------
-- LIGHT STRIKE ARRAY
-------------------------------------------
imba_lina_light_strike_array = class({})
LinkLuaModifier("modifier_imba_lsa_talent_magma", "components/abilities/heroes/hero_lina", LUA_MODIFIER_MOTION_NONE)
function imba_lina_light_strike_array:OnSpellStart()
if IsServer() then
local caster = self:GetCaster()
local target_loc = self:GetCursorPosition()
local caster_loc = caster:GetAbsOrigin()
-- Parameters
local radius = self:GetSpecialValueFor("aoe_radius")
local cast_delay = self:GetSpecialValueFor("cast_delay")
local stun_duration = self:GetSpecialValueFor("stun_duration")
local damage = self:GetTalentSpecialValueFor("damage")
local secondary_delay = self:GetSpecialValueFor("secondary_delay")
local array_count = self:GetSpecialValueFor("array_count")
local array_rings_count = self:GetSpecialValueFor("array_rings_count")
local rings_radius = self:GetSpecialValueFor("rings_radius")
local rings_delay = self:GetSpecialValueFor("rings_delay")
local rings_distance = self:GetSpecialValueFor("rings_distance")
-- Distances
local direction = (target_loc - caster_loc):Normalized()
-- Emit cast-sound
caster:EmitSound("Ability.PreLightStrikeArray")
-- Response 20%
if (math.random(1,5) < 2) and (caster:GetName() == "npc_dota_hero_lina") then
caster:EmitSound("lina_lina_ability_lightstrike_0"..math.random(1,6))
end
-- Only create the main array blast
self:CreateStrike( target_loc, 0, cast_delay, radius, damage, stun_duration )
-- #7 Talent, Main Light Strike Array's explosion is repeated 2 times
if caster:HasTalent("special_bonus_imba_lina_7") then
local nuclear_radius = radius
local nuclear_stun_duration = stun_duration
for k=1, caster:FindTalentValue("special_bonus_imba_lina_7")-1, 1 do
nuclear_radius = nuclear_radius + caster:FindTalentValue("special_bonus_imba_lina_7","add_radius") * k
nuclear_stun_duration = nuclear_stun_duration * (1/(caster:FindTalentValue("special_bonus_imba_lina_7","stun_reduct")*k))
self:CreateStrike( target_loc, (cast_delay * k), cast_delay, nuclear_radius, damage, nuclear_stun_duration )
end
end
for i=0, array_count-1, 1 do
-- local distance = i
-- local count = i
-- local next_distance = i+1
local array_strike = i+1
-- distance = radius * (distance + rings_distance)
-- next_distance = radius * (next_distance + rings_distance)
--if i == 0 then
-- distance = 0
-- next_distance = 0.25 * radius
--else
--if math.mod(i,2) == 1 then
-- distance = radius * (distance + 0.25)
-- next_distance = radius * (next_distance + 0.25)
--else
-- distance = radius * distance * (-1)
--end
--end
-- local delay = math.abs(distance / (radius * 2)) * cast_delay
-- local position = target_loc + distance * direction
-- Create 6 LSA rings around the explosion
local rings_direction = direction
for j=1, array_rings_count, 1 do
rings_direction = RotateVector2D(rings_direction,((360/array_rings_count)),true)
-- new_rings_direction = RotateVector2D(rings_direction,30,true) -- Determines the Hexagon angle
local ring_distance = rings_radius * (array_strike + 1)
local ring_delay = math.abs((radius * (i + cast_delay + rings_distance)) / (rings_radius * 2)) * cast_delay
local ring_position = target_loc + ring_distance * rings_direction
self:CreateStrike( ring_position, (cast_delay + ring_delay), (cast_delay + rings_delay), rings_radius, damage, stun_duration )
end
end
end
end
function imba_lina_light_strike_array:CreateStrike( position, delay, cast_delay, radius, damage, stun_duration )
local caster = self:GetCaster()
Timers:CreateTimer(delay, function()
local cast_pfx = ParticleManager:CreateParticleForTeam("particles/units/heroes/hero_lina/lina_spell_light_strike_array_ray_team.vpcf", PATTACH_WORLDORIGIN, caster, caster:GetTeam(), caster)
ParticleManager:SetParticleControl(cast_pfx, 0, position)
ParticleManager:SetParticleControl(cast_pfx, 1, Vector(radius * 2, 0, 0))
ParticleManager:ReleaseParticleIndex(cast_pfx)
end)
Timers:CreateTimer((delay+cast_delay), function()
-- Emit particle + sound
local blast_pfx = ParticleManager:CreateParticle("particles/units/heroes/hero_lina/lina_spell_light_strike_array.vpcf", PATTACH_CUSTOMORIGIN, nil, caster)
ParticleManager:SetParticleControl(blast_pfx, 0, position)
ParticleManager:SetParticleControl(blast_pfx, 1, Vector(radius, 0, 0))
ParticleManager:ReleaseParticleIndex(blast_pfx)
EmitSoundOnLocationWithCaster( position, "Ability.LightStrikeArray", caster )
-- Destroys trees
GridNav:DestroyTreesAroundPoint(position, radius, false)
-- Deal damage and stun
local enemies = FindUnitsInRadius(caster:GetTeamNumber(), position, nil, radius, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, DOTA_UNIT_TARGET_FLAG_NONE, FIND_ANY_ORDER, false)
for _,enemy in ipairs(enemies) do
self:OnHit(enemy, damage, stun_duration)
end
-- #4 Talent: After a Light Strike Array hits the ground, magma erupts and damages nearby enemy units
if caster:HasTalent("special_bonus_imba_lina_4") then
CreateModifierThinker(caster, self, "modifier_imba_lsa_talent_magma", {duration = stun_duration, radius = radius}, position, caster:GetTeamNumber(), false)
end
end)
end
function imba_lina_light_strike_array:OnHit( target, damage, stun_duration )
local caster = self:GetCaster()
ApplyDamage({attacker = caster, victim = target, ability = self, damage = damage, damage_type = self:GetAbilityDamageType()})
-- #5 Talent: Lina's Spells causes DoT based on Fiery Soul stacks
if caster:HasTalent("special_bonus_imba_lina_5") then
local blaze_burn = target:FindModifierByName("modifier_imba_fiery_soul_blaze_burn")
if blaze_burn then
blaze_burn:ForceRefresh()
else
local fiery_soul = caster:FindAbilityByName("imba_lina_fiery_soul")
if fiery_soul:GetLevel() > 0 then
target:AddNewModifier(caster,fiery_soul,"modifier_imba_fiery_soul_blaze_burn",{duration = caster:FindTalentValue("special_bonus_imba_lina_5","duration") * (1 - target:GetStatusResistance())})
end
end
end
target:RemoveModifierByName("modifier_imba_blazing_fire")
-- more fail-safe, AddNewModifier attempt to index a nil value
if target:IsAlive() then
target:AddNewModifier(caster, self, "modifier_stunned", {duration = stun_duration * (1 - target:GetStatusResistance())})
end
end
function imba_lina_light_strike_array:GetAOERadius()
return self:GetSpecialValueFor("aoe_radius")
end
function imba_lina_light_strike_array:IsHiddenWhenStolen()
return false
end
-- From The Ash magma modifier
modifier_imba_lsa_talent_magma = modifier_imba_lsa_talent_magma or class({})
function modifier_imba_lsa_talent_magma:OnCreated(kv)
if IsServer() then
-- Talent properties
self.caster = self:GetCaster()
self.ability = self:GetAbility()
self.parent = self:GetParent()
-- Talent specials
self.radius = kv.radius
-- print(self.radius)
self.damage = self.caster:FindTalentValue("special_bonus_imba_lina_4", "damage")
self.tick_interval = self.caster:FindTalentValue("special_bonus_imba_lina_4", "tick_interval")
-- Play magma particle effect, assign to modifier
local particle_magma = ParticleManager:CreateParticle("particles/hero/lina/from_the_ash.vpcf", PATTACH_WORLDORIGIN, nil, self.caster)
ParticleManager:SetParticleControl(particle_magma, 0, self.parent:GetAbsOrigin())
ParticleManager:SetParticleControl(particle_magma, 1, self.parent:GetAbsOrigin())
ParticleManager:SetParticleControl(particle_magma, 2, Vector(1,0,0))
ParticleManager:SetParticleControl(particle_magma, 3, self.parent:GetAbsOrigin())
self:AddParticle(particle_magma, false, false, -1, false, false)
-- Calculate damage per tick
self.damage_per_tick = self.damage * self.tick_interval
-- Start thinking
self:StartIntervalThink(self.tick_interval)
end
end
function modifier_imba_lsa_talent_magma:OnIntervalThink()
if IsServer() then
-- Find enemies in AoE
local enemies = FindUnitsInRadius(self.caster:GetTeamNumber(),
self.parent:GetAbsOrigin(),
nil,
self.radius,
DOTA_UNIT_TARGET_TEAM_ENEMY,
DOTA_UNIT_TARGET_BASIC + DOTA_UNIT_TARGET_HERO,
DOTA_UNIT_TARGET_FLAG_NONE,
FIND_ANY_ORDER,
false)
local damage_table = (
{
attacker = self.caster,
ability = self.ability,
damage = self.damage,
damage_type = DAMAGE_TYPE_MAGICAL
}
)
-- Deal damage per tick to each enemy
for _, enemy in pairs(enemies) do
damage_table.victim = enemy
ApplyDamage(damage_table)
end
end
end
-- Version 2 with "cleaner" code; no IMBAfications for now, but might use this for a rework down the line.
LinkLuaModifier("modifier_imba_lina_light_strike_array_v2_thinker", "components/abilities/heroes/hero_lina", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_lina_light_strike_array_v2_thinker_single", "components/abilities/heroes/hero_lina", LUA_MODIFIER_MOTION_NONE)
-------------------------------------
-- IMBA_LINA_LIGHT_STRIKE_ARRAY_V2 --
-------------------------------------
imba_lina_light_strike_array_v2 = imba_lina_light_strike_array_v2 or class({})
modifier_imba_lina_light_strike_array_v2_thinker = modifier_imba_lina_light_strike_array_v2_thinker or class({})
modifier_imba_lina_light_strike_array_v2_thinker_single = modifier_imba_lina_light_strike_array_v2_thinker_single or class({})
function imba_lina_light_strike_array_v2:GetAOERadius()
return self:GetSpecialValueFor("light_strike_array_aoe")
end
function imba_lina_light_strike_array_v2:OnSpellStart()
CreateModifierThinker(self:GetCaster(), self, "modifier_imba_lina_light_strike_array_v2_thinker", {duration = self:GetSpecialValueFor("light_strike_array_delay_time")}, self:GetCursorPosition(), self:GetCaster():GetTeamNumber(), false)
end
------------------------------------------------------
-- MODIFIER_IMBA_LINA_LIGHT_STRIKE_ARRAY_V2_THINKER --
------------------------------------------------------
function modifier_imba_lina_light_strike_array_v2_thinker:OnCreated()
self.light_strike_array_aoe = self:GetAbility():GetSpecialValueFor("light_strike_array_aoe")
self.light_strike_array_delay_time = self:GetAbility():GetSpecialValueFor("light_strike_array_delay_time")
self.light_strike_array_stun_duration = self:GetAbility():GetSpecialValueFor("light_strike_array_stun_duration")
if not IsServer() then return end
self.light_strike_array_damage = self:GetAbility():GetTalentSpecialValueFor("light_strike_array_damage")
self.damage_type = self:GetAbility():GetAbilityDamageType()
EmitSoundOnLocationForAllies(self:GetParent():GetAbsOrigin(), "Ability.PreLightStrikeArray", self:GetCaster())
local ray_team_particle = ParticleManager:CreateParticleForTeam("particles/units/heroes/hero_lina/lina_spell_light_strike_array_ray_team.vpcf", PATTACH_WORLDORIGIN, self:GetCaster(), self:GetCaster():GetTeamNumber())
ParticleManager:SetParticleControl(ray_team_particle, 0, self:GetParent():GetAbsOrigin())
ParticleManager:SetParticleControl(ray_team_particle, 1, Vector(self.light_strike_array_aoe, 0, 0))
ParticleManager:ReleaseParticleIndex(ray_team_particle)
self:OnIntervalThink()
-- self:StartIntervalThink(-1)
end
function modifier_imba_lina_light_strike_array_v2_thinker:OnIntervalThink()
CreateModifierThinker(self:GetCaster(), self, "modifier_imba_lina_light_strike_array_v2_thinker_single", {
duration = self.light_strike_array_delay_time,
light_strike_array_aoe = self.light_strike_array_aoe,
light_strike_array_stun_duration = self.light_strike_array_stun_duration,
light_strike_array_damage = self.light_strike_array_damage,
damage_type = self.damage_type
}, self:GetParent():GetAbsOrigin(), self:GetCaster():GetTeamNumber(), false)
end
-------------------------------------------------------------
-- MODIFIER_IMBA_LINA_LIGHT_STRIKE_ARRAY_V2_THINKER_SINGLE --
-------------------------------------------------------------
function modifier_imba_lina_light_strike_array_v2_thinker_single:OnCreated(keys)
if not IsServer() then return end
self.light_strike_array_aoe = keys.light_strike_array_aoe
self.light_strike_array_stun_duration = keys.light_strike_array_stun_duration
self.light_strike_array_damage = keys.light_strike_array_damage
self.damage_type = keys.damage_type
EmitSoundOnLocationForAllies(self:GetParent():GetAbsOrigin(), "Ability.PreLightStrikeArray", self:GetCaster())
local ray_team_particle = ParticleManager:CreateParticleForTeam("particles/units/heroes/hero_lina/lina_spell_light_strike_array_ray_team.vpcf", PATTACH_WORLDORIGIN, self:GetCaster(), self:GetCaster():GetTeamNumber())
ParticleManager:SetParticleControl(ray_team_particle, 0, self:GetParent():GetAbsOrigin())
ParticleManager:SetParticleControl(ray_team_particle, 1, Vector(self.light_strike_array_aoe, 0, 0))
ParticleManager:ReleaseParticleIndex(ray_team_particle)
end
function modifier_imba_lina_light_strike_array_v2_thinker_single:OnDestroy()
if not IsServer() then return end
EmitSoundOnLocationWithCaster(self:GetParent():GetAbsOrigin(), "Ability.LightStrikeArray", self:GetCaster())
local array_particle = ParticleManager:CreateParticle("particles/units/heroes/hero_lina/lina_spell_light_strike_array.vpcf", PATTACH_CUSTOMORIGIN, nil)
ParticleManager:SetParticleControl(array_particle, 0, self:GetParent():GetAbsOrigin())
ParticleManager:SetParticleControl(array_particle, 1, Vector(self.light_strike_array_aoe, 1, 1))
ParticleManager:ReleaseParticleIndex(array_particle)
-- "Light Strike Array destroys trees within the affected radius."
GridNav:DestroyTreesAroundPoint(self:GetParent():GetAbsOrigin(), self.light_strike_array_aoe, false)
for _, enemy in pairs(FindUnitsInRadius(self:GetCaster():GetTeamNumber(), self:GetParent():GetAbsOrigin(), nil, self.light_strike_array_aoe, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, DOTA_UNIT_TARGET_FLAG_NONE, FIND_ANY_ORDER, false)) do
-- "Light Strike Array first applies the debuff, then the damage."
enemy:AddNewModifier(self:GetCaster(), self:GetAbility(), "modifier_stunned", {duration = self.light_strike_array_stun_duration * (1 - enemy:GetStatusResistance())})
ApplyDamage({
victim = enemy,
damage = self.light_strike_array_damage,
damage_type = self.damage_type,
damage_flags = DOTA_DAMAGE_FLAG_NONE,
attacker = self:GetCaster(),
ability = self:GetAbility()
})
end
end
-------------------------------------------
-- FIERY SOUL
-------------------------------------------
imba_lina_fiery_soul = class({})
LinkLuaModifier("modifier_imba_fiery_soul", "components/abilities/heroes/hero_lina", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_fiery_soul_counter", "components/abilities/heroes/hero_lina", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_fiery_soul_blaze_burn", "components/abilities/heroes/hero_lina", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_fiery_soul_talent", "components/abilities/heroes/hero_lina", LUA_MODIFIER_MOTION_NONE)
function imba_lina_fiery_soul:IsStealable() return false end
function imba_lina_fiery_soul:GetIntrinsicModifierName()
return "modifier_imba_fiery_soul"
end
function imba_lina_fiery_soul:GetCastRange(location, target)
return self:GetSpecialValueFor("immolation_aoe") - self:GetCaster():GetCastRangeBonus()
end
function imba_lina_fiery_soul:GetCooldown()
return self:GetSpecialValueFor("active_cooldown")
end
function imba_lina_fiery_soul:OnSpellStart()
if IsServer() then
local caster = self:GetCaster()
local caster_loc = caster:GetAbsOrigin()
-- Wait for the game to tick to remove the modifier
Timers:CreateTimer(FrameTime(), function()
local fiery_modifier = caster:FindModifierByName("modifier_imba_fiery_soul_counter")
if fiery_modifier then
fiery_modifier:Destroy()
end
end)
-- -- Parameters
-- local immolation_damage_min = caster:FindTalentValue("special_bonus_imba_lina_3")
-- local immolation_damage_max = caster:FindTalentValue("special_bonus_imba_lina_3","value2")
-- local immolation_aoe = caster:FindTalentValue("special_bonus_imba_lina_3","aoe")
-- local min_damage_aoe = caster:FindTalentValue("special_bonus_imba_lina_3","min_damage_aoe")
-- local max_damage_aoe = caster:FindTalentValue("special_bonus_imba_lina_3","max_damage_aoe")
-- Parameters
local immolation_damage_min = self:GetSpecialValueFor("immolation_damage_min")
local immolation_damage_max = self:GetSpecialValueFor("immolation_damage_max")
local immolation_aoe = self:GetSpecialValueFor("immolation_aoe")
local min_damage_aoe = self:GetSpecialValueFor("min_damage_aoe")
local max_damage_aoe = self:GetSpecialValueFor("max_damage_aoe")
-- Emit particle + sound
EmitSoundOnLocationWithCaster(caster_loc, "Hero_Phoenix.SuperNova.Explode", caster)
local blast_pfx = ParticleManager:CreateParticle("particles/hero/lina/lina_immolation.vpcf", PATTACH_CUSTOMORIGIN, nil, caster)
ParticleManager:SetParticleControl(blast_pfx, 0, caster_loc)
ParticleManager:SetParticleControl(blast_pfx, 1, Vector(1.5,1.5,1.5))
ParticleManager:SetParticleControl(blast_pfx, 3, caster_loc)
ParticleManager:SetParticleControl(blast_pfx, 13, Vector(immolation_aoe, 0, 0))
ParticleManager:SetParticleControl(blast_pfx, 15, caster_loc)
ParticleManager:ReleaseParticleIndex(blast_pfx)
-- Destroys trees
GridNav:DestroyTreesAroundPoint(caster_loc, immolation_aoe, false)
-- Deal damage
local enemies = FindUnitsInRadius(caster:GetTeamNumber(), caster_loc, nil, immolation_aoe, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, DOTA_UNIT_TARGET_FLAG_NONE, FIND_ANY_ORDER, false)
for _,enemy in ipairs(enemies) do
local distance = (caster_loc - enemy:GetAbsOrigin()):Length2D()
local immolation_damage
-- Deal the damage based on the target's distance
if distance >= min_damage_aoe then
immolation_damage = immolation_damage_min
elseif distance <= max_damage_aoe then
immolation_damage = immolation_damage_max
else
immolation_damage = immolation_damage_min + math.floor((immolation_damage_max - immolation_damage_min) * ((min_damage_aoe - distance)/(min_damage_aoe - max_damage_aoe)))
end
enemy:RemoveModifierByName("modifier_imba_blazing_fire")
ApplyDamage({attacker = caster, victim = enemy, ability = self, damage = immolation_damage, damage_type = self:GetAbilityDamageType()})
-- #5 Talent: Lina's Spells causes DoT based on Fiery Soul stacks
if caster:HasTalent("special_bonus_imba_lina_5") then
local blaze_burn = enemy:FindModifierByName("modifier_imba_fiery_soul_blaze_burn")
if blaze_burn then
blaze_burn:ForceRefresh()
else
local fiery_soul = caster:FindAbilityByName("imba_lina_fiery_soul")
if fiery_soul:GetLevel() > 0 then
enemy:AddNewModifier(caster,fiery_soul,"modifier_imba_fiery_soul_blaze_burn",{duration = caster:FindTalentValue("special_bonus_imba_lina_5","duration") * (1 - enemy:GetStatusResistance())})
end
end
end
end
end
end
modifier_imba_fiery_soul = class({})
function modifier_imba_fiery_soul:OnCreated()
-- Turns the skill into passive, tooltip purposes
self:GetAbility().GetBehavior = function() return DOTA_ABILITY_BEHAVIOR_PASSIVE end
self:GetAbility():GetBehavior()
end
function modifier_imba_fiery_soul:DeclareFunctions()
local decFuncs =
{
MODIFIER_EVENT_ON_ABILITY_FULLY_CAST,
}
return decFuncs
end
function modifier_imba_fiery_soul:OnAbilityFullyCast( params )
if IsServer() then
local item = params.ability:IsItem()
if item then
return
end
local parent = self:GetParent()
local caster = params.ability:GetCaster()
if (caster == parent) and params.ability:GetName() ~= "ability_capture" then
parent:AddNewModifier(parent, self:GetAbility(), "modifier_imba_fiery_soul_counter", {duration = self:GetAbility():GetSpecialValueFor("duration")})
-- Fiery Soul ability cooldown reduction
for ability_id = 0, 15 do
local caster_ability = caster:GetAbilityByIndex(ability_id)
if caster_ability then
local ability_name = caster_ability:GetAbilityName()
-- Does not reduce the cooldown of the current ability being casted
if params.ability:GetName() == ability_name then
else
-- Get the modifier
local fiery_counter = caster:FindModifierByName("modifier_imba_fiery_soul_counter")
if fiery_counter then
-- Get the ability cooldown
local cooldown_remaining = caster_ability:GetCooldownTimeRemaining()
local cooldown_reduction = self:GetAbility():GetSpecialValueFor("cdr_pct") -- * fiery_counter:GetStackCount()
caster_ability:EndCooldown()
if cooldown_remaining > cooldown_reduction then
caster_ability:StartCooldown( cooldown_remaining - cooldown_reduction )
end
end
end
end
end
end
return true
end
end
function modifier_imba_fiery_soul:IsHidden()
return true
end
function modifier_imba_fiery_soul:IsPurgable()
return false
end
-- ClientSide fails the check on "GetCaster():HasTalent" so we need a workaround.
-- instead i created a permanent modifier and used check GetCaster():HasModifier()
-- to determine if we have talent selected. // naowin
modifier_imba_fiery_soul_talent = class({})
function modifier_imba_fiery_soul_talent:IsPassive() return true end
function modifier_imba_fiery_soul_talent:RemoveOnDeath() return false end
function modifier_imba_fiery_soul_talent:IsHidden() return true end
modifier_imba_fiery_soul_counter = class({})
function modifier_imba_fiery_soul_counter:OnCreated()
self.bonus_as = self:GetAbility():GetTalentSpecialValueFor("bonus_as")
self.bonus_ms_pct = self:GetAbility():GetSpecialValueFor("bonus_ms_pct") + self:GetCaster():FindTalentValue("special_bonus_imba_lina_9", "value2")
self.animation_pct = self:GetAbility():GetTalentSpecialValueFor("animation_pct")
if IsServer() then
local caster = self:GetCaster()
self:SetStackCount(1)
self.particle = ParticleManager:CreateParticle("particles/hero/lina/fiery_soul.vpcf", PATTACH_ABSORIGIN_FOLLOW, caster, caster)
ParticleManager:SetParticleControl(self.particle, 0, caster:GetAbsOrigin())
ParticleManager:SetParticleControlEnt(self.particle, 1, caster, PATTACH_POINT_FOLLOW, nil, caster:GetAbsOrigin(), true)
ParticleManager:SetParticleControl(self.particle, 3, Vector(1,0,0))
ParticleManager:SetParticleControl(self.particle, 4, Vector(1,0,0))
-- if caster:HasTalent("special_bonus_imba_lina_3") then
caster:AddNewModifier(caster , self:GetAbility(), "modifier_imba_fiery_soul_talent", {})
-- end
end
end
-- Credits: yannich
-- #3 Talent: Reaching 3 Fiery Soul stacks allows Lina to unleash a blast of hot shockwave.
function modifier_imba_fiery_soul_counter:OnRefresh()
local caster = self:GetCaster()
local ability = self:GetAbility()
local stacks = self:GetStackCount()
local max_stacks = ability:GetTalentSpecialValueFor("max_stacks")
self.bonus_as = self:GetAbility():GetTalentSpecialValueFor("bonus_as")
self.bonus_ms_pct = self:GetAbility():GetSpecialValueFor("bonus_ms_pct") + self:GetCaster():FindTalentValue("special_bonus_imba_lina_9", "value2")
self.animation_pct = self:GetAbility():GetTalentSpecialValueFor("animation_pct")
if IsServer() then
if stacks < max_stacks and not caster:PassivesDisabled() then
self:SetStackCount(stacks+1)
ParticleManager:SetParticleControl(self.particle, 3, Vector(stacks,0,0))
ParticleManager:SetParticleControl(self.particle, 4, Vector(stacks,0,3 ))
end
-- if caster:HasTalent("special_bonus_imba_lina_3") then
caster:AddNewModifier(caster, ability, "modifier_imba_fiery_soul_talent", {})
-- end
end
local stacks = self:GetStackCount()
-- if caster:HasModifier("modifier_imba_fiery_soul_talent") then
if stacks == max_stacks then -- inject function calls clientside and serverside (but this is not run on clientside?)
-- Change behavior
ability.GetBehavior = function() return DOTA_ABILITY_BEHAVIOR_NO_TARGET + DOTA_ABILITY_BEHAVIOR_IGNORE_BACKSWING + DOTA_ABILITY_BEHAVIOR_IMMEDIATE end
ability:GetBehavior()
ability:GetCooldown()
if IsClient() then
ability:GetBehavior()
end
elseif stacks < max_stacks then
ability.GetBehavior = function() return DOTA_ABILITY_BEHAVIOR_PASSIVE end
ability:GetBehavior()
ability:GetCooldown()
end
-- end
end
-- When selecting #3 Talent while having max stacks, refresh the modifier to inject function calls
LinkLuaModifier("modifier_special_bonus_imba_lina_3", "components/abilities/heroes/hero_lina.lua", LUA_MODIFIER_MOTION_NONE)
modifier_special_bonus_imba_lina_3 = modifier_special_bonus_imba_lina_3 or class({})
function modifier_special_bonus_imba_lina_3:IsHidden() return true end
function modifier_special_bonus_imba_lina_3:IsPurgable() return false end
function modifier_special_bonus_imba_lina_3:RemoveOnDeath() return false end
function modifier_special_bonus_imba_lina_3:OnCreated()
if IsServer() then
local fiery_soul = self:GetParent():FindAbilityByName("imba_lina_fiery_soul")
if fiery_soul:GetLevel() > 0 then
local fiery_soul_modifier = self:GetParent():FindModifierByName("modifier_imba_fiery_soul_counter")
if fiery_soul_modifier then
-- On refresh, it adds a stack count if its less than max stacks
fiery_soul_modifier:DecrementStackCount()
fiery_soul_modifier:ForceRefresh()
end
end
end
end
function modifier_imba_fiery_soul_counter:OnDestroy()
if IsServer() then
ParticleManager:DestroyParticle(self.particle, false)
ParticleManager:ReleaseParticleIndex(self.particle)
end
self:GetAbility().GetBehavior = function() return DOTA_ABILITY_BEHAVIOR_PASSIVE end
self:GetAbility():GetBehavior()
self:GetAbility():GetCooldown(self:GetAbility():GetLevel())
end
function modifier_imba_fiery_soul_counter:GetTexture()
return "lina_fiery_soul"
end
function modifier_imba_fiery_soul_counter:DeclareFunctions()
local decFuncs =
{
MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT,
MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE,
MODIFIER_PROPERTY_CASTTIME_PERCENTAGE,
}
return decFuncs
end
function modifier_imba_fiery_soul_counter:GetModifierAttackSpeedBonus_Constant()
return self.bonus_as * self:GetStackCount()
end
function modifier_imba_fiery_soul_counter:GetModifierMoveSpeedBonus_Percentage()
return self.bonus_ms_pct * self:GetStackCount()
end
function modifier_imba_fiery_soul_counter:GetModifierPercentageCasttime()
return self.animation_pct * self:GetStackCount()
end
--function modifier_imba_fiery_soul_counter:GetCustomCooldownReductionStacking()
-- return self:GetAbility():GetSpecialValueFor("cdr_pct") * self:GetStackCount()
--end
modifier_imba_fiery_soul_blaze_burn = class({})
function modifier_imba_fiery_soul_blaze_burn:IsHidden() return false end
function modifier_imba_fiery_soul_blaze_burn:IsPurgable() return true end
function modifier_imba_fiery_soul_blaze_burn:IsDebuff() return true end
function modifier_imba_fiery_soul_blaze_burn:OnCreated()
self.caster = self:GetCaster()
self.parent = self:GetParent()
self.ability = self:GetAbility()
self.tick = self.caster:FindTalentValue("special_bonus_imba_lina_5","tick")
self.particle_flame = "particles/hero/clinkz/searing_flames_active/burn_effect.vpcf"
if IsServer() then
-- Add and attach flaming particle
self.particle_flame_fx = ParticleManager:CreateParticle(self.particle_flame, PATTACH_POINT_FOLLOW, self.parent, self.caster)
ParticleManager:SetParticleControlEnt(self.particle_flame_fx, 0, self.parent, PATTACH_POINT_FOLLOW, "attach_hitloc", self.parent:GetAbsOrigin(), true)
self:AddParticle(self.particle_flame_fx, false, false, -1, false, false)
-- Set the flaming color like Firetoad. RE
self.parent:SetRenderColor(255, 86, 1)
self:StartIntervalThink(self.tick)
end
end
function modifier_imba_fiery_soul_blaze_burn:OnIntervalThink()
if IsServer() then
local fiery_soul_counter = self.caster:FindModifierByName("modifier_imba_fiery_soul_counter")
if fiery_soul_counter then
local damage = fiery_soul_counter:GetStackCount() * self.caster:FindTalentValue("special_bonus_imba_lina_5")
ApplyDamage({attacker = self.caster, victim = self.parent, ability = self.ability, damage = damage, damage_type = self.ability:GetAbilityDamageType()})
self.parent:RemoveModifierByName("modifier_imba_blazing_fire")
end
end
end
function modifier_imba_fiery_soul_blaze_burn:OnRefresh()
if IsServer() then
self:SetDuration(self.caster:FindTalentValue("special_bonus_imba_lina_5","duration"),true)
end
end
function modifier_imba_fiery_soul_blaze_burn:OnDestroy()
if IsServer() then
-- Prevent conflict with Firetoad. :D
if self.parent:HasModifier("modifier_imba_lion_hex") then
else
self.parent:SetRenderColor(255,255,255)
end
end
end
-------------------------------------------
-- LAGUNA BLADE
-------------------------------------------
imba_lina_laguna_blade = class({})
function imba_lina_laguna_blade:OnSpellStart()
if IsServer() then
local caster = self:GetCaster()
local target = self:GetCursorTarget()
local target_loc = target:GetAbsOrigin()
local caster_loc = caster:GetAbsOrigin()
local damage_type = self:GetAbilityDamageType()
local damage = self:GetSpecialValueFor("damage")
local effect_delay = self:GetSpecialValueFor("effect_delay")
local bounce_amount = self:GetSpecialValueFor("bounce_amount")
local bounce_range = self:GetSpecialValueFor("bounce_range")
local bounce_delay = self:GetSpecialValueFor("bounce_delay")
-- Play the cast sound + fire particle
caster:EmitSound("Ability.LagunaBlade")
local blade_pfx = ParticleManager:CreateParticle("particles/units/heroes/hero_lina/lina_spell_laguna_blade.vpcf", PATTACH_CUSTOMORIGIN, caster, caster)
ParticleManager:SetParticleControlEnt(blade_pfx, 0, caster, PATTACH_POINT_FOLLOW, "attach_attack1", caster_loc, true)
ParticleManager:SetParticleControlEnt(blade_pfx, 1, target, PATTACH_POINT_FOLLOW, "attach_hitloc", target_loc, true)
ParticleManager:ReleaseParticleIndex(blade_pfx)
-- If the target possesses a ready Spell-Counter, do nothing further
if target:GetTeam() ~= caster:GetTeam() then
if target:TriggerSpellAbsorb(self) then
return nil
end
end
Timers:CreateTimer(effect_delay, function()
ApplyDamage({victim = target, attacker = caster, ability = self, damage = damage, damage_type = damage_type})
-- #5 Talent: Lina's Spells causes DoT based on Fiery Soul stacks
if caster:HasTalent("special_bonus_imba_lina_5") then
local blaze_burn = target:FindModifierByName("modifier_imba_fiery_soul_blaze_burn")
if blaze_burn then
blaze_burn:ForceRefresh()
else
local fiery_soul = caster:FindAbilityByName("imba_lina_fiery_soul")
if fiery_soul:GetLevel() > 0 then
target:AddNewModifier(caster,fiery_soul,"modifier_imba_fiery_soul_blaze_burn",{duration = caster:FindTalentValue("special_bonus_imba_lina_5","duration") * (1 - target:GetStatusResistance())})
end
end
end
target:RemoveModifierByName("modifier_imba_blazing_fire")
if caster:HasTalent("special_bonus_imba_lina_6") then
target:AddNewModifier(caster, self, "modifier_stunned", { duration = caster:FindTalentValue("special_bonus_imba_lina_6") * (1 - target:GetStatusResistance()) })
end
-- Bouncing --
local enemies = FindUnitsInRadius(caster:GetTeamNumber(), target_loc, nil, bounce_range, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, DOTA_UNIT_TARGET_FLAG_NONE, FIND_ANY_ORDER, false)
-- Remove main-target from list
for i=1,#enemies,1 do
if enemies[i] == target then
table.remove(enemies, i)
end
end
-- Bounce on remaining targets
Timers:CreateTimer(bounce_delay, function()
for i=1, math.min(#enemies,bounce_amount),1 do
local bounce_pfx = ParticleManager:CreateParticle("particles/units/heroes/hero_lina/lina_spell_laguna_blade.vpcf", PATTACH_CUSTOMORIGIN, caster, caster)
ParticleManager:SetParticleControlEnt(bounce_pfx, 0, target, PATTACH_POINT_FOLLOW, "attach_hitloc", target_loc, true)
ParticleManager:SetParticleControlEnt(bounce_pfx, 1, enemies[i], PATTACH_POINT_FOLLOW, "attach_hitloc", enemies[i]:GetAbsOrigin(), true)
ParticleManager:ReleaseParticleIndex(bounce_pfx)
Timers:CreateTimer(effect_delay, function()
ApplyDamage({victim = enemies[i], attacker = caster, ability = self, damage = damage, damage_type = damage_type})
-- #5 Talent: Lina's Spells causes DoT based on Fiery Soul stacks
if caster:HasTalent("special_bonus_imba_lina_5") then
local blaze_burn = enemies[i]:FindModifierByName("modifier_imba_fiery_soul_blaze_burn")
if blaze_burn then
blaze_burn:ForceRefresh()
else
local fiery_soul = caster:FindAbilityByName("imba_lina_fiery_soul")
if fiery_soul:GetLevel() > 0 then
enemies[i]:AddNewModifier(caster,fiery_soul,"modifier_imba_fiery_soul_blaze_burn",{duration = caster:FindTalentValue("special_bonus_imba_lina_5","duration") * (1 -enemies[i]:GetStatusResistance())})
end
end
end
enemies[i]:RemoveModifierByName("modifier_imba_blazing_fire")
if caster:HasTalent("special_bonus_imba_lina_6") then
enemies[i]:AddNewModifier(caster, self, "modifier_stunned", { duration = caster:FindTalentValue("special_bonus_imba_lina_6") * (1 -enemies[i]:GetStatusResistance())})
end
end)
end
end)
end)
end
end
-- Restrict Laguna Blade being casted on magic immune without scepter
function imba_lina_laguna_blade:CastFilterResultTarget( target )
if IsServer() then
if target ~= nil and target:IsMagicImmune() and ( not self:GetCaster():HasScepter() ) then
return UF_FAIL_MAGIC_IMMUNE_ENEMY
end
local nResult = UnitFilter( target, self:GetAbilityTargetTeam(), self:GetAbilityTargetType(), self:GetAbilityTargetFlags(), self:GetCaster():GetTeamNumber() )
return nResult
end
end
function imba_lina_laguna_blade:GetAbilityDamageType()
if self:GetCaster():HasScepter() then return DAMAGE_TYPE_PURE end
return DAMAGE_TYPE_MAGICAL
end
function imba_lina_laguna_blade:GetAOERadius()
return self:GetSpecialValueFor("bounce_range")
end
function imba_lina_laguna_blade:GetCooldown( nLevel )
local cooldown = self.BaseClass.GetCooldown( self, nLevel )
local caster = self:GetCaster()
return cooldown
end
function imba_lina_laguna_blade:IsHiddenWhenStolen()
return false
end
---------------------
-- TALENT HANDLERS --
---------------------
LinkLuaModifier("modifier_special_bonus_imba_lina_6", "components/abilities/heroes/hero_lina", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_special_bonus_imba_lina_7", "components/abilities/heroes/hero_lina", LUA_MODIFIER_MOTION_NONE)
modifier_special_bonus_imba_lina_6 = modifier_special_bonus_imba_lina_6 or class({})
modifier_special_bonus_imba_lina_7 = modifier_special_bonus_imba_lina_7 or class({})
function modifier_special_bonus_imba_lina_6:IsHidden() return true end
function modifier_special_bonus_imba_lina_6:IsPurgable() return false end
function modifier_special_bonus_imba_lina_6:RemoveOnDeath() return false end
function modifier_special_bonus_imba_lina_7:IsHidden() return true end
function modifier_special_bonus_imba_lina_7:IsPurgable() return false end
function modifier_special_bonus_imba_lina_7:RemoveOnDeath() return false end
LinkLuaModifier("modifier_special_bonus_imba_lina_9", "components/abilities/heroes/hero_lina", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_special_bonus_imba_lina_10", "components/abilities/heroes/hero_lina", LUA_MODIFIER_MOTION_NONE)
modifier_special_bonus_imba_lina_9 = class({})
modifier_special_bonus_imba_lina_10 = class({})
function modifier_special_bonus_imba_lina_9:IsHidden() return true end
function modifier_special_bonus_imba_lina_9:IsPurgable() return false end
function modifier_special_bonus_imba_lina_9:RemoveOnDeath() return false end
function modifier_special_bonus_imba_lina_10:IsHidden() return true end
function modifier_special_bonus_imba_lina_10:IsPurgable() return false end
function modifier_special_bonus_imba_lina_10:RemoveOnDeath() return false end
function imba_lina_dragon_slave:OnOwnerSpawned()
if self:GetCaster():HasTalent("special_bonus_imba_lina_10") and not self:GetCaster():HasModifier("modifier_special_bonus_imba_lina_10") then
self:GetCaster():AddNewModifier(self:GetCaster(), self:GetCaster():FindAbilityByName("special_bonus_imba_lina_10"), "modifier_special_bonus_imba_lina_10", {})
end
end
function imba_lina_fiery_soul:OnOwnerSpawned()
if self:GetCaster():HasTalent("special_bonus_imba_lina_9") and not self:GetCaster():HasModifier("modifier_special_bonus_imba_lina_9") then
self:GetCaster():AddNewModifier(self:GetCaster(), self:GetCaster():FindAbilityByName("special_bonus_imba_lina_9"), "modifier_special_bonus_imba_lina_9", {})
end
end
| 0 | 0.957672 | 1 | 0.957672 | game-dev | MEDIA | 0.982235 | game-dev | 0.976025 | 1 | 0.976025 |
ReikaKalseki/DragonAPI | 5,796 | ASM/Patchers/RaytracePatcher.java | /*******************************************************************************
* @author Reika Kalseki
*
* Copyright 2017
*
* All rights reserved.
* Distribution of the software in any form is only allowed with
* explicit, prior permission from the owner.
******************************************************************************/
package Reika.DragonAPI.ASM.Patchers;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.VarInsnNode;
import net.minecraftforge.classloading.FMLForgePlugin;
import Reika.DragonAPI.Libraries.Java.ReikaASMHelper;
public abstract class RaytracePatcher extends Patcher {
public RaytracePatcher(String deobf, String obf) {
super(deobf, obf);
}
@Override
protected final void apply(ClassNode cn) {
/*
MethodNode m = ReikaASMHelper.getMethodByName(cn, "func_70071_h_", "onUpdate", "()V");
InsnList li = new InsnList();
li.add(new VarInsnNode(Opcodes.ALOAD, 0));
li.add(new MethodInsnNode(Opcodes.INVOKESTATIC, "Reika/DragonAPI/Instantiable/Event/EntityAboutToRayTraceEvent", "fire", "(Lnet/minecraft/entity/Entity;)V", false));
String func1 = FMLForgePlugin.RUNTIME_DEOBF ? "func_149668_a" : "getCollisionBoundingBoxFromPool";
String func2 = FMLForgePlugin.RUNTIME_DEOBF ? "func_72933_a" : "rayTraceBlocks";
String func3 = FMLForgePlugin.RUNTIME_DEOBF ? "func_147447_a" : "func_147447_a";
String world = FMLForgePlugin.RUNTIME_DEOBF ? "field_70170_p" : "worldObj";
AbstractInsnNode min1 = null;
AbstractInsnNode min2 = null;
AbstractInsnNode min3 = null;
try {
min1 = ReikaASMHelper.getFirstMethodCall(cn, m, "net/minecraft/block/Block", func1, "(Lnet/minecraft/world/World;III)Lnet/minecraft/util/AxisAlignedBB;");
}
catch (NoSuchASMMethodInstructionException e) {
}
try {
min2 = ReikaASMHelper.getFirstMethodCall(cn, m, "net/minecraft/world/World", func2, "(Lnet/minecraft/util/Vec3;Lnet/minecraft/util/Vec3;)Lnet/minecraft/util/MovingObjectPosition;");
}
catch (NoSuchASMMethodInstructionException e) {
}
try {
min3 = ReikaASMHelper.getFirstMethodCall(cn, m, "net/minecraft/world/World", func3, "(Lnet/minecraft/util/Vec3;Lnet/minecraft/util/Vec3;ZZZ)Lnet/minecraft/util/MovingObjectPosition;");
}
catch (NoSuchASMMethodInstructionException e) {
}
AbstractInsnNode pre1 = min1 != null ? ReikaASMHelper.getLastNonZeroALOADBefore(m.instructions, m.instructions.indexOf(min1)) : null;
AbstractInsnNode pre2 = min2 != null ? ReikaASMHelper.getLastFieldRefBefore(m.instructions, m.instructions.indexOf(min2), world).getPrevious() : null;
AbstractInsnNode pre3 = min3 != null ? ReikaASMHelper.getLastFieldRefBefore(m.instructions, m.instructions.indexOf(min3), world).getPrevious() : null;
if (min1 == null && min2 == null && min3 == null) {
ReikaASMHelper.log("WARNING: Found no raytrace hooks?!");
ReikaASMHelper.log(ReikaASMHelper.clearString(m.instructions));
}
if (min1 != null && pre1 == null) {
ReikaASMHelper.log("WARNING: Have injectable raytrace code but no landmark 1!");
}
if (min2 != null && pre2 == null) {
ReikaASMHelper.log("WARNING: Have injectable raytrace code but no landmark 2!");
}
if (min3 != null && pre3 == null) {
ReikaASMHelper.log("WARNING: Have injectable raytrace code but no landmark 3!");
}
if (pre1 != null) {
m.instructions.insertBefore(pre1, ReikaASMHelper.copyInsnList(li));
}
if (pre2 != null) {
m.instructions.insertBefore(pre2, ReikaASMHelper.copyInsnList(li));
}
if (pre3 != null) {
m.instructions.insertBefore(pre3, ReikaASMHelper.copyInsnList(li));
}
//ReikaJavaLibrary.pConsole(ReikaASMHelper.clearString(m.instructions));*/
MethodNode m = ReikaASMHelper.getMethodByName(cn, "func_70071_h_", "onUpdate", "()V");
String func1 = FMLForgePlugin.RUNTIME_DEOBF ? "func_149668_a" : "getCollisionBoundingBoxFromPool";
String func2 = FMLForgePlugin.RUNTIME_DEOBF ? "func_72933_a" : "rayTraceBlocks";
String func3 = FMLForgePlugin.RUNTIME_DEOBF ? "func_147447_a" : "func_147447_a";
String world = FMLForgePlugin.RUNTIME_DEOBF ? "field_70170_p" : "worldObj";
for (int i = 0; i < m.instructions.size(); i++) {
AbstractInsnNode ain = m.instructions.get(i);
if (ain.getOpcode() == Opcodes.INVOKEVIRTUAL) {
MethodInsnNode min = (MethodInsnNode)ain;
if (min.name.equals(func1)) {
VarInsnNode pre = (VarInsnNode)ReikaASMHelper.getLastNonZeroALOADBefore(m.instructions, i);
//m.instructions.remove(pre);
pre.var = 0;
min.owner = "Reika/DragonAPI/Instantiable/Event/EntityCollisionEvents";
ReikaASMHelper.addLeadingArgument(min, "Lnet/minecraft/entity/Entity;");
min.name = "getInterceptedCollisionBox";
ReikaASMHelper.changeOpcode(min, Opcodes.INVOKESTATIC);
}
else if (min.name.equals(func2)) {
AbstractInsnNode pre = ReikaASMHelper.getLastFieldRefBefore(m.instructions, i, world);
m.instructions.remove(pre);
min.owner = "Reika/DragonAPI/Instantiable/Event/EntityCollisionEvents";
ReikaASMHelper.addLeadingArgument(min, "Lnet/minecraft/entity/Entity;");
min.name = "getInterceptedRaytrace";
ReikaASMHelper.changeOpcode(min, Opcodes.INVOKESTATIC);
}
else if (min.name.equals(func3)) {
AbstractInsnNode pre = ReikaASMHelper.getLastFieldRefBefore(m.instructions, i, world);
m.instructions.remove(pre);
min.owner = "Reika/DragonAPI/Instantiable/Event/EntityCollisionEvents";
ReikaASMHelper.addLeadingArgument(min, "Lnet/minecraft/entity/Entity;");
min.name = "getInterceptedRaytrace";
ReikaASMHelper.changeOpcode(min, Opcodes.INVOKESTATIC);
}
}
}
}
}
| 0 | 0.900786 | 1 | 0.900786 | game-dev | MEDIA | 0.953578 | game-dev | 0.952002 | 1 | 0.952002 |
mordgren/GTCA | 5,780 | src/main/java/net/mordgren/gtca/data/recipe/permachine/GreenHouseRecipes.java | package net.mordgren.gtca.data.recipe.permachine;
import com.gregtechceu.gtceu.common.data.GTBlocks;
import com.gregtechceu.gtceu.common.data.GTItems;
import com.gregtechceu.gtceu.common.data.GTMaterials;
import net.minecraft.data.recipes.FinishedRecipe;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.Items;
import static com.gregtechceu.gtceu.common.data.GTItems.FERTILIZER;
import java.util.ArrayList;
import java.util.function.Consumer;
import static net.mordgren.gtca.common.data.GTCARecipeTypes.GREEN_HOUSE;
public class GreenHouseRecipes {
public static void init(Consumer<FinishedRecipe> provider) {
treeRecipes(provider);
plantRecipes(provider);
rubberTreeRecipes(provider);
}
private static ArrayList<Item[]> Trees;
private static ArrayList<Object[]> Plants;
private static void treesArrayInit() {
Trees = new ArrayList<>();
Trees.add(new Item[]{Items.OAK_SAPLING, Items.OAK_LOG});
Trees.add(new Item[]{Items.SPRUCE_SAPLING, Items.SPRUCE_LOG});
Trees.add(new Item[]{Items.BIRCH_SAPLING, Items.BIRCH_LOG});
Trees.add(new Item[]{Items.JUNGLE_SAPLING, Items.JUNGLE_LOG});
Trees.add(new Item[]{Items.ACACIA_SAPLING, Items.ACACIA_LOG});
Trees.add(new Item[]{Items.DARK_OAK_SAPLING, Items.DARK_OAK_LOG});
Trees.add(new Item[]{Items.MANGROVE_PROPAGULE, Items.MANGROVE_LOG});
Trees.add(new Item[]{Items.CHERRY_SAPLING, Items.CHERRY_LOG});
}
private static void plantsArrayInit() {
Plants = new ArrayList<>();
Plants.add(new Object[]{Items.PUMPKIN_SEEDS, Items.PUMPKIN, 6});
Plants.add(new Object[]{Items.BEETROOT_SEEDS, Items.BEETROOT, 16});
Plants.add(new Object[]{Items.SWEET_BERRIES, Items.SWEET_BERRIES, 16});
Plants.add(new Object[]{Items.GLOW_BERRIES, Items.GLOW_BERRIES, 8});
Plants.add(new Object[]{Items.WHEAT_SEEDS, Items.WHEAT, 16});
Plants.add(new Object[]{Items.MELON_SEEDS, Items.MELON, 6});
Plants.add(new Object[]{Items.CARROT, Items.CARROT, 12});
Plants.add(new Object[]{Items.SUGAR_CANE, Items.SUGAR_CANE, 12});
Plants.add(new Object[]{Items.KELP, Items.KELP, 12});
Plants.add(new Object[]{Items.CACTUS, Items.CACTUS, 12});
Plants.add(new Object[]{Items.BROWN_MUSHROOM, Items.BROWN_MUSHROOM, 12});
Plants.add(new Object[]{Items.RED_MUSHROOM, Items.RED_MUSHROOM, 12});
Plants.add(new Object[]{Items.NETHER_WART, Items.NETHER_WART, 12});
Plants.add(new Object[]{Items.BAMBOO, Items.BAMBOO, 16});
}
private static void treeRecipes(Consumer<FinishedRecipe> provider) {
treesArrayInit();
for(Item[] woodType : Trees){
GREEN_HOUSE.recipeBuilder(woodType[1].toString())
.EUt(40)
.duration(1200)
.circuitMeta(1)
.inputFluids(GTMaterials.Water.getFluid(1000))
.notConsumable(woodType[0])
.outputItems(woodType[1], 64)
.outputItems(woodType[0], 6)
.save(provider);
GREEN_HOUSE.recipeBuilder(woodType[1].toString() + "_fertilizer")
.EUt(60)
.duration(900)
.circuitMeta(2)
.inputFluids(GTMaterials.Water.getFluid(1000))
.notConsumable(woodType[0])
.inputItems(FERTILIZER, 4)
.outputItems(woodType[1], 64)
.outputItems(woodType[1], 64)
.outputItems(woodType[0], 12)
.save(provider);
}
}
private static void plantRecipes(Consumer<FinishedRecipe> provider) {
plantsArrayInit();
for(Object[] seedType : Plants) {
GREEN_HOUSE.recipeBuilder(seedType[1].toString())
.EUt(40)
.duration(1200)
.circuitMeta(1)
.inputFluids(GTMaterials.Water.getFluid(1000))
.notConsumable((Item) seedType[0])
.outputItems((Item) seedType[1], (int)seedType[2])
.save(provider);
GREEN_HOUSE.recipeBuilder(seedType[1].toString() + "_fertilizer")
.EUt(60)
.duration(900)
.circuitMeta(2)
.inputFluids(GTMaterials.Water.getFluid(1000))
.notConsumable((Item) seedType[0])
.inputItems(FERTILIZER, 4)
.outputItems((Item) seedType[1], 2 * (int) seedType[2])
.save(provider);
}
}
private static void rubberTreeRecipes(Consumer<FinishedRecipe> provider) {
GREEN_HOUSE.recipeBuilder("rubber_tree")
.EUt(40)
.duration(1200)
.circuitMeta(1)
.inputFluids(GTMaterials.Water.getFluid(1000))
.notConsumable(GTBlocks.RUBBER_SAPLING.asStack())
.outputItems(GTBlocks.RUBBER_LOG, 16)
.outputItems(GTBlocks.RUBBER_SAPLING, 3)
.outputItems(GTItems.STICKY_RESIN, 4)
.save(provider);
GREEN_HOUSE.recipeBuilder("rubber_tree_fertilizer")
.EUt(60)
.duration(900)
.circuitMeta(2)
.inputFluids(GTMaterials.Water.getFluid(1000))
.notConsumable(GTBlocks.RUBBER_SAPLING.asStack())
.inputItems(FERTILIZER, 4)
.outputItems(GTBlocks.RUBBER_LOG, 32)
.outputItems(GTBlocks.RUBBER_SAPLING, 6)
.outputItems(GTItems.STICKY_RESIN, 8)
.save(provider);
}
}
| 0 | 0.835577 | 1 | 0.835577 | game-dev | MEDIA | 0.971408 | game-dev | 0.845969 | 1 | 0.845969 |
cgeo/cgeo | 7,577 | main/src/main/java/cgeo/geocaching/brouter/mapaccess/OsmFile.java | /**
* cache for a single square
*
* @author ab
*/
package cgeo.geocaching.brouter.mapaccess;
import cgeo.geocaching.brouter.codec.DataBuffers;
import cgeo.geocaching.brouter.codec.MicroCache;
import cgeo.geocaching.brouter.codec.MicroCache2;
import cgeo.geocaching.brouter.codec.StatCoderContext;
import cgeo.geocaching.brouter.codec.TagValueValidator;
import cgeo.geocaching.brouter.codec.WaypointMatcher;
import cgeo.geocaching.brouter.util.ByteDataReader;
import cgeo.geocaching.brouter.util.Crc32Utils;
import java.io.IOException;
final class OsmFile {
public int lonDegree;
public int latDegree;
public String filename;
private PhysicalFile rafile = null;
private long fileOffset;
private int[] posIdx;
private MicroCache[] microCaches;
private int divisor;
private int cellsize;
private int indexsize;
byte elevationType = 3;
OsmFile(final PhysicalFile rafile, final int lonDegree, final int latDegree, final DataBuffers dataBuffers) throws IOException {
this.lonDegree = lonDegree;
this.latDegree = latDegree;
final int lonMod5 = lonDegree % 5;
final int latMod5 = latDegree % 5;
final int tileIndex = lonMod5 * 5 + latMod5;
if (rafile != null) {
divisor = rafile.divisor;
elevationType = rafile.elevationType;
cellsize = 1000000 / divisor;
final int ncaches = divisor * divisor;
indexsize = ncaches * 4;
final byte[] iobuffer = dataBuffers.iobuffer;
filename = rafile.fileName;
final long[] index = rafile.fileIndex;
fileOffset = tileIndex > 0 ? index[tileIndex - 1] : 200L;
if (fileOffset == index[tileIndex]) {
return; // empty
}
this.rafile = rafile;
posIdx = new int[ncaches];
microCaches = new MicroCache[ncaches];
this.rafile.readFully(fileOffset, indexsize, iobuffer);
if (rafile.fileHeaderCrcs != null) {
final int headerCrc = Crc32Utils.crc(iobuffer, 0, indexsize);
if (rafile.fileHeaderCrcs[tileIndex] != headerCrc) {
throw new IOException("sub index checksum error");
}
}
final ByteDataReader dis = new ByteDataReader(iobuffer);
for (int i = 0; i < ncaches; i++) {
posIdx[i] = dis.readInt();
}
}
}
public boolean hasData() {
return microCaches != null;
}
public MicroCache getMicroCache(final int ilon, final int ilat) {
final int lonIdx = ilon / cellsize;
final int latIdx = ilat / cellsize;
final int subIdx = (latIdx - divisor * latDegree) * divisor + (lonIdx - divisor * lonDegree);
return microCaches[subIdx];
}
public MicroCache createMicroCache(final int ilon, final int ilat, final DataBuffers dataBuffers, final TagValueValidator wayValidator, final WaypointMatcher waypointMatcher, final OsmNodesMap hollowNodes)
throws Exception {
final int lonIdx = ilon / cellsize;
final int latIdx = ilat / cellsize;
final MicroCache segment = createMicroCache(lonIdx, latIdx, dataBuffers, wayValidator, waypointMatcher, true, hollowNodes);
final int subIdx = (latIdx - divisor * latDegree) * divisor + (lonIdx - divisor * lonDegree);
microCaches[subIdx] = segment;
return segment;
}
private int getPosIdx(final int idx) {
return idx == -1 ? indexsize : posIdx[idx];
}
public int getDataInputForSubIdx(final int subIdx, final byte[] iobuffer) throws IOException {
final int startPos = getPosIdx(subIdx - 1);
final int endPos = getPosIdx(subIdx);
final int size = endPos - startPos;
if (size > 0 && size <= iobuffer.length) {
this.rafile.readFully(fileOffset + startPos, size, iobuffer);
}
return size;
}
public MicroCache createMicroCache(final int lonIdx, final int latIdx, final DataBuffers dataBuffers, final TagValueValidator wayValidator,
final WaypointMatcher waypointMatcher, final boolean reallyDecode, final OsmNodesMap hollowNodes) throws IOException {
final int subIdx = (latIdx - divisor * latDegree) * divisor + (lonIdx - divisor * lonDegree);
byte[] ab = dataBuffers.iobuffer;
int asize = getDataInputForSubIdx(subIdx, ab);
if (asize == 0) {
return MicroCache.emptyCache();
}
if (asize > ab.length) {
ab = new byte[asize];
asize = getDataInputForSubIdx(subIdx, ab);
}
final StatCoderContext bc = new StatCoderContext(ab);
try {
if (!reallyDecode) {
return null;
}
if (hollowNodes == null) {
return new MicroCache2(bc, dataBuffers, lonIdx, latIdx, divisor, wayValidator, waypointMatcher);
}
new DirectWeaver(bc, dataBuffers, lonIdx, latIdx, divisor, wayValidator, waypointMatcher, hollowNodes);
return MicroCache.emptyNonVirgin;
} finally {
// crc check only if the buffer has not been fully read
final int readBytes = (bc.getReadingBitPosition() + 7) >> 3;
if (readBytes != asize - 4) {
final int crcData = Crc32Utils.crc(ab, 0, asize - 4);
final int crcFooter = new ByteDataReader(ab, asize - 4).readInt();
if (crcData == crcFooter) {
throw new IOException("old, unsupported data-format");
} else if ((crcData ^ 2) != crcFooter) {
throw new IOException("checkum error");
}
}
}
}
// set this OsmFile to ghost-state:
public long setGhostState() {
long sum = 0;
final int nc = microCaches == null ? 0 : microCaches.length;
for (int i = 0; i < nc; i++) {
final MicroCache mc = microCaches[i];
if (mc == null) {
continue;
}
if (mc.virgin) {
mc.ghost = true;
sum += mc.getDataSize();
} else {
microCaches[i] = null;
}
}
return sum;
}
public long collectAll() {
long deleted = 0;
final int nc = microCaches == null ? 0 : microCaches.length;
for (int i = 0; i < nc; i++) {
final MicroCache mc = microCaches[i];
if (mc == null) {
continue;
}
if (!mc.ghost) {
deleted += mc.collect(0);
}
}
return deleted;
}
public long cleanGhosts() {
final long deleted = 0;
final int nc = microCaches == null ? 0 : microCaches.length;
for (int i = 0; i < nc; i++) {
final MicroCache mc = microCaches[i];
if (mc == null) {
continue;
}
if (mc.ghost) {
microCaches[i] = null;
}
}
return deleted;
}
public void clean(final boolean all) {
final int nc = microCaches == null ? 0 : microCaches.length;
for (int i = 0; i < nc; i++) {
final MicroCache mc = microCaches[i];
if (mc == null) {
continue;
}
if (all || !mc.virgin) {
microCaches[i] = null;
}
}
}
}
| 0 | 0.933725 | 1 | 0.933725 | game-dev | MEDIA | 0.355878 | game-dev | 0.969085 | 1 | 0.969085 |
greenplum-db/gporca-archive | 1,565 | libgpos/include/gpos/error/CMiniDumper.h | //---------------------------------------------------------------------------
// Greenplum Database
// Copyright (C) 2011 EMC Corp.
//
// @filename:
// CMiniDumper.h
//
// @doc:
// Interface for minidump handler;
//---------------------------------------------------------------------------
#ifndef GPOS_CMiniDumper_H
#define GPOS_CMiniDumper_H
#include "gpos/base.h"
#include "gpos/io/COstream.h"
namespace gpos
{
//---------------------------------------------------------------------------
// @class:
// CMiniDumper
//
// @doc:
// Interface for minidump handler;
//
//---------------------------------------------------------------------------
class CMiniDumper : CStackObject
{
private:
// memory pool
CMemoryPool *m_mp;
// flag indicating if handler is initialized
BOOL m_initialized;
// flag indicating if handler is finalized
BOOL m_finalized;
// private copy ctor
CMiniDumper(const CMiniDumper &);
protected:
// stream to serialize objects to
COstream *m_oos;
public:
// ctor
CMiniDumper(CMemoryPool *mp);
// dtor
virtual ~CMiniDumper();
// initialize
void Init(COstream *oos);
// finalize
void Finalize();
// get stream to serialize to
COstream &GetOStream();
// serialize minidump header
virtual void SerializeHeader() = 0;
// serialize minidump footer
virtual void SerializeFooter() = 0;
// serialize entry header
virtual void SerializeEntryHeader() = 0;
// serialize entry footer
virtual void SerializeEntryFooter() = 0;
}; // class CMiniDumper
} // namespace gpos
#endif // !GPOS_CMiniDumper_H
// EOF
| 0 | 0.913109 | 1 | 0.913109 | game-dev | MEDIA | 0.29682 | game-dev | 0.604131 | 1 | 0.604131 |
JerichoFletcher/mechanical-warfare | 3,537 | scripts/blocks/turret/seism.js | const elib = require("mechanical-warfare/effectlib");
const plib = require("mechanical-warfare/plib");
const bulletLib = require("mechanical-warfare/bulletlib");
const seismHE = bulletLib.bullet(BasicBulletType, 20, 26, 0, 0, 350, 720, 60, 4, 12, 40, null, cons(b => {
if(Mathf.chance(0.75)){
Effects.effect(seismHE.trailEffect, b.x, b.y, b.rot());
}
}), null, null, null);
seismHE.frontColor = plib.frontColorHE;
seismHE.backColor = plib.backColorHE;
seismHE.ammoMultiplier = 2;
seismHE.hitSound = Sounds.boom;
seismHE.trailEffect = newEffect(30, e => {
elib.fillCircle(e.x, e.y, seismHE.frontColor, 1, Mathf.lerp(2, 0.2, e.fin()));
});
seismHE.hitEffect = newEffect(42, e => {
e.scaled(4, cons(i => {
c1Thickness = 6 * i.fout();
c1Radius = Mathf.lerp(3, 60, i.fin());
elib.outlineCircle(e.x, e.y, Pal.missileYellow, c1Thickness, c1Radius);
}));
sAlpha = 0.3 + e.fout() * 0.7;
sRadius = Mathf.lerp(10, 1, e.fin());
Angles.randLenVectors(e.id, 15, Mathf.lerp(5, 84, e.finpow()), new Floatc2(){get: (a, b) => {
elib.fillCircle(e.x + a, e.y + b, Color.gray, sAlpha, sRadius);
}});
lThickness = e.fout() * 3;
lDistance = Mathf.lerp(20, 120, e.finpow());
lLength = Mathf.lerp(14, 1, e.fin());
elib.splashLines(e.x, e.y, Pal.missileYellow, lThickness, lDistance, lLength, 15, e.id);
});
seismHE.despawnEffect = seismHE.hitEffect;
const seismAP = bulletLib.bullet(BasicBulletType, 20, 26, 0, 0, 3300, 160, 15, 8, 20, 26, null, cons(b => {
if(Mathf.chance(0.75)){
Effects.effect(seismHE.trailEffect, b.x, b.y, b.rot());
}
}), null, null, null);
seismAP.frontColor = plib.frontColorAP;
seismAP.backColor = plib.backColorAP;
seismAP.ammoMultiplier = 2;
seismAP.reloadMultiplier = 1.2;
seismAP.hitSound = Sounds.boom;
seismAP.trailEffect = newEffect(30, e => {
elib.fillCircle(e.x, e.y, seismAP.frontColor, 1, Mathf.lerp(2, 0.2, e.fin()));
});
seismAP.hitEffect = newEffect(13, e => {
e.scaled(4, cons(i => {
cThickness = 4 * i.fout();
cRadius = Mathf.lerp(2, 30, i.fin());
elib.outlineCircle(e.x, e.y, seismAP.frontColor, cThickness, cRadius);
}));
lThickness = e.fout() * 3;
lDistance = Mathf.lerp(3, 45, e.finpow());
lLength = Mathf.lerp(5, 1, e.fin());
elib.splashLines(e.x, e.y, seismAP.backColor, lThickness, lDistance, lLength, 12, e.id);
});
seismAP.despawnEffect = seismAP.hitEffect;
const seism = extendContent(ArtilleryTurret, "seism", {
load(){
this.region = Core.atlas.find(this.name);
this.baseRegion = Core.atlas.find("mechanical-warfare-block-5");
this.heatRegion = Core.atlas.find(this.name + "-heat");
},
draw(tile){
Draw.rect(this.baseRegion, tile.drawx(), tile.drawy());
Draw.color();
},
generateIcons: function(){
return [
Core.atlas.find("mechanical-warfare-block-5"),
Core.atlas.find(this.name)
];
},
init(){
this.ammo(
Vars.content.getByName(ContentType.item, "mechanical-warfare-he-shell"), seismHE,
Vars.content.getByName(ContentType.item, "mechanical-warfare-ap-shell"), seismAP
);
this.super$init();
},
drawLayer(tile){
this.super$drawLayer(tile);
var entity = tile.ent();
var val = entity.totalAmmo / this.maxAmmo;
for(var i = 0; i <= 2; i++){
var j = i + 1;
var lo = i / 3;
var hi = j / 3;
Draw.color(Pal.lancerLaser);
Draw.alpha((Mathf.clamp(val, lo, hi) - lo) * 3);
Draw.rect(Core.atlas.find(this.name + "-phase" + i), tile.drawx() + this.tr2.x, tile.drawy() + this.tr2.y, entity.rotation - 90);
Draw.color();
}
}
});
| 0 | 0.926047 | 1 | 0.926047 | game-dev | MEDIA | 0.920533 | game-dev | 0.995501 | 1 | 0.995501 |
glKarin/com.n0n3m4.diii4a | 5,498 | Q3E/src/main/jni/doom3/neo/d3xp/IK.h | /*
===========================================================================
Doom 3 GPL Source Code
Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company.
This file is part of the Doom 3 GPL Source Code (?Doom 3 Source Code?).
Doom 3 Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Doom 3 Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
#ifndef __GAME_IK_H__
#define __GAME_IK_H__
/*
===============================================================================
IK base class with a simple fast two bone solver.
===============================================================================
*/
#define IK_ANIM "ik_pose"
class idIK
{
public:
idIK(void);
virtual ~idIK(void);
void Save(idSaveGame *savefile) const;
void Restore(idRestoreGame *savefile);
bool IsInitialized(void) const;
virtual bool Init(idEntity *self, const char *anim, const idVec3 &modelOffset);
virtual void Evaluate(void);
virtual void ClearJointMods(void);
bool SolveTwoBones(const idVec3 &startPos, const idVec3 &endPos, const idVec3 &dir, float len0, float len1, idVec3 &jointPos);
float GetBoneAxis(const idVec3 &startPos, const idVec3 &endPos, const idVec3 &dir, idMat3 &axis);
protected:
bool initialized;
bool ik_activate;
idEntity *self; // entity using the animated model
idAnimator *animator; // animator on entity
int modifiedAnim; // animation modified by the IK
idVec3 modelOffset;
};
/*
===============================================================================
IK controller for a walking character with an arbitrary number of legs.
===============================================================================
*/
class idIK_Walk : public idIK
{
public:
idIK_Walk(void);
virtual ~idIK_Walk(void);
void Save(idSaveGame *savefile) const;
void Restore(idRestoreGame *savefile);
virtual bool Init(idEntity *self, const char *anim, const idVec3 &modelOffset);
virtual void Evaluate(void);
virtual void ClearJointMods(void);
void EnableAll(void);
void DisableAll(void);
void EnableLeg(int num);
void DisableLeg(int num);
private:
static const int MAX_LEGS = 8;
idClipModel *footModel;
int numLegs;
int enabledLegs;
jointHandle_t footJoints[MAX_LEGS];
jointHandle_t ankleJoints[MAX_LEGS];
jointHandle_t kneeJoints[MAX_LEGS];
jointHandle_t hipJoints[MAX_LEGS];
jointHandle_t dirJoints[MAX_LEGS];
jointHandle_t waistJoint;
idVec3 hipForward[MAX_LEGS];
idVec3 kneeForward[MAX_LEGS];
float upperLegLength[MAX_LEGS];
float lowerLegLength[MAX_LEGS];
idMat3 upperLegToHipJoint[MAX_LEGS];
idMat3 lowerLegToKneeJoint[MAX_LEGS];
float smoothing;
float waistSmoothing;
float footShift;
float waistShift;
float minWaistFloorDist;
float minWaistAnkleDist;
float footUpTrace;
float footDownTrace;
bool tiltWaist;
bool usePivot;
// state
int pivotFoot;
float pivotYaw;
idVec3 pivotPos;
bool oldHeightsValid;
float oldWaistHeight;
float oldAnkleHeights[MAX_LEGS];
idVec3 waistOffset;
};
/*
===============================================================================
IK controller for reaching a position with an arm or leg.
===============================================================================
*/
class idIK_Reach : public idIK
{
public:
idIK_Reach(void);
virtual ~idIK_Reach(void);
void Save(idSaveGame *savefile) const;
void Restore(idRestoreGame *savefile);
virtual bool Init(idEntity *self, const char *anim, const idVec3 &modelOffset);
virtual void Evaluate(void);
virtual void ClearJointMods(void);
private:
static const int MAX_ARMS = 2;
int numArms;
int enabledArms;
jointHandle_t handJoints[MAX_ARMS];
jointHandle_t elbowJoints[MAX_ARMS];
jointHandle_t shoulderJoints[MAX_ARMS];
jointHandle_t dirJoints[MAX_ARMS];
idVec3 shoulderForward[MAX_ARMS];
idVec3 elbowForward[MAX_ARMS];
float upperArmLength[MAX_ARMS];
float lowerArmLength[MAX_ARMS];
idMat3 upperArmToShoulderJoint[MAX_ARMS];
idMat3 lowerArmToElbowJoint[MAX_ARMS];
};
#endif /* !__GAME_IK_H__ */
| 0 | 0.913819 | 1 | 0.913819 | game-dev | MEDIA | 0.994873 | game-dev | 0.640626 | 1 | 0.640626 |
sam-ple/minescript-memo | 1,733 | 03_utility/06_autoloot/autoloot_v0.1.02_20250809.py | # Fabric 1.21.8 / Minescript 5.0b1 / Minescript Plus v0.10a
# Same, but always closes the screen afterwards
import time
import minescript as m
from minescript_plus import Inventory, Keybind, Screen # Screen added
# Target items
TARGET_ITEMS = [
"minecraft:diamond",
"minecraft:emerald",
"minecraft:gold_ingot",
]
# Anti-spam guard
_busy = False
def move_items_from_chest():
global _busy
if _busy:
m.echo("⏳ Already running…")
return
_busy = True
try:
if not Inventory.open_targeted_chest():
m.echo("⚠️ Look straight at a chest/barrel/shulker and try again.")
return
chest_slot_range = range(27) # Single chest assumed (use 54 for double chest)
moved = 0
for item_id in TARGET_ITEMS:
while True:
slot = Inventory.find_item(item_id, container=True)
if slot is None or slot not in chest_slot_range:
break
if not Inventory.shift_click_slot(slot):
m.echo(f"⚠️ Move failed: slot {slot}")
return
moved += 1
time.sleep(0.2)
m.echo(f"✅ Target item transfer complete. (moved {moved})")
finally:
# Always try to close the screen (no-op if none open)
try:
Screen.close_screen()
except Exception:
pass
_busy = False
# Bind G
kb = Keybind()
kb.set_keybind(
71,
move_items_from_chest,
name="PullFromChest",
category="Minescript+",
description="Move target items from the targeted chest."
)
m.echo("🎹 Press 'G' to pull target items from the chest you're looking at.")
while True:
time.sleep(1)
| 0 | 0.512624 | 1 | 0.512624 | game-dev | MEDIA | 0.977087 | game-dev | 0.777672 | 1 | 0.777672 |
Joystream/joystream | 3,622 | storage-node/src/commands/leader/update-bags.ts | import { flags } from '@oclif/command'
import _ from 'lodash'
import { customFlags } from '../../command-base/CustomFlags'
import ExitCodes from '../../command-base/ExitCodes'
import LeaderCommandBase from '../../command-base/LeaderCommandBase'
import logger from '../../services/logger'
import { updateStorageBucketsForBags } from '../../services/runtime/extrinsics'
/**
* CLI command:
* Updates bags-to-buckets relationships.
*
* @remarks
* Storage working group leader command. Requires storage WG leader priviliges.
* Shell command: "leader:update-bag"
*/
export default class LeaderUpdateBag extends LeaderCommandBase {
static description =
`Add/remove a storage bucket/s from a bag/s. If multiple bags are ` +
`provided, then the same input bucket ID/s would be added/removed from all bags.`
static flags = {
add: customFlags.integerArr({
char: 'a',
description: 'Comma separated list of bucket IDs to add to all bag/s',
default: [],
}),
remove: customFlags.integerArr({
char: 'r',
description: 'Comma separated list of bucket IDs to remove from all bag/s',
default: [],
}),
bagIds: customFlags.bagId({
char: 'i',
required: true,
multiple: true,
}),
updateStrategy: flags.enum<'atomic' | 'force'>({
char: 's',
options: ['atomic', 'force'],
description: 'Update strategy to use. Either "atomic" or "force".',
default: 'atomic',
}),
...LeaderCommandBase.flags,
}
async run(): Promise<void> {
const { flags } = this.parse(LeaderUpdateBag)
logger.info('Updating the bag...')
if (flags.dev) {
await this.ensureDevelopmentChain()
}
const uniqueBagIds = _.uniqBy(flags.bagIds, (b) => b.toString())
const uniqueAddBuckets = _.uniq(flags.add)
const uniqueRemoveBuckets = _.uniq(flags.remove)
if (_.isEmpty(uniqueAddBuckets) && _.isEmpty(uniqueRemoveBuckets)) {
logger.error('No bucket ID provided.')
this.exit(ExitCodes.InvalidParameters)
}
if (_.isEmpty(uniqueBagIds)) {
logger.error('No bag ID provided.')
this.exit(ExitCodes.InvalidParameters)
}
const account = this.getAccount()
const api = await this.getApi()
// Ensure that input bag ids exist
for (const bagId of uniqueBagIds) {
const bag = await api.query.storage.bags(bagId)
if (bag.isEmpty) {
logger.error(`Bag with ID ${bagId} does not exist`)
this.exit(ExitCodes.InvalidParameters)
}
}
// Ensure that input add bucket ids exist
for (const b of uniqueAddBuckets) {
const bucket = await api.query.storage.storageBucketById(b)
if (bucket.isEmpty) {
logger.error(`Add Bucket input with ID ${b} does not exist`)
this.exit(ExitCodes.InvalidParameters)
}
}
// Ensure that input remove bucket ids exist
for (const b of uniqueRemoveBuckets) {
const bucket = await api.query.storage.storageBucketById(b)
if (bucket.isEmpty) {
logger.error(`Remove Bucket input with ID ${b} does not exist`)
this.exit(ExitCodes.InvalidParameters)
}
}
const [success, failedCalls] = await updateStorageBucketsForBags(
api,
uniqueBagIds,
account,
flags.add,
flags.remove,
flags.updateStrategy
)
if (!_.isEmpty(failedCalls)) {
logger.error(`Following extrinsic calls in the batch Tx failed:\n ${JSON.stringify(failedCalls, null, 2)}}`)
} else {
logger.info('All extrinsic calls in the batch Tx succeeded!')
}
this.exitAfterRuntimeCall(success)
}
}
| 0 | 0.96973 | 1 | 0.96973 | game-dev | MEDIA | 0.227871 | game-dev | 0.972982 | 1 | 0.972982 |
pathea-games/planetexplorers | 977 | Assets/PeCustomGame/Scenario/PEScenario/Statements/Actions/EnableSpawnAction.cs | using UnityEngine;
using ScenarioRTL;
using Pathea;
namespace PeCustom
{
[Statement("ENABLE SPAWN", true)]
public class EnableSpawnAction : ScenarioRTL.Action
{
// 在此列举参数
OBJECT spawn; // SPAWN
// 在此初始化参数
protected override void OnCreate()
{
spawn = Utility.ToObject(parameters["spawnpoint"]);
}
// 执行动作
// 若为瞬间动作,返回true;
// 若为持续动作,该函数会每帧被调用,直到返回true
public override bool Logic()
{
if (Pathea.PeGameMgr.IsMulti)
{
byte[] data = PETools.Serialize.Export(w => { BufferHelper.Serialize(w, spawn); });
PlayerNetwork.RequestServer(EPacketType.PT_Custom_EnableSpawn, data);
}
else
{
if (!PeScenarioUtility.EnableSpawnPoint(spawn, true))
{
Debug.LogWarning("Enable spawn point error");
}
}
return true;
}
}
}
| 0 | 0.868663 | 1 | 0.868663 | game-dev | MEDIA | 0.991823 | game-dev | 0.758451 | 1 | 0.758451 |
SimonGaufreteau/ZygorGuidesViewer | 6,682 | Libs/AceGUI-3.0/widgets/AceGUIWidget-EditBox.lua | --[[-----------------------------------------------------------------------------
EditBox Widget
-------------------------------------------------------------------------------]]
local Type, Version = 'EditBox', 21
local AceGUI = LibStub and LibStub('AceGUI-3.0', true)
if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then
return
end
-- Lua APIs
local tostring, pairs = tostring, pairs
-- WoW APIs
local PlaySound = PlaySound
local GetCursorInfo, ClearCursor, GetSpellName = GetCursorInfo, ClearCursor, GetSpellName
local CreateFrame, UIParent = CreateFrame, UIParent
local _G = _G
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
-- List them here for Mikk's FindGlobals script
-- GLOBALS: AceGUIEditBoxInsertLink, ChatFontNormal, OKAY
--[[-----------------------------------------------------------------------------
Support functions
-------------------------------------------------------------------------------]]
if not AceGUIEditBoxInsertLink then
-- upgradeable hook
hooksecurefunc('ChatEdit_InsertLink', function(...)
return _G.AceGUIEditBoxInsertLink(...)
end)
end
function _G.AceGUIEditBoxInsertLink(text)
for i = 1, AceGUI:GetWidgetCount(Type) do
local editbox = _G['AceGUI-3.0EditBox' .. i]
if editbox and editbox:IsVisible() and editbox:HasFocus() then
editbox:Insert(text)
return true
end
end
end
local function ShowButton(self)
if not self.disablebutton then
self.button:Show()
self.editbox:SetTextInsets(0, 20, 3, 3)
end
end
local function HideButton(self)
self.button:Hide()
self.editbox:SetTextInsets(0, 0, 3, 3)
end
--[[-----------------------------------------------------------------------------
Scripts
-------------------------------------------------------------------------------]]
local function Control_OnEnter(frame)
frame.obj:Fire('OnEnter')
end
local function Control_OnLeave(frame)
frame.obj:Fire('OnLeave')
end
local function EditBox_OnEscapePressed(frame)
AceGUI:ClearFocus()
end
local function EditBox_OnEnterPressed(frame)
local self = frame.obj
local value = frame:GetText()
local cancel = self:Fire('OnEnterPressed', value)
if not cancel then
PlaySound('igMainMenuOptionCheckBoxOn')
HideButton(self)
end
end
local function EditBox_OnReceiveDrag(frame)
local self = frame.obj
local type, id, info = GetCursorInfo()
if type == 'item' then
self:SetText(info)
self:Fire('OnEnterPressed', info)
ClearCursor()
elseif type == 'spell' then
local name, rank = GetSpellName(id, info)
if rank and rank:match('%d') then
name = name .. '(' .. rank .. ')'
end
self:SetText(name)
self:Fire('OnEnterPressed', name)
ClearCursor()
end
HideButton(self)
AceGUI:ClearFocus()
end
local function EditBox_OnTextChanged(frame)
local self = frame.obj
local value = frame:GetText()
if tostring(value) ~= tostring(self.lasttext) then
self:Fire('OnTextChanged', value)
self.lasttext = value
ShowButton(self)
end
end
local function Button_OnClick(frame)
local editbox = frame.obj.editbox
editbox:ClearFocus()
EditBox_OnEnterPressed(editbox)
end
--[[-----------------------------------------------------------------------------
Methods
-------------------------------------------------------------------------------]]
local methods = {
['OnAcquire'] = function(self)
-- height is controlled by SetLabel
self:SetWidth(200)
self:SetDisabled(false)
self:SetLabel()
self:SetText()
self:DisableButton(false)
self:SetMaxLetters(0)
end,
-- ["OnRelease"] = nil,
['SetDisabled'] = function(self, disabled)
self.disabled = disabled
if disabled then
self.editbox:EnableMouse(false)
self.editbox:ClearFocus()
self.editbox:SetTextColor(0.5, 0.5, 0.5)
self.label:SetTextColor(0.5, 0.5, 0.5)
else
self.editbox:EnableMouse(true)
self.editbox:SetTextColor(1, 1, 1)
self.label:SetTextColor(1, 0.82, 0)
end
end,
['SetText'] = function(self, text)
self.lasttext = text or ''
self.editbox:SetText(text or '')
self.editbox:SetCursorPosition(0)
HideButton(self)
end,
['SetLabel'] = function(self, text)
if text and text ~= '' then
self.label:SetText(text)
self.label:Show()
self.editbox:SetPoint('TOPLEFT', self.frame, 'TOPLEFT', 7, -18)
self:SetHeight(44)
self.alignoffset = 30
else
self.label:SetText('')
self.label:Hide()
self.editbox:SetPoint('TOPLEFT', self.frame, 'TOPLEFT', 7, 0)
self:SetHeight(26)
self.alignoffset = 12
end
end,
['DisableButton'] = function(self, disabled)
self.disablebutton = disabled
end,
['SetMaxLetters'] = function(self, num)
self.editbox:SetMaxLetters(num or 0)
end,
}
--[[-----------------------------------------------------------------------------
Constructor
-------------------------------------------------------------------------------]]
local function Constructor()
local num = AceGUI:GetNextWidgetNum(Type)
local frame = CreateFrame('Frame', nil, UIParent)
frame:Hide()
local editbox = CreateFrame('EditBox', 'AceGUI-3.0EditBox' .. num, frame, 'InputBoxTemplate')
editbox:SetAutoFocus(false)
editbox:SetFontObject(ChatFontNormal)
editbox:SetScript('OnEnter', Control_OnEnter)
editbox:SetScript('OnLeave', Control_OnLeave)
editbox:SetScript('OnEscapePressed', EditBox_OnEscapePressed)
editbox:SetScript('OnEnterPressed', EditBox_OnEnterPressed)
editbox:SetScript('OnTextChanged', EditBox_OnTextChanged)
editbox:SetScript('OnReceiveDrag', EditBox_OnReceiveDrag)
editbox:SetScript('OnMouseDown', EditBox_OnReceiveDrag)
editbox:SetTextInsets(0, 0, 3, 3)
editbox:SetMaxLetters(256)
editbox:SetPoint('BOTTOMLEFT', 6, 0)
editbox:SetPoint('BOTTOMRIGHT')
editbox:SetHeight(19)
local label = frame:CreateFontString(nil, 'OVERLAY', 'GameFontNormalSmall')
label:SetPoint('TOPLEFT', 0, -2)
label:SetPoint('TOPRIGHT', 0, -2)
label:SetJustifyH('LEFT')
label:SetHeight(18)
local button = CreateFrame('Button', nil, editbox, 'UIPanelButtonTemplate')
button:SetWidth(40)
button:SetHeight(20)
button:SetPoint('RIGHT', -2, 0)
button:SetText(OKAY)
button:SetScript('OnClick', Button_OnClick)
button:Hide()
local widget = {
alignoffset = 30,
editbox = editbox,
label = label,
button = button,
frame = frame,
type = Type,
}
for method, func in pairs(methods) do
widget[method] = func
end
editbox.obj, button.obj = widget, widget
return AceGUI:RegisterAsWidget(widget)
end
AceGUI:RegisterWidgetType(Type, Constructor, Version)
| 0 | 0.926198 | 1 | 0.926198 | game-dev | MEDIA | 0.922874 | game-dev | 0.9269 | 1 | 0.9269 |
Hoto-Mocha/Re-ARranged-Pixel-Dungeon | 4,593 | core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/items/weapon/melee/Dagger.java | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2025 Evan Debenham
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee;
import com.shatteredpixel.shatteredpixeldungeon.Assets;
import com.shatteredpixel.shatteredpixeldungeon.Dungeon;
import com.shatteredpixel.shatteredpixeldungeon.actors.Actor;
import com.shatteredpixel.shatteredpixeldungeon.actors.Char;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Buff;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Invisibility;
import com.shatteredpixel.shatteredpixeldungeon.actors.hero.Hero;
import com.shatteredpixel.shatteredpixeldungeon.actors.mobs.Mob;
import com.shatteredpixel.shatteredpixeldungeon.effects.CellEmitter;
import com.shatteredpixel.shatteredpixeldungeon.effects.Speck;
import com.shatteredpixel.shatteredpixeldungeon.messages.Messages;
import com.shatteredpixel.shatteredpixeldungeon.scenes.GameScene;
import com.shatteredpixel.shatteredpixeldungeon.scenes.PixelScene;
import com.shatteredpixel.shatteredpixeldungeon.sprites.ItemSpriteSheet;
import com.shatteredpixel.shatteredpixeldungeon.utils.GLog;
import com.watabou.noosa.audio.Sample;
import com.watabou.utils.BArray;
import com.watabou.utils.PathFinder;
public class Dagger extends MeleeWeapon {
{
image = ItemSpriteSheet.DAGGER;
hitSound = Assets.Sounds.HIT_STAB;
hitSoundPitch = 1.1f;
tier = 1;
bones = false;
}
@Override
public int max(int lvl) {
return 4*(tier+1) + //8 base, down from 10
lvl*(tier+1); //scaling unchanged
}
@Override
public int damageRoll(Char owner) {
if (owner instanceof Hero) {
Hero hero = (Hero)owner;
Char enemy = hero.attackTarget();
if (enemy instanceof Mob && ((Mob) enemy).surprisedBy(hero)) {
//deals 75% toward max to max on surprise, instead of min to max.
int diff = max() - min();
int damage = augment.damageFactor(Hero.heroDamageIntRange(
min() + Math.round(diff*0.75f),
max()));
int exStr = hero.STR() - STRReq();
if (exStr > 0) {
damage += Hero.heroDamageIntRange(0, exStr);
}
return damage;
}
}
return super.damageRoll(owner);
}
@Override
public String targetingPrompt() {
return Messages.get(this, "prompt");
}
public boolean useTargeting(){
return false;
}
@Override
protected void duelistAbility(Hero hero, Integer target) {
sneakAbility(hero, target, 5, 2+buffedLvl(), this);
}
@Override
public String abilityInfo() {
if (levelKnown){
return Messages.get(this, "ability_desc", 2+buffedLvl());
} else {
return Messages.get(this, "typical_ability_desc", 2);
}
}
@Override
public String upgradeAbilityStat(int level) {
return Integer.toString(2+level);
}
public static void sneakAbility(Hero hero, Integer target, int maxDist, int invisTurns, MeleeWeapon wep){
if (target == null) {
return;
}
PathFinder.buildDistanceMap(Dungeon.hero.pos, BArray.or(Dungeon.level.passable, Dungeon.level.avoid, null), maxDist);
if (PathFinder.distance[target] == Integer.MAX_VALUE || !Dungeon.level.heroFOV[target] || hero.rooted) {
GLog.w(Messages.get(wep, "ability_target_range"));
if (Dungeon.hero.rooted) PixelScene.shake( 1, 1f );
return;
}
if (Actor.findChar(target) != null) {
GLog.w(Messages.get(wep, "ability_occupied"));
return;
}
wep.beforeAbilityUsed(hero, null);
Buff.prolong(hero, Invisibility.class, invisTurns-1); //1 fewer turns as ability is instant
Dungeon.hero.sprite.turnTo( Dungeon.hero.pos, target);
Dungeon.hero.pos = target;
Dungeon.level.occupyCell(Dungeon.hero);
Dungeon.observe();
GameScene.updateFog();
Dungeon.hero.checkVisibleMobs();
Dungeon.hero.sprite.place( Dungeon.hero.pos );
CellEmitter.get( Dungeon.hero.pos ).burst( Speck.factory( Speck.WOOL ), 6 );
Sample.INSTANCE.play( Assets.Sounds.PUFF );
hero.next();
wep.afterAbilityUsed(hero);
}
}
| 0 | 0.884889 | 1 | 0.884889 | game-dev | MEDIA | 0.979355 | game-dev | 0.979818 | 1 | 0.979818 |
HeBianGu/WPF-ControlBase | 1,340 | Source/Service/HeBianGu.Service.Animation/Transition/HorizontalTransition.cs | // Copyright © 2022 By HeBianGu(QQ:908293466) https://github.com/HeBianGu/WPF-ControlBase
using System;
using System.Windows;
using System.Windows.Media.Animation;
namespace HeBianGu.Service.Animation
{
public class HorizontalTransition : TransitionBase
{
public override void BeginCurrent(UIElement element, Action complate = null)
{
if (!element.CheckDefaultTransformGroup()) return;
base.BeginCurrent(element);
element.BeginAnimationX(-(element as FrameworkElement).ActualWidth, 0, this.VisibleDuration, l => complate?.Invoke(), l =>
{
l.Easing = this.VisibleEasing;
});
}
public override void BeginPrevious(UIElement element, Action complate = null)
{
if (!element.CheckDefaultTransformGroup()) return;
base.BeginPrevious(element);
element.BeginAnimationX(0, (element as FrameworkElement).ActualWidth, this.HideDuration, l =>
{
//element.Visibility = HiddenOrCollapsed;
element.Visibility = Visibility.Collapsed;
complate?.Invoke();
}, l =>
{
l.Storyboard.FillBehavior = FillBehavior.Stop;
l.Easing = this.HideEasing;
});
}
}
}
| 0 | 0.846373 | 1 | 0.846373 | game-dev | MEDIA | 0.606943 | game-dev,desktop-app | 0.913047 | 1 | 0.913047 |
Jermesa-Studio/JRS_Vehicle_Physics_Controller | 1,661 | Library/PackageCache/com.unity.ugui@1.0.0/Runtime/UI/Core/SpriteState.cs | using System;
using UnityEngine.Serialization;
namespace UnityEngine.UI
{
[Serializable]
/// <summary>
/// Structure that stores the state of a sprite transition on a Selectable.
/// </summary>
public struct SpriteState : IEquatable<SpriteState>
{
[SerializeField]
private Sprite m_HighlightedSprite;
[SerializeField]
private Sprite m_PressedSprite;
[FormerlySerializedAs("m_HighlightedSprite")]
[SerializeField]
private Sprite m_SelectedSprite;
[SerializeField]
private Sprite m_DisabledSprite;
/// <summary>
/// Highlighted sprite.
/// </summary>
public Sprite highlightedSprite { get { return m_HighlightedSprite; } set { m_HighlightedSprite = value; } }
/// <summary>
/// Pressed sprite.
/// </summary>
public Sprite pressedSprite { get { return m_PressedSprite; } set { m_PressedSprite = value; } }
/// <summary>
/// Selected sprite.
/// </summary>
public Sprite selectedSprite { get { return m_SelectedSprite; } set { m_SelectedSprite = value; } }
/// <summary>
/// Disabled sprite.
/// </summary>
public Sprite disabledSprite { get { return m_DisabledSprite; } set { m_DisabledSprite = value; } }
public bool Equals(SpriteState other)
{
return highlightedSprite == other.highlightedSprite &&
pressedSprite == other.pressedSprite &&
selectedSprite == other.selectedSprite &&
disabledSprite == other.disabledSprite;
}
}
}
| 0 | 0.788102 | 1 | 0.788102 | game-dev | MEDIA | 0.866329 | game-dev | 0.626162 | 1 | 0.626162 |
holycake/mhsj | 1,240 | clone/xisui.c | #include <ansi.h>
inherit ITEM;
void create()
{
set_name(YEL "万年洗髓丹" NOR, ({ "dan", "xisui dan", "xisuidan" }) );
set_weight(200);
if( clonep() )
set_default_object(__FILE__);
else {
set("long", "一颗黑不溜秋的丹药,不知道有什么用。\n");
set("value", 10000);
set("unit", "颗");
}
}
void init()
{
add_action("do_eat", "eat");
}
int do_eat(string arg)
{
object me;
if (! id(arg))
return notify_fail("你要吃什么?\n");
me = this_player();
message_vision("$N一仰脖,吞下了一颗" + this_object()->name() +
"。\n", me);
/*if (me->query("liwu/xisuidan") >= 5)
{
message_vision("$N突然放了一个奇臭无比的响屁。\n", me);
tell_object(me, "你觉得大概是吃坏了肚子。\n");
} else
if (random(5) == 0)
{
tell_object(me, "不过你觉得好像没什么作用。\n");
} else
{*/
message("vision", "你似乎听见" + me->name() + "的骨头哗啦啦的响。\n",
environment(me), ({ me }));
tell_object(me, HIY "你浑身的骨骼登时哗啦啦的响个不停,可把你吓坏了,"
"好在一会儿就听了下来,似乎筋骨更灵活了。\n" NOR);
me->add("con", 1);
//}
me->add("liwu/xisuidan", 1);
destruct(this_object());
return 1;
}
| 0 | 0.527715 | 1 | 0.527715 | game-dev | MEDIA | 0.426703 | game-dev | 0.531548 | 1 | 0.531548 |
shxzu/Simp | 3,490 | src/main/java/net/minecraft/client/gui/GuiIngameMenu.java | package net.minecraft.client.gui;
import java.io.IOException;
import net.minecraft.client.gui.achievement.GuiAchievements;
import net.minecraft.client.gui.achievement.GuiStats;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.client.resources.I18n;
import net.minecraft.realms.RealmsBridge;
public class GuiIngameMenu extends GuiScreen
{
private int field_146445_a;
private int field_146444_f;
public void initGui()
{
this.field_146445_a = 0;
this.buttonList.clear();
int i = -16;
int j = 98;
this.buttonList.add(new GuiButton(1, this.width / 2 - 100, this.height / 4 + 120 + i, I18n.format("menu.returnToMenu")));
if (!this.mc.isIntegratedServerRunning())
{
this.buttonList.get(0).displayString = I18n.format("menu.disconnect");
}
this.buttonList.add(new GuiButton(4, this.width / 2 - 100, this.height / 4 + 24 + i, I18n.format("menu.returnToGame")));
this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 4 + 96 + i, 98, 20, I18n.format("menu.options")));
GuiButton guibutton;
this.buttonList.add(guibutton = new GuiButton(7, this.width / 2 + 2, this.height / 4 + 96 + i, 98, 20, I18n.format("menu.shareToLan")));
this.buttonList.add(new GuiButton(5, this.width / 2 - 100, this.height / 4 + 48 + i, 98, 20, I18n.format("gui.achievements")));
this.buttonList.add(new GuiButton(6, this.width / 2 + 2, this.height / 4 + 48 + i, 98, 20, I18n.format("gui.stats")));
guibutton.enabled = this.mc.isSingleplayer() && !this.mc.getIntegratedServer().getPublic();
}
protected void actionPerformed(GuiButton button) throws IOException
{
switch (button.id)
{
case 0:
this.mc.displayGuiScreen(new GuiOptions(this, this.mc.gameSettings));
break;
case 1:
boolean flag = this.mc.isIntegratedServerRunning();
boolean flag1 = this.mc.isConnectedToRealms();
button.enabled = false;
this.mc.theWorld.sendQuittingDisconnectingPacket();
this.mc.loadWorld(null);
if (flag)
{
this.mc.displayGuiScreen(new GuiMainMenu());
}
else
{
this.mc.displayGuiScreen(new GuiMultiplayer(new GuiMainMenu()));
}
case 2:
case 3:
default:
break;
case 4:
this.mc.displayGuiScreen(null);
this.mc.setIngameFocus();
break;
case 5:
this.mc.displayGuiScreen(new GuiAchievements(this, this.mc.thePlayer.getStatFileWriter()));
break;
case 6:
this.mc.displayGuiScreen(new GuiStats(this, this.mc.thePlayer.getStatFileWriter()));
break;
case 7:
this.mc.displayGuiScreen(new GuiShareToLan(this));
}
}
public void updateScreen()
{
super.updateScreen();
++this.field_146444_f;
}
public void drawScreen(int mouseX, int mouseY, float partialTicks)
{
this.drawDefaultBackground();
this.drawCenteredString(this.fontRendererObj, I18n.format("menu.game"), this.width / 2, 40, 16777215);
super.drawScreen(mouseX, mouseY, partialTicks);
}
}
| 0 | 0.661718 | 1 | 0.661718 | game-dev | MEDIA | 0.888764 | game-dev | 0.895837 | 1 | 0.895837 |
CnCNet/WorldAlteringEditor | 1,022 | src/TSMapEditor/UI/CursorActions/HeightActions/RaiseGroundCursorAction.cs | using TSMapEditor.GameMath;
using TSMapEditor.Mutations.Classes.HeightMutations;
namespace TSMapEditor.UI.CursorActions.HeightActions
{
public class RaiseGroundCursorAction : CursorAction
{
public RaiseGroundCursorAction(ICursorActionTarget cursorActionTarget) : base(cursorActionTarget)
{
}
public override string GetName() => Translate("Name", "Raise Ground (Steep Ramps)");
public override void OnActionEnter()
{
CursorActionTarget.BrushSize = Map.EditorConfig.BrushSizes.Find(bs => bs.Width == 3 && bs.Height == 3) ?? Map.EditorConfig.BrushSizes[0];
}
public override bool DrawCellCursor => true;
public override void LeftClick(Point2D cellCoords)
{
base.LeftClick(cellCoords);
var mutation = new RaiseGroundMutation(CursorActionTarget.MutationTarget, cellCoords, CursorActionTarget.BrushSize);
CursorActionTarget.MutationManager.PerformMutation(mutation);
}
}
}
| 0 | 0.728888 | 1 | 0.728888 | game-dev | MEDIA | 0.513813 | game-dev,testing-qa,desktop-app | 0.962938 | 1 | 0.962938 |
GaLicn/ExtendedAE_Plus | 5,845 | src/main/java/com/extendedae_plus/ae/screen/EntitySpeedTickerScreen.java | package com.extendedae_plus.ae.screen;
import appeng.api.config.Settings;
import appeng.api.config.YesNo;
import appeng.client.gui.Icon;
import appeng.client.gui.implementations.UpgradeableScreen;
import appeng.client.gui.style.ScreenStyle;
import appeng.client.gui.widgets.CommonButtons;
import appeng.client.gui.widgets.SettingToggleButton;
import appeng.util.Platform;
import com.extendedae_plus.ae.menu.EntitySpeedTickerMenu;
import com.extendedae_plus.init.ModNetwork;
import com.extendedae_plus.network.ToggleEntityTickerC2SPacket;
import com.extendedae_plus.util.entitySpeed.PowerUtils;
import net.minecraft.network.chat.Component;
import net.minecraft.world.entity.player.Inventory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 实体加速器界面,显示加速状态、卡数量、能耗和倍率信息。
*/
public class EntitySpeedTickerScreen<C extends EntitySpeedTickerMenu> extends UpgradeableScreen<C> {
private boolean eap$entitySpeedTickerEnabled = false; // 本地缓存的加速开关状态
private final SettingToggleButton<YesNo> eap$entitySpeedTickerToggle; // 加速开关按钮
/**
* 构造函数,初始化界面和控件。
* @param menu 实体加速器菜单
* @param playerInventory 玩家背包
* @param title 界面标题
* @param style 界面样式
*/
public EntitySpeedTickerScreen(EntitySpeedTickerMenu menu, Inventory playerInventory, Component title, ScreenStyle style) {
super((C) menu, playerInventory, title, style);
this.addToLeftToolbar(CommonButtons.togglePowerUnit()); // 添加功率单位切换按钮
this.eap$entitySpeedTickerEnabled = menu.getAccelerateEnabled();
// 初始化加速开关按钮
eap$entitySpeedTickerToggle = new SettingToggleButton<>(
Settings.BLOCKING_MODE,
this.eap$entitySpeedTickerEnabled ? YesNo.YES : YesNo.NO,
(btn, backwards) ->
ModNetwork.CHANNEL.sendToServer(new ToggleEntityTickerC2SPacket())
) {
@Override
public List<Component> getTooltipMessage() {
if (menu.targetBlacklisted) {
return List.of(
Component.literal("实体加速"),
Component.literal("已禁用(目标在黑名单)")
);
}
boolean enabled = eap$entitySpeedTickerEnabled;
return List.of(
Component.literal("实体加速"),
enabled ? Component.literal("已启用: 将加速目标方块实体的tick") :
Component.literal("已关闭: 不会对目标方块实体进行加速")
);
}
@Override
protected Icon getIcon() {
if (menu.targetBlacklisted) return Icon.INVALID;
return this.getCurrentValue() == YesNo.YES ? Icon.VALID : Icon.INVALID;
}
};
eap$entitySpeedTickerToggle.set(this.eap$entitySpeedTickerEnabled ? YesNo.YES : YesNo.NO);
this.addToLeftToolbar(eap$entitySpeedTickerToggle);
}
/**
* 在渲染前更新界面状态。
*/
@Override
protected void updateBeforeRender() {
super.updateBeforeRender();
if (eap$entitySpeedTickerToggle != null && menu != null) {
eap$entitySpeedTickerEnabled = menu.getAccelerateEnabled();
// 如果目标在黑名单,禁用按钮并显示关闭状态
eap$entitySpeedTickerToggle.set(menu.targetBlacklisted ? YesNo.NO : (eap$entitySpeedTickerEnabled ? YesNo.YES : YesNo.NO));
eap$entitySpeedTickerToggle.active = !menu.targetBlacklisted;
}
textData();
}
/**
* 刷新界面显示。
*/
public void refreshGui() {
textData();
}
/**
* 更新界面文本内容,包括加速状态、速度、能耗和倍率。
*/
private void textData() {
Map<String, Component> textContents = new HashMap<>();
if (getMenu().targetBlacklisted || !getMenu().getAccelerateEnabled()) {
// 黑名单禁用或加速关闭时的默认显示
textContents.put("enable", Component.translatable("screen.extendedae_plus.entity_speed_ticker.enable"));
textContents.put("speed", Component.translatable("screen.extendedae_plus.entity_speed_ticker.speed", 0));
textContents.put("energy", Component.translatable("screen.extendedae_plus.entity_speed_ticker.energy", Platform.formatPower(0.0, false)));
textContents.put("power_ratio", Component.translatable("screen.extendedae_plus.entity_speed_ticker.power_ratio", PowerUtils.formatPercentage(0.0)));
textContents.put("multiplier", Component.translatable("screen.extendedae_plus.entity_speed_ticker.multiplier", String.format("%.2fx", 0.0)));
} else {
// 正常状态下显示实际数据
int energyCardCount = getMenu().energyCardCount;
double multiplier = getMenu().multiplier;
int effectiveSpeed = getMenu().effectiveSpeed;
double finalPower = PowerUtils.getCachedPower(effectiveSpeed, energyCardCount);
double remainingRatio = PowerUtils.getCachedRatio(energyCardCount);
textContents.put("enable", getMenu().networkEnergySufficient ? null :
Component.translatable("screen.extendedae_plus.entity_speed_ticker.warning_network_energy_insufficient"));
textContents.put("speed", Component.translatable("screen.extendedae_plus.entity_speed_ticker.speed", effectiveSpeed));
textContents.put("energy", Component.translatable("screen.extendedae_plus.entity_speed_ticker.energy", Platform.formatPower(finalPower, false)));
textContents.put("power_ratio", Component.translatable("screen.extendedae_plus.entity_speed_ticker.power_ratio", PowerUtils.formatPercentage(remainingRatio)));
textContents.put("multiplier", Component.translatable("screen.extendedae_plus.entity_speed_ticker.multiplier", String.format("%.2fx", multiplier)));
}
textContents.forEach(this::setTextContent);
}
} | 0 | 0.762883 | 1 | 0.762883 | game-dev | MEDIA | 0.877969 | game-dev | 0.501645 | 1 | 0.501645 |
seppukudevelopment/seppuku | 1,783 | src/main/java/me/rigamortis/seppuku/impl/module/misc/DyeModule.java | package me.rigamortis.seppuku.impl.module.misc;
import me.rigamortis.seppuku.api.event.EventStageable;
import me.rigamortis.seppuku.api.event.player.EventPlayerUpdate;
import me.rigamortis.seppuku.api.module.Module;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import net.minecraft.entity.passive.EntitySheep;
import net.minecraft.item.EnumDyeColor;
import net.minecraft.item.ItemDye;
import net.minecraft.util.EnumHand;
import team.stiff.pomelo.impl.annotated.handler.annotation.Listener;
/**
* Author Seth
* 5/8/2019 @ 12:49 AM.
*/
public final class DyeModule extends Module {
public DyeModule() {
super("Dye", new String[]{"dy"}, "Automatically dyes nearby sheep if holding a dye", "NONE", -1, ModuleType.MISC);
}
@Listener
public void onUpdate(EventPlayerUpdate event) {
if (event.getStage() == EventStageable.EventStage.PRE) {
final Minecraft mc = Minecraft.getMinecraft();
if (mc.player.inventory.getCurrentItem().getItem() instanceof ItemDye) {
final EnumDyeColor color = EnumDyeColor.byDyeDamage(mc.player.inventory.getCurrentItem().getMetadata());
for (Entity e : mc.world.loadedEntityList) {
if (e != null && e instanceof EntitySheep) {
final EntitySheep sheep = (EntitySheep) e;
if (sheep.getHealth() > 0) {
if (sheep.getFleeceColor() != color && !sheep.getSheared() && mc.player.getDistance(sheep) <= 4.5f) {
mc.playerController.interactWithEntity(mc.player, sheep, EnumHand.MAIN_HAND);
}
}
}
}
}
}
}
}
| 0 | 0.804886 | 1 | 0.804886 | game-dev | MEDIA | 0.991047 | game-dev | 0.805071 | 1 | 0.805071 |
pfeodrippe/vybe | 25,201 | src-java/org/vybe/flecs/ecs_iter_to_json_desc_t.java | // Generated by jextract
package org.vybe.flecs;
import java.lang.invoke.*;
import java.lang.foreign.*;
import java.nio.ByteOrder;
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
import static java.lang.foreign.ValueLayout.*;
import static java.lang.foreign.MemoryLayout.PathElement.*;
/**
* {@snippet lang=c :
* struct ecs_iter_to_json_desc_t {
* bool serialize_entity_ids;
* bool serialize_values;
* bool serialize_builtin;
* bool serialize_doc;
* bool serialize_full_paths;
* bool serialize_fields;
* bool serialize_inherited;
* bool serialize_table;
* bool serialize_type_info;
* bool serialize_field_info;
* bool serialize_query_info;
* bool serialize_query_plan;
* bool serialize_query_profile;
* bool dont_serialize_results;
* bool serialize_alerts;
* ecs_entity_t serialize_refs;
* bool serialize_matches;
* ecs_poly_t *query;
* }
* }
*/
public class ecs_iter_to_json_desc_t {
ecs_iter_to_json_desc_t() {
// Should not be called directly
}
private static final GroupLayout $LAYOUT = MemoryLayout.structLayout(
flecs.C_BOOL.withName("serialize_entity_ids"),
flecs.C_BOOL.withName("serialize_values"),
flecs.C_BOOL.withName("serialize_builtin"),
flecs.C_BOOL.withName("serialize_doc"),
flecs.C_BOOL.withName("serialize_full_paths"),
flecs.C_BOOL.withName("serialize_fields"),
flecs.C_BOOL.withName("serialize_inherited"),
flecs.C_BOOL.withName("serialize_table"),
flecs.C_BOOL.withName("serialize_type_info"),
flecs.C_BOOL.withName("serialize_field_info"),
flecs.C_BOOL.withName("serialize_query_info"),
flecs.C_BOOL.withName("serialize_query_plan"),
flecs.C_BOOL.withName("serialize_query_profile"),
flecs.C_BOOL.withName("dont_serialize_results"),
flecs.C_BOOL.withName("serialize_alerts"),
MemoryLayout.paddingLayout(1),
flecs.C_LONG_LONG.withName("serialize_refs"),
flecs.C_BOOL.withName("serialize_matches"),
MemoryLayout.paddingLayout(7),
flecs.C_POINTER.withName("query")
).withName("ecs_iter_to_json_desc_t");
/**
* The layout of this struct
*/
public static final GroupLayout layout() {
return $LAYOUT;
}
private static final OfBoolean serialize_entity_ids$LAYOUT = (OfBoolean)$LAYOUT.select(groupElement("serialize_entity_ids"));
/**
* Layout for field:
* {@snippet lang=c :
* bool serialize_entity_ids
* }
*/
public static final OfBoolean serialize_entity_ids$layout() {
return serialize_entity_ids$LAYOUT;
}
private static final long serialize_entity_ids$OFFSET = 0;
/**
* Offset for field:
* {@snippet lang=c :
* bool serialize_entity_ids
* }
*/
public static final long serialize_entity_ids$offset() {
return serialize_entity_ids$OFFSET;
}
/**
* Getter for field:
* {@snippet lang=c :
* bool serialize_entity_ids
* }
*/
public static boolean serialize_entity_ids(MemorySegment struct) {
return struct.get(serialize_entity_ids$LAYOUT, serialize_entity_ids$OFFSET);
}
/**
* Setter for field:
* {@snippet lang=c :
* bool serialize_entity_ids
* }
*/
public static void serialize_entity_ids(MemorySegment struct, boolean fieldValue) {
struct.set(serialize_entity_ids$LAYOUT, serialize_entity_ids$OFFSET, fieldValue);
}
private static final OfBoolean serialize_values$LAYOUT = (OfBoolean)$LAYOUT.select(groupElement("serialize_values"));
/**
* Layout for field:
* {@snippet lang=c :
* bool serialize_values
* }
*/
public static final OfBoolean serialize_values$layout() {
return serialize_values$LAYOUT;
}
private static final long serialize_values$OFFSET = 1;
/**
* Offset for field:
* {@snippet lang=c :
* bool serialize_values
* }
*/
public static final long serialize_values$offset() {
return serialize_values$OFFSET;
}
/**
* Getter for field:
* {@snippet lang=c :
* bool serialize_values
* }
*/
public static boolean serialize_values(MemorySegment struct) {
return struct.get(serialize_values$LAYOUT, serialize_values$OFFSET);
}
/**
* Setter for field:
* {@snippet lang=c :
* bool serialize_values
* }
*/
public static void serialize_values(MemorySegment struct, boolean fieldValue) {
struct.set(serialize_values$LAYOUT, serialize_values$OFFSET, fieldValue);
}
private static final OfBoolean serialize_builtin$LAYOUT = (OfBoolean)$LAYOUT.select(groupElement("serialize_builtin"));
/**
* Layout for field:
* {@snippet lang=c :
* bool serialize_builtin
* }
*/
public static final OfBoolean serialize_builtin$layout() {
return serialize_builtin$LAYOUT;
}
private static final long serialize_builtin$OFFSET = 2;
/**
* Offset for field:
* {@snippet lang=c :
* bool serialize_builtin
* }
*/
public static final long serialize_builtin$offset() {
return serialize_builtin$OFFSET;
}
/**
* Getter for field:
* {@snippet lang=c :
* bool serialize_builtin
* }
*/
public static boolean serialize_builtin(MemorySegment struct) {
return struct.get(serialize_builtin$LAYOUT, serialize_builtin$OFFSET);
}
/**
* Setter for field:
* {@snippet lang=c :
* bool serialize_builtin
* }
*/
public static void serialize_builtin(MemorySegment struct, boolean fieldValue) {
struct.set(serialize_builtin$LAYOUT, serialize_builtin$OFFSET, fieldValue);
}
private static final OfBoolean serialize_doc$LAYOUT = (OfBoolean)$LAYOUT.select(groupElement("serialize_doc"));
/**
* Layout for field:
* {@snippet lang=c :
* bool serialize_doc
* }
*/
public static final OfBoolean serialize_doc$layout() {
return serialize_doc$LAYOUT;
}
private static final long serialize_doc$OFFSET = 3;
/**
* Offset for field:
* {@snippet lang=c :
* bool serialize_doc
* }
*/
public static final long serialize_doc$offset() {
return serialize_doc$OFFSET;
}
/**
* Getter for field:
* {@snippet lang=c :
* bool serialize_doc
* }
*/
public static boolean serialize_doc(MemorySegment struct) {
return struct.get(serialize_doc$LAYOUT, serialize_doc$OFFSET);
}
/**
* Setter for field:
* {@snippet lang=c :
* bool serialize_doc
* }
*/
public static void serialize_doc(MemorySegment struct, boolean fieldValue) {
struct.set(serialize_doc$LAYOUT, serialize_doc$OFFSET, fieldValue);
}
private static final OfBoolean serialize_full_paths$LAYOUT = (OfBoolean)$LAYOUT.select(groupElement("serialize_full_paths"));
/**
* Layout for field:
* {@snippet lang=c :
* bool serialize_full_paths
* }
*/
public static final OfBoolean serialize_full_paths$layout() {
return serialize_full_paths$LAYOUT;
}
private static final long serialize_full_paths$OFFSET = 4;
/**
* Offset for field:
* {@snippet lang=c :
* bool serialize_full_paths
* }
*/
public static final long serialize_full_paths$offset() {
return serialize_full_paths$OFFSET;
}
/**
* Getter for field:
* {@snippet lang=c :
* bool serialize_full_paths
* }
*/
public static boolean serialize_full_paths(MemorySegment struct) {
return struct.get(serialize_full_paths$LAYOUT, serialize_full_paths$OFFSET);
}
/**
* Setter for field:
* {@snippet lang=c :
* bool serialize_full_paths
* }
*/
public static void serialize_full_paths(MemorySegment struct, boolean fieldValue) {
struct.set(serialize_full_paths$LAYOUT, serialize_full_paths$OFFSET, fieldValue);
}
private static final OfBoolean serialize_fields$LAYOUT = (OfBoolean)$LAYOUT.select(groupElement("serialize_fields"));
/**
* Layout for field:
* {@snippet lang=c :
* bool serialize_fields
* }
*/
public static final OfBoolean serialize_fields$layout() {
return serialize_fields$LAYOUT;
}
private static final long serialize_fields$OFFSET = 5;
/**
* Offset for field:
* {@snippet lang=c :
* bool serialize_fields
* }
*/
public static final long serialize_fields$offset() {
return serialize_fields$OFFSET;
}
/**
* Getter for field:
* {@snippet lang=c :
* bool serialize_fields
* }
*/
public static boolean serialize_fields(MemorySegment struct) {
return struct.get(serialize_fields$LAYOUT, serialize_fields$OFFSET);
}
/**
* Setter for field:
* {@snippet lang=c :
* bool serialize_fields
* }
*/
public static void serialize_fields(MemorySegment struct, boolean fieldValue) {
struct.set(serialize_fields$LAYOUT, serialize_fields$OFFSET, fieldValue);
}
private static final OfBoolean serialize_inherited$LAYOUT = (OfBoolean)$LAYOUT.select(groupElement("serialize_inherited"));
/**
* Layout for field:
* {@snippet lang=c :
* bool serialize_inherited
* }
*/
public static final OfBoolean serialize_inherited$layout() {
return serialize_inherited$LAYOUT;
}
private static final long serialize_inherited$OFFSET = 6;
/**
* Offset for field:
* {@snippet lang=c :
* bool serialize_inherited
* }
*/
public static final long serialize_inherited$offset() {
return serialize_inherited$OFFSET;
}
/**
* Getter for field:
* {@snippet lang=c :
* bool serialize_inherited
* }
*/
public static boolean serialize_inherited(MemorySegment struct) {
return struct.get(serialize_inherited$LAYOUT, serialize_inherited$OFFSET);
}
/**
* Setter for field:
* {@snippet lang=c :
* bool serialize_inherited
* }
*/
public static void serialize_inherited(MemorySegment struct, boolean fieldValue) {
struct.set(serialize_inherited$LAYOUT, serialize_inherited$OFFSET, fieldValue);
}
private static final OfBoolean serialize_table$LAYOUT = (OfBoolean)$LAYOUT.select(groupElement("serialize_table"));
/**
* Layout for field:
* {@snippet lang=c :
* bool serialize_table
* }
*/
public static final OfBoolean serialize_table$layout() {
return serialize_table$LAYOUT;
}
private static final long serialize_table$OFFSET = 7;
/**
* Offset for field:
* {@snippet lang=c :
* bool serialize_table
* }
*/
public static final long serialize_table$offset() {
return serialize_table$OFFSET;
}
/**
* Getter for field:
* {@snippet lang=c :
* bool serialize_table
* }
*/
public static boolean serialize_table(MemorySegment struct) {
return struct.get(serialize_table$LAYOUT, serialize_table$OFFSET);
}
/**
* Setter for field:
* {@snippet lang=c :
* bool serialize_table
* }
*/
public static void serialize_table(MemorySegment struct, boolean fieldValue) {
struct.set(serialize_table$LAYOUT, serialize_table$OFFSET, fieldValue);
}
private static final OfBoolean serialize_type_info$LAYOUT = (OfBoolean)$LAYOUT.select(groupElement("serialize_type_info"));
/**
* Layout for field:
* {@snippet lang=c :
* bool serialize_type_info
* }
*/
public static final OfBoolean serialize_type_info$layout() {
return serialize_type_info$LAYOUT;
}
private static final long serialize_type_info$OFFSET = 8;
/**
* Offset for field:
* {@snippet lang=c :
* bool serialize_type_info
* }
*/
public static final long serialize_type_info$offset() {
return serialize_type_info$OFFSET;
}
/**
* Getter for field:
* {@snippet lang=c :
* bool serialize_type_info
* }
*/
public static boolean serialize_type_info(MemorySegment struct) {
return struct.get(serialize_type_info$LAYOUT, serialize_type_info$OFFSET);
}
/**
* Setter for field:
* {@snippet lang=c :
* bool serialize_type_info
* }
*/
public static void serialize_type_info(MemorySegment struct, boolean fieldValue) {
struct.set(serialize_type_info$LAYOUT, serialize_type_info$OFFSET, fieldValue);
}
private static final OfBoolean serialize_field_info$LAYOUT = (OfBoolean)$LAYOUT.select(groupElement("serialize_field_info"));
/**
* Layout for field:
* {@snippet lang=c :
* bool serialize_field_info
* }
*/
public static final OfBoolean serialize_field_info$layout() {
return serialize_field_info$LAYOUT;
}
private static final long serialize_field_info$OFFSET = 9;
/**
* Offset for field:
* {@snippet lang=c :
* bool serialize_field_info
* }
*/
public static final long serialize_field_info$offset() {
return serialize_field_info$OFFSET;
}
/**
* Getter for field:
* {@snippet lang=c :
* bool serialize_field_info
* }
*/
public static boolean serialize_field_info(MemorySegment struct) {
return struct.get(serialize_field_info$LAYOUT, serialize_field_info$OFFSET);
}
/**
* Setter for field:
* {@snippet lang=c :
* bool serialize_field_info
* }
*/
public static void serialize_field_info(MemorySegment struct, boolean fieldValue) {
struct.set(serialize_field_info$LAYOUT, serialize_field_info$OFFSET, fieldValue);
}
private static final OfBoolean serialize_query_info$LAYOUT = (OfBoolean)$LAYOUT.select(groupElement("serialize_query_info"));
/**
* Layout for field:
* {@snippet lang=c :
* bool serialize_query_info
* }
*/
public static final OfBoolean serialize_query_info$layout() {
return serialize_query_info$LAYOUT;
}
private static final long serialize_query_info$OFFSET = 10;
/**
* Offset for field:
* {@snippet lang=c :
* bool serialize_query_info
* }
*/
public static final long serialize_query_info$offset() {
return serialize_query_info$OFFSET;
}
/**
* Getter for field:
* {@snippet lang=c :
* bool serialize_query_info
* }
*/
public static boolean serialize_query_info(MemorySegment struct) {
return struct.get(serialize_query_info$LAYOUT, serialize_query_info$OFFSET);
}
/**
* Setter for field:
* {@snippet lang=c :
* bool serialize_query_info
* }
*/
public static void serialize_query_info(MemorySegment struct, boolean fieldValue) {
struct.set(serialize_query_info$LAYOUT, serialize_query_info$OFFSET, fieldValue);
}
private static final OfBoolean serialize_query_plan$LAYOUT = (OfBoolean)$LAYOUT.select(groupElement("serialize_query_plan"));
/**
* Layout for field:
* {@snippet lang=c :
* bool serialize_query_plan
* }
*/
public static final OfBoolean serialize_query_plan$layout() {
return serialize_query_plan$LAYOUT;
}
private static final long serialize_query_plan$OFFSET = 11;
/**
* Offset for field:
* {@snippet lang=c :
* bool serialize_query_plan
* }
*/
public static final long serialize_query_plan$offset() {
return serialize_query_plan$OFFSET;
}
/**
* Getter for field:
* {@snippet lang=c :
* bool serialize_query_plan
* }
*/
public static boolean serialize_query_plan(MemorySegment struct) {
return struct.get(serialize_query_plan$LAYOUT, serialize_query_plan$OFFSET);
}
/**
* Setter for field:
* {@snippet lang=c :
* bool serialize_query_plan
* }
*/
public static void serialize_query_plan(MemorySegment struct, boolean fieldValue) {
struct.set(serialize_query_plan$LAYOUT, serialize_query_plan$OFFSET, fieldValue);
}
private static final OfBoolean serialize_query_profile$LAYOUT = (OfBoolean)$LAYOUT.select(groupElement("serialize_query_profile"));
/**
* Layout for field:
* {@snippet lang=c :
* bool serialize_query_profile
* }
*/
public static final OfBoolean serialize_query_profile$layout() {
return serialize_query_profile$LAYOUT;
}
private static final long serialize_query_profile$OFFSET = 12;
/**
* Offset for field:
* {@snippet lang=c :
* bool serialize_query_profile
* }
*/
public static final long serialize_query_profile$offset() {
return serialize_query_profile$OFFSET;
}
/**
* Getter for field:
* {@snippet lang=c :
* bool serialize_query_profile
* }
*/
public static boolean serialize_query_profile(MemorySegment struct) {
return struct.get(serialize_query_profile$LAYOUT, serialize_query_profile$OFFSET);
}
/**
* Setter for field:
* {@snippet lang=c :
* bool serialize_query_profile
* }
*/
public static void serialize_query_profile(MemorySegment struct, boolean fieldValue) {
struct.set(serialize_query_profile$LAYOUT, serialize_query_profile$OFFSET, fieldValue);
}
private static final OfBoolean dont_serialize_results$LAYOUT = (OfBoolean)$LAYOUT.select(groupElement("dont_serialize_results"));
/**
* Layout for field:
* {@snippet lang=c :
* bool dont_serialize_results
* }
*/
public static final OfBoolean dont_serialize_results$layout() {
return dont_serialize_results$LAYOUT;
}
private static final long dont_serialize_results$OFFSET = 13;
/**
* Offset for field:
* {@snippet lang=c :
* bool dont_serialize_results
* }
*/
public static final long dont_serialize_results$offset() {
return dont_serialize_results$OFFSET;
}
/**
* Getter for field:
* {@snippet lang=c :
* bool dont_serialize_results
* }
*/
public static boolean dont_serialize_results(MemorySegment struct) {
return struct.get(dont_serialize_results$LAYOUT, dont_serialize_results$OFFSET);
}
/**
* Setter for field:
* {@snippet lang=c :
* bool dont_serialize_results
* }
*/
public static void dont_serialize_results(MemorySegment struct, boolean fieldValue) {
struct.set(dont_serialize_results$LAYOUT, dont_serialize_results$OFFSET, fieldValue);
}
private static final OfBoolean serialize_alerts$LAYOUT = (OfBoolean)$LAYOUT.select(groupElement("serialize_alerts"));
/**
* Layout for field:
* {@snippet lang=c :
* bool serialize_alerts
* }
*/
public static final OfBoolean serialize_alerts$layout() {
return serialize_alerts$LAYOUT;
}
private static final long serialize_alerts$OFFSET = 14;
/**
* Offset for field:
* {@snippet lang=c :
* bool serialize_alerts
* }
*/
public static final long serialize_alerts$offset() {
return serialize_alerts$OFFSET;
}
/**
* Getter for field:
* {@snippet lang=c :
* bool serialize_alerts
* }
*/
public static boolean serialize_alerts(MemorySegment struct) {
return struct.get(serialize_alerts$LAYOUT, serialize_alerts$OFFSET);
}
/**
* Setter for field:
* {@snippet lang=c :
* bool serialize_alerts
* }
*/
public static void serialize_alerts(MemorySegment struct, boolean fieldValue) {
struct.set(serialize_alerts$LAYOUT, serialize_alerts$OFFSET, fieldValue);
}
private static final OfLong serialize_refs$LAYOUT = (OfLong)$LAYOUT.select(groupElement("serialize_refs"));
/**
* Layout for field:
* {@snippet lang=c :
* ecs_entity_t serialize_refs
* }
*/
public static final OfLong serialize_refs$layout() {
return serialize_refs$LAYOUT;
}
private static final long serialize_refs$OFFSET = 16;
/**
* Offset for field:
* {@snippet lang=c :
* ecs_entity_t serialize_refs
* }
*/
public static final long serialize_refs$offset() {
return serialize_refs$OFFSET;
}
/**
* Getter for field:
* {@snippet lang=c :
* ecs_entity_t serialize_refs
* }
*/
public static long serialize_refs(MemorySegment struct) {
return struct.get(serialize_refs$LAYOUT, serialize_refs$OFFSET);
}
/**
* Setter for field:
* {@snippet lang=c :
* ecs_entity_t serialize_refs
* }
*/
public static void serialize_refs(MemorySegment struct, long fieldValue) {
struct.set(serialize_refs$LAYOUT, serialize_refs$OFFSET, fieldValue);
}
private static final OfBoolean serialize_matches$LAYOUT = (OfBoolean)$LAYOUT.select(groupElement("serialize_matches"));
/**
* Layout for field:
* {@snippet lang=c :
* bool serialize_matches
* }
*/
public static final OfBoolean serialize_matches$layout() {
return serialize_matches$LAYOUT;
}
private static final long serialize_matches$OFFSET = 24;
/**
* Offset for field:
* {@snippet lang=c :
* bool serialize_matches
* }
*/
public static final long serialize_matches$offset() {
return serialize_matches$OFFSET;
}
/**
* Getter for field:
* {@snippet lang=c :
* bool serialize_matches
* }
*/
public static boolean serialize_matches(MemorySegment struct) {
return struct.get(serialize_matches$LAYOUT, serialize_matches$OFFSET);
}
/**
* Setter for field:
* {@snippet lang=c :
* bool serialize_matches
* }
*/
public static void serialize_matches(MemorySegment struct, boolean fieldValue) {
struct.set(serialize_matches$LAYOUT, serialize_matches$OFFSET, fieldValue);
}
private static final AddressLayout query$LAYOUT = (AddressLayout)$LAYOUT.select(groupElement("query"));
/**
* Layout for field:
* {@snippet lang=c :
* ecs_poly_t *query
* }
*/
public static final AddressLayout query$layout() {
return query$LAYOUT;
}
private static final long query$OFFSET = 32;
/**
* Offset for field:
* {@snippet lang=c :
* ecs_poly_t *query
* }
*/
public static final long query$offset() {
return query$OFFSET;
}
/**
* Getter for field:
* {@snippet lang=c :
* ecs_poly_t *query
* }
*/
public static MemorySegment query(MemorySegment struct) {
return struct.get(query$LAYOUT, query$OFFSET);
}
/**
* Setter for field:
* {@snippet lang=c :
* ecs_poly_t *query
* }
*/
public static void query(MemorySegment struct, MemorySegment fieldValue) {
struct.set(query$LAYOUT, query$OFFSET, fieldValue);
}
/**
* Obtains a slice of {@code arrayParam} which selects the array element at {@code index}.
* The returned segment has address {@code arrayParam.address() + index * layout().byteSize()}
*/
public static MemorySegment asSlice(MemorySegment array, long index) {
return array.asSlice(layout().byteSize() * index);
}
/**
* The size (in bytes) of this struct
*/
public static long sizeof() { return layout().byteSize(); }
/**
* Allocate a segment of size {@code layout().byteSize()} using {@code allocator}
*/
public static MemorySegment allocate(SegmentAllocator allocator) {
return allocator.allocate(layout());
}
/**
* Allocate an array of size {@code elementCount} using {@code allocator}.
* The returned segment has size {@code elementCount * layout().byteSize()}.
*/
public static MemorySegment allocateArray(long elementCount, SegmentAllocator allocator) {
return allocator.allocate(MemoryLayout.sequenceLayout(elementCount, layout()));
}
/**
* Reinterprets {@code addr} using target {@code arena} and {@code cleanupAction} (if any).
* The returned segment has size {@code layout().byteSize()}
*/
public static MemorySegment reinterpret(MemorySegment addr, Arena arena, Consumer<MemorySegment> cleanup) {
return reinterpret(addr, 1, arena, cleanup);
}
/**
* Reinterprets {@code addr} using target {@code arena} and {@code cleanupAction} (if any).
* The returned segment has size {@code elementCount * layout().byteSize()}
*/
public static MemorySegment reinterpret(MemorySegment addr, long elementCount, Arena arena, Consumer<MemorySegment> cleanup) {
return addr.reinterpret(layout().byteSize() * elementCount, arena, cleanup);
}
}
| 0 | 0.895942 | 1 | 0.895942 | game-dev | MEDIA | 0.152046 | game-dev | 0.551024 | 1 | 0.551024 |
Quenty/NevermoreEngine | 2,067 | src/accessorytypeutils/src/Shared/AccessoryTypeUtils.lua | --!strict
--[=[
@class AccessoryTypeUtils
]=]
local require = require(script.Parent.loader).load(script)
local EnumUtils = require("EnumUtils")
local AvatarEditorService = game:GetService("AvatarEditorService")
local AccessoryTypeUtils = {}
--[=[
Converts an enum value (retrieved from AvatarEditorService) into a proper enum if possible
@param avatarAssetType Enum.AvatarAssetType
@return Enum.AccessoryType?
]=]
function AccessoryTypeUtils.tryGetAccessoryType(avatarAssetType: Enum.AvatarAssetType): (Enum.AccessoryType?, string?)
if not avatarAssetType then
return nil, "No avatarAssetType"
end
local accessoryType
local ok, err = pcall(function()
accessoryType = AvatarEditorService:GetAccessoryType(avatarAssetType)
end)
if not ok then
return nil, err or "Failed to GetAccessoryType from avatarAssetType"
end
return accessoryType
end
--[=[
Converts a string into an enum value
@param accessoryType string
@return Enum.AccessoryType
]=]
function AccessoryTypeUtils.getAccessoryTypeFromName(accessoryType: string): Enum.AccessoryType
for _, enumItem in Enum.AccessoryType:GetEnumItems() do
if enumItem.Name == accessoryType then
return enumItem
end
end
return Enum.AccessoryType.Unknown
end
--[=[
Converts an enum value (retrieved from MarketplaceService) into a proper enum if possible
@param assetTypeId number
@return Enum.AssetType?
]=]
function AccessoryTypeUtils.convertAssetTypeIdToAssetType(assetTypeId: number): Enum.AssetType?
assert(type(assetTypeId) == "number", "Bad assetTypeId")
return EnumUtils.toEnum(Enum.AssetType, assetTypeId) :: any
end
--[=[
Converts an enum value (retrieved from MarketplaceService) into a proper enum if possible
@param avatarAssetTypeId number
@return Enum.AvatarAssetType?
]=]
function AccessoryTypeUtils.convertAssetTypeIdToAvatarAssetType(avatarAssetTypeId: number): Enum.AvatarAssetType?
assert(type(avatarAssetTypeId) == "number", "Bad avatarAssetTypeId")
return EnumUtils.toEnum(Enum.AvatarAssetType, avatarAssetTypeId) :: any
end
return AccessoryTypeUtils
| 0 | 0.674564 | 1 | 0.674564 | game-dev | MEDIA | 0.659767 | game-dev | 0.544614 | 1 | 0.544614 |
LandSandBoat/server | 1,467 | scripts/actions/mobskills/random_needles.lua | -----------------------------------
-- ??? Needles
-- Description: Shoots multiple needles at enemies within range.
-- 'The Amigo Sabotender's special ability 1000 Needles has been renamed ??? Needles.''
-- https://forum.square-enix.com/ffxi/threads/46068-Feb-19-2015-(JST)-Version-Update
-----------------------------------
---@type TMobSkill
local mobskillObject = {}
mobskillObject.onMobSkillCheck = function(target, mob, skill)
return 0
end
mobskillObject.onMobWeaponSkill = function(target, mob, skill)
-- from http://ffxiclopedia.wikia.com/wiki/%3F%3F%3F_Needles
-- "Seen totals ranging from 15, 000 to 55, 000 needles."
if mob:getID() == zones[xi.zone.ABYSSEA_ALTEPA].mob.CUIJATENDER then
local needles = math.random(15000, 55000) / skill:getTotalTargets()
local dmg = xi.mobskills.mobFinalAdjustments(needles, mob, skill, target, xi.attackType.PHYSICAL, xi.damageType.LIGHT, xi.mobskills.shadowBehavior.WIPE_SHADOWS)
target:takeDamage(dmg, mob, xi.attackType.PHYSICAL, xi.damageType.LIGHT)
return dmg
else
local needles = math.random(1000, 10000) / skill:getTotalTargets()
local dmg = xi.mobskills.mobFinalAdjustments(needles, mob, skill, target, xi.attackType.PHYSICAL, xi.damageType.LIGHT, xi.mobskills.shadowBehavior.WIPE_SHADOWS)
target:takeDamage(dmg, mob, xi.attackType.PHYSICAL, xi.damageType.LIGHT)
return dmg
end
end
return mobskillObject
| 0 | 0.649713 | 1 | 0.649713 | game-dev | MEDIA | 0.925638 | game-dev | 0.806866 | 1 | 0.806866 |
MMMaellon/SmartObjectSync | 94,741 | Packages/com.mmmaellon.smartobjectsync/Runtime/Scripts/SmartObjectSync.cs | using UdonSharp;
using UnityEngine;
using VRC.SDKBase;
#if !COMPILER_UDONSHARP && UNITY_EDITOR
using VRC.SDKBase.Editor.BuildPipeline;
using UnityEditor;
using UdonSharpEditor;
using System.Collections.Generic;
namespace MMMaellon
{
[CustomEditor(typeof(SmartObjectSync), true), CanEditMultipleObjects]
public class SmartObjectSyncEditor : Editor
{
public static bool foldoutOpen = false;
//Advanced settings
SerializedProperty m_printDebugMessages;
SerializedProperty m_performanceModeCollisions;
SerializedProperty m_forceContinuousSpeculative;
SerializedProperty m_kinematicWhileHeld;
SerializedProperty m_nonKinematicPickupJitterPreventionTime;
SerializedProperty m_reduceJitterDuringSleep;
SerializedProperty m_worldSpaceTeleport;
SerializedProperty m_worldSpaceSleep;
SerializedProperty m_worldSpacePhysics;
SerializedProperty m_preventStealWhileAttachedToPlayer;
SerializedProperty m_startingState;
SerializedProperty m_checkSyncTimes;
void OnEnable()
{
m_printDebugMessages = serializedObject.FindProperty("printDebugMessages");
m_performanceModeCollisions = serializedObject.FindProperty("performanceModeCollisions");
m_forceContinuousSpeculative = serializedObject.FindProperty("forceContinuousSpeculative");
m_kinematicWhileHeld = serializedObject.FindProperty("kinematicWhileHeld");
m_nonKinematicPickupJitterPreventionTime = serializedObject.FindProperty("nonKinematicPickupJitterPreventionTime");
m_reduceJitterDuringSleep = serializedObject.FindProperty("reduceJitterDuringSleep");
m_worldSpaceTeleport = serializedObject.FindProperty("worldSpaceTeleport");
m_worldSpaceSleep = serializedObject.FindProperty("worldSpaceSleep");
m_worldSpacePhysics = serializedObject.FindProperty("worldSpacePhysics");
m_preventStealWhileAttachedToPlayer = serializedObject.FindProperty("preventStealWhileAttachedToPlayer");
m_startingState = serializedObject.FindProperty("startingState");
m_checkSyncTimes = serializedObject.FindProperty("checkSyncTimes");
}
public static void _print(SmartObjectSync sync, string message)
{
if (sync && sync.printDebugMessages)
{
Debug.LogFormat(sync, "[SmartObjectSync] {0}: {1}", sync.name, message);
}
}
public static void SetupSmartObjectSync(SmartObjectSync sync)
{
if (sync)
{
_print(sync, "SetupSmartObjectSync");
SerializedObject serializedSync = new SerializedObject(sync);
serializedSync.FindProperty("pickup").objectReferenceValue = sync.GetComponent<VRC_Pickup>();
serializedSync.FindProperty("rigid").objectReferenceValue = sync.GetComponent<Rigidbody>();
if (VRC_SceneDescriptor.Instance)
{
serializedSync.FindProperty("respawnHeight").floatValue = VRC_SceneDescriptor.Instance.RespawnHeightY;
}
serializedSync.ApplyModifiedProperties();
SetupStates(sync);
if (sync.printDebugMessages)
_print(sync, "Auto Setup Complete!\n" + (sync.pickup == null ? "No VRC_Pickup component found" : "VRC_Pickup component found\n" + (sync.rigid == null ? "No Rigidbody component found" : "Rigidbody component found")));
}
else
{
Debug.LogWarning("[SmartObjectSync] Auto Setup failed: No SmartObjectSync selected");
}
}
public static void SetupStates(SmartObjectSync sync)
{
if (sync)
{
_print(sync, "SetupStates");
SerializedObject serializedSync = new SerializedObject(sync);
serializedSync.FindProperty("states").ClearArray();
SmartObjectSyncState[] states = sync.GetComponents<SmartObjectSyncState>();
int stateCounter = 0;
_print(sync, "adding custom states: " + states.Length);
foreach (SmartObjectSyncState state in states)
{
AddStateSerialized(ref sync, ref serializedSync, state, stateCounter);
stateCounter++;
}
serializedSync.ApplyModifiedProperties();
}
else
{
Debug.LogWarningFormat("[SmartObjectSync] Auto Setup failed: No SmartObjectSync selected");
}
}
public static void AddStateSerialized(ref SmartObjectSync sync, ref SerializedObject serializedSync, SmartObjectSyncState newState, int index)
{
if (newState != null && serializedSync != null)
{
SerializedObject serializedState = new SerializedObject(newState);
serializedState.FindProperty("stateID").intValue = index;
serializedState.FindProperty("sync").objectReferenceValue = sync;
serializedState.ApplyModifiedProperties();
serializedSync.FindProperty("states").InsertArrayElementAtIndex(index);
serializedSync.FindProperty("states").GetArrayElementAtIndex(index).objectReferenceValue = newState;
}
}
public static void SetupSelectedSmartObjectSyncs()
{
bool syncFound = false;
foreach (SmartObjectSync sync in Selection.GetFiltered<SmartObjectSync>(SelectionMode.Editable))
{
syncFound = true;
SetupSmartObjectSync(sync);
}
if (!syncFound)
{
Debug.LogWarningFormat("[SmartObjectSync] Auto Setup failed: No SmartObjectSync selected");
}
}
public override void OnInspectorGUI()
{
int syncCount = 0;
int pickupSetupCount = 0;
int rigidSetupCount = 0;
int respawnYSetupCount = 0;
int stateSetupCount = 0;
foreach (SmartObjectSync sync in Selection.GetFiltered<SmartObjectSync>(SelectionMode.Editable))
{
if (Utilities.IsValid(sync))
{
syncCount++;
if (sync.pickup != sync.GetComponent<VRC_Pickup>())
{
pickupSetupCount++;
}
if (sync.rigid != sync.GetComponent<Rigidbody>())
{
rigidSetupCount++;
}
if (Utilities.IsValid(VRC_SceneDescriptor.Instance) && !Mathf.Approximately(VRC_SceneDescriptor.Instance.RespawnHeightY, sync.respawnHeight))
{
respawnYSetupCount++;
}
if (!Utilities.IsValid(sync.states))
{
sync.states = new SmartObjectSyncState[0];
}
SmartObjectSyncState[] stateComponents = sync.GetComponents<SmartObjectSyncState>();
if (sync.states.Length != stateComponents.Length)//+ 1 because of bone attachment
{
stateSetupCount++;
}
else
{
bool errorFound = false;
foreach (SmartObjectSyncState state in sync.states)
{
if (state == null || state.sync != sync || state.stateID < 0 || state.stateID >= sync.states.Length || sync.states[state.stateID] != state)
{
errorFound = true;
break;
}
}
if (!errorFound)
{
foreach (SmartObjectSyncState state in stateComponents)
{
if (state != null && (state.sync != sync || state.stateID < 0 || state.stateID >= sync.states.Length || sync.states[state.stateID] != state))
{
errorFound = true;
break;
}
}
}
if (errorFound)
{
stateSetupCount++;
}
}
}
}
if ((pickupSetupCount > 0 || rigidSetupCount > 0 || respawnYSetupCount > 0 || stateSetupCount > 0))
{
if (pickupSetupCount == 1)
{
EditorGUILayout.HelpBox(@"Object not set up for VRC_Pickup", MessageType.Warning);
}
else if (pickupSetupCount > 1)
{
EditorGUILayout.HelpBox(pickupSetupCount.ToString() + @" Objects not set up for VRC_Pickup", MessageType.Warning);
}
if (rigidSetupCount == 1)
{
EditorGUILayout.HelpBox(@"Object not set up for Rigidbody", MessageType.Warning);
}
else if (rigidSetupCount > 1)
{
EditorGUILayout.HelpBox(rigidSetupCount.ToString() + @" Objects not set up for Rigidbody", MessageType.Warning);
}
if (respawnYSetupCount == 1)
{
EditorGUILayout.HelpBox(@"Respawn Height is different from the scene's", MessageType.Info);
}
else if (respawnYSetupCount > 1)
{
EditorGUILayout.HelpBox(respawnYSetupCount.ToString() + @" Objects have a Respawn Height that is different from the scene's", MessageType.Info);
}
if (stateSetupCount == 1)
{
EditorGUILayout.HelpBox(@"States misconfigured", MessageType.Warning);
}
else if (stateSetupCount > 1)
{
EditorGUILayout.HelpBox(stateSetupCount.ToString() + @" SmartObjectSyncs with misconfigured States", MessageType.Warning);
}
if (GUILayout.Button(new GUIContent("Auto Setup")))
{
SetupSelectedSmartObjectSyncs();
}
}
if (target && UdonSharpGUI.DrawDefaultUdonSharpBehaviourHeader(target)) return;
EditorGUILayout.Space();
EditorGUILayout.Space();
EditorGUILayout.Space();
base.OnInspectorGUI();
EditorGUILayout.Space();
EditorGUILayout.Space();
EditorGUILayout.Space();
foldoutOpen = EditorGUILayout.BeginFoldoutHeaderGroup(foldoutOpen, "Advanced Settings");
if (foldoutOpen)
{
if (GUILayout.Button(new GUIContent("Force Setup")))
{
SetupSelectedSmartObjectSyncs();
}
EditorGUILayout.PropertyField(m_printDebugMessages);
EditorGUILayout.PropertyField(m_performanceModeCollisions);
EditorGUILayout.PropertyField(m_forceContinuousSpeculative);
EditorGUILayout.PropertyField(m_kinematicWhileHeld);
EditorGUILayout.PropertyField(m_nonKinematicPickupJitterPreventionTime);
EditorGUILayout.PropertyField(m_reduceJitterDuringSleep);
EditorGUILayout.PropertyField(m_worldSpaceTeleport);
EditorGUILayout.PropertyField(m_worldSpaceSleep);
EditorGUILayout.PropertyField(m_worldSpacePhysics);
EditorGUILayout.PropertyField(m_preventStealWhileAttachedToPlayer);
EditorGUILayout.PropertyField(m_startingState);
EditorGUILayout.PropertyField(m_checkSyncTimes);
serializedObject.ApplyModifiedProperties();
}
EditorGUILayout.EndFoldoutHeaderGroup();
}
}
}
#endif
namespace MMMaellon
{
[UdonBehaviourSyncMode(BehaviourSyncMode.Manual)]
[RequireComponent(typeof(Rigidbody))]
public partial class SmartObjectSync : UdonSharpBehaviour
{
public bool takeOwnershipOfOtherObjectsOnCollision = true;
public bool allowOthersToTakeOwnershipOnCollision = true;
public bool allowTheftFromSelf = true;
public bool syncParticleCollisions = false;
public float respawnHeight = -1001f;
[HideInInspector]
public bool printDebugMessages = false;
[HideInInspector]
public bool performanceModeCollisions = true;
[HideInInspector, Tooltip("By default, calling respawn will make the object reset it's local object space transforms.")]
public bool worldSpaceTeleport = false;
[HideInInspector, Tooltip("By default, everything is in world space. Uncheck if the relationship between this object and it's parent is more important than it and the world.")]
public bool worldSpaceSleep = true;
[HideInInspector, Tooltip("By default, everything is in world space. Uncheck if the relationship between this object and it's parent is more important than it and the world.")]
public bool worldSpacePhysics = true;
[HideInInspector, Tooltip("VRCObjectSync will set rigidbodies' collision detection mode to ContinuousSpeculative. This recreates that feature.")]
public bool forceContinuousSpeculative = true;
[HideInInspector, Tooltip("Turns the object kinematic when held. Will result in dampened collisions because that's just how Unity is.")]
public bool kinematicWhileHeld = true;
[HideInInspector, Tooltip("Forces the local pickup object into the right position after a certain amount of time. Disabled if set to 0 or negative. You should only enable this if you need the collisions to be accurate, otherwise reduce jitter by enabling kinematic while held instead.")]
public float nonKinematicPickupJitterPreventionTime = 0;
[HideInInspector, Tooltip("If the rigidbody is unable to fall asleep we hold it in place. Makes object sync more accurate, at the cost of more CPU usage for non-owners in some edge cases where your physics are unstable.")]
public bool reduceJitterDuringSleep = true;
[HideInInspector, Tooltip("Only applies when we're attached to a player's playspace or avatar. Prevents other players from taking it.")]
public bool preventStealWhileAttachedToPlayer = true;
[HideInInspector]
public bool respawnIntoStartingState = true;
[HideInInspector]
public SmartObjectSyncState startingState = null;
[HideInInspector]
public bool checkSyncTimes = false;
[HideInInspector]
public VRC_Pickup pickup;
[HideInInspector]
public Rigidbody rigid;
[System.NonSerialized, UdonSynced(UdonSyncMode.None)]
public Vector3 pos;
[System.NonSerialized, UdonSynced(UdonSyncMode.None)]
public Quaternion rot;
[System.NonSerialized, UdonSynced(UdonSyncMode.None)]
public Vector3 vel;
[System.NonSerialized, UdonSynced(UdonSyncMode.None)]
public Vector3 spin;
[System.NonSerialized, FieldChangeCallback(nameof(state))]
public int _state = STATE_TELEPORTING;
[System.NonSerialized, UdonSynced(UdonSyncMode.None), FieldChangeCallback(nameof(stateData))]
public int _stateData;
[System.NonSerialized]
public int _stateChangeCounter = 0;
public const int STATE_SLEEPING = 0;
//slowly lerp to final synced transform and velocity and then put rigidbody to sleep
public const int STATE_TELEPORTING = 1;
//instantly teleport to last synced transform and velocity
public const int STATE_INTERPOLATING = 2;
//just use a simple hermite spline to lerp it into place
public const int STATE_FALLING = 3;
//similar to STATE_INTERPOLATING except we don't take the final velocity into account when interpolating
//instead we assume the object is in projectile motion
//we use a hermite spline with the ending velocity being the starting velocity + (gravity * lerpTime)
//once we reach the destination, we set the velocity to the synced velocity
//hopefully, suddenly changing the velocity makes it look like a bounce.
public const int STATE_LEFT_HAND_HELD = 4;
public const int STATE_RIGHT_HAND_HELD = 5;
public const int STATE_NO_HAND_HELD = 6;//when an avatar has no hands and the position needs to follow their head instead
public const int STATE_ATTACHED_TO_PLAYSPACE = 7;
public const int STATE_WORLD_LOCK = 8;
public const int STATE_CUSTOM = 9;
[HideInInspector]
public SmartObjectSyncState[] states;
public SmartObjectSyncState customState
{
get
{
if (state >= STATE_CUSTOM && state - STATE_CUSTOM < states.Length)
{
return states[state - STATE_CUSTOM];
}
return null;
}
}
[System.NonSerialized]
public float interpolationStartTime = -1001f;
[System.NonSerialized]
public float interpolationEndTime = -1001f;
[System.NonSerialized]
public float fallSpeed = 0f;
#if !UNITY_EDITOR
public float lagTime
{
get => Time.realtimeSinceStartup - Networking.SimulationTime(gameObject);
}
#else
public float lagTime
{
get => 0.25f;
}
#endif
public float interpolation
{
get
{
return lagTime <= 0 ? 1 : Mathf.Lerp(0, 1, (Time.timeSinceLevelLoad - interpolationStartTime) / lagTime);
}
}
public SmartObjectSyncListener[] listeners = new SmartObjectSyncListener[0];
[System.NonSerialized]
public Vector3 posOnSync;
[System.NonSerialized]
public Quaternion rotOnSync;
[System.NonSerialized]
public Vector3 velOnSync;
[System.NonSerialized]
public Vector3 spinOnSync;
[System.NonSerialized]
public int lastState;
[System.NonSerialized]
public int stateChangeCounter = 0;//counts how many times we change state
bool teleportFlagSet = false;
public int state
{
get => _state;
set
{
OnExitState();
lastState = _state;
_state = value;
OnEnterState();
if (pickup && pickup.IsHeld && !IsHeld())
{
//no ownership check because there's another pickup.Drop() when ownership is transferred
pickup.Drop();
}
if (IsLocalOwner())
{
stateChangeCounter++;
//we call OnPreSerialization here to make it snappier for the local owner
//if any transforms and stuff happen in OnInterpolationStart, they happen here
// OnPreSerialization();
//we don't actually call onpreserialization so that serializationnotification works properly
OnSmartObjectSerialize();
StartInterpolation();
//we put in the request for actual serialization
Serialize();
}
_print("STATE: " + StateToString(value));
if (Utilities.IsValid(listeners))
{
foreach (SmartObjectSyncListener listener in listeners)
{
if (Utilities.IsValid(listener))
{
listener.OnChangeState(this, lastState, value);
}
}
}
}
}
public int stateData
{
get
{
if (IsLocalOwner())
{
return _state >= 0 ? (_state * 10) + (stateChangeCounter % 10) : (_state * 10) - (stateChangeCounter % 10);
}
return _stateData;
}
set
{
if (_stateData == value)
{
return;
}
_stateData = value;
if (!IsLocalOwner())
{
state = value / 10;
stateChangeCounter = Mathf.Abs(value) % 10;
}
_print("stateData received " + value);
}
}
[System.NonSerialized, FieldChangeCallback(nameof(owner))]
public VRCPlayerApi _owner;
public VRCPlayerApi owner
{
get => _owner;
set
{
if (_owner != value)
{
foreach (SmartObjectSyncListener listener in listeners)
{
if (Utilities.IsValid(listener))
{
listener.OnChangeOwner(this, _owner, value);
}
}
_owner = value;
if (IsLocalOwner())
{
//if the it was attached to the previous owner
if (IsAttachedToPlayer() && (pickup == null || !pickup.IsHeld))
{
state = STATE_INTERPOLATING;
}
}
else
{
serializeRequested = false;
if (pickup)
{
pickup.Drop();
}
}
}
}
}
[HideInInspector]
public bool SetupRan = false;
#if !COMPILER_UDONSHARP && UNITY_EDITOR
public void Reset()
{
if (!SetupRan)
{
SmartObjectSyncEditor.SetupSmartObjectSync(this);
}
SetupRan = true;
}
#endif
public void _print(string message)
{
if (!printDebugMessages)
{
return;
}
Debug.LogFormat("<color=yellow>[SmartObjectSync] {0}:</color> {1}", name, message);
}
public void _printErr(string message)
{
if (!printDebugMessages)
{
return;
}
Debug.LogErrorFormat("<color=yellow>[SmartObjectSync] {0}:</color> {1}", name, message);
}
//Helpers
Vector3 posControl1;
Vector3 posControl2;
Quaternion rotControl1;
Quaternion rotControl2;
public Vector3 HermiteInterpolatePosition(Vector3 startPos, Vector3 startVel, Vector3 endPos, Vector3 endVel, float interpolation)
{//Shout out to Kit Kat for suggesting the improved hermite interpolation
posControl1 = startPos + startVel * lagTime * interpolation / 3f;
posControl2 = endPos - endVel * lagTime * (1.0f - interpolation) / 3f;
return Vector3.Lerp(Vector3.Lerp(posControl1, endPos, interpolation), Vector3.Lerp(startPos, posControl2, interpolation), interpolation);
}
public Quaternion HermiteInterpolateRotation(Quaternion startRot, Vector3 startSpin, Quaternion endRot, Vector3 endSpin, float interpolation)
{
// rotControl1 = startRot * Quaternion.Euler(startSpin * lagTime * interpolation / 3f);
// rotControl2 = endRot * Quaternion.Euler(-1.0f * endSpin * lagTime * (1.0f - interpolation) / 3f);
// return Quaternion.Slerp(rotControl1, rotControl2, interpolation);
//we aren't actually doing hermite. It turns out higher order stuff isn't necessary just do a slerp
return Quaternion.Slerp(startRot, endRot, interpolation);
}
public bool IsLocalOwner()
{
return Utilities.IsValid(owner) && owner.isLocal;
}
public bool IsOwnerLocal()
{
return Utilities.IsValid(owner) && owner.isLocal;
}
public bool IsHeld()
{
return state == STATE_LEFT_HAND_HELD || state == STATE_RIGHT_HAND_HELD || state == STATE_NO_HAND_HELD;
}
public bool IsAttachedToPlayer()
{
return state < 0 || state == STATE_ATTACHED_TO_PLAYSPACE || IsHeld();
}
public string StateToString(int value)
{
switch (value)
{
case (STATE_SLEEPING):
{
return "STATE_SLEEPING";
}
case (STATE_TELEPORTING):
{
return "STATE_TELEPORTING";
}
case (STATE_INTERPOLATING):
{
return "STATE_INTERPOLATING";
}
case (STATE_FALLING):
{
return "STATE_FALLING";
}
case (STATE_LEFT_HAND_HELD):
{
return "STATE_LEFT_HAND_HELD";
}
case (STATE_RIGHT_HAND_HELD):
{
return "STATE_RIGHT_HAND_HELD";
}
case (STATE_NO_HAND_HELD):
{
return "STATE_HEAD_HELD";
}
case (STATE_ATTACHED_TO_PLAYSPACE):
{
return "STATE_ATTACHED_TO_PLAYSPACE";
}
case (STATE_WORLD_LOCK):
{
return "STATE_WORLD_LOCK";
}
default:
{
if (value < 0)
{
return ((HumanBodyBones)(-1 - value)).ToString();
}
else if (value >= STATE_CUSTOM && (value - STATE_CUSTOM) < states.Length)
{
return "Custom State " + (value - STATE_CUSTOM).ToString() + " " + (value - STATE_CUSTOM >= 0 && value - STATE_CUSTOM < states.Length && states[value - STATE_CUSTOM] != null ? states[value - STATE_CUSTOM].GetType().ToString() : "NULL");
}
return "INVALID STATE";
}
}
}
bool startRan = false;
[System.NonSerialized]
public Vector3 spawnPos;
[System.NonSerialized]
public Quaternion spawnRot;
int randomSeed = 0;
int randomCount = 0;
public void Start()
{
if (startRan)
{
return;
}
owner = Networking.GetOwner(gameObject);
_pickupable = Utilities.IsValid(pickup) && pickup.pickupable;
randomSeed = Random.Range(0, 10);
if (forceContinuousSpeculative)
{
rigid.collisionDetectionMode = CollisionDetectionMode.ContinuousSpeculative;
}
SetSpawn();
//speed we gain from gravity in a free fall over the lerp time
//used to decide if we simulate a bounce in the falling state
fallSpeed = lagTime <= 0 ? 0 : Physics.gravity.magnitude * lagTime;
if (IsLocalOwner())
{
Respawn();
}
else
{
//network sync happened, we have to walk it back and set up the starting state stuff first
if (startingState)
{
state = STATE_CUSTOM + startingState.stateID;
}
if (lastSuccessfulNetworkSync >= 0)
{
state = stateData / 10;
stateChangeCounter = Mathf.Abs(_stateData) % 10;
}
}
startRan = true;
}
[System.NonSerialized]
public bool _loop = false;
bool loopRequested = false;
public bool loop
{
get => _loop;
set
{
if (value)
{
disableRequested = false;
_loop = true;
if (!loopRequested)
{
loopRequested = true;
SendCustomEventDelayedFrames(nameof(UpdateLoop), 0);
}
}
else if (serializeRequested)
{
disableRequested = true;
}
else
{
_loop = false;
}
}
}
[System.NonSerialized]
public bool disableRequested = false;
[System.NonSerialized]
public bool serializeRequested = false;
public void UpdateLoop()
{
_print("update");
loopRequested = false;
if (!_loop)
{
return;
}
if (!Utilities.IsValid(owner))
{
//we use underscore here
_loop = false;
return;
}
if (interpolationStartTime < 0)
{
//if we haven't received data yet, do nothing. Otherwise this will move the object to the origin
//we use underscore here
_loop = false;
return;
}
loopRequested = true;
SendCustomEventDelayedFrames(nameof(UpdateLoop), 0);
if (!disableRequested)
{
Interpolate();
}
if (serializeRequested && !IsNetworkAtRisk())
{
if (state <= STATE_SLEEPING || state > STATE_FALLING)
{
//prioritize non-collision serializations because they will settle our world faster
RequestSerialization();
}
else
{
//randomize it, so we stagger the synchronizations
randomCount = (randomCount + 1) % 10;
if (randomCount == randomSeed)
{
RequestSerialization();
}
}
}
}
public void OnSerializationFailure()
{
_printErr("OnSerializationFailure");
serializeRequested = true;
loop = true;//we're just going to wait around for the network to allow us to synchronize again
}
public void OnSerializationSuccess()
{
serializeRequested = false;
}
public void OnEnable()
{
_print("OnEnable");
if (!startRan)
{
Start();
return;
}
owner = Networking.GetOwner(gameObject);
if (IsLocalOwner())
{
if (startRan)
{
//force a reset
state = state;
}
}
else
{
if (interpolationStartTime > 0)
{
//only do this after we've received some data from the owner to prevent being sucked into spawn
_print("onenable start interpolate");
StartInterpolation();
//force no interpolation
interpolationStartTime = -1001f;
Interpolate();
}
else
{
RequestResync();
}
}
}
float lastResyncRequest = -1001f;
public void RequestResync()
{
lastResyncRequest = Time.timeSinceLevelLoad;
//stagger requests randomly to prevent network clogging
SendCustomEventDelayedSeconds(nameof(RequestResyncCallback), (2 * lagTime) + Random.Range(0.0f, 1.0f));
}
public void RequestResyncCallback()
{
if (IsLocalOwner() || lastSuccessfulNetworkSync > lastResyncRequest || lastResyncRequest < 0)
{
return;
}
if (IsNetworkAtRisk())
{
//just wait it out;
RequestResync();
return;
}
SendCustomNetworkEvent(VRC.Udon.Common.Interfaces.NetworkEventTarget.Owner, nameof(Serialize));
}
public void SetSpawn()
{
if (worldSpaceTeleport)
{
spawnPos = transform.position;
spawnRot = transform.rotation;
}
else
{
generic_CalcParentTransform();
_print("parentPos " + parentPos);
spawnPos = Quaternion.Inverse(parentRot) * (transform.position - parentPos);
spawnRot = Quaternion.Inverse(parentRot) * transform.rotation;
}
}
public void Respawn()
{
_print("Respawn");
TakeOwnership(false);
if (Utilities.IsValid(startingState))
{
startingState.EnterState();
}
else if (worldSpaceTeleport)
{
// TeleportTo(spawnPos, spawnRot, Vector3.zero, Vector3.zero);
TeleportToWorldSpace(spawnPos, spawnRot, Vector3.zero, Vector3.zero);
}
else
{
TeleportToLocalSpace(spawnPos, spawnRot, Vector3.zero, Vector3.zero);
}
}
public void TeleportTo(Vector3 newPos, Quaternion newRot, Vector3 newVel, Vector3 newSpin)
{
// if (!IsLocalOwner())
// {
// TakeOwnership(false);
// }
// pos = newPos;
// rot = newRot;
// vel = newVel;
// spin = newSpin;
// if (startRan)
// {
// state = STATE_TELEPORTING;
// }
//just an alias for backwards compatibility reasons
TeleportToWorldSpace(newPos, newRot, newVel, newSpin);
}
public void TeleportToWorldSpace(Vector3 newPos, Quaternion newRot, Vector3 newVel, Vector3 newSpin)
{
if (!IsLocalOwner())
{
TakeOwnership(false);
}
if (worldSpaceTeleport)
{
pos = newPos;
rot = newRot;
vel = newVel;
spin = newSpin;
}
else
{
generic_CalcParentTransform();
pos = Quaternion.Inverse(parentRot) * (newPos - parentPos);
rot = Quaternion.Inverse(parentRot) * newRot;
// vel = transform.InverseTransformVector(newVel);
// spin = transform.InverseTransformVector(newSpin);
vel = Quaternion.Inverse(parentRot) * vel;
spin = Quaternion.Inverse(parentRot) * spin;
}
if (startRan)
{
state = STATE_TELEPORTING;
}
}
public void TeleportToLocalSpace(Vector3 newPos, Quaternion newRot, Vector3 newVel, Vector3 newSpin)
{
if (!IsLocalOwner())
{
TakeOwnership(false);
}
if (worldSpaceTeleport)
{
generic_CalcParentTransform();
pos = parentPos + parentRot * newPos;
rot = parentRot * newRot;
// vel = transform.TransformPoint(newVel);
// spin = transform.TransformPoint(newSpin);
vel = parentRot * vel;
spin = parentRot * spin;
}
else
{
pos = newPos;
rot = newRot;
vel = newVel;
spin = newSpin;
}
if (startRan)
{
state = STATE_TELEPORTING;
}
}
public void StartInterpolation()
{
loop = true;
OnInterpolationStart();
}
public void Interpolate()
{
OnInterpolate(interpolation);
if (interpolation < 1.0)
{
return;
}
//decide if we keep running the helper
if (!OnInterpolationEnd())
{
loop = false;
}
}
bool transformRecorded = false;
public void RecordLastTransform()
{
lastPos = transform.position;
lastRot = transform.rotation;
transformRecorded = true;
}
public void SetVelocityFromLastTransform()
{
if (transformRecorded && !rigid.isKinematic)
{
rigid.velocity = CalcVel();
rigid.angularVelocity = CalcSpin();
}
}
//Serialization
[System.NonSerialized]
public float lastSerializeRequest = -1001f;
public bool IsNetworkAtRisk()
{
return Networking.IsClogged;
}
public void Serialize()
{
if (IsNetworkAtRisk())
{
OnSerializationFailure();
}
else
{
RequestSerialization();
}
lastSerializeRequest = Time.timeSinceLevelLoad;
}
public override void OnPreSerialization()
{
// _print("OnPreSerialization");
OnSmartObjectSerialize();
StartInterpolation();
stateData = stateData;
}
float last_send_time = -1001;
Vector3 _cache_pos;
Quaternion _cache_rot;
Vector3 _cache_vel;
Vector3 _cache_spin;
int _cache_stateData;
float lastSuccessfulNetworkSync = -1001f;
public override void OnDeserialization(VRC.Udon.Common.DeserializationResult result)
{
if (checkSyncTimes && result.sendTime < last_send_time)
{
//we fucking got updates out of order auuuuuuuuugghhhh
pos = _cache_pos;
rot = _cache_rot;
vel = _cache_vel;
spin = _cache_spin;
stateData = _cache_stateData;
return;
}
last_send_time = result.sendTime;
_cache_pos = pos;
_cache_rot = rot;
_cache_vel = vel;
_cache_spin = spin;
_cache_stateData = _stateData;
// _print("OnDeserialization");
StartInterpolation();
lastSuccessfulNetworkSync = Time.timeSinceLevelLoad;
}
public override void OnPostSerialization(VRC.Udon.Common.SerializationResult result)
{
if (result.success)
{
OnSerializationSuccess();
lastSuccessfulNetworkSync = Time.timeSinceLevelLoad;
}
else
{
//it sets a flag in the helper which will try to synchronize everything once the network gets less congested
OnSerializationFailure();
}
}
public void AttachToBone(HumanBodyBones bone)
{
if (!IsLocalOwner())
{
TakeOwnership(false);
}
state = (-1 - (int)bone);
}
//Collision Events
SmartObjectSync otherSync;
float lastCollision = -1001;
public void OnCollisionEnter(Collision other)
{
if (rigid.isKinematic || (performanceModeCollisions && lastCollision + Time.deltaTime > Time.timeSinceLevelLoad))
{
return;
}
lastCollision = Time.timeSinceLevelLoad;
if (IsLocalOwner())
{
//check if we're in a state where physics matters
if (!IsAttachedToPlayer() && state < STATE_CUSTOM && TeleportSynced())
{
state = STATE_INTERPOLATING;
}
//decide if we need to take ownership of the object we collided with
if (takeOwnershipOfOtherObjectsOnCollision && Utilities.IsValid(other) && Utilities.IsValid(other.collider))
{
otherSync = other.collider.GetComponent<SmartObjectSync>();
if (otherSync && !otherSync.IsLocalOwner() && otherSync.allowOthersToTakeOwnershipOnCollision && !otherSync.IsAttachedToPlayer() && (IsAttachedToPlayer() || otherSync.state == STATE_SLEEPING || !otherSync.takeOwnershipOfOtherObjectsOnCollision || otherSync.rigid.velocity.sqrMagnitude < rigid.velocity.sqrMagnitude))
{
otherSync.TakeOwnership(true);
otherSync.Serialize();
}
}
}
else if (state == STATE_SLEEPING && interpolationEndTime + Time.deltaTime < Time.timeSinceLevelLoad)//we ignore the very first frame after interpolation to give rigidbodies time to settle down
{
//we may have been knocked out of sync, restart interpolation to get us back in line
StartInterpolation();
}
}
public bool TeleportSynced()
{
return (state != STATE_TELEPORTING || !teleportFlagSet);
}
float lastCollisionExit = -1001;
public void OnCollisionExit(Collision other)
{
if (rigid.isKinematic || (performanceModeCollisions && lastCollisionExit + Time.deltaTime > Time.timeSinceLevelLoad))
{
return;
}
lastCollisionExit = Time.timeSinceLevelLoad;
if (IsLocalOwner())
{
//check if we're in a state where physics matters
if (!IsAttachedToPlayer() && state < STATE_CUSTOM && TeleportSynced())
{
state = STATE_FALLING;
}
}
else if (state == STATE_SLEEPING && interpolationEndTime + Time.deltaTime < Time.timeSinceLevelLoad)
{
//we may have been knocked out of sync, restart interpolation to get us back in line
StartInterpolation();
}
}
public void OnParticleCollision(GameObject other)
{
if (!syncParticleCollisions || !Utilities.IsValid(other) || rigid.isKinematic)
{
return;
}
if (IsLocalOwner())
{
//check if we're in a state where physics matters
if (!IsAttachedToPlayer() && state < STATE_CUSTOM && TeleportSynced())
{
state = STATE_INTERPOLATING;
}
}
else
{
//decide if we need to take ownership of the object we collided with
if (allowOthersToTakeOwnershipOnCollision && Utilities.IsValid(other.GetComponent<ParticleSystem>()) && !IsAttachedToPlayer())
{
otherSync = other.GetComponent<SmartObjectSync>();
if (!Utilities.IsValid(otherSync) && Utilities.IsValid(other.transform.parent))
{
otherSync = other.GetComponentInParent<SmartObjectSync>();
}
if (Utilities.IsValid(otherSync) && otherSync.IsLocalOwner() && otherSync.takeOwnershipOfOtherObjectsOnCollision)
{
TakeOwnership(true);
if (!IsAttachedToPlayer() && state < STATE_CUSTOM && TeleportSynced())
{
state = STATE_INTERPOLATING;
}
Serialize();
}
}
}
}
//Pickup Events
[System.NonSerialized] public float lastPickup;
public override void OnPickup()
{
lastPickup = Time.timeSinceLevelLoad;
TakeOwnership(false);
if (pickup)
{
if (pickup.currentHand == VRC_Pickup.PickupHand.Left)
{
Vector3 leftHandPos = Networking.LocalPlayer.GetBonePosition(HumanBodyBones.LeftHand);
if (leftHandPos != Vector3.zero)
{
state = STATE_LEFT_HAND_HELD;
}
else //couldn't find left hand bone
{
state = STATE_NO_HAND_HELD;
}
}
else if (pickup.currentHand == VRC_Pickup.PickupHand.Right)
{
Vector3 rightHandPos = Networking.LocalPlayer.GetBonePosition(HumanBodyBones.RightHand);
if (rightHandPos != Vector3.zero)
{
state = STATE_RIGHT_HAND_HELD;
}
else //couldn't find right hand bone
{
state = STATE_NO_HAND_HELD;
}
}
}
}
public override void OnDrop()
{
_print("OnDrop");
//it takes 1 frame for VRChat to give the pickup the correct velocity, so let's wait 1 frame
//many different states will want to change the state and in doing so force us to drop the object
//To know if this is a player initiated drop, we check that the state is still one of being held
//we need to set the state to interpolating next frame so we also set the lastState variable to
//remind us to do that
//The reason we need the lastState variable is because switching hands will cause the state to
//go from a held state to another held state, and if, one frame from now, we set the state to
//interpolating that will make transferring objects from one hand to another impossible
//transferring one object from your hand to your same hand is already impossible, so if lastState
//is equal to current state we know that it was a genuine drop
if (IsHeld())
{
lastState = state;
if (kinematicWhileHeld && rigid.isKinematic)
{
rigid.isKinematic = lastKinematic;
}
SendCustomEventDelayedFrames(nameof(OnDropDelayed), 1);
}
}
public void OnDropDelayed()
{
if (!IsLocalOwner() || lastState != state || !IsHeld())
{
return;
}
state = STATE_INTERPOLATING;
}
//Ownership Events
public override void OnOwnershipTransferred(VRCPlayerApi player)
{
_print("OnOwnershipTransferred");
owner = player;
}
//bug fix found by BoatFloater
//bug canny here: https://vrchat.canny.io/udon-networking-update/p/1258-onownershiptransferred-does-not-fire-at-onplayerleft-if-last-owner-is-passi
public override void OnPlayerLeft(VRCPlayerApi player)
{
_print("OnPlayerLeft");
if (player == owner)
{
owner = Networking.GetOwner(gameObject);
}
}
public void TakeOwnership(bool checkIfClogged)
{
if ((checkIfClogged && IsNetworkAtRisk()) || IsLocalOwner())
{
//Let them cook
return;
}
_print("TakeOwnership");
Networking.SetOwner(Networking.LocalPlayer, gameObject);
}
public void _TakeOwnership(){
TakeOwnership(false);
}
//STATES
//If Udon supported custom classes that aren't subclasses of UdonBehaviour, these would be in separate files
//Look at the 2.0 Prerelease on the github if you want to see what I mean
//Instead, I'm going to copy all the functions in those files here
[System.NonSerialized]
public Vector3 startPos;
[System.NonSerialized]
public Quaternion startRot;
[System.NonSerialized]
public Vector3 startVel;
[System.NonSerialized]
public Vector3 startSpin;
[System.NonSerialized]
public Vector3 lastPos;
[System.NonSerialized]
public Quaternion lastRot;
public void OnEnterState()
{
switch (state)
{
case (STATE_SLEEPING):
{
//do nothing
return;
}
case (STATE_TELEPORTING):
{
teleport_OnEnterState();
return;
}
case (STATE_INTERPOLATING):
{
//do nothing
return;
}
case (STATE_FALLING):
{
//do nothing
return;
}
case (STATE_LEFT_HAND_HELD):
{
left_OnEnterState();
return;
}
case (STATE_RIGHT_HAND_HELD):
{
right_OnEnterState();
return;
}
case (STATE_NO_HAND_HELD):
{
genericHand_OnEnterState();
return;
}
case (STATE_ATTACHED_TO_PLAYSPACE):
{
//do nothing
if (preventStealWhileAttachedToPlayer && Utilities.IsValid(pickup))
{
pickup.pickupable = IsLocalOwner() && pickupable;
}
return;
}
case (STATE_WORLD_LOCK):
{
//do nothing
return;
}
default:
{
if (state < 0)
{
bone_OnEnterState();
}
else if (customState)
{
customState.OnEnterState();
}
return;
}
}
}
public void OnExitState()
{
switch (state)
{
case (STATE_SLEEPING):
{
//do nothing
return;
}
case (STATE_TELEPORTING):
{
//do nothing
return;
}
case (STATE_INTERPOLATING):
{
//do nothing
return;
}
case (STATE_FALLING):
{
//do nothing
return;
}
case (STATE_LEFT_HAND_HELD):
{
genericHand_OnExitState();
return;
}
case (STATE_RIGHT_HAND_HELD):
{
genericHand_OnExitState();
return;
}
case (STATE_NO_HAND_HELD):
{
genericHand_OnExitState();
return;
}
case (STATE_ATTACHED_TO_PLAYSPACE):
{
//do nothing
if (preventStealWhileAttachedToPlayer && Utilities.IsValid(pickup))
{
pickup.pickupable = pickupable;
}
return;
}
case (STATE_WORLD_LOCK):
{
//do nothing
return;
}
default:
{
if (state < 0)
{
SetVelocityFromLastTransform();
if (preventStealWhileAttachedToPlayer && Utilities.IsValid(pickup))
{
pickup.pickupable = pickupable;
}
}
else if (customState)
{
customState.OnExitState();
}
return;
}
}
}
public void OnSmartObjectSerialize()
{
switch (state)
{
case (STATE_SLEEPING):
{
sleep_OnSmartObjectSerialize();
return;
}
case (STATE_TELEPORTING):
{
teleport_OnSmartObjectSerialize();
return;
}
case (STATE_INTERPOLATING):
{
interpolate_OnSmartObjectSerialize();
return;
}
case (STATE_FALLING):
{
interpolate_OnSmartObjectSerialize();
return;
}
case (STATE_LEFT_HAND_HELD):
{
bone_CalcParentTransform();
generic_OnSmartObjectSerialize();
return;
}
case (STATE_RIGHT_HAND_HELD):
{
bone_CalcParentTransform();
generic_OnSmartObjectSerialize();
return;
}
case (STATE_NO_HAND_HELD):
{
noHand_CalcParentTransform();
generic_OnSmartObjectSerialize();
return;
}
case (STATE_ATTACHED_TO_PLAYSPACE):
{
playspace_CalcParentTransform();
generic_OnSmartObjectSerialize();
return;
}
case (STATE_WORLD_LOCK):
{
world_OnSmartObjectSerialize();
return;
}
default:
{
if (state < 0)
{
bone_CalcParentTransform();
generic_OnSmartObjectSerialize();
}
else if (customState)
{
customState.OnSmartObjectSerialize();
}
return;
}
}
}
public void OnInterpolationStart()
{
interpolationStartTime = Time.timeSinceLevelLoad;
switch (state)
{
case (STATE_SLEEPING):
{
sleep_OnInterpolationStart();
return;
}
case (STATE_TELEPORTING):
{
teleport_OnInterpolationStart();
return;
}
case (STATE_INTERPOLATING):
{
interpolate_OnInterpolationStart();
return;
}
case (STATE_FALLING):
{
falling_OnInterpolationStart();
return;
}
case (STATE_LEFT_HAND_HELD):
{
bone_OnInterpolationStart();
return;
}
case (STATE_RIGHT_HAND_HELD):
{
bone_OnInterpolationStart();
return;
}
case (STATE_NO_HAND_HELD):
{
noHand_OnInterpolationStart();
return;
}
case (STATE_ATTACHED_TO_PLAYSPACE):
{
playspace_CalcParentTransform();
generic_OnInterpolationStart();
return;
}
case (STATE_WORLD_LOCK):
{
world_OnInterpolationStart();
return;
}
default:
{
if (state < 0)
{
bone_OnInterpolationStart();
}
else if (customState)
{
customState.OnInterpolationStart();
}
return;
}
}
}
public void OnInterpolate(float interpolation)
{
transformRecorded = false;
switch (state)
{
case (STATE_SLEEPING):
{
sleep_Interpolate(interpolation);
return;
}
case (STATE_TELEPORTING):
{
//do nothing
return;
}
case (STATE_INTERPOLATING):
{
interpolate_Interpolate(interpolation);
return;
}
case (STATE_FALLING):
{
falling_Interpolate(interpolation);
return;
}
case (STATE_LEFT_HAND_HELD):
{
left_Interpolate(interpolation);
return;
}
case (STATE_RIGHT_HAND_HELD):
{
right_Interpolate(interpolation);
return;
}
case (STATE_NO_HAND_HELD):
{
noHand_Interpolate(interpolation);
return;
}
case (STATE_ATTACHED_TO_PLAYSPACE):
{
playspace_CalcParentTransform();
generic_Interpolate(interpolation);
return;
}
case (STATE_WORLD_LOCK):
{
world_Interpolate(interpolation);
return;
}
default:
{
if (state < 0)
{
bone_CalcParentTransform();
generic_Interpolate(interpolation);
}
else if (customState)
{
customState.Interpolate(interpolation);
}
return;
}
}
}
public bool OnInterpolationEnd()
{
if (interpolationEndTime <= interpolationStartTime)
{
interpolationEndTime = Time.timeSinceLevelLoad;
}
switch (state)
{
case (STATE_SLEEPING):
{
return sleep_OnInterpolationEnd();
}
case (STATE_TELEPORTING):
{
return false;//do nothing
}
case (STATE_INTERPOLATING):
{
return interpolate_OnInterpolationEnd();
}
case (STATE_FALLING):
{
return interpolate_OnInterpolationEnd();
}
case (STATE_LEFT_HAND_HELD):
{
return genericHand_onInterpolationEnd();
}
case (STATE_RIGHT_HAND_HELD):
{
return genericHand_onInterpolationEnd();
}
case (STATE_NO_HAND_HELD):
{
return genericHand_onInterpolationEnd();
}
case (STATE_ATTACHED_TO_PLAYSPACE):
{
return genericAttachment_OnInterpolationEnd();
}
case (STATE_WORLD_LOCK):
{
return world_OnInterpolationEnd();
}
default:
{
if (state < 0)
{
return genericAttachment_OnInterpolationEnd();
}
else if (customState)
{
return customState.OnInterpolationEnd();
}
return false;
}
}
}
//Sleep State
//This state interpolates objects to a position and then attempts to put their rigidbody to sleep
//If the rigidbody can't sleep, like if it's floating in mid-air or something, then the just holds the position and rotation.
//If the rigidbody does fall asleep in the right position and rotation, then the state disables the update loop for optimization
[System.NonSerialized] public Vector3 sleepPos;
[System.NonSerialized] public Quaternion sleepRot;
[System.NonSerialized] public float lastSleep = -1001f;
public void sleep_OnInterpolationStart()
{
if (worldSpaceSleep)
{
startPos = transform.position;
startRot = transform.rotation;
startVel = rigid.velocity;
startSpin = rigid.angularVelocity;
}
else
{
startPos = transform.localPosition;
startRot = transform.localRotation;
startVel = transform.InverseTransformVector(rigid.velocity);
startSpin = transform.InverseTransformVector(rigid.angularVelocity);
}
}
public void sleep_Interpolate(float interpolation)
{
if (IsLocalOwner())
{
return;
}
if (interpolation < 1.0f)
{
if (worldSpaceSleep)
{
transform.position = HermiteInterpolatePosition(startPos, startVel, pos, Vector3.zero, interpolation);
transform.rotation = HermiteInterpolateRotation(startRot, startSpin, rot, Vector3.zero, interpolation);
}
else
{
transform.localPosition = HermiteInterpolatePosition(startPos, startVel, pos, Vector3.zero, interpolation);
transform.localRotation = HermiteInterpolateRotation(startRot, startSpin, rot, Vector3.zero, interpolation);
}
if (!rigid.isKinematic)
{
rigid.velocity = Vector3.zero;
rigid.angularVelocity = Vector3.zero;
}
}
else if (!reduceJitterDuringSleep || ObjectMovedDuringSleep())
{
if (worldSpaceSleep)
{
transform.position = pos;
transform.rotation = rot;
}
else
{
transform.localPosition = pos;
transform.localRotation = rot;
}
if (!rigid.isKinematic)
{
rigid.velocity = Vector3.zero;
rigid.angularVelocity = Vector3.zero;
}
rigid.Sleep();
lastSleep = Time.timeSinceLevelLoad;
}
}
public bool sleep_OnInterpolationEnd()
{
if (IsLocalOwner() || rigid.isKinematic || (rigid.IsSleeping() && (!reduceJitterDuringSleep || lastSleep != Time.timeSinceLevelLoad)))
{
_print("successfully slept");
return false;
}
return true;
}
public void sleep_OnSmartObjectSerialize()
{
if (worldSpaceSleep)
{
pos = transform.position;
rot = transform.rotation;
}
else
{
pos = transform.localPosition;
rot = transform.localRotation;
}
vel = Vector3.zero;
spin = Vector3.zero;
}
public bool ObjectMovedDuringSleep()
{
return transform.position != pos || transform.rotation != rot;
}
//Teleport State
//This state has no interpolation. It simply places sets the transforms and velocity then disables the update loop, letting physics take over
//For the owner this has to happen when we enter the state before we serialize everything for the first time
//non-owners see this happen in OnInterpolationStart like normal
public void teleport_SetTransforms()
{
_print("settransforms pos: " + pos);
if (!startRan)
{
return;
}
if (worldSpaceTeleport)
{
transform.position = pos;
transform.rotation = rot;
if (!rigid.isKinematic)
{
rigid.velocity = vel;
rigid.angularVelocity = spin;
}
}
else
{
// transform.localPosition = pos;
// transform.localRotation = rot;
generic_CalcParentTransform();
transform.position = parentPos + parentRot * pos;
transform.rotation = parentRot * rot;
if (!rigid.isKinematic)
{
// rigid.velocity = transform.TransformVector(vel);
// rigid.angularVelocity = transform.TransformVector(spin);
rigid.velocity = parentRot * vel;
rigid.angularVelocity = parentRot * spin;
}
}
}
public void teleport_OnEnterState()
{
teleportFlagSet = true;
if (IsLocalOwner())
{
teleport_SetTransforms();
}
}
public void teleport_OnInterpolationStart()
{
if (!IsLocalOwner())
{
teleport_SetTransforms();
}
loop = IsLocalOwner();//turn off immediately for max optimization
}
public void teleport_Interpolation()
{
if (IsLocalOwner())
{
if (transform.position.y <= respawnHeight)
{
Respawn();
}
return;
}
}
public void teleport_OnSmartObjectSerialize()
{
teleportFlagSet = false;
if (worldSpaceTeleport)
{
pos = transform.position;
rot = transform.rotation;
if (!rigid.isKinematic)
{
vel = rigid.velocity;
spin = rigid.angularVelocity;
}
}
else
{
generic_CalcParentTransform();
pos = Quaternion.Inverse(parentRot) * (transform.position - parentPos);
rot = Quaternion.Inverse(parentRot) * transform.rotation;
if (!rigid.isKinematic)
{
vel = transform.InverseTransformVector(rigid.velocity);
spin = transform.InverseTransformVector(rigid.angularVelocity);
}
}
}
//Interpolate State
//This state interpolates objects into place using Hermite interpolation which makes sure that all changes in velocity are gradual and smooth
//At the end of the state we set the velocity and then disable the update loop for optimization and to allow the physics engine to take over
public void interpolate_OnInterpolationStart()
{
if (worldSpacePhysics)
{
startPos = transform.position;
startRot = transform.rotation;
startVel = rigid.velocity;
startSpin = rigid.angularVelocity;
}
else
{
generic_CalcParentTransform();
startPos = transform.localPosition;
startRot = transform.localRotation;
startVel = Quaternion.Inverse(parentRot) * rigid.velocity;
startSpin = Quaternion.Inverse(parentRot) * rigid.angularVelocity;
}
}
public void interpolate_Interpolate(float interpolation)
{
if (IsLocalOwner())
{
if (transform.position.y <= respawnHeight)
{
Respawn();
}
return;
}
if (worldSpacePhysics)
{
transform.position = HermiteInterpolatePosition(startPos, startVel, pos, vel, interpolation);
transform.rotation = HermiteInterpolateRotation(startRot, startSpin, rot, spin, interpolation);
}
else
{
transform.localPosition = HermiteInterpolatePosition(startPos, startVel, pos, vel, interpolation);
transform.localRotation = HermiteInterpolateRotation(startRot, startSpin, rot, spin, interpolation);
}
}
public bool interpolate_OnInterpolationEnd()
{
if (IsLocalOwner())
{
if (rigid.isKinematic || rigid.IsSleeping())
{
//wait around for the rigidbody to fall asleep
state = STATE_SLEEPING;
}
// else if (NonGravitationalAcceleration())
// {
// //some force other than gravity is acting upon our object
// if (lastResync + lerpTime < Time.timeSinceLevelLoad)
// {
// Synchronize();
// }
// }
//returning true means we extend the interpolation period
return true;
}
if (!rigid.isKinematic)
{
if (worldSpacePhysics)
{
rigid.velocity = vel;
rigid.angularVelocity = spin;
}
else
{
generic_CalcParentTransform();
rigid.velocity = parentRot * vel;
rigid.angularVelocity = parentRot * spin;
}
}
//let physics take over by returning false
return false;
}
public void interpolate_OnSmartObjectSerialize()
{
if (worldSpacePhysics)
{
pos = transform.position;
rot = transform.rotation;
if (!rigid.isKinematic)
{
vel = rigid.velocity;
spin = rigid.angularVelocity;
}
else
{
vel = Vector3.zero;
spin = Vector3.zero;
}
}
else
{
generic_CalcParentTransform();
pos = transform.localPosition;
rot = transform.localRotation;
if (!rigid.isKinematic)
{
vel = Quaternion.Inverse(parentRot) * rigid.velocity;
spin = Quaternion.Inverse(parentRot) * rigid.angularVelocity;
}
else
{
vel = Vector3.zero;
spin = Vector3.zero;
}
}
}
[System.NonSerialized]
Vector3 changeInVelocity;
public bool NonGravitationalAcceleration()
{
if (rigid.isKinematic)
{
return false;
}
//returns true of object's velocity changed along an axis other than gravity's
//this will let us know if the object stayed in projectile motion or if another force acted upon it
changeInVelocity = rigid.velocity - vel;
if (changeInVelocity.magnitude < 0.001f)
{
//too small to care
return false;
}
if (!rigid.useGravity)
{
return true;
}
if (Vector3.Angle(changeInVelocity, Physics.gravity) > 90)
{
//This means that the object was moving against the force of gravity
//there is definitely a non-gravitational velocity change
return true;
}
//we know that the object acelerated along the gravity vector,
//but if it also acelerated on another axis then another force acted upon it
//here we remove the influence of gravity and compare the velocity with the last synced velocity
return Vector3.ProjectOnPlane(changeInVelocity, Physics.gravity).magnitude > 0.001f;
}
//Falling State
//This state also uses Hermite interpolation, but assumes that the object is in projectile motion and intentionally creates a sudden change in velocity at the end of the interpolation to mimic a bounce.
//To mimic projectile motion, we assume that the velocity at the end of the interpolation is the start velocity plus the change in velocity gravity would have caused over the same time period
//At the end of the interpolation, we change the velocity to match what was sent by the owner, putting us back in sync with the owner.
//Then we disable to update loop for optimization and to allow the physics engine to take over
bool simulateBounce = false;
public void falling_OnInterpolationStart()
{
interpolate_OnInterpolationStart();
simulateBounce = Vector3.Distance(startVel, vel) > fallSpeed;
}
public void falling_Interpolate(float interpolation)
{
if (!simulateBounce || rigid.isKinematic || !rigid.useGravity)
{
//change in velocity wasn't great enough to be a bounce, so we just interpolate normally instead
interpolate_Interpolate(interpolation);
return;
}
if (IsLocalOwner())
{
if (transform.position.y <= respawnHeight)
{
Respawn();
}
return;
}
if (worldSpacePhysics)
{
transform.position = HermiteInterpolatePosition(startPos, startVel, pos, startVel + Physics.gravity * lagTime, interpolation);
transform.rotation = HermiteInterpolateRotation(startRot, startSpin, rot, startSpin, interpolation);
}
else
{
generic_CalcParentTransform();
transform.localPosition = HermiteInterpolatePosition(startPos, startVel, pos, startVel + Quaternion.Inverse(parentRot) * Physics.gravity * lagTime, interpolation);
transform.localRotation = HermiteInterpolateRotation(startRot, startSpin, rot, startSpin, interpolation);
}
}
//Generic Attachment State
//We can't actually set the state to this state. This is just a helper that we use in other states when objects need to be attached to things
[System.NonSerialized]
public Vector3 parentPos;
[System.NonSerialized]
public Quaternion parentRot;
//these values are arbitrary, but they work pretty good for most pickups
[System.NonSerialized]
public float positionResyncThreshold = 0.015f;
[System.NonSerialized]
public float rotationResyncThreshold = 0.995f;
[System.NonSerialized]
public float lastResync = -1001f;
public void generic_CalcParentTransform()
{
if (Utilities.IsValid(transform.parent))
{
parentPos = transform.parent.position;
parentRot = transform.parent.rotation;
}
else
{
parentPos = Vector3.zero;
parentRot = Quaternion.identity;
}
}
public void generic_OnInterpolationStart()
{
startPos = CalcPos();
startRot = CalcRot();
}
public void generic_Interpolate(float interpolation)
{
RecordLastTransform();
transform.position = HermiteInterpolatePosition(parentPos + parentRot * startPos, Vector3.zero, parentPos + parentRot * pos, Vector3.zero, interpolation);
transform.rotation = HermiteInterpolateRotation(parentRot * startRot, Vector3.zero, parentRot * rot, Vector3.zero, interpolation);
if (!rigid.isKinematic)
{
rigid.velocity = Vector3.zero;
rigid.angularVelocity = Vector3.zero;
}
}
public bool genericAttachment_OnInterpolationEnd()
{
if (IsLocalOwner())
{
if (generic_ObjectMoved())
{
if (lastResync + lagTime < Time.timeSinceLevelLoad)
{
lastResync = Time.timeSinceLevelLoad;
Serialize();
}
}
else
{
lastResync = Time.timeSinceLevelLoad;
}
}
return true;
}
public void generic_OnSmartObjectSerialize()
{
// CalcParentTransform();
pos = CalcPos();
rot = CalcRot();
vel = CalcVel();
spin = CalcSpin();
lastResync = Time.timeSinceLevelLoad;
}
public Vector3 CalcPos()
{
return Quaternion.Inverse(parentRot) * (transform.position - parentPos);
}
public Quaternion CalcRot()
{
return Quaternion.Inverse(parentRot) * transform.rotation;
}
public Vector3 CalcVel()
{
return (transform.position - lastPos) / Time.deltaTime;
}
float angle;
Vector3 axis;
public Vector3 CalcSpin()
{
//angular velocity is normalized rotation axis * angle in radians: https://answers.unity.com/questions/49082/rotation-quaternion-to-angular-velocity.html
Quaternion.Normalize(Quaternion.Inverse(lastRot) * transform.rotation).ToAngleAxis(out angle, out axis);
//Make sure we are using the smallest angle of rotation. I.E. -90 degrees instead of 270 degrees wherever possible
if (angle < -180)
{
angle += 360;
}
else if (angle > 180)
{
angle -= 360;
}
return transform.rotation * axis * angle * Mathf.Deg2Rad / Time.deltaTime;
}
public bool generic_ObjectMoved()
{
return Vector3.Distance(CalcPos(), pos) > positionResyncThreshold || Quaternion.Dot(CalcRot(), rot) < rotationResyncThreshold;//arbitrary values to account for pickups wiggling a little in your hand
}
[System.NonSerialized] public bool _pickupable = true;
public bool pickupable
{
get => _pickupable;
set
{
_pickupable = value;
if (Utilities.IsValid(pickup))
{
if (IsHeld())
{
if (IsLocalOwner())
{
pickup.pickupable = value && allowTheftFromSelf;
}
else
{
pickup.pickupable = value && !pickup.DisallowTheft;
}
}
else if (IsAttachedToPlayer())
{
pickup.pickupable = value && (!preventStealWhileAttachedToPlayer || IsLocalOwner());
}
else
{
pickup.pickupable = value;
}
}
}
}
[System.NonSerialized] public bool lastKinematic = false;
public void preventPickupJitter()
{
transform.position = parentPos + parentRot * pos;
transform.rotation = parentRot * rot;
}
//Left Hand Held State
//This state syncs the transforms relative to the left hand of the owner
//This state is useful for when someone is holding the object in their left hand
//We do not disable the update loop because the left hand is going to move around and we need to continually update the object transforms to match.
//Falls back to Playspace Attachment State if no left hand bone is found
public void left_OnEnterState()
{
bone = HumanBodyBones.LeftHand;
genericHand_OnEnterState();
}
public void left_Interpolate(float interpolation)
{
//let the VRC_pickup script handle transforms for the local owner
//only reposition it for non-owners
bone_CalcParentTransform();
if (!IsLocalOwner())
{
generic_Interpolate(interpolation);
}
else
{
RecordLastTransform();
if (nonKinematicPickupJitterPreventionTime > 0 && lastState == state && Time.timeSinceLevelLoad - lastPickup > nonKinematicPickupJitterPreventionTime)
{
preventPickupJitter();
}
}
}
//Right Hand Held State
//Same as the Left Hand Held State, but for right hands
public void right_OnEnterState()
{
bone = HumanBodyBones.RightHand;
genericHand_OnEnterState();
}
public void right_Interpolate(float interpolation)
{
//let the VRC_pickup script handle transforms for the local owner
//only reposition it for non-owners
//we need to keep the parent transform up to date though
bone_CalcParentTransform();
if (!IsLocalOwner())
{
generic_Interpolate(interpolation);
}
else
{
RecordLastTransform();
if (nonKinematicPickupJitterPreventionTime > 0 && lastState == state && Time.timeSinceLevelLoad - lastPickup > nonKinematicPickupJitterPreventionTime)
{
preventPickupJitter();
}
}
}
//Right Hand Held State
//Same as the Left Hand Held State, but for right hands
public void genericHand_OnEnterState()
{
if (Utilities.IsValid(pickup))
{
if (IsLocalOwner())
{
pickup.pickupable = pickupable && allowTheftFromSelf;
}
else
{
pickup.pickupable = pickupable && !pickup.DisallowTheft;
}
}
if (kinematicWhileHeld)
{
lastKinematic = rigid.isKinematic;
rigid.isKinematic = true;
}
}
public bool genericHand_onInterpolationEnd()
{
CalcVel();
if (IsLocalOwner() && (pickup.orientation != VRC_Pickup.PickupOrientation.Any || owner.IsUserInVR()) && (rigid.isKinematic || nonKinematicPickupJitterPreventionTime > 0) && lastResync + lagTime < Time.timeSinceLevelLoad && interpolationStartTime + 0.5f < Time.timeSinceLevelLoad)//hard coded 0.5f because VRChat is like that
{
if (generic_ObjectMoved())
{
lastResync = Time.timeSinceLevelLoad;
Serialize();
}
else
{
lastResync = Time.timeSinceLevelLoad;
return false;
}
}
return genericAttachment_OnInterpolationEnd();
}
public void genericHand_OnExitState()
{
if (Utilities.IsValid(pickup))
{
pickup.pickupable = pickupable;
}
if (kinematicWhileHeld && rigid.isKinematic)
{
rigid.isKinematic = lastKinematic;
// if (!lastKinematic)
// {
// if (worldSpacePhysics)
// {
// rigid.velocity = vel;
// rigid.angularVelocity = spin;
// }
// else
// {
// generic_CalcParentTransform();
// rigid.velocity = parentRot * vel;
// rigid.angularVelocity = parentRot * spin;
// }
// }
}
}
public void noHand_OnInterpolationStart()
{
//if the avatar we're wearing doesn't have the bones required, fallback to attach to playspace
noHand_CalcParentTransform();
generic_OnInterpolationStart();
}
public void noHand_Interpolate(float interpolation)
{
//let the VRC_pickup script handle transforms for the local owner
//only reposition it for non-owners
//we need to keep the parent transform up to date though
noHand_CalcParentTransform();
if (!IsLocalOwner())
{
generic_Interpolate(interpolation);
}
else if (nonKinematicPickupJitterPreventionTime > 0 && lastState == state && Time.timeSinceLevelLoad - lastPickup > nonKinematicPickupJitterPreventionTime)
{
preventPickupJitter();
}
}
public void noHand_CalcParentTransform()
{
if (Utilities.IsValid(owner))
{
parentPos = owner.GetPosition();
parentRot = owner.GetRotation();
}
}
//Bone Attachment State
//Same as the left and right hand held states, but can be applied to any bone defined in HumanBodyBones
[System.NonSerialized]
public bool hasBones = false;
[System.NonSerialized]
public HumanBodyBones bone;
public void bone_OnEnterState()
{
bone = (HumanBodyBones)(-1 - state);
if (preventStealWhileAttachedToPlayer && Utilities.IsValid(pickup))
{
pickup.pickupable = IsLocalOwner() && pickupable;
}
}
public void bone_OnInterpolationStart()
{
//if the avatar we're wearing doesn't have the bones required, fallback to attach to playspace
bone_CalcParentTransform();
if (IsLocalOwner())
{
if (!hasBones)
{
_printErr("Avatar is missing the correct bone. Falling back to playspace attachment.");
state = STATE_ATTACHED_TO_PLAYSPACE;
return;
}
}
generic_OnInterpolationStart();
}
public void bone_CalcParentTransform()
{
if (Utilities.IsValid(owner))
{
parentPos = owner.GetBonePosition(bone);
parentRot = owner.GetBoneRotation(bone);
hasBones = parentPos != Vector3.zero;
parentPos = hasBones ? parentPos : owner.GetPosition();
parentRot = hasBones ? parentRot : owner.GetRotation();
}
}
//Playspace Attachment State
//Same as Bone Attachment state, but uses the player's transform instead of one of their bone's transforms.
//Useful as a fallback when the avatar is missing certain bones
public void playspace_CalcParentTransform()
{
if (Utilities.IsValid(owner))
{
parentPos = owner.GetPosition();
parentRot = owner.GetRotation();
}
}
//Worldspace Attachment State
//Locks an object's transform in world space
//Useful as intermediate state when transferring ownership.
//For example, if request to transfer ownership of an object comes before the new owner can update the state and transform of that object,
//there will be a few frames when the owner is correct, but the state and transforms are wrong.
//If the old state was left hand held, but it's meant to be right hand held, then you'll see a few confusing frames where the object teleports between hands.
//It's often better in this scenario to just lock the object to world space before transferring ownership so there's no teleporting in these intermediate frames.
public void world_OnInterpolationStart()
{
startPos = transform.position;
startRot = transform.rotation;
}
public void world_Interpolate(float interpolation)
{
transform.position = HermiteInterpolatePosition(startPos, Vector3.zero, pos, Vector3.zero, interpolation);
transform.rotation = HermiteInterpolateRotation(startRot, Vector3.zero, rot, Vector3.zero, interpolation);
if (!rigid.isKinematic)
{
rigid.velocity = Vector3.zero;
rigid.angularVelocity = Vector3.zero;
}
}
public bool world_OnInterpolationEnd()
{
return true;
}
public void world_OnSmartObjectSerialize()
{
pos = transform.position;
rot = transform.rotation;
vel = Vector3.zero;
spin = Vector3.zero;
}
public void AddListener(SmartObjectSyncListener newListener)
{
foreach (SmartObjectSyncListener l in listeners)
{
if (l == newListener)
{
//it's already in there, don't do anything
return;
}
}
SmartObjectSyncListener[] newListeners = new SmartObjectSyncListener[listeners.Length + 1];
listeners.CopyTo(newListeners, 0);
newListeners[newListeners.Length - 1] = newListener;
listeners = newListeners;
}
public void RemoveListener(SmartObjectSyncListener oldListener)
{
if (listeners.Length <= 0)
{
//no listeners
return;
}
SmartObjectSyncListener[] newListeners = new SmartObjectSyncListener[listeners.Length - 1];
int i = 0;
foreach (SmartObjectSyncListener l in listeners)
{
if (l == oldListener)
{
//this is the listener we're removing
break;
}
if (i >= newListeners.Length)
{
//only happens when no match is found
return;
}
newListeners[i] = l;
i++;
}
listeners = newListeners;
}
public void TogglePickupable()
{
pickupable = !pickupable;
}
public void DisablePickupable()
{
pickupable = false;
}
public void EnablePickupable()
{
pickupable = true;
}
}
}
| 0 | 0.937947 | 1 | 0.937947 | game-dev | MEDIA | 0.306066 | game-dev | 0.937616 | 1 | 0.937616 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.