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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
tai-kun/use-machine-ts | 2,688 | src/use-shared-machine.ts | import { useIsMounted, useSyncState } from "./core/logic";
import { useSyncExternalStore } from "./core/react";
import type {
Send,
SharedMachine,
SharedMachineSignature,
State,
StateSignature,
} from "./types";
/**
* Uses a shared state machine.
*
* This hook allows a state machine to be shared between hooks or between hooks and external asynchronous events.
* You need to create a state machine specifically for this hook using `createSharedMachine`.
* The shared state machine returned by `createSharedMachine` includes functions such as `.send()` to trigger state transitions and `.getState()` to return a snapshot of the current state.
* These mechanisms are implemented using `React.useSyncExternalStore`.
*
* @template D The type of state machine definition.
* @param machine The shared state machine.
* @param getServerState A function that returns the state on the server.
* @returns An array with two elements:
* - The first element is the current state of the state machine.
* - The second element is a function that sends an event to the state machine.
* @example
* ```tsx
* import { useSharedMachine, createSharedMachine } from "use-machine-ts"
*
* const network = createSharedMachine({
* // definition
* {
* initial: "inactive",
* states: {
* inactive: {
* on: { ONLINE: "active" },
* },
* active: {
* on: { OFFLINE: "inactive" },
* },
* },
* },
* })
*
* window.addEventListener("online", () => network.send("ONLINE"))
* window.addEventListener("offline", () => network.send("OFFLINE"))
*
* function NetworkStatus() {
* const [state] = useSharedMachine(network)
*
* return (
* <p>
* Network status: {state.value}
* </p>
* )
* }
* ```
*/
function useSharedMachine<D>(
machine: SharedMachine<D>,
getServerState?: () => State<D>,
): [
state: State<D>,
send: Send<D>,
] {
const isMounted = useIsMounted();
const {
instance: [def, conf = {}],
dispatch,
getState,
subscribe,
} = machine as unknown as SharedMachineSignature;
const state = useSyncExternalStore(
subscribe,
getState,
(getServerState as () => StateSignature) || getState,
) as StateSignature;
useSyncState(def, conf, state, dispatch, isMounted);
return [state as any, machine.send];
}
export { useSharedMachine };
export { and, guards, not, or } from "./core/guard";
export { createSharedMachine } from "./create-shared-machine";
export type * from "./types";
if (import.meta.vitest) {
const { describe, test } = import.meta.vitest;
describe("src/use-shared-machine", () => {
test.skip("Should be tested");
});
}
| 412 | 0.755392 | 1 | 0.755392 | game-dev | MEDIA | 0.271546 | game-dev | 0.582608 | 1 | 0.582608 |
CardboardPowered/cardboard | 3,006 | src/main/java/org/cardboardpowered/mixin/network/handler/MixinSPNH_SignUpdateEvent.java | package org.cardboardpowered.mixin.network.handler;
import org.cardboardpowered.interfaces.IMixinMinecraftServer;
import org.cardboardpowered.interfaces.IMixinServerEntityPlayer;
import org.cardboardpowered.interfaces.IMixinSignBlockEntity;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.block.entity.SignBlockEntity;
import net.minecraft.network.packet.c2s.play.UpdateSignC2SPacket;
import net.minecraft.server.network.ServerPlayNetworkHandler;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.util.Formatting;
import org.bukkit.craftbukkit.CraftServer;
import org.bukkit.entity.Player;
import org.bukkit.event.block.SignChangeEvent;
import org.cardboardpowered.impl.block.CardboardSign;
import org.cardboardpowered.util.MixinInfo;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@MixinInfo(events = {"SignChangeEvent"})
@Mixin(value = ServerPlayNetworkHandler.class, priority = 800)
public class MixinSPNH_SignUpdateEvent {
@Shadow
public ServerPlayerEntity player;
@SuppressWarnings("deprecation")
@Inject(at = @At(value = "INVOKE", target = "Lnet/minecraft/network/packet/c2s/play/UpdateSignC2SPacket;getText()[Ljava/lang/String;"), method = "onUpdateSign", cancellable = true)
public void fireSignUpdateEvent(UpdateSignC2SPacket packet, CallbackInfo ci) {
try {
String[] astring = packet.getText();
Player player = (Player) ((IMixinServerEntityPlayer)this.player).getBukkitEntity();
int x = packet.getPos().getX();
int y = packet.getPos().getY();
int z = packet.getPos().getZ();
String[] lines = new String[4];
for (int i = 0; i < astring.length; ++i)
lines[i] = Formatting.strip(Formatting.strip(astring[i]));
((IMixinMinecraftServer)CraftServer.server).cardboard_runOnMainThread(() -> {
try {
SignChangeEvent event = new SignChangeEvent((org.bukkit.craftbukkit.block.CraftBlock) player.getWorld().getBlockAt(x, y, z), player, lines);
CraftServer.INSTANCE.getPluginManager().callEvent(event);
if (!event.isCancelled()) {
BlockEntity tileentity = this.player.getWorld().getBlockEntity(packet.getPos());
SignBlockEntity tileentitysign = (SignBlockEntity) tileentity;
System.arraycopy(CardboardSign.sanitizeLines(event.getLines()), 0, ((IMixinSignBlockEntity)tileentitysign).getTextBF(), 0, 4);
//tileentitysign.editable = false;
}
} catch (NullPointerException serverNoLikeSigns) {}
});
} catch (NullPointerException serverNoLikeSigns) {}
}
}
| 412 | 0.85913 | 1 | 0.85913 | game-dev | MEDIA | 0.976714 | game-dev | 0.943016 | 1 | 0.943016 |
MMMaellon/SmartObjectSync | 88,636 | Packages/com.vrchat.worlds/Runtime/Udon/Serialization/OdinSerializer/Utilities/Extensions/TypeExtensions.cs | //-----------------------------------------------------------------------
// <copyright file="TypeExtensions.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 VRC.Udon.Serialization.OdinSerializer.Utilities
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using UnityEngine;
/// <summary>
/// Type method extensions.
/// </summary>
public static class TypeExtensions
{
private static readonly Func<float, float, bool> FloatEqualityComparerFunc = FloatEqualityComparer;
private static readonly Func<double, double, bool> DoubleEqualityComparerFunc = DoubleEqualityComparer;
private static readonly Func<Quaternion, Quaternion, bool> QuaternionEqualityComparerFunc = QuaternionEqualityComparer;
private static readonly object GenericConstraintsSatisfaction_LOCK = new object();
private static readonly Dictionary<Type, Type> GenericConstraintsSatisfactionInferredParameters = new Dictionary<Type, Type>();
private static readonly Dictionary<Type, Type> GenericConstraintsSatisfactionResolvedMap = new Dictionary<Type, Type>();
private static readonly HashSet<Type> GenericConstraintsSatisfactionProcessedParams = new HashSet<Type>();
private static readonly HashSet<Type> GenericConstraintsSatisfactionTypesToCheck = new HashSet<Type>();
private static readonly List<Type> GenericConstraintsSatisfactionTypesToCheck_ToAdd = new List<Type>();
private static readonly Type GenericListInterface = typeof(IList<>);
private static readonly Type GenericCollectionInterface = typeof(ICollection<>);
private static readonly object WeaklyTypedTypeCastDelegates_LOCK = new object();
private static readonly object StronglyTypedTypeCastDelegates_LOCK = new object();
private static readonly DoubleLookupDictionary<Type, Type, Func<object, object>> WeaklyTypedTypeCastDelegates = new DoubleLookupDictionary<Type, Type, Func<object, object>>();
private static readonly DoubleLookupDictionary<Type, Type, Delegate> StronglyTypedTypeCastDelegates = new DoubleLookupDictionary<Type, Type, Delegate>();
private static readonly Type[] TwoLengthTypeArray_Cached = new Type[2];
private static readonly Stack<Type> GenericArgumentsContainsTypes_ArgsToCheckCached = new Stack<Type>();
private static HashSet<string> ReservedCSharpKeywords = new HashSet<string>()
{
"abstract",
"as",
"base",
"bool",
"break",
"byte",
"case",
"catch",
"char",
"checked",
"class",
"const",
"continue",
"decimal",
"default",
"delegate",
"do",
"double",
"else",
"enum",
"event",
"explicit",
"extern",
"false",
"finally",
"fixed",
"float",
"for",
"foreach",
"goto",
"if",
"implicit",
"in",
"int",
"interface",
"internal",
"is",
"lock",
"long",
"namespace",
"new",
"null",
"object",
"operator",
"out",
"override",
"params",
"private",
"protected",
"public",
"readonly",
"ref",
"return",
"sbyte",
"sealed",
"short",
"sizeof",
"stackalloc",
"static",
"string",
"struct",
"switch",
"this",
"throw",
"true",
"try",
"typeof",
"uint",
"ulong",
"unchecked",
"unsafe",
"ushort",
"using",
"static",
"void",
"volatile",
"while",
"in",
"get",
"set",
"var",
//"async", // Identifiers can be named async and await
//"await",
};
/// <summary>
/// Type name alias lookup.
/// TypeNameAlternatives["Single"] will give you "float", "UInt16" will give you "ushort", "Boolean[]" will give you "bool[]" etc..
/// </summary>
public static readonly Dictionary<string, string> TypeNameAlternatives = new Dictionary<string, string>()
{
{ "Single", "float" },
{ "Double", "double" },
{ "SByte", "sbyte" },
{ "Int16", "short" },
{ "Int32", "int" },
{ "Int64", "long" },
{ "Byte", "byte" },
{ "UInt16", "ushort" },
{ "UInt32", "uint" },
{ "UInt64", "ulong" },
{ "Decimal", "decimal" },
{ "String", "string" },
{ "Char", "char" },
{ "Boolean", "bool" },
{ "Single[]", "float[]" },
{ "Double[]", "double[]" },
{ "SByte[]", "sbyte[]" },
{ "Int16[]", "short[]" },
{ "Int32[]", "int[]" },
{ "Int64[]", "long[]" },
{ "Byte[]", "byte[]" },
{ "UInt16[]", "ushort[]" },
{ "UInt32[]", "uint[]" },
{ "UInt64[]", "ulong[]" },
{ "Decimal[]", "decimal[]" },
{ "String[]", "string[]" },
{ "Char[]", "char[]" },
{ "Boolean[]", "bool[]" },
};
private static readonly object CachedNiceNames_LOCK = new object();
private static readonly Dictionary<Type, string> CachedNiceNames = new Dictionary<Type, string>();
private static string GetCachedNiceName(Type type)
{
string result;
lock (CachedNiceNames_LOCK)
{
if (!CachedNiceNames.TryGetValue(type, out result))
{
result = CreateNiceName(type);
CachedNiceNames.Add(type, result);
}
}
return result;
}
private static string CreateNiceName(Type type)
{
if (type.IsArray)
{
int rank = type.GetArrayRank();
return type.GetElementType().GetNiceName() + (rank == 1 ? "[]" : "[,]");
}
if (type.InheritsFrom(typeof(Nullable<>)))
{
return type.GetGenericArguments()[0].GetNiceName() + "?";
}
if (type.IsByRef)
{
return "ref " + type.GetElementType().GetNiceName();
}
if (type.IsGenericParameter || !type.IsGenericType)
{
return TypeNameGauntlet(type);
}
var builder = new StringBuilder();
var name = type.Name;
var index = name.IndexOf("`");
if (index != -1)
{
builder.Append(name.Substring(0, index));
}
else
{
builder.Append(name);
}
builder.Append('<');
var args = type.GetGenericArguments();
for (int i = 0; i < args.Length; i++)
{
var arg = args[i];
if (i != 0)
{
builder.Append(", ");
}
builder.Append(GetNiceName(arg));
}
builder.Append('>');
return builder.ToString();
}
private static readonly Type VoidPointerType = typeof(void).MakePointerType();
private static readonly Dictionary<Type, HashSet<Type>> PrimitiveImplicitCasts = new Dictionary<Type, HashSet<Type>>()
{
{ typeof(Int64), new HashSet<Type>() { typeof(Single), typeof(Double), typeof(Decimal) } },
{ typeof(Int32), new HashSet<Type>() { typeof(Int64), typeof(Single), typeof(Double), typeof(Decimal) } },
{ typeof(Int16), new HashSet<Type>() { typeof(Int32), typeof(Int64), typeof(Single), typeof(Double), typeof(Decimal) } },
{ typeof(SByte), new HashSet<Type>() { typeof(Int16), typeof(Int32), typeof(Int64), typeof(Single), typeof(Double), typeof(Decimal) } },
{ typeof(UInt64), new HashSet<Type>() { typeof(Single), typeof(Double), typeof(Decimal) } },
{ typeof(UInt32), new HashSet<Type>() { typeof(Int64), typeof(UInt64), typeof(Single), typeof(Double), typeof(Decimal) } },
{ typeof(UInt16), new HashSet<Type>() { typeof(Int32), typeof(UInt32), typeof(Int64), typeof(UInt64), typeof(Single), typeof(Double), typeof(Decimal) } },
{ typeof(Byte), new HashSet<Type>() { typeof(Int16), typeof(UInt16), typeof(Int32), typeof(UInt32), typeof(Int64), typeof(UInt64), typeof(Single), typeof(Double), typeof(Decimal) } },
{ typeof(Char), new HashSet<Type>() { typeof(UInt16), typeof(Int32), typeof(UInt32), typeof(Int64), typeof(UInt64), typeof(Single), typeof(Double), typeof(Decimal) } },
{ typeof(Boolean), new HashSet<Type>() { } },
{ typeof(Decimal), new HashSet<Type>() { } },
{ typeof(Single), new HashSet<Type>() { typeof(Double) } },
{ typeof(Double), new HashSet<Type>() { } },
{ typeof(IntPtr), new HashSet<Type>() { } },
{ typeof(UIntPtr), new HashSet<Type>() { } },
{ VoidPointerType, new HashSet<Type>() { } },
};
private static readonly HashSet<Type> ExplicitCastIntegrals = new HashSet<Type>()
{
{ typeof(Int64) },
{ typeof(Int32) },
{ typeof(Int16) },
{ typeof(SByte) },
{ typeof(UInt64) },
{ typeof(UInt32) },
{ typeof(UInt16) },
{ typeof(Byte) },
{ typeof(Char) },
{ typeof(Decimal) },
{ typeof(Single) },
{ typeof(Double) },
{ typeof(IntPtr) },
{ typeof(UIntPtr) }
};
internal static bool HasCastDefined(this Type from, Type to, bool requireImplicitCast)
{
if (from.IsEnum)
{
return Enum.GetUnderlyingType(from).IsCastableTo(to);
}
if (to.IsEnum)
{
return Enum.GetUnderlyingType(to).IsCastableTo(from);
}
if ((from.IsPrimitive || from == VoidPointerType) && (to.IsPrimitive || to == VoidPointerType))
{
if (requireImplicitCast)
{
return PrimitiveImplicitCasts[from].Contains(to);
}
else
{
if (from == typeof(IntPtr))
{
if (to == typeof(UIntPtr))
{
return false;
}
else if (to == VoidPointerType)
{
return true;
}
}
else if (from == typeof(UIntPtr))
{
if (to == typeof(IntPtr))
{
return false;
}
else if (to == VoidPointerType)
{
return true;
}
}
return ExplicitCastIntegrals.Contains(from) && ExplicitCastIntegrals.Contains(to);
}
}
return from.GetCastMethod(to, requireImplicitCast) != null;
}
/// <summary>
/// Checks whether a given string is a valid CSharp identifier name. This also checks full type names including namespaces.
/// </summary>
/// <param name="identifier">The identifier to check.</param>
public static bool IsValidIdentifier(string identifier)
{
if (identifier == null || identifier.Length == 0)
{
return false;
}
int dotIndex = identifier.IndexOf('.');
if (dotIndex >= 0)
{
string[] identifiers = identifier.Split('.');
for (int i = 0; i < identifiers.Length; i++)
{
if (!IsValidIdentifier(identifiers[i]))
{
return false;
}
}
return true;
}
if (ReservedCSharpKeywords.Contains(identifier))
{
return false;
}
if (!IsValidIdentifierStartCharacter(identifier[0]))
{
return false;
}
for (int i = 1; i < identifier.Length; i++)
{
if (!IsValidIdentifierPartCharacter(identifier[i]))
{
return false;
}
}
return true;
}
private static bool IsValidIdentifierStartCharacter(char c)
{
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || c == '@' || char.IsLetter(c);
}
private static bool IsValidIdentifierPartCharacter(char c)
{
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c >= '0' && c <= '9') || char.IsLetter(c);
}
/// <summary>
/// Determines whether a type can be casted to another type.
/// </summary>
/// <param name="from">From.</param>
/// <param name="to">To.</param>
/// <param name="requireImplicitCast">if set to <c>true</c> an implicit or explicit operator must be defined on the given type.</param>
public static bool IsCastableTo(this Type from, Type to, bool requireImplicitCast = false)
{
if (from == null)
{
throw new ArgumentNullException("from");
}
if (to == null)
{
throw new ArgumentNullException("to");
}
if (from == to)
{
return true;
}
return to.IsAssignableFrom(from) || from.HasCastDefined(to, requireImplicitCast);
}
/// <summary>
/// If a type can be casted to another type, this provides a function to manually convert the type.
/// </summary>
/// <param name="from">From.</param>
/// <param name="to">To.</param>
/// <param name="requireImplicitCast">if set to <c>true</c> an implicit or explicit operator must be defined on the given type.</param>
public static Func<object, object> GetCastMethodDelegate(this Type from, Type to, bool requireImplicitCast = false)
{
Func<object, object> result;
lock (WeaklyTypedTypeCastDelegates_LOCK)
{
if (WeaklyTypedTypeCastDelegates.TryGetInnerValue(from, to, out result) == false)
{
var method = GetCastMethod(from, to, requireImplicitCast);
if (method != null)
{
result = (obj) => method.Invoke(null, new object[] { obj });
}
WeaklyTypedTypeCastDelegates.AddInner(from, to, result);
}
}
return result;
}
/// <summary>
/// If a type can be casted to another type, this provides a function to manually convert the type.
/// </summary>
/// <param name="requireImplicitCast">if set to <c>true</c> an implicit or explicit operator must be defined on the given type.</param>
public static Func<TFrom, TTo> GetCastMethodDelegate<TFrom, TTo>(bool requireImplicitCast = false)
{
Delegate del;
lock (StronglyTypedTypeCastDelegates_LOCK)
{
if (StronglyTypedTypeCastDelegates.TryGetInnerValue(typeof(TFrom), typeof(TTo), out del) == false)
{
var method = GetCastMethod(typeof(TFrom), typeof(TTo), requireImplicitCast);
if (method != null)
{
del = Delegate.CreateDelegate(typeof(Func<TFrom, TTo>), method);
}
StronglyTypedTypeCastDelegates.AddInner(typeof(TFrom), typeof(TTo), del);
}
}
return (Func<TFrom, TTo>)del;
}
/// <summary>
/// If a type can be casted to another type, this provides the method info of the method in charge of converting the type.
/// </summary>
/// <param name="from">From.</param>
/// <param name="to">To.</param>
/// <param name="requireImplicitCast">if set to <c>true</c> an implicit or explicit operator must be defined on the given type.</param>
public static MethodInfo GetCastMethod(this Type from, Type to, bool requireImplicitCast = false)
{
var fromMethods = from.GetAllMembers<MethodInfo>(BindingFlags.Public | BindingFlags.Static);
foreach (var method in fromMethods)
{
if ((method.Name == "op_Implicit" || (requireImplicitCast == false && method.Name == "op_Explicit")) && method.GetParameters()[0].ParameterType.IsAssignableFrom(from) && to.IsAssignableFrom(method.ReturnType))
{
return method;
}
}
var toMethods = to.GetAllMembers<MethodInfo>(BindingFlags.Public | BindingFlags.Static);
foreach (var method in toMethods)
{
if ((method.Name == "op_Implicit" || (requireImplicitCast == false && method.Name == "op_Explicit")) && method.GetParameters()[0].ParameterType.IsAssignableFrom(from) && to.IsAssignableFrom(method.ReturnType))
{
return method;
}
}
return null;
}
private static bool FloatEqualityComparer(float a, float b)
{
if (float.IsNaN(a) && float.IsNaN(b)) return true;
return a == b;
}
private static bool DoubleEqualityComparer(double a, double b)
{
if (double.IsNaN(a) && double.IsNaN(b)) return true;
return a == b;
}
private static bool QuaternionEqualityComparer(Quaternion a, Quaternion b)
{
return a.x == b.x && a.y == b.y && a.z == b.z && a.w == b.w;
}
/// <summary>
/// Gets an equality comparer delegate used to compare the equality of values of a given type. In order, this will be:
///
/// 1. The == operator, if one is defined on the type.
/// 2. A delegate that uses <see cref="IEquatable{T}"/>, if the type implements that interface.
/// 3. .NET's own <see cref="EqualityComparer{T}.Default"/>
/// </summary>
/// <remarks>
/// <para>Note that in the special case of the type <see cref="UnityEngine.Quaternion"/>, a special equality comparer is returned that only checks whether all the Quaternion components are equal.</para>
/// <para>This is because, by default, Quaternion's equality operator is broken when operating on invalid quaternions; "default(Quaternion) == default(Quaternion)" evaluates to false, and this causes a multitude of problems.</para>
/// <para>Special delegates are also returned for float and double, that consider float.NaN to be equal to float.NaN, and double.NaN to be equal to double.NaN.</para>
/// </remarks>
public static Func<T, T, bool> GetEqualityComparerDelegate<T>()
{
if (typeof(T) == typeof(float))
return (Func<T, T, bool>)(object)FloatEqualityComparerFunc;
else if (typeof(T) == typeof(double))
return (Func<T, T, bool>)(object)DoubleEqualityComparerFunc;
else if (typeof(T) == typeof(Quaternion))
return (Func<T, T, bool>)(object)QuaternionEqualityComparerFunc;
Func<T, T, bool> result = null;
MethodInfo equalityMethod;
if (typeof(IEquatable<T>).IsAssignableFrom(typeof(T)))
{
if (typeof(T).IsValueType)
{
result = (a, b) =>
{
return ((IEquatable<T>)a).Equals(b);
};
}
else
{
result = (a, b) =>
{
if (object.ReferenceEquals(a, b))
{
return true;
}
else if (object.ReferenceEquals(a, null))
{
return false;
}
else
{
return ((IEquatable<T>)a).Equals(b);
}
};
}
}
else
{
Type currentType = typeof(T);
while (currentType != null && currentType != typeof(object))
{
equalityMethod = currentType.GetOperatorMethod(Operator.Equality, currentType, currentType);
if (equalityMethod != null)
{
result = (Func<T, T, bool>)Delegate.CreateDelegate(typeof(Func<T, T, bool>), equalityMethod, true);
break;
}
currentType = currentType.BaseType;
}
}
if (result == null)
{
var comparer = EqualityComparer<T>.Default;
result = comparer.Equals;
}
return result;
}
/// <summary>
/// Gets the first attribute of type T. Returns null in the no attribute of type T was found.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="inherit">If true, specifies to also search the ancestors of element for custom attributes.</param>
public static T GetAttribute<T>(this Type type, bool inherit) where T : Attribute
{
var attrs = type.GetCustomAttributes(typeof(T), inherit);
if (attrs.Length == 0)
{
return null;
}
else
{
return (T)attrs[0];
}
}
/// <summary>
/// Determines whether a type implements or inherits from another type.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="to">To.</param>
public static bool ImplementsOrInherits(this Type type, Type to)
{
return to.IsAssignableFrom(type);
}
/// <summary>
/// Determines whether a type implements an open generic interface or class such as IList<> or List<>.
/// </summary>
/// <param name="candidateType">Type of the candidate.</param>
/// <param name="openGenericType">Type of the open generic type.</param>
/// <returns></returns>
public static bool ImplementsOpenGenericType(this Type candidateType, Type openGenericType)
{
if (openGenericType.IsInterface) return candidateType.ImplementsOpenGenericInterface(openGenericType);
else return candidateType.ImplementsOpenGenericClass(openGenericType);
}
/// <summary>
/// Determines whether a type implements an open generic interface such as IList<>.
/// </summary>
/// <param name="candidateType">Type of the candidate.</param>
/// <param name="openGenericInterfaceType">Type of the open generic interface.</param>
/// <exception cref="System.ArgumentNullException"></exception>
/// <exception cref="System.ArgumentException">Type " + openGenericInterfaceType.Name + " is not a generic type definition and an interface.</exception>
public static bool ImplementsOpenGenericInterface(this Type candidateType, Type openGenericInterfaceType)
{
if (candidateType == openGenericInterfaceType)
return true;
if (candidateType.IsGenericType && candidateType.GetGenericTypeDefinition() == openGenericInterfaceType)
return true;
var interfaces = candidateType.GetInterfaces();
for (int i = 0; i < interfaces.Length; i++)
{
if (interfaces[i].ImplementsOpenGenericInterface(openGenericInterfaceType))
return true;
}
return false;
}
/// <summary>
/// Determines whether a type implements an open generic class such as List<>.
/// </summary>
/// <param name="candidateType">Type of the candidate.</param>
/// <param name="openGenericType">Type of the open generic interface.</param>
public static bool ImplementsOpenGenericClass(this Type candidateType, Type openGenericType)
{
if (candidateType.IsGenericType && candidateType.GetGenericTypeDefinition() == openGenericType)
return true;
var baseType = candidateType.BaseType;
if (baseType != null && baseType.ImplementsOpenGenericClass(openGenericType))
return true;
return false;
}
/// <summary>
/// Gets the generic arguments of an inherited open generic class or interface.
/// </summary>
/// <param name="candidateType">Type of the candidate.</param>
/// <param name="openGenericType">The open generic type to get the arguments of.</param>
public static Type[] GetArgumentsOfInheritedOpenGenericType(this Type candidateType, Type openGenericType)
{
if (openGenericType.IsInterface) return candidateType.GetArgumentsOfInheritedOpenGenericInterface(openGenericType);
else return candidateType.GetArgumentsOfInheritedOpenGenericClass(openGenericType);
}
/// <summary>
/// Gets the generic arguments of an inherited open generic class.
/// </summary>
/// <param name="candidateType">Type of the candidate.</param>
/// <param name="openGenericType">Type of the open generic class.</param>
public static Type[] GetArgumentsOfInheritedOpenGenericClass(this Type candidateType, Type openGenericType)
{
if (candidateType.IsGenericType && candidateType.GetGenericTypeDefinition() == openGenericType)
return candidateType.GetGenericArguments();
var baseType = candidateType.BaseType;
if (baseType != null)
return baseType.GetArgumentsOfInheritedOpenGenericClass(openGenericType);
return null;
}
/// <summary>
/// Gets the generic arguments of an inherited open generic interface.
/// </summary>
/// <param name="candidateType">Type of the candidate.</param>
/// <param name="openGenericInterfaceType">Type of the open generic interface.</param>
public static Type[] GetArgumentsOfInheritedOpenGenericInterface(this Type candidateType, Type openGenericInterfaceType)
{
// This if clause fixes an "error" in newer .NET Runtimes where enum arrays
// implement interfaces like IList<int>, which will be matched on by Odin
// before the IList<TheEnum> interface and cause a lot of issues because
// you can't actually use an enum array as if it was an IList<int>.
if ((openGenericInterfaceType == GenericListInterface || openGenericInterfaceType == GenericCollectionInterface) && candidateType.IsArray)
{
return new Type[] { candidateType.GetElementType() };
}
if (candidateType == openGenericInterfaceType)
return candidateType.GetGenericArguments();
if (candidateType.IsGenericType && candidateType.GetGenericTypeDefinition() == openGenericInterfaceType)
return candidateType.GetGenericArguments();
var interfaces = candidateType.GetInterfaces();
for (int i = 0; i < interfaces.Length; i++)
{
var @interface = interfaces[i];
if (!@interface.IsGenericType) continue;
var result = @interface.GetArgumentsOfInheritedOpenGenericInterface(openGenericInterfaceType);
if (result != null)
return result;
}
return null;
}
/// <summary>
/// Gets the MethodInfo of a specific operator kind, with the given left and right operands. This overload is *far* faster than any of the other GetOperatorMethod implementations, and should be used whenever possible.
/// </summary>
public static MethodInfo GetOperatorMethod(this Type type, Operator op, Type leftOperand, Type rightOperand)
{
string methodName;
switch (op)
{
case Operator.Equality:
methodName = "op_Equality";
break;
case Operator.Inequality:
methodName = "op_Inequality";
break;
case Operator.Addition:
methodName = "op_Addition";
break;
case Operator.Subtraction:
methodName = "op_Subtraction";
break;
case Operator.Multiply:
methodName = "op_Multiply";
break;
case Operator.Division:
methodName = "op_Division";
break;
case Operator.LessThan:
methodName = "op_LessThan";
break;
case Operator.GreaterThan:
methodName = "op_GreaterThan";
break;
case Operator.LessThanOrEqual:
methodName = "op_LessThanOrEqual";
break;
case Operator.GreaterThanOrEqual:
methodName = "op_GreaterThanOrEqual";
break;
case Operator.Modulus:
methodName = "op_Modulus";
break;
case Operator.RightShift:
methodName = "op_RightShift";
break;
case Operator.LeftShift:
methodName = "op_LeftShift";
break;
case Operator.BitwiseAnd:
methodName = "op_BitwiseAnd";
break;
case Operator.BitwiseOr:
methodName = "op_BitwiseOr";
break;
case Operator.ExclusiveOr:
methodName = "op_ExclusiveOr";
break;
case Operator.BitwiseComplement:
methodName = "op_OnesComplement";
break;
case Operator.LogicalNot:
methodName = "op_LogicalNot";
break;
case Operator.LogicalAnd:
case Operator.LogicalOr:
return null; // Not overridable
default:
throw new NotImplementedException();
}
var types = TwoLengthTypeArray_Cached;
lock (types)
{
types[0] = leftOperand;
types[1] = rightOperand;
try
{
var result = type.GetMethod(methodName, Flags.StaticAnyVisibility, null, types, null);
if (result != null && result.ReturnType != typeof(bool)) return null;
return result;
}
catch (AmbiguousMatchException)
{
// We fallback to manual resolution
var methods = type.GetMethods(Flags.StaticAnyVisibility);
for (int i = 0; i < methods.Length; i++)
{
var method = methods[i];
if (method.Name != methodName) continue;
if (method.ReturnType != typeof(bool)) continue;
var parameters = method.GetParameters();
if (parameters.Length != 2) continue;
if (!parameters[0].ParameterType.IsAssignableFrom(leftOperand)) continue;
if (!parameters[1].ParameterType.IsAssignableFrom(rightOperand)) continue;
return method;
}
return null;
}
}
}
/// <summary>
/// Gets the MethodInfo of a specific operator type.
/// </summary>
public static MethodInfo GetOperatorMethod(this Type type, Operator op)
{
string methodName;
switch (op)
{
case Operator.Equality:
methodName = "op_Equality";
break;
case Operator.Inequality:
methodName = "op_Inequality";
break;
case Operator.Addition:
methodName = "op_Addition";
break;
case Operator.Subtraction:
methodName = "op_Subtraction";
break;
case Operator.Multiply:
methodName = "op_Multiply";
break;
case Operator.Division:
methodName = "op_Division";
break;
case Operator.LessThan:
methodName = "op_LessThan";
break;
case Operator.GreaterThan:
methodName = "op_GreaterThan";
break;
case Operator.LessThanOrEqual:
methodName = "op_LessThanOrEqual";
break;
case Operator.GreaterThanOrEqual:
methodName = "op_GreaterThanOrEqual";
break;
case Operator.Modulus:
methodName = "op_Modulus";
break;
case Operator.RightShift:
methodName = "op_RightShift";
break;
case Operator.LeftShift:
methodName = "op_LeftShift";
break;
case Operator.BitwiseAnd:
methodName = "op_BitwiseAnd";
break;
case Operator.BitwiseOr:
methodName = "op_BitwiseOr";
break;
case Operator.ExclusiveOr:
methodName = "op_ExclusiveOr";
break;
case Operator.BitwiseComplement:
methodName = "op_OnesComplement";
break;
case Operator.LogicalNot:
methodName = "op_LogicalNot";
break;
case Operator.LogicalAnd:
case Operator.LogicalOr:
return null; // Not overridable
default:
throw new NotImplementedException();
}
return type.GetAllMembers<MethodInfo>(Flags.StaticAnyVisibility).FirstOrDefault(m => m.Name == methodName);
}
/// <summary>
/// Gets the MethodInfo of a specific operator type.
/// </summary>
public static MethodInfo[] GetOperatorMethods(this Type type, Operator op)
{
string methodName;
switch (op)
{
// TODO: Add Divide and other names for other .Net versions
case Operator.Equality:
methodName = "op_Equality";
break;
case Operator.Inequality:
methodName = "op_Inequality";
break;
case Operator.Addition:
methodName = "op_Addition";
break;
case Operator.Subtraction:
methodName = "op_Subtraction";
break;
case Operator.Multiply:
methodName = "op_Multiply";
break;
case Operator.Division:
methodName = "op_Division";
break;
case Operator.LessThan:
methodName = "op_LessThan";
break;
case Operator.GreaterThan:
methodName = "op_GreaterThan";
break;
case Operator.LessThanOrEqual:
methodName = "op_LessThanOrEqual";
break;
case Operator.GreaterThanOrEqual:
methodName = "op_GreaterThanOrEqual";
break;
case Operator.Modulus:
methodName = "op_Modulus";
break;
case Operator.RightShift:
methodName = "op_RightShift";
break;
case Operator.LeftShift:
methodName = "op_LeftShift";
break;
case Operator.BitwiseAnd:
methodName = "op_BitwiseAnd";
break;
case Operator.BitwiseOr:
methodName = "op_BitwiseOr";
break;
case Operator.ExclusiveOr:
methodName = "op_ExclusiveOr";
break;
case Operator.BitwiseComplement:
methodName = "op_OnesComplement";
break;
case Operator.LogicalNot:
methodName = "op_LogicalNot";
break;
case Operator.LogicalAnd:
case Operator.LogicalOr:
return null; // Not overridable
default:
throw new NotImplementedException();
}
return type.GetAllMembers<MethodInfo>(Flags.StaticAnyVisibility).Where(x => x.Name == methodName).ToArray();
}
/// <summary>
/// Gets all members from a given type, including members from all base types if the <see cref="BindingFlags.DeclaredOnly"/> flag isn't set.
/// </summary>
public static IEnumerable<MemberInfo> GetAllMembers(this Type type, BindingFlags flags = BindingFlags.Default)
{
Type currentType = type;
if ((flags & BindingFlags.DeclaredOnly) == BindingFlags.DeclaredOnly)
{
foreach (var member in currentType.GetMembers(flags))
{
yield return member;
}
}
else
{
flags |= BindingFlags.DeclaredOnly;
do
{
foreach (var member in currentType.GetMembers(flags))
{
yield return member;
}
currentType = currentType.BaseType;
}
while (currentType != null);
}
}
/// <summary>
/// Gets all members from a given type, including members from all base types.
/// </summary>
public static IEnumerable<MemberInfo> GetAllMembers(this Type type, string name, BindingFlags flags = BindingFlags.Default)
{
foreach (var member in type.GetAllMembers(flags))
{
if (member.Name != name) continue;
yield return member;
}
}
/// <summary>
/// Gets all members of a specific type from a type, including members from all base types, if the <see cref="BindingFlags.DeclaredOnly"/> flag isn't set.
/// </summary>
public static IEnumerable<T> GetAllMembers<T>(this Type type, BindingFlags flags = BindingFlags.Default) where T : MemberInfo
{
if (type == null) throw new ArgumentNullException("type");
if (type == typeof(object)) yield break;
Type currentType = type;
if ((flags & BindingFlags.DeclaredOnly) == BindingFlags.DeclaredOnly)
{
foreach (var member in currentType.GetMembers(flags))
{
var found = member as T;
if (found != null)
{
yield return found;
}
}
}
else
{
flags |= BindingFlags.DeclaredOnly;
do
{
foreach (var member in currentType.GetMembers(flags))
{
var found = member as T;
if (found != null)
{
yield return found;
}
}
currentType = currentType.BaseType;
}
while (currentType != null);
}
}
/// <summary>
/// Gets the generic type definition of an open generic base type.
/// </summary>
public static Type GetGenericBaseType(this Type type, Type baseType)
{
int count;
return GetGenericBaseType(type, baseType, out count);
}
/// <summary>
/// Gets the generic type definition of an open generic base type.
/// </summary>
public static Type GetGenericBaseType(this Type type, Type baseType, out int depthCount)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
if (baseType == null)
{
throw new ArgumentNullException("baseType");
}
if (baseType.IsGenericType == false)
{
throw new ArgumentException("Type " + baseType.Name + " is not a generic type.");
}
if (type.InheritsFrom(baseType) == false)
{
throw new ArgumentException("Type " + type.Name + " does not inherit from " + baseType.Name + ".");
}
var t = type;
depthCount = 0;
while (t != null && (t.IsGenericType == false || t.GetGenericTypeDefinition() != baseType))
{
depthCount++;
t = t.BaseType;
}
if (t == null)
{
throw new ArgumentException(type.Name + " is assignable from " + baseType.Name + ", but base type was not found?");
}
return t;
}
/// <summary>
/// Returns a lazy enumerable of all the base types of this type including interfaces and classes
/// </summary>
public static IEnumerable<Type> GetBaseTypes(this Type type, bool includeSelf = false)
{
var result = GetBaseClasses(type, includeSelf).Concat(type.GetInterfaces());
if (includeSelf && type.IsInterface)
{
result.Concat(new Type[] { type });
}
return result;
}
/// <summary>
/// Returns a lazy enumerable of all the base classes of this type
/// </summary>
public static IEnumerable<Type> GetBaseClasses(this Type type, bool includeSelf = false)
{
if (type == null || type.BaseType == null)
{
yield break;
}
if (includeSelf)
{
yield return type;
}
var current = type.BaseType;
while (current != null)
{
yield return current;
current = current.BaseType;
}
}
/// <summary>
/// Used to filter out unwanted type names. Ex "int" instead of "Int32"
/// </summary>
private static string TypeNameGauntlet(this Type type)
{
string typeName = type.Name;
string altTypeName = string.Empty;
if (TypeNameAlternatives.TryGetValue(typeName, out altTypeName))
{
typeName = altTypeName;
}
return typeName;
}
/// <summary>
/// Returns a nicely formatted name of a type.
/// </summary>
public static string GetNiceName(this Type type)
{
if (type.IsNested && type.IsGenericParameter == false)
{
return type.DeclaringType.GetNiceName() + "." + GetCachedNiceName(type);
}
return GetCachedNiceName(type);
}
/// <summary>
/// Returns a nicely formatted full name of a type.
/// </summary>
public static string GetNiceFullName(this Type type)
{
string result;
if (type.IsNested && type.IsGenericParameter == false)
{
return type.DeclaringType.GetNiceFullName() + "." + GetCachedNiceName(type);
}
result = GetCachedNiceName(type);
if (type.Namespace != null)
{
result = type.Namespace + "." + result;
}
return result;
}
/// <summary>
/// Gets the name of the compilable nice.
/// </summary>
/// <param name="type">The type.</param>
public static string GetCompilableNiceName(this Type type)
{
return type.GetNiceName().Replace('<', '_').Replace('>', '_').TrimEnd('_');
}
/// <summary>
/// Gets the full name of the compilable nice.
/// </summary>
/// <param name="type">The type.</param>
public static string GetCompilableNiceFullName(this Type type)
{
return type.GetNiceFullName().Replace('<', '_').Replace('>', '_').TrimEnd('_');
}
/// <summary>
/// Returns the first found custom attribute of type T on this type
/// Returns null if none was found
/// </summary>
public static T GetCustomAttribute<T>(this Type type, bool inherit) where T : Attribute
{
var attrs = type.GetCustomAttributes(typeof(T), inherit);
if (attrs.Length == 0) return null;
return attrs[0] as T;
}
/// <summary>
/// Returns the first found non-inherited custom attribute of type T on this type
/// Returns null if none was found
/// </summary>
public static T GetCustomAttribute<T>(this Type type) where T : Attribute
{
return GetCustomAttribute<T>(type, false);
}
/// <summary>
/// Gets all attributes of type T.
/// </summary>
/// <param name="type">The type.</param>
public static IEnumerable<T> GetCustomAttributes<T>(this Type type) where T : Attribute
{
return GetCustomAttributes<T>(type, false);
}
/// <summary>
/// Gets all attributes of type T.
/// </summary>
/// <param name="type">The type</param>
/// <param name="inherit">If true, specifies to also search the ancestors of element for custom attributes.</param>
public static IEnumerable<T> GetCustomAttributes<T>(this Type type, bool inherit) where T : Attribute
{
var attrs = type.GetCustomAttributes(typeof(T), inherit);
for (int i = 0; i < attrs.Length; i++)
{
yield return attrs[i] as T;
}
}
/// <summary>
/// Returns true if the attribute whose type is specified by the generic argument is defined on this type
/// </summary>
public static bool IsDefined<T>(this Type type) where T : Attribute
{
return type.IsDefined(typeof(T), false);
}
/// <summary>
/// Returns true if the attribute whose type is specified by the generic argument is defined on this type
/// </summary>
public static bool IsDefined<T>(this Type type, bool inherit) where T : Attribute
{
return type.IsDefined(typeof(T), inherit);
}
/// <summary>
/// Determines whether a type inherits or implements another type. Also include support for open generic base types such as List<>.
/// </summary>
/// <param name="type"></param>
public static bool InheritsFrom<TBase>(this Type type)
{
return type.InheritsFrom(typeof(TBase));
}
/// <summary>
/// Determines whether a type inherits or implements another type. Also include support for open generic base types such as List<>.
/// </summary>
/// <param name="type"></param>
/// <param name="baseType"></param>
public static bool InheritsFrom(this Type type, Type baseType)
{
if (baseType.IsAssignableFrom(type))
{
return true;
}
if (type.IsInterface && baseType.IsInterface == false)
{
return false;
}
if (baseType.IsInterface)
{
return type.GetInterfaces().Contains(baseType);
}
var t = type;
while (t != null)
{
if (t == baseType)
{
return true;
}
if (baseType.IsGenericTypeDefinition && t.IsGenericType && t.GetGenericTypeDefinition() == baseType)
{
return true;
}
t = t.BaseType;
}
return false;
}
/// <summary>
/// Gets the number of base types between given type and baseType.
/// </summary>
public static int GetInheritanceDistance(this Type type, Type baseType)
{
Type lowerType;
Type higherType;
if (type.IsAssignableFrom(baseType))
{
higherType = type;
lowerType = baseType;
}
else if (baseType.IsAssignableFrom(type))
{
higherType = baseType;
lowerType = type;
}
else
{
throw new ArgumentException("Cannot assign types '" + type.GetNiceName() + "' and '" + baseType.GetNiceName() + "' to each other.");
}
Type currentType = lowerType;
int count = 0;
if (higherType.IsInterface)
{
while (currentType != null && currentType != typeof(object))
{
count++;
currentType = currentType.BaseType;
var interfaces = currentType.GetInterfaces();
for (int i = 0; i < interfaces.Length; i++)
{
if (interfaces[i] == higherType)
{
currentType = null;
break;
}
}
}
}
else
{
while (currentType != higherType && currentType != null && currentType != typeof(object))
{
count++;
currentType = currentType.BaseType;
}
}
return count;
}
/// <summary>
/// Determines whether a method has the specified parameter types.
/// </summary>
public static bool HasParamaters(this MethodInfo methodInfo, IList<Type> paramTypes, bool inherit = true)
{
var methodParams = methodInfo.GetParameters();
if (methodParams.Length == paramTypes.Count)
{
for (int i = 0; i < methodParams.Length; i++)
{
if (inherit && paramTypes[i].InheritsFrom(methodParams[i].ParameterType) == false)
{
return false;
}
else if (methodParams[i].ParameterType != paramTypes[i])
{
return false;
}
}
return true;
}
return false;
}
/// <summary>
/// FieldInfo will return the fieldType, propertyInfo the PropertyType, MethodInfo the return type and EventInfo will return the EventHandlerType.
/// </summary>
/// <param name="memberInfo">The MemberInfo.</param>
public static Type GetReturnType(this MemberInfo memberInfo)
{
var fieldInfo = memberInfo as FieldInfo;
if (fieldInfo != null)
{
return fieldInfo.FieldType;
}
var propertyInfo = memberInfo as PropertyInfo;
if (propertyInfo != null)
{
return propertyInfo.PropertyType;
}
var methodInfo = memberInfo as MethodInfo;
if (methodInfo != null)
{
return methodInfo.ReturnType;
}
var eventInfo = memberInfo as EventInfo;
if (eventInfo != null)
{
return eventInfo.EventHandlerType;
}
return null;
}
/// <summary>
/// Gets the value contained in a given <see cref="MemberInfo"/>. Currently only <see cref="FieldInfo"/> and <see cref="PropertyInfo"/> is supported.
/// </summary>
/// <param name="member">The <see cref="MemberInfo"/> to get the value of.</param>
/// <param name="obj">The instance to get the value from.</param>
/// <returns>The value contained in the given <see cref="MemberInfo"/>.</returns>
/// <exception cref="System.ArgumentException">Can't get the value of the given <see cref="MemberInfo"/> type.</exception>
public static object GetMemberValue(this MemberInfo member, object obj)
{
if (member is FieldInfo)
{
return (member as FieldInfo).GetValue(obj);
}
else if (member is PropertyInfo)
{
return (member as PropertyInfo).GetGetMethod(true).Invoke(obj, null);
}
else
{
throw new ArgumentException("Can't get the value of a " + member.GetType().Name);
}
}
/// <summary>
/// Sets the value of a given MemberInfo. Currently only <see cref="FieldInfo"/> and <see cref="PropertyInfo"/> is supported.
/// </summary>
/// <param name="member">The <see cref="MemberInfo"/> to set the value of.</param>
/// <param name="obj">The object to set the value on.</param>
/// <param name="value">The value to set.</param>
/// <exception cref="System.ArgumentException">
/// Property has no setter
/// or
/// Can't set the value of the given <see cref="MemberInfo"/> type.
/// </exception>
public static void SetMemberValue(this MemberInfo member, object obj, object value)
{
if (member is FieldInfo)
{
(member as FieldInfo).SetValue(obj, value);
}
else if (member is PropertyInfo)
{
var method = (member as PropertyInfo).GetSetMethod(true);
if (method != null)
{
method.Invoke(obj, new object[] { value });
}
else
{
throw new ArgumentException("Property " + member.Name + " has no setter");
}
}
else
{
throw new ArgumentException("Can't set the value of a " + member.GetType().Name);
}
}
/// <summary>
/// Tries to infer a set of valid generic parameters for a generic type definition, given a subset of known parameters.
/// </summary>
/// <param name="genericTypeDefinition">The generic type definition to attempt to infer parameters for.</param>
/// <param name="inferredParams">The inferred parameters, if inferral was successful.</param>
/// <param name="knownParameters">The known parameters to infer from.</param>
/// <returns>True if the parameters could be inferred, otherwise, false.</returns>
/// <exception cref="System.ArgumentNullException">
/// genericTypeDefinition is null
/// or
/// knownParameters is null
/// </exception>
/// <exception cref="System.ArgumentException">The genericTypeDefinition parameter must be a generic type definition.</exception>
public static bool TryInferGenericParameters(this Type genericTypeDefinition, out Type[] inferredParams, params Type[] knownParameters)
{
// NOTE: When modifying this method, also remember to modify Sirenix.Utilities.TypeExtensions.TryInferGenericParameters
// and GenericParameterInferenceTypeMatcher.TryInferGenericParameters!
if (genericTypeDefinition == null)
{
throw new ArgumentNullException("genericTypeDefinition");
}
if (knownParameters == null)
{
throw new ArgumentNullException("knownParameters");
}
if (!genericTypeDefinition.IsGenericType)
{
throw new ArgumentException("The genericTypeDefinition parameter must be a generic type.");
}
lock (GenericConstraintsSatisfaction_LOCK)
{
Dictionary<Type, Type> matches = GenericConstraintsSatisfactionInferredParameters;
matches.Clear();
HashSet<Type> typesToCheck = GenericConstraintsSatisfactionTypesToCheck;
typesToCheck.Clear();
List<Type> typesToCheck_ToAdd = GenericConstraintsSatisfactionTypesToCheck_ToAdd;
typesToCheck_ToAdd.Clear();
for (int i = 0; i < knownParameters.Length; i++)
{
typesToCheck.Add(knownParameters[i]);
}
Type[] definitions = genericTypeDefinition.GetGenericArguments();
if (!genericTypeDefinition.IsGenericTypeDefinition)
{
Type[] constructedParameters = definitions;
genericTypeDefinition = genericTypeDefinition.GetGenericTypeDefinition();
definitions = genericTypeDefinition.GetGenericArguments();
int unknownCount = 0;
for (int i = 0; i < constructedParameters.Length; i++)
{
if (!constructedParameters[i].IsGenericParameter && (!constructedParameters[i].IsGenericType || constructedParameters[i].IsFullyConstructedGenericType()))
{
matches[definitions[i]] = constructedParameters[i];
}
else
{
unknownCount++;
}
}
if (unknownCount == knownParameters.Length)
{
int count = 0;
for (int i = 0; i < constructedParameters.Length; i++)
{
if (constructedParameters[i].IsGenericParameter)
{
constructedParameters[i] = knownParameters[count++];
}
}
if (genericTypeDefinition.AreGenericConstraintsSatisfiedBy(constructedParameters))
{
inferredParams = constructedParameters;
return true;
}
}
}
if (definitions.Length == knownParameters.Length && genericTypeDefinition.AreGenericConstraintsSatisfiedBy(knownParameters))
{
inferredParams = knownParameters;
return true;
}
foreach (var typeArg in definitions)
{
//if (matches.ContainsKey(type)) continue;
var constraints = typeArg.GetGenericParameterConstraints();
foreach (var constraint in constraints)
{
foreach (var parameter in typesToCheck)
{
if (!constraint.IsGenericType)
{
continue;
}
Type constraintDefinition = constraint.GetGenericTypeDefinition();
var constraintParams = constraint.GetGenericArguments();
Type[] paramParams;
if (parameter.IsGenericType && constraintDefinition == parameter.GetGenericTypeDefinition())
{
paramParams = parameter.GetGenericArguments();
}
else if (constraintDefinition.IsInterface && parameter.ImplementsOpenGenericInterface(constraintDefinition))
{
paramParams = parameter.GetArgumentsOfInheritedOpenGenericInterface(constraintDefinition);
}
else if (constraintDefinition.IsClass && parameter.ImplementsOpenGenericClass(constraintDefinition))
{
paramParams = parameter.GetArgumentsOfInheritedOpenGenericClass(constraintDefinition);
}
else
{
continue;
}
matches[typeArg] = parameter;
typesToCheck_ToAdd.Add(parameter);
for (int i = 0; i < constraintParams.Length; i++)
{
if (constraintParams[i].IsGenericParameter)
{
matches[constraintParams[i]] = paramParams[i];
typesToCheck_ToAdd.Add(paramParams[i]);
}
}
}
foreach (var type in typesToCheck_ToAdd)
{
typesToCheck.Add(type);
}
typesToCheck_ToAdd.Clear();
}
}
if (matches.Count == definitions.Length)
{
inferredParams = new Type[matches.Count];
for (int i = 0; i < definitions.Length; i++)
{
inferredParams[i] = matches[definitions[i]];
}
if (AreGenericConstraintsSatisfiedBy(genericTypeDefinition, inferredParams))
{
return true;
}
}
inferredParams = null;
return false;
}
}
/// <summary>
/// <para>Checks whether an array of types satisfy the constraints of a given generic type definition.</para>
/// <para>If this method returns true, the given parameters can be safely used with <see cref="Type.MakeGenericType(Type[])"/> with the given generic type definition.</para>
/// </summary>
/// <param name="genericType">The generic type definition to check.</param>
/// <param name="parameters">The parameters to check validity for.</param>
/// <exception cref="System.ArgumentNullException">
/// genericType is null
/// or
/// types is null
/// </exception>
/// <exception cref="System.ArgumentException">The genericType parameter must be a generic type definition.</exception>
public static bool AreGenericConstraintsSatisfiedBy(this Type genericType, params Type[] parameters)
{
if (genericType == null)
{
throw new ArgumentNullException("genericType");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (!genericType.IsGenericType)
{
throw new ArgumentException("The genericTypeDefinition parameter must be a generic type.");
}
return AreGenericConstraintsSatisfiedBy(genericType.GetGenericArguments(), parameters);
}
/// <summary>
/// <para>Checks whether an array of types satisfy the constraints of a given generic method definition.</para>
/// <para>If this method returns true, the given parameters can be safely used with <see cref="MethodInfo.MakeGenericMethod(Type[])"/> with the given generic method definition.</para>
/// </summary>
/// <param name="genericType">The generic method definition to check.</param>
/// <param name="parameters">The parameters to check validity for.</param>
/// <exception cref="System.ArgumentNullException">
/// genericType is null
/// or
/// types is null
/// </exception>
/// <exception cref="System.ArgumentException">The genericMethod parameter must be a generic method definition.</exception>
public static bool AreGenericConstraintsSatisfiedBy(this MethodBase genericMethod, params Type[] parameters)
{
if (genericMethod == null)
{
throw new ArgumentNullException("genericMethod");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (!genericMethod.IsGenericMethod)
{
throw new ArgumentException("The genericMethod parameter must be a generic method.");
}
return AreGenericConstraintsSatisfiedBy(genericMethod.GetGenericArguments(), parameters);
}
public static bool AreGenericConstraintsSatisfiedBy(Type[] definitions, Type[] parameters)
{
if (definitions.Length != parameters.Length)
{
return false;
}
lock (GenericConstraintsSatisfaction_LOCK)
{
Dictionary<Type, Type> resolvedMap = GenericConstraintsSatisfactionResolvedMap;
resolvedMap.Clear();
for (int i = 0; i < definitions.Length; i++)
{
Type definition = definitions[i];
Type parameter = parameters[i];
if (!definition.GenericParameterIsFulfilledBy(parameter, resolvedMap))
{
return false;
}
}
return true;
}
}
public static bool GenericParameterIsFulfilledBy(this Type genericParameterDefinition, Type parameterType)
{
lock (GenericConstraintsSatisfaction_LOCK)
{
GenericConstraintsSatisfactionResolvedMap.Clear();
return genericParameterDefinition.GenericParameterIsFulfilledBy(parameterType, GenericConstraintsSatisfactionResolvedMap);
}
}
/// <summary>
/// Before calling this method we must ALWAYS hold a lock on the GenericConstraintsSatisfaction_LOCK object, as that is an implicit assumption it works with.
/// </summary>
private static bool GenericParameterIsFulfilledBy(this Type genericParameterDefinition, Type parameterType, Dictionary<Type, Type> resolvedMap, HashSet<Type> processedParams = null)
{
if (genericParameterDefinition == null)
{
throw new ArgumentNullException("genericParameterDefinition");
}
if (parameterType == null)
{
throw new ArgumentNullException("parameterType");
}
if (resolvedMap == null)
{
throw new ArgumentNullException("resolvedMap");
}
if (genericParameterDefinition.IsGenericParameter == false && genericParameterDefinition == parameterType)
{
return true;
}
if (genericParameterDefinition.IsGenericParameter == false)
{
return false;
}
if (processedParams == null)
{
processedParams = GenericConstraintsSatisfactionProcessedParams; // This is safe because we are currently holding the lock
processedParams.Clear();
}
processedParams.Add(genericParameterDefinition);
// First, check up on the special constraint flags
GenericParameterAttributes specialConstraints = genericParameterDefinition.GenericParameterAttributes;
if (specialConstraints != GenericParameterAttributes.None)
{
// Struct constraint (must not be nullable)
if ((specialConstraints & GenericParameterAttributes.NotNullableValueTypeConstraint) == GenericParameterAttributes.NotNullableValueTypeConstraint)
{
if (!parameterType.IsValueType || (parameterType.IsGenericType && parameterType.GetGenericTypeDefinition() == typeof(Nullable<>)))
{
return false;
}
}
// Class constraint
else if ((specialConstraints & GenericParameterAttributes.ReferenceTypeConstraint) == GenericParameterAttributes.ReferenceTypeConstraint)
{
if (parameterType.IsValueType)
{
return false;
}
}
// Must have a public parameterless constructor
if ((specialConstraints & GenericParameterAttributes.DefaultConstructorConstraint) == GenericParameterAttributes.DefaultConstructorConstraint)
{
if (parameterType.IsAbstract || (!parameterType.IsValueType && parameterType.GetConstructor(Type.EmptyTypes) == null))
{
return false;
}
}
}
// If this parameter has already been resolved to a type, check if that resolved type is assignable with the argument type
if (resolvedMap.ContainsKey(genericParameterDefinition))
{
if (!parameterType.IsAssignableFrom(resolvedMap[genericParameterDefinition]))
{
return false;
}
}
// Then, check up on the actual type constraints, of which there can be three kinds:
// Type inheritance, Interface implementation and fulfillment of another generic parameter.
Type[] constraints = genericParameterDefinition.GetGenericParameterConstraints();
for (int i = 0; i < constraints.Length; i++)
{
Type constraint = constraints[i];
// Replace resolved constraint parameters with their resolved types
if (constraint.IsGenericParameter && resolvedMap.ContainsKey(constraint))
{
constraint = resolvedMap[constraint];
}
if (constraint.IsGenericParameter)
{
if (!constraint.GenericParameterIsFulfilledBy(parameterType, resolvedMap, processedParams))
{
return false;
}
}
else if (constraint.IsClass || constraint.IsInterface || constraint.IsValueType)
{
if (constraint.IsGenericType)
{
Type constraintDefinition = constraint.GetGenericTypeDefinition();
Type[] constraintParams = constraint.GetGenericArguments();
Type[] paramParams;
if (parameterType.IsGenericType && constraintDefinition == parameterType.GetGenericTypeDefinition())
{
paramParams = parameterType.GetGenericArguments();
}
else
{
if (constraintDefinition.IsClass)
{
if (parameterType.ImplementsOpenGenericClass(constraintDefinition))
{
paramParams = parameterType.GetArgumentsOfInheritedOpenGenericClass(constraintDefinition);
}
else
{
return false;
}
}
else
{
if (parameterType.ImplementsOpenGenericInterface(constraintDefinition))
{
paramParams = parameterType.GetArgumentsOfInheritedOpenGenericInterface(constraintDefinition);
}
else
{
return false;
}
}
}
for (int j = 0; j < constraintParams.Length; j++)
{
var c = constraintParams[j];
var p = paramParams[j];
// Replace resolved constraint parameters with their resolved types
if (c.IsGenericParameter && resolvedMap.ContainsKey(c))
{
c = resolvedMap[c];
}
if (c.IsGenericParameter)
{
if (!processedParams.Contains(c) && !GenericParameterIsFulfilledBy(c, p, resolvedMap, processedParams))
{
return false;
}
}
else if (c != p && !c.IsAssignableFrom(p))
{
return false;
}
}
}
else if (!constraint.IsAssignableFrom(parameterType))
{
return false;
}
}
else
{
throw new Exception("Unknown parameter constraint type! " + constraint.GetNiceName());
}
}
resolvedMap[genericParameterDefinition] = parameterType;
return true;
}
/// <summary>
/// Not yet documented.
/// </summary>
public static string GetGenericConstraintsString(this Type type, bool useFullTypeNames = false)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
if (!type.IsGenericTypeDefinition)
{
throw new ArgumentException("Type '" + type.GetNiceName() + "' is not a generic type definition!");
}
var parameters = type.GetGenericArguments();
var strings = new string[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
{
strings[i] = parameters[i].GetGenericParameterConstraintsString(useFullTypeNames);
}
return string.Join(" ", strings);
}
/// <summary>
/// Formats a string with the specified generic parameter constraints on any given type. Example output: <c>where T : class</c>
/// </summary>
public static string GetGenericParameterConstraintsString(this Type type, bool useFullTypeNames = false)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
if (!type.IsGenericParameter)
{
throw new ArgumentException("Type '" + type.GetNiceName() + "' is not a generic parameter!");
}
StringBuilder sb = new StringBuilder();
bool started = false;
var specialConstraints = type.GenericParameterAttributes;
// Struct constraint (must not be nullable)
if ((specialConstraints & GenericParameterAttributes.NotNullableValueTypeConstraint) == GenericParameterAttributes.NotNullableValueTypeConstraint)
{
sb.Append("where ")
.Append(type.Name)
.Append(" : struct");
started = true;
}
// Class constraint
else if ((specialConstraints & GenericParameterAttributes.ReferenceTypeConstraint) == GenericParameterAttributes.ReferenceTypeConstraint)
{
sb.Append("where ")
.Append(type.Name)
.Append(" : class");
started = true;
}
// Must have a public parameterless constructor
if ((specialConstraints & GenericParameterAttributes.DefaultConstructorConstraint) == GenericParameterAttributes.DefaultConstructorConstraint)
{
if (started)
{
sb.Append(", new()");
}
else
{
sb.Append("where ")
.Append(type.Name)
.Append(" : new()");
started = true;
}
}
// Then add type constraints
var constraints = type.GetGenericParameterConstraints();
if (constraints.Length > 0)
{
for (int j = 0; j < constraints.Length; j++)
{
var constraint = constraints[j];
if (started)
{
sb.Append(", ");
if (useFullTypeNames)
sb.Append(constraint.GetNiceFullName());
else
sb.Append(constraint.GetNiceName());
}
else
{
sb.Append("where ")
.Append(type.Name)
.Append(" : ");
if (useFullTypeNames)
sb.Append(constraint.GetNiceFullName());
else
sb.Append(constraint.GetNiceName());
started = true;
}
}
}
return sb.ToString();
}
/// <summary>
/// Determines whether a generic type contains the specified generic argument constraints.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="types">The generic argument types.</param>
public static bool GenericArgumentsContainsTypes(this Type type, params Type[] types)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
if (type.IsGenericType == false)
{
return false;
}
bool[] typesSeen = new bool[types.Length];
var args = type.GetGenericArguments();
var argsToCheck = GenericArgumentsContainsTypes_ArgsToCheckCached;
lock (argsToCheck)
{
argsToCheck.Clear();
for (int i = 0; i < args.Length; i++)
{
argsToCheck.Push(args[i]);
}
while (argsToCheck.Count > 0)
{
var arg = argsToCheck.Pop();
// Check if it's one of the types we're looking for, and if so, mark that as seen
for (int i = 0; i < types.Length; i++)
{
Type lookingForType = types[i];
if (lookingForType == arg)
{
typesSeen[i] = true;
}
else if (lookingForType.IsGenericTypeDefinition && arg.IsGenericType && !arg.IsGenericTypeDefinition && arg.GetGenericTypeDefinition() == lookingForType)
{
typesSeen[i] = true;
}
}
// Check if all types we're looking for have been seen
{
bool allSeen = true;
for (int i = 0; i < typesSeen.Length; i++)
{
if (typesSeen[i] == false)
{
allSeen = false;
break;
}
}
if (allSeen)
{
return true;
}
}
// If argument is a generic type, we have to also check its arguments
if (arg.IsGenericType)
{
foreach (var innerArg in arg.GetGenericArguments())
{
argsToCheck.Push(innerArg);
}
}
}
}
return false;
}
/// <summary>
/// Determines whether a type is a fully constructed generic type.
/// </summary>
public static bool IsFullyConstructedGenericType(this Type type)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
if (type.IsGenericTypeDefinition)
{
return false;
}
if (type.HasElementType)
{
var element = type.GetElementType();
if (element.IsGenericParameter || element.IsFullyConstructedGenericType() == false)
{
return false;
}
}
var args = type.GetGenericArguments();
for (int i = 0; i < args.Length; i++)
{
var arg = args[i];
if (arg.IsGenericParameter)
{
return false;
}
else if (!arg.IsFullyConstructedGenericType())
{
return false;
}
}
return !type.IsGenericTypeDefinition;
//if (type.IsGenericType == false || type.IsGenericTypeDefinition)
//{
// return false;
//}
//var args = type.GetGenericArguments();
//for (int i = 0; i < args.Length; i++)
//{
// var arg = args[i];
// if (arg.IsGenericParameter)
// {
// return false;
// }
// else if (arg.IsGenericType && !arg.IsFullyConstructedGenericType())
// {
// return false;
// }
//}
//return true;
}
/// <summary>
/// Determines whether a type is nullable by ensuring the type is neither a PrimitiveType, ValueType or an Enum.
/// </summary>
public static bool IsNullableType(this Type type)
{
return !(type.IsPrimitive || type.IsValueType || type.IsEnum);
}
/// <summary>
/// Gets the enum bitmask in a ulong.
/// </summary>
/// <exception cref="System.ArgumentException">enumType</exception>
public static ulong GetEnumBitmask(object value, Type enumType)
{
if (!enumType.IsEnum)
{
throw new ArgumentException("enumType");
}
ulong selectedValue;
try
{
selectedValue = Convert.ToUInt64(value, CultureInfo.InvariantCulture);
}
catch (OverflowException)
{
unchecked
{
selectedValue = (ulong)Convert.ToInt64(value, CultureInfo.InvariantCulture);
}
}
return selectedValue;
}
public static Type[] SafeGetTypes(this Assembly assembly)
{
try
{
return assembly.GetTypes();
}
catch
{
return Type.EmptyTypes;
}
}
public static bool SafeIsDefined(this Assembly assembly, Type attribute, bool inherit)
{
try
{
return assembly.IsDefined(attribute, inherit);
}
catch
{
return false;
}
}
public static object[] SafeGetCustomAttributes(this Assembly assembly, Type type, bool inherit)
{
try
{
return assembly.GetCustomAttributes(type, inherit);
}
catch
{
return new object[0];
}
}
}
} | 412 | 0.981768 | 1 | 0.981768 | game-dev | MEDIA | 0.358808 | game-dev | 0.860266 | 1 | 0.860266 |
dbjorkholm/FORGOTTENSERVER-ORTS | 6,032 | data/npc/scripts/Kawill.lua | local keywordHandler = KeywordHandler:new()
local npcHandler = NpcHandler:new(keywordHandler)
NpcSystem.parseParameters(npcHandler)
function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end
function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end
function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end
function onThink() npcHandler:onThink() end
-- Kawill Blessing
local blessKeyword = keywordHandler:addKeyword({'spark of the phoenix'}, StdModule.say, {npcHandler = npcHandler, text = 'The Spark of the Phoenix is given by me and by the great pyromancer in the nearby fire temple. Do you wish to receive my part of the Spark of the Phoenix?'}, function(player) return player:getStorageValue(Storage.KawillBlessing) ~= 1 end)
blessKeyword:addChildKeyword({'yes'}, StdModule.say, {npcHandler = npcHandler, text = 'So receive the blessing of the life-giving earth, pilgrim.', reset = true}, nil, function(player) player:setStorageValue(Storage.KawillBlessing, 1) player:getPosition():sendMagicEffect(CONST_ME_MAGIC_BLUE) end)
blessKeyword:addChildKeyword({''}, StdModule.say, {npcHandler = npcHandler, text = 'Ok. If you don\'t want it...', reset = true})
-- Basic
keywordHandler:addKeyword({'god'}, StdModule.say, {npcHandler = npcHandler, text = 'The gods are treacherous and vain. They want to use us like they did in the past. Only the elements can be trusted, because all they want is for nature to run its set course.'})
keywordHandler:addKeyword({'job'}, StdModule.say, {npcHandler = npcHandler, text = 'I am the great geomancer of dwarvenkind.'})
keywordHandler:addKeyword({'geomancer'}, StdModule.say, {npcHandler = npcHandler, text = 'We investigate the will of the earth. It is our duty to make sure things to work in their natural way.'})
keywordHandler:addKeyword({'life'}, StdModule.say, {npcHandler = npcHandler, text = 'Life is born by earth and fed by earth.'})
keywordHandler:addKeyword({'name'}, StdModule.say, {npcHandler = npcHandler, text = 'I am Kawill Marbleeye, Son of Earth, from the Molten Rock.'})
keywordHandler:addKeyword({'quest'}, StdModule.say, {npcHandler = npcHandler, text = 'There\'s nothing I need, better ask others.'})
keywordHandler:addKeyword({'tibia'}, StdModule.say, {npcHandler = npcHandler, text = 'Nice world in general. It\'s a shame there is so much water ruining the general impression.'})
keywordHandler:addKeyword({'time'}, StdModule.say, {npcHandler = npcHandler, text = 'Time is not of importance.'})
keywordHandler:addKeyword({'monsters'}, StdModule.say, {npcHandler = npcHandler, text = 'May the earth swallow them all!'})
keywordHandler:addKeyword({'excalibug'}, StdModule.say, {npcHandler = npcHandler, text = 'Ah, a weapon to be feared by man, beast and god alike, jawoll. He who wields it will be both blessed and cursed at the same time.'})
keywordHandler:addKeyword({'ferumbras'}, StdModule.say, {npcHandler = npcHandler, text = 'The day will come when he finally bites the dust.'})
keywordHandler:addKeyword({'kazordoon'}, StdModule.say, {npcHandler = npcHandler, text = 'By using the powers of fire and earth we forced the river that once wound its way through the big old one in other directions, and created our home.'})
keywordHandler:addKeyword({'bezil'}, StdModule.say, {npcHandler = npcHandler, text = 'Bezil and Nezil have pawn and equpiment shop with an amazing stock.'})
keywordHandler:addKeyword({'nezil'}, StdModule.say, {npcHandler = npcHandler, text = 'Bezil and Nezil have pawn and equpiment shop with an amazing stock.'})
keywordHandler:addKeyword({'duria'}, StdModule.say, {npcHandler = npcHandler, text = 'The first knight of dwarvenkind is a fine woman.'})
keywordHandler:addKeyword({'etzel'}, StdModule.say, {npcHandler = npcHandler, text = 'I fear the sorcerers focus on the destructive forces of fire. They forget about the protection earth could provide.'})
keywordHandler:addKeyword({'jimbin'}, StdModule.say, {npcHandler = npcHandler, text = 'He is a jolly fellow and one of the oldest dwarves alive.'})
keywordHandler:addKeyword({'kroox'}, StdModule.say, {npcHandler = npcHandler, text = 'He is a fine smith and his armour may save your neck one day.'})
keywordHandler:addKeyword({'maryza'}, StdModule.say, {npcHandler = npcHandler, text = 'She is a fine cook, jawoll.'})
keywordHandler:addKeyword({'uzgod'}, StdModule.say, {npcHandler = npcHandler, text = 'Uzgod is a blacksmith and understands the ways of his element well.'})
keywordHandler:addKeyword({'kruzak'}, StdModule.say, {npcHandler = npcHandler, text = 'The emperor has rarely visited the temple district in the last years. He should care more about spirituality then about politics. Jawoll.'})
keywordHandler:addKeyword({'emperor'}, StdModule.say, {npcHandler = npcHandler, text = 'The emperor has rarely visited the temple district in the last years. He should care more about spirituality then about politics. Jawoll.'})
keywordHandler:addKeyword({'durin'}, StdModule.say, {npcHandler = npcHandler, text = 'The celestial paladin, the protector of our race. The only divine being we care for and the only one who still cares for dwarfs.'})
keywordHandler:addKeyword({'fire'}, StdModule.say, {npcHandler = npcHandler, text = 'Where earth is giving, fire is taking. That is the way of the elements.'})
keywordHandler:addKeyword({'earth'}, StdModule.say, {npcHandler = npcHandler, text = 'The lifegiving earth protects us, feeds us and takes us home after death.'})
keywordHandler:addKeyword({'the big old one'}, StdModule.say, {npcHandler = npcHandler, text = 'The mountain we live in is called the big old one. It\'s the mountain of mountains, and it isand like a friend and protector to our race.'})
npcHandler:setMessage(MESSAGE_GREET, 'Welcome |PLAYERNAME|! May earth protect you!')
npcHandler:setMessage(MESSAGE_FAREWELL, 'Earth under your feet, |PLAYERNAME|!')
npcHandler:setMessage(MESSAGE_WALKAWAY, 'Earth under your feet, pilgrim. What brings you here?')
npcHandler:addModule(FocusModule:new())
| 412 | 0.523849 | 1 | 0.523849 | game-dev | MEDIA | 0.820711 | game-dev | 0.521327 | 1 | 0.521327 |
MohistMC/Youer | 3,352 | src/main/java/org/bukkit/craftbukkit/entity/CraftTropicalFish.java | package org.bukkit.craftbukkit.entity;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.DyeColor;
import org.bukkit.craftbukkit.CraftServer;
import org.bukkit.entity.TropicalFish;
public class CraftTropicalFish extends io.papermc.paper.entity.PaperSchoolableFish implements TropicalFish {
public CraftTropicalFish(CraftServer server, net.minecraft.world.entity.animal.TropicalFish entity) {
super(server, entity);
}
@Override
public net.minecraft.world.entity.animal.TropicalFish getHandle() {
return (net.minecraft.world.entity.animal.TropicalFish) this.entity;
}
@Override
public String toString() {
return "CraftTropicalFish";
}
@Override
public DyeColor getPatternColor() {
return CraftTropicalFish.getPatternColor(this.getHandle().getPackedVariant());
}
@Override
public void setPatternColor(DyeColor color) {
this.getHandle().setPackedVariant(CraftTropicalFish.getData(color, this.getBodyColor(), this.getPattern()));
}
@Override
public DyeColor getBodyColor() {
return CraftTropicalFish.getBodyColor(this.getHandle().getPackedVariant());
}
@Override
public void setBodyColor(DyeColor color) {
this.getHandle().setPackedVariant(CraftTropicalFish.getData(this.getPatternColor(), color, this.getPattern()));
}
@Override
public Pattern getPattern() {
return CraftTropicalFish.getPattern(this.getHandle().getPackedVariant());
}
@Override
public void setPattern(Pattern pattern) {
this.getHandle().setPackedVariant(CraftTropicalFish.getData(this.getPatternColor(), this.getBodyColor(), pattern));
}
public static enum CraftPattern {
KOB(0, false),
SUNSTREAK(1, false),
SNOOPER(2, false),
DASHER(3, false),
BRINELY(4, false),
SPOTTY(5, false),
FLOPPER(0, true),
STRIPEY(1, true),
GLITTER(2, true),
BLOCKFISH(3, true),
BETTY(4, true),
CLAYFISH(5, true);
private final int variant;
private final boolean large;
//
private static final Map<Integer, Pattern> BY_DATA = new HashMap<>();
static {
for (CraftPattern type : values()) {
BY_DATA.put(type.getDataValue(), Pattern.values()[type.ordinal()]);
}
}
public static Pattern fromData(int data) {
return BY_DATA.get(data);
}
private CraftPattern(int variant, boolean large) {
this.variant = variant;
this.large = large;
}
public int getDataValue() {
return this.variant << 8 | ((this.large) ? 1 : 0);
}
}
public static int getData(DyeColor patternColor, DyeColor bodyColor, Pattern type) {
return patternColor.getWoolData() << 24 | bodyColor.getWoolData() << 16 | CraftPattern.values()[type.ordinal()].getDataValue();
}
public static DyeColor getPatternColor(int data) {
return DyeColor.getByWoolData((byte) ((data >> 24) & 0xFF));
}
public static DyeColor getBodyColor(int data) {
return DyeColor.getByWoolData((byte) ((data >> 16) & 0xFF));
}
public static Pattern getPattern(int data) {
return CraftPattern.fromData(data & 0xFFFF);
}
}
| 412 | 0.741315 | 1 | 0.741315 | game-dev | MEDIA | 0.626363 | game-dev,graphics-rendering | 0.922125 | 1 | 0.922125 |
Monkestation/Monkestation2.0 | 1,239 | code/modules/antagonists/heretic/magic/ash_jaunt.dm | /datum/action/cooldown/spell/jaunt/ethereal_jaunt/ash
name = "Ashen Passage"
desc = "A short range spell that allows you to pass unimpeded through walls."
background_icon_state = "bg_heretic"
overlay_icon_state = "bg_heretic_border"
button_icon = 'icons/mob/actions/actions_ecult.dmi'
button_icon_state = "ash_shift"
sound = null
school = SCHOOL_FORBIDDEN
cooldown_time = 15 SECONDS
invocation = "ASH'N P'SSG'"
invocation_type = INVOCATION_WHISPER
spell_requirements = NONE
exit_jaunt_sound = null
jaunt_duration = 1.1 SECONDS
jaunt_in_time = 1.3 SECONDS
jaunt_out_time = 0.6 SECONDS
jaunt_in_type = /obj/effect/temp_visual/dir_setting/ash_shift
jaunt_out_type = /obj/effect/temp_visual/dir_setting/ash_shift/out
/datum/action/cooldown/spell/jaunt/ethereal_jaunt/ash/do_steam_effects()
return
/datum/action/cooldown/spell/jaunt/ethereal_jaunt/ash/long
name = "Ashen Walk"
desc = "A long range spell that allows you pass unimpeded through multiple walls."
jaunt_duration = 5 SECONDS
/obj/effect/temp_visual/dir_setting/ash_shift
name = "ash_shift"
icon = 'icons/mob/simple/mob.dmi'
icon_state = "ash_shift2"
duration = 1.3 SECONDS
/obj/effect/temp_visual/dir_setting/ash_shift/out
icon_state = "ash_shift"
| 412 | 0.611751 | 1 | 0.611751 | game-dev | MEDIA | 0.969599 | game-dev | 0.84641 | 1 | 0.84641 |
ixray-team/ixray-1.6-stcop | 1,130 | src/xrGame/PhysicObject_script.cpp | #include "StdAfx.h"
#include "pch_script.h"
#include "PhysicObject.h"
#include "PHCollisionDamageReceiver.h"
#include "PHDestroyable.h"
#include "hit_immunity.h"
#include "damage_manager.h"
#include "DestroyablePhysicsObject.h"
using namespace luabind;
#pragma optimize("s",on)
void CPhysicObject::script_register(lua_State *L)
{
module(L)
[
class_<CPhysicObject,CGameObject>("CPhysicObject")
.def(constructor<>())
.def("run_anim_forward", &CPhysicObject::run_anim_forward)
.def("run_anim_back", &CPhysicObject::run_anim_back)
.def("stop_anim", &CPhysicObject::stop_anim)
.def("anim_time_get", &CPhysicObject::anim_time_get)
.def("anim_time_set", &CPhysicObject::anim_time_set)
.def("play_bones_sound", &CPhysicObject::play_bones_sound)
.def("stop_bones_sound", &CPhysicObject::stop_bones_sound)
.def("set_door_ignore_dynamics", &CPhysicObject::set_door_ignore_dynamics)
.def("unset_door_ignore_dynamics", &CPhysicObject::unset_door_ignore_dynamics),
class_<CDestroyablePhysicsObject, CPhysicObject>("CDestroyablePhysicsObject")
.def(constructor<>())
];
}
| 412 | 0.599387 | 1 | 0.599387 | game-dev | MEDIA | 0.912596 | game-dev | 0.509771 | 1 | 0.509771 |
exelix11/SysDVR | 7,105 | SysDVRConfig/source/translaton.cpp | #include <map>
#include "Libs/nlohmann/json.hpp"
#include "translaton.hpp"
#include "Platform/Platform.hpp"
#include "Platform/fs.hpp"
namespace Strings
{
std::string FontName;
GlyphRange ImguiFontGlyphRange;
MainPageTable Main = {};
GuideTable Guide = {};
ErrorTable Error = {};
PatchesTable Patches = {};
ConnectingTable Connecting = {};
// TODO: Uncomment the line of the language you want to add and change the name of the json
static std::map<std::string, std::string> Translations = {
{ "SetLanguage_ENUS", ASSET("strings/english.json")},
{ "SetLanguage_ENGB", ASSET("strings/english.json")},
{ "SetLanguage_IT", ASSET("strings/italian.json")},
{ "SetLanguage_ZHCN", ASSET("strings/simplifiedChinese.json")},
{ "SetLanguage_ZHHANS", ASSET("strings/simplifiedChinese.json")},
{ "SetLanguage_ZHTW", ASSET("strings/traditionalChinese.json")},
{ "SetLanguage_ZHHANT", ASSET("strings/traditionalChinese.json")},
//{ "SetLanguage_JA", ASSET("strings/example.json")},
{ "SetLanguage_FR", ASSET("strings/french.json")},
//{ "SetLanguage_DE", ASSET("strings/example.json")},
{ "SetLanguage_ES", ASSET("strings/spanish.json")},
//{ "SetLanguage_KO", ASSET("strings/example.json")},
//{ "SetLanguage_NL", ASSET("strings/example.json")},
{ "SetLanguage_PT", ASSET("strings/portuguese.json")},
//{ "SetLanguage_RU", ASSET("strings/example.json")},
//{ "SetLanguage_FRCA", ASSET("strings/example.json")},
{ "SetLanguage_ES419", ASSET("strings/spanish.json")},
{ "SetLanguage_PTBR", ASSET("strings/brazilianPortuguese.json")}
};
#define STRING_META_ITERATE(v1) cb(ptr, obj.v1);
// Use a version that accepts missing fields, they are default-initialized with english text
#undef NLOHMANN_JSON_FROM
#define NLOHMANN_JSON_FROM(v1) if (nlohmann_json_j.count(#v1)) nlohmann_json_j.at(#v1).get_to(nlohmann_json_t.v1);
// We need to be able to iterate over all the strings in the language structs to build the proper font atlases
// This macro resues macro crimes from nlohmann/json.hpp to also generate the iterator we need
#define DEFINE_LANGUAGE_JSON_PARSER(classname, ...) \
static void iterate_strings_##classname(const classname& obj, void* ptr, void (*cb)(void*, std::string_view s)) \
{ \
NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(STRING_META_ITERATE, __VA_ARGS__)) \
} \
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(classname, __VA_ARGS__)
DEFINE_LANGUAGE_JSON_PARSER(MainPageTable, ModeUsbTitle, ModeUsb, ModeTcpTitle, ModeTcp, ModeRtspTitle, ModeRtsp, ModeDisabled, ConsoleIPPlcaceholder, SelectMode, OptGuide, OptSetDefault, OptPatchManager, OptSave, ActiveMode, DefaultMode, OptTerminateSysmodule, WarnSysmoduleKill, ContinueQuestion, Yes, No, OptTryStart, StartFailed, StartSuccess)
DEFINE_LANGUAGE_JSON_PARSER(GuideTable, GuideTitle)
DEFINE_LANGUAGE_JSON_PARSER(ErrorTable, FailedToDetectMode, InvalidMode, TroubleshootReboot, ModeChangeFailed, BootModeChangeFailed, TroubleshootBootMode, SysmoduleConnectionFailed, SysmoduleConnectionTroubleshoot, SysmoduleConnectionTroubleshootLink, FailExitButton, SysdvrVersionError, OlderVersion, NewerVersion, VersionTroubleshoot, SysmoduleConnectionTroubleshootFull, SysmoduleConnectionTroubleshootUsbOnly, DiagProcessStatusOn, DiagProcessStatusOff)
DEFINE_LANGUAGE_JSON_PARSER(PatchesTable, CurlError, CurlGETFailed, CurlNoData, ParseReleaseFailure, ParseTagFailure, ParseTagCommitFailure, ParseDownloadFailure, NoLinkFound, ZipExtractFail, LatestVer, NewVerAvail, DownloadOk, Title, Loading, Description, Status, StatusNotInstalled, StatusUnknownVersion, StatusInstalled, SdcardPath, UninstallButton, DownloadButton, RebootWarning, RebootButton, BackButton, SearchLatestButton)
DEFINE_LANGUAGE_JSON_PARSER(ConnectingTable, Title, Description, Troubleshoot1, Troubleshoot2)
void IterateAllStringsForFontBuilding(void* obj, void (*cb)(void*, std::string_view))
{
iterate_strings_MainPageTable(Main, obj, cb);
iterate_strings_ErrorTable(Error, obj, cb);
iterate_strings_PatchesTable(Patches, obj, cb);
iterate_strings_GuideTable(Guide, obj, cb);
iterate_strings_ConnectingTable(Connecting, obj, cb);
}
#define map(x) { Strings::GlyphRange::x, #x }
NLOHMANN_JSON_SERIALIZE_ENUM(Strings::GlyphRange, {
map(NotSpecified),
map(ChineseSimplifiedCommon),
map(Cyrillic),
map(Default),
map(Greek),
map(Japanese),
map(Korean),
map(Thai),
map(Vietnamese)
})
#undef map
struct TranslationFile
{
std::string LanguageName;
std::string TranslationAuthor;
std::string FontName;
Strings::GlyphRange ImguiGlyphRange;
MainPageTable Main;
GuideTable Guide;
ErrorTable Error;
PatchesTable Patches;
ConnectingTable Connecting;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(TranslationFile, LanguageName, TranslationAuthor, FontName, ImguiGlyphRange,
Main, Guide, Error, Patches, Connecting)
};
void ResetStringTable()
{
FontName = ASSET("fonts/opensans.ttf");
ImguiFontGlyphRange = GlyphRange::Default;
Main = {};
Guide = {};
Error = {};
Patches = {};
Connecting = {};
}
static std::string ReadString(const std::string& path)
{
auto file = fs::OpenFile(path);
return std::string(file.begin(), file.end());
}
static std::vector<uint8_t> GetLanguageJson()
{
if (fs::Exists(SDMC "/config/sysdvr/language.json"))
{
return fs::OpenFile(SDMC "/config/sysdvr/language.json");
}
auto name = std::string(Platform::GetSystemLanguage());
if (fs::Exists(SDMC "/config/sysdvr/force_language"))
{
auto forceName = ReadString(SDMC "/config/sysdvr/force_language");
if (Translations.count(forceName))
{
name = forceName;
}
else
{
printf("force_language does not contain a valid language: %s\n", forceName.c_str());
}
}
if (Translations.count(name))
{
auto path = Translations[name];
printf("Loading translation %s: %s\n", name.c_str(), path.c_str());
return fs::OpenFile(path);
}
return {};
}
void LoadTranslationForSystemLanguage()
{
FontName = ASSET("fonts/opensans.ttf");
TranslationFile translation;
try {
auto file = GetLanguageJson();
if (file.empty())
return;
auto json = nlohmann::json::parse(file.begin(), file.end());
translation = json.get<TranslationFile>();
}
catch (std::exception& ex)
{
printf("Failed to load translation: %s\n", ex.what());
return;
}
if (translation.FontName != "")
{
auto fontPath = std::string(ASSET("fonts/")) + translation.FontName;
if (!fs::Exists(fontPath))
{
printf("The specified font does not exist: %s %s\n", translation.FontName.c_str(), fontPath.c_str());
return;
}
FontName = fontPath;
}
ImguiFontGlyphRange = translation.ImguiGlyphRange;
Main = translation.Main;
Guide = translation.Guide;
Error = translation.Error;
Patches = translation.Patches;
Connecting = translation.Connecting;
}
// Only for development purposes
void SerializeCurrentLanguage()
{
TranslationFile translation;
nlohmann::json json = translation;
std::string s = json.dump(4);
std::vector<u8> data(s.begin(), s.end());
fs::WriteFile("english.json", data);
}
}
| 412 | 0.793627 | 1 | 0.793627 | game-dev | MEDIA | 0.503084 | game-dev | 0.905095 | 1 | 0.905095 |
herotc/hero-rotation | 5,244 | HeroRotation_DeathKnight/Overrides.lua | --- ============================ HEADER ============================
-- HeroLib
local HL = HeroLib
local Cache = HeroCache
local Unit = HL.Unit
local Player = Unit.Player
local Pet = Unit.Pet
local Target = Unit.Target
local Spell = HL.Spell
local Item = HL.Item
-- HeroRotation
local HR = HeroRotation
-- Spells
local SpellBlood = Spell.DeathKnight.Blood
local SpellFrost = Spell.DeathKnight.Frost
local SpellUnholy = Spell.DeathKnight.Unholy
-- Lua
local GetTime = GetTime
local next = next
-- Commons
local DeathKnight = HeroRotation.Commons.DeathKnight
--- ============================ CONTENT ============================
-- Generic
-- Blood, ID: 250
local OldBloodIsCastable
OldBloodIsCastable = HL.AddCoreOverride("Spell.IsCastable",
function (self, BypassRecovery, Range, AoESpell, ThisUnit, Offset)
local BaseCheck = OldBloodIsCastable(self, BypassRecovery, Range, AoESpell, ThisUnit, Offset)
if self == SpellBlood.RaiseDead then
return (not Pet:IsActive()) and BaseCheck
else
return BaseCheck
end
end
, 250)
HL.AddCoreOverride("Player.DnDTicking",
function (self)
if next(DeathKnight.DnDTable) == nil then return false end
local Ticking = false
for TarGUID, LastTick in pairs(DeathKnight.DnDTable) do
if GetTime() - LastTick < 1.25 then
Ticking = true
end
end
if Ticking and Player:BuffUp(SpellBlood.DeathAndDecayBuff) then
return true
end
return false
end
, 250)
HL.AddCoreOverride("Player.BonestormTicking",
function (self)
if next(DeathKnight.BonestormTable) == nil then return false end
for TarGUID, LastTick in pairs(DeathKnight.BonestormTable) do
if GetTime() - LastTick < 1.25 then
return true
end
end
return false
end
, 250)
HL.AddCoreOverride("Player.DRWBPTicking",
function (self)
return Player:BuffUp(SpellBlood.DancingRuneWeaponBuff) and (SpellBlood.BloodBoil:TimeSinceLastCast() < SpellBlood.DancingRuneWeapon:TimeSinceLastCast() or SpellBlood.DeathsCaress:TimeSinceLastCast() < SpellBlood.DancingRuneWeapon:TimeSinceLastCast())
end
, 250)
-- Frost, ID: 251
local OldFrostIsCastable
OldFrostIsCastable = HL.AddCoreOverride("Spell.IsCastable",
function (self, BypassRecovery, Range, AoESpell, ThisUnit, Offset)
local BaseCheck = OldFrostIsCastable(self, BypassRecovery, Range, AoESpell, ThisUnit, Offset)
if self == SpellFrost.RaiseDead then
return (not Pet:IsActive()) and BaseCheck
else
return BaseCheck
end
end
, 251)
local OldFrostBuffUp
OldFrostBuffUp = HL.AddCoreOverride("Player.BuffUp",
function (self, Spell, AnyCaster, BypassRecovery)
local BaseCheck = OldFrostBuffUp(self, Spell, AnyCaster, BypassRecovery)
if Spell == SpellFrost.KillingMachineBuff then
return BaseCheck or DeathKnight.Exterminate
else
return BaseCheck
end
end
, 251)
-- Unholy, ID: 252
local OldUHIsCastable
OldUHIsCastable = HL.AddCoreOverride("Spell.IsCastable",
function (self, BypassRecovery, Range, AoESpell, ThisUnit, Offset)
local BaseCheck = OldUHIsCastable(self, BypassRecovery, Range, AoESpell, ThisUnit, Offset)
if self == SpellUnholy.RaiseDead then
return (not Pet:IsActive()) and BaseCheck
elseif self == SpellUnholy.DarkTransformation then
return (Pet:IsActive() and Pet:NPCID() == 26125) and BaseCheck
else
return BaseCheck
end
end
, 252)
local OldUHIsReady
OldUHIsReady = HL.AddCoreOverride("Spell.IsReady",
function (self, Range, AoESpell, ThisUnit, BypassRecovery, Offset)
local BaseCheck = OldUHIsReady(self, Range, AoESpell, ThisUnit, BypassRecovery, Offset)
if self == SpellUnholy.Epidemic then
return (SpellUnholy.VirulentPlagueDebuff:AuraActiveCount() > 1) and BaseCheck
else
return BaseCheck
end
end
, 252)
local OldUHIsAvailable
OldUHIsAvailable = HL.AddCoreOverride("Spell.IsAvailable",
function (self)
local BaseCheck = OldUHIsAvailable(self)
if not HR.CDsON() and (self == SpellUnholy.Apocalypse or self == SpellUnholy.UnholyAssault) then
return false
else
return BaseCheck
end
end
, 252)
HL.AddCoreOverride("Player.DnDTicking",
function (self)
if next(DeathKnight.DnDTable) == nil then return false end
local Ticking = false
for TarGUID, LastTick in pairs(DeathKnight.DnDTable) do
if GetTime() - LastTick < 1.25 then
Ticking = true
end
end
if Ticking and Player:BuffUp(SpellUnholy.DeathAndDecayBuff) then
return true
end
return false
end
, 252)
-- Example (Arcane Mage)
-- HL.AddCoreOverride ("Spell.IsCastableP",
-- function (self, Range, AoESpell, ThisUnit, BypassRecovery, Offset)
-- if Range then
-- local RangeUnit = ThisUnit or Target;
-- return self:IsLearned() and self:CooldownRemainsP( BypassRecovery, Offset or "Auto") == 0 and RangeUnit:IsInRange( Range, AoESpell );
-- elseif self == SpellArcane.MarkofAluneth then
-- return self:IsLearned() and self:CooldownRemainsP( BypassRecovery, Offset or "Auto") == 0 and not Player:IsCasting(self);
-- else
-- return self:IsLearned() and self:CooldownRemainsP( BypassRecovery, Offset or "Auto") == 0;
-- end;
-- end
-- , 62);
| 412 | 0.956292 | 1 | 0.956292 | game-dev | MEDIA | 0.971205 | game-dev | 0.997974 | 1 | 0.997974 |
afs/rdf-delta | 6,323 | rdf-delta-server-local/src/main/java/org/seaborne/delta/server/local/patchstores/any/PatchStoreAnyLocal.java | /*
* 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.
*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*/
package org.seaborne.delta.server.local.patchstores.any;
import static org.seaborne.delta.DeltaConst.F_LOG_TYPE;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Objects;
import org.apache.jena.atlas.json.JSON;
import org.apache.jena.atlas.json.JsonObject;
import org.seaborne.delta.*;
import org.seaborne.delta.server.Provider;
import org.seaborne.delta.server.local.*;
import org.seaborne.delta.server.local.patchstores.FileNames;
import org.seaborne.delta.server.local.patchstores.PatchLogIndex;
import org.seaborne.delta.server.local.patchstores.PatchStorage;
import org.seaborne.delta.server.local.patchstores.file.PatchStoreFile;
import org.seaborne.delta.server.local.patchstores.filestore.FileArea;
import org.seaborne.delta.server.local.patchstores.mem.PatchStoreMem;
import org.seaborne.delta.server.local.patchstores.rdb.PatchStoreRocks;
import org.seaborne.delta.server.local.patchstores.rdb.RocksConst;
//This class exists to handle newPatchLog.
/**
* A {@link PatchStore} that create a local file-based or RocksDB-based {@link PatchLog}
* by intercepting {@link #newPatchLog}.
*/
public class PatchStoreAnyLocal extends PatchStore {
private final PatchStoreFile patchStoreFile;
private final PatchStoreRocks patchStoreRocks;
// Hidden - or the source.cfg type="mem" case.
private final PatchStoreMem patchStoreMem;
private final PatchStore patchStoreDefaultNew;
private final Path patchLogDirectory;
public PatchStoreAnyLocal(String patchLogDirectory, PatchStoreProvider provider) {
super(provider);
Objects.requireNonNull(patchLogDirectory);
this.patchLogDirectory = Paths.get(patchLogDirectory);
patchStoreFile = new PatchStoreFile(patchLogDirectory, PatchStoreMgr.getPatchStoreProvider(Provider.FILE));
patchStoreRocks = new PatchStoreRocks(patchLogDirectory, PatchStoreMgr.getPatchStoreProvider(Provider.ROCKS));
patchStoreMem = new PatchStoreMem(provider);
patchStoreDefaultNew = patchStoreRocks;
}
@Override
public void initialize(DataSourceRegistry dataSourceRegistry, LocalServerConfig config) {
patchStoreFile.initialize(dataSourceRegistry, config);
patchStoreRocks.initialize(dataSourceRegistry, config);
super.initialize(dataSourceRegistry, config);
}
@Override
protected void initialize(LocalServerConfig config) {}
@Override
protected List<DataSourceDescription> initialDataSources() {
return FileArea.scanForLogs(patchLogDirectory);
}
@Override
protected PatchLog newPatchLog(DataSourceDescription dsd) {
Id id = dsd.getId();
Path fileStoreDir = patchLogDirectory.resolve(dsd.getName());
PatchStore patchStore = choose(dsd, fileStoreDir);
if ( patchStore == null )
return null;
return patchStore.createLog(dsd);
}
private PatchStore choose(DataSourceDescription dsd, Path patchLogDir) {
//Look in source.cfg.
if ( ! Files.exists(patchLogDir) )
return patchStoreDefaultNew;
Path sourceCfgPath = patchLogDir.resolve(FileNames.DS_CONFIG);
if ( ! Files.exists(sourceCfgPath) ) {
// Directory, no source.cfg.
return patchStoreDefaultNew;
}
try {
//c.f. LocalServerConfig.
JsonObject obj = JSON.read(sourceCfgPath.toString());
DataSourceDescription dsdCfg = DataSourceDescription.fromJson(obj);
String logTypeName = obj.get(F_LOG_TYPE).getAsString().value();
if ( logTypeName != null ) {
Provider provider = DPS.providerByName(logTypeName);
if ( provider == null )
throw new DeltaConfigException("Unknown log type: "+logTypeName);
switch(provider) {
case FILE : return patchStoreFile;
case MEM : return patchStoreMem;
case ROCKS : return patchStoreRocks;
case LOCAL :
throw new DeltaException(dsdCfg.getName()+":"+FileNames.DS_CONFIG+" : log_type = local");
default:
throw new DeltaException(dsdCfg.getName()+":"+FileNames.DS_CONFIG+" : log_type not for a local patch store");
}
}
Path dbPath = patchLogDir.resolve(RocksConst.databaseFilename).toAbsolutePath();
boolean rocks = Files.exists(dbPath);
if ( rocks )
return patchStoreRocks;
return patchStoreDefaultNew;
} catch (Exception ex) {
throw new DeltaException("Exception while reading log configuration: "+dsd.getName(), ex);
}
}
// Not called.
@Override
protected PatchLogIndex newPatchLogIndex(DataSourceDescription dsd, PatchStore patchStore, LocalServerConfig configuration) {
throw new DeltaException("PatchStoreAnyLocal.newPatchLogIndex called");
}
@Override
protected PatchStorage newPatchStorage(DataSourceDescription dsd, PatchStore patchStore, LocalServerConfig configuration) {
throw new DeltaException("PatchStoreAnyLocal.newPatchStorage called");
}
@Override
protected void delete(PatchLog patchLog) {
// This should have gone to the concrete file/rocks PatchStore
throw new DeltaException("PatchStoreAnyLocal.delete called");
}
@Override
protected void shutdownSub() {
patchStoreFile.shutdown();
patchStoreRocks.shutdown();
}
}
| 412 | 0.937402 | 1 | 0.937402 | game-dev | MEDIA | 0.271292 | game-dev | 0.914934 | 1 | 0.914934 |
JiepengTan/LockstepEngine_ARPGDemo | 2,630 | Unity/Assets/Scripts/View/EnemyView.cs | using System.Collections;
using Lockstep.Math;
using UnityEngine;
namespace Lockstep.Logic {
public class EnemyView : MonoBehaviour, IEnemyView {
public Enemy owner;
private bool _isSinking = false;
private float _sinkSpeed = 1f;
Animator anim;
GameObject player;
[HideInInspector] public AudioClip deathClip;
AudioSource enemyAudio;
ParticleSystem hitParticles;
public int scoreValue => owner.scoreValue;
public void BindEntity(BaseEntity entity){
owner = entity as Enemy;
owner.eventHandler = this;
}
void Awake(){
// Setting up the references.
anim = GetComponent<Animator>();
enemyAudio = GetComponent<AudioSource>();
hitParticles = GetComponentInChildren<ParticleSystem>();
}
void Update(){
if (!_isSinking) {
var pos = owner.transform.Pos3.ToVector3();
transform.position = Vector3.Lerp(transform.position, pos, 0.3f);
var deg = owner.transform.deg.ToFloat();
//deg = Mathf.Lerp(transform.rotation.eulerAngles.y, deg, 0.3f);
transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(0, deg, 0), 0.3f);
}
}
public void OnPlayerDied(){
anim.SetTrigger("PlayerDead");
}
public void TakeDamage(int amount, LVector3 hitPoint){
enemyAudio.Play();
hitParticles.transform.position = hitPoint.ToVector3();
hitParticles.Play();
}
public void Death(){
anim.SetTrigger("Dead");
enemyAudio.clip = deathClip;
enemyAudio.Play();
}
public void StartSinking(){
GetComponent<UnityEngine.AI.NavMeshAgent>().enabled = false;
ScoreManager.score += scoreValue;
_isSinking = true;
StartCoroutine(Sinking());
}
IEnumerator Sinking(){
yield return null;
var animatorInfo = anim.GetCurrentAnimatorStateInfo(0);
while (true) {
if (animatorInfo.normalizedTime >= 1.0f)
{
break;
}
yield return null;
}
float timer = 0;
while (timer < 3) {
timer += Time.deltaTime;
transform.Translate(-Vector3.up * _sinkSpeed * Time.deltaTime);
yield return null;
}
Destroy(gameObject);
}
}
} | 412 | 0.940886 | 1 | 0.940886 | game-dev | MEDIA | 0.993906 | game-dev | 0.986216 | 1 | 0.986216 |
latte-soft/builtinplugins | 2,724 | src/BuiltInPlugins/Toolbox/Core/Networking/Requests/UGCAccessoryUploadRequest.luau | local l_PublishService_0 = game:GetService("PublishService");
local l_UGCValidationService_0 = game:GetService("UGCValidationService");
local l_Parent_0 = script.Parent.Parent.Parent.Parent;
local v3 = require(l_Parent_0.Core.Actions.SetAssetId);
local v4 = require(l_Parent_0.Core.Actions.NetworkError);
local v5 = require(l_Parent_0.Core.Actions.SetCurrentScreen);
local v6 = require(l_Parent_0.Core.Actions.UploadResult);
local l_Util_0 = l_Parent_0.Core.Util;
local v8 = require(l_Util_0.DebugFlags);
local v9 = require(l_Util_0.getUserId);
local v10 = require(l_Util_0.AssetConfigConstants);
local v11 = require(l_Util_0.Analytics.Analytics);
local v12 = require(l_Parent_0.Core.Networking.Requests.ConfigureItemTagsRequest);
local l_Promise_0 = require(l_Parent_0.Packages.Framework).Util.Promise;
return function(v14, v15, _, v17, v18, v19, v20, v21, v22)
return function(v23, _)
local l_v19_0 = v19;
v15 = not v15 and "" or string.sub(v15, 1, v10.NAME_CHARACTER_LIMIT);
v17 = not v17 and "" or string.sub(v17, 1, v10.DESCRIPTION_CHARACTER_LIMIT);
v23:dispatch(v5(v10.SCREENS.UPLOADING_ASSET));
local v26 = l_v19_0[1];
if v26 then
local l_Handle_0 = v26:FindFirstChild("Handle");
if not (not l_Handle_0 or not l_Handle_0:IsA("MeshPart")) then
l_UGCValidationService_0:ResetCollisionFidelity(l_Handle_0);
end;
end;
local v28 = nil;
local v29 = nil;
if v21 ~= nil then
v28 = Enum.AssetCreatorType.Group;
v29 = v21;
else
v28 = Enum.AssetCreatorType.User;
v29 = v9();
end;
return l_Promise_0.new(function(v30, v31)
task.spawn(function()
local l_status_0, l_result_0 = pcall(function()
return l_PublishService_0:CreateAssetAndWaitForAssetId(l_v19_0, "", v28, v29, v18.Name, v15, v17, v22);
end);
if (l_status_0 and l_result_0 ~= nil) and l_result_0 ~= 0 then
v30(l_result_0);
return ;
else
v31(l_result_0);
return ;
end;
end);
end):andThen(function(v34)
v23:dispatch(v3(v34));
v23:dispatch(v12(v14, v34, {}, v20));
v11.incrementUploadAssetSuccess(v18);
end):catch(function(v35)
if v8.shouldDebugWarnings() then
warn("Lua toolbox: Could not upload catalog item");
end;
v23:dispatch(v4(v35));
v23:dispatch(v6(false));
v11.incrementUploadAssetFailure(v18);
end);
end;
end;
| 412 | 0.764689 | 1 | 0.764689 | game-dev | MEDIA | 0.321051 | game-dev | 0.764869 | 1 | 0.764869 |
Demonheadge/PokeScape | 4,436 | test/battle/exp.c | #include "global.h"
#include "test/battle.h"
#if B_EXP_CATCH >= GEN_6
WILD_BATTLE_TEST("Pokemon gain exp after catching a Pokemon")
{
u8 level = 0;
PARAMETRIZE { level = 50; }
PARAMETRIZE { level = MAX_LEVEL; }
GIVEN {
PLAYER(SPECIES_WOBBUFFET) { Level(level); }
OPPONENT(SPECIES_CATERPIE) { HP(1); }
} WHEN {
TURN { USE_ITEM(player, ITEM_POUCH_IRON); }
} SCENE {
MESSAGE("You used Ultra Ball!");
ANIMATION(ANIM_TYPE_SPECIAL, B_ANIM_BALL_THROW, player);
if (level != MAX_LEVEL) {
EXPERIENCE_BAR(player);
}
}
}
#endif // B_EXP_CATCH
WILD_BATTLE_TEST("Higher leveled Pokemon give more exp", s32 exp)
{
u8 level = 0;
PARAMETRIZE { level = 5; }
PARAMETRIZE { level = 10; }
GIVEN {
PLAYER(SPECIES_WOBBUFFET) { Level(20); }
OPPONENT(SPECIES_CATERPIE) { Level(level); HP(1); }
} WHEN {
TURN { MOVE(player, MOVE_TACKLE); }
} SCENE {
MESSAGE("Wobbuffet used Tackle!");
MESSAGE("Wild Caterpie fainted!");
EXPERIENCE_BAR(player, captureGainedExp: &results[i].exp);
} FINALLY {
EXPECT_GT(results[1].exp, results[0].exp);
}
}
WILD_BATTLE_TEST("Lucky Egg boosts gained exp points by 50%", s32 exp)
{
u32 item = 0;
PARAMETRIZE { item = ITEM_LUCKY_EGG; }
PARAMETRIZE { item = ITEM_NONE; }
GIVEN {
PLAYER(SPECIES_WOBBUFFET) { Level(20); Item(item); }
OPPONENT(SPECIES_CATERPIE) { Level(10); HP(1); }
} WHEN {
TURN { MOVE(player, MOVE_TACKLE); }
} SCENE {
MESSAGE("Wobbuffet used Tackle!");
MESSAGE("Wild Caterpie fainted!");
EXPERIENCE_BAR(player, captureGainedExp: &results[i].exp);
} FINALLY {
EXPECT_MUL_EQ(results[1].exp, Q_4_12(1.5), results[0].exp);
}
}
#if (B_SCALED_EXP == GEN_5 || B_SCALED_EXP >= GEN_7)
WILD_BATTLE_TEST("Exp is scaled to player and opponent's levels", s32 exp)
{
u8 level = 0;
PARAMETRIZE { level = 5; }
PARAMETRIZE { level = 10; }
GIVEN {
PLAYER(SPECIES_WOBBUFFET) { Level(level); }
OPPONENT(SPECIES_CATERPIE) { Level(5); HP(1); }
} WHEN {
TURN { MOVE(player, MOVE_TACKLE); }
} SCENE {
MESSAGE("Wobbuffet used Tackle!");
MESSAGE("Wild Caterpie fainted!");
EXPERIENCE_BAR(player, captureGainedExp: &results[i].exp);
} FINALLY {
EXPECT_GT(results[0].exp, results[1].exp);
}
}
#endif
WILD_BATTLE_TEST("Large exp gains are supported", s32 exp) // #1455
{
u8 level = 0;
PARAMETRIZE { level = 10; }
PARAMETRIZE { level = 50; }
PARAMETRIZE { level = MAX_LEVEL; }
GIVEN {
PLAYER(SPECIES_WOBBUFFET) { Level(1); Item(ITEM_LUCKY_EGG); OTName("Test"); } // OT Name is different so it gets more exp as a traded mon
OPPONENT(SPECIES_BLISSEY) { Level(level); HP(1); }
} WHEN {
TURN { MOVE(player, MOVE_TACKLE); }
} SCENE {
MESSAGE("Wobbuffet used Tackle!");
MESSAGE("Wild Blissey fainted!");
EXPERIENCE_BAR(player, captureGainedExp: &results[i].exp);
} THEN {
EXPECT(GetMonData(&gPlayerParty[0], MON_DATA_LEVEL) > 1);
EXPECT(GetMonData(&gPlayerParty[0], MON_DATA_EXP) > 1);
} FINALLY {
EXPECT_GT(results[1].exp, results[0].exp);
EXPECT_GT(results[2].exp, results[1].exp);
}
}
#if I_EXP_SHARE_ITEM < GEN_6
WILD_BATTLE_TEST("Exp Share(held) gives Experience to mons which did not participate in battle")
{
u32 item = 0;
PARAMETRIZE { item = ITEM_NONE; }
PARAMETRIZE { item = ITEM_EXP_SHARE; }
GIVEN {
PLAYER(SPECIES_WOBBUFFET);
PLAYER(SPECIES_WYNAUT) { Level(40); Item(item); }
OPPONENT(SPECIES_CATERPIE) { Level(10); HP(1); }
} WHEN {
TURN { MOVE(player, MOVE_TACKLE); }
} SCENE {
MESSAGE("Wobbuffet used Tackle!");
MESSAGE("Wild Caterpie fainted!");
// This message should appear only for gen6> exp share.
NOT MESSAGE("The rest of your team gained EXP. Points thanks to the Pulse Core!");
} THEN {
if (item == ITEM_EXP_SHARE)
EXPECT_GT(GetMonData(&gPlayerParty[1], MON_DATA_EXP), gExperienceTables[gSpeciesInfo[SPECIES_WYNAUT].growthRate][40]);
else
EXPECT_EQ(GetMonData(&gPlayerParty[1], MON_DATA_EXP), gExperienceTables[gSpeciesInfo[SPECIES_WYNAUT].growthRate][40]);
}
}
#endif // I_EXP_SHARE_ITEM
| 412 | 0.944574 | 1 | 0.944574 | game-dev | MEDIA | 0.861657 | game-dev | 0.851026 | 1 | 0.851026 |
tx00100xt/SeriousSamClassic | 13,226 | SamTFE/Sources/EntitiesMP/Boneman.es | /* Copyright (c) 2002-2012 Croteam Ltd.
This program is free software; you can redistribute it and/or modify
it under the terms of version 2 of the GNU General Public License as published by
the Free Software Foundation
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */
305
%{
#include "EntitiesMP/StdH/StdH.h"
#include "Models/Enemies/Boneman/Boneman.h"
%}
uses "EntitiesMP/EnemyBase";
%{
// info structure
static EntityInfo eiBoneman = {
EIBT_BONES, 250.0f,
0.0f, 1.9f, 0.0f, // source (eyes)
0.0f, 1.9f, 0.0f, // target (body)
};
#define BONES_HIT 2.8f
#define FIRE_RIGHT_HAND FLOAT3D( 0.25f, 1.5f, 0.0f)
#define FIRE_LEFT_HAND FLOAT3D(-0.25f, 1.5f, 0.0f)
%}
class CBoneman : CEnemyBase {
name "Boneman";
thumbnail "Thumbnails\\Boneman.tbn";
properties:
2 BOOL m_bFistHit = FALSE, // used for close attack
3 BOOL m_bTouchAnother = FALSE, // another entity touched on far attack
4 CSoundObject m_soFeet, // for running sound
5 BOOL m_bRunSoundPlaying = FALSE,
components:
0 class CLASS_BASE "Classes\\EnemyBase.ecl",
1 model MODEL_BONEMAN "Models\\Enemies\\Boneman\\Boneman.mdl",
2 texture TEXTURE_BONEMAN "Models\\Enemies\\Boneman\\Boneman.tex",
3 class CLASS_PROJECTILE "Classes\\Projectile.ecl",
// ************** BONEMAN PARTS **************
10 model MODEL_BONEMAN_BODY "Models\\Enemies\\Boneman\\Debris\\Body.mdl",
11 model MODEL_BONEMAN_HAND "Models\\Enemies\\Boneman\\Debris\\Hand.mdl",
12 model MODEL_BONEMAN_LEGS "Models\\Enemies\\Boneman\\Debris\\Legs.mdl",
// ************** SOUNDS **************
50 sound SOUND_IDLE "Models\\Enemies\\Boneman\\Sounds\\Idle.wav",
51 sound SOUND_SIGHT "Models\\Enemies\\Boneman\\Sounds\\Sight.wav",
52 sound SOUND_WOUND "Models\\Enemies\\Boneman\\Sounds\\Wound.wav",
53 sound SOUND_FIRE "Models\\Enemies\\Boneman\\Sounds\\Fire.wav",
54 sound SOUND_KICK "Models\\Enemies\\Boneman\\Sounds\\Kick.wav",
55 sound SOUND_PUNCH "Models\\Enemies\\Boneman\\Sounds\\Punch.wav",
56 sound SOUND_DEATH "Models\\Enemies\\Boneman\\Sounds\\Death.wav",
57 sound SOUND_RUN "Models\\Enemies\\Boneman\\Sounds\\Run.wav",
functions:
void Precache(void) {
CEnemyBase::Precache();
PrecacheSound(SOUND_IDLE );
PrecacheSound(SOUND_SIGHT);
PrecacheSound(SOUND_WOUND);
PrecacheSound(SOUND_FIRE );
PrecacheSound(SOUND_KICK );
PrecacheSound(SOUND_PUNCH);
PrecacheSound(SOUND_DEATH);
PrecacheSound(SOUND_RUN );
PrecacheModel(MODEL_BONEMAN_BODY);
PrecacheModel(MODEL_BONEMAN_HAND);
PrecacheModel(MODEL_BONEMAN_LEGS);
PrecacheClass(CLASS_PROJECTILE, PRT_BONEMAN_FIRE);
};
// describe how this enemy killed player
virtual CTString GetPlayerKillDescription(const CTString &strPlayerName, const EDeath &eDeath)
{
CTString str;
if (eDeath.eLastDamage.dmtType==DMT_CLOSERANGE) {
str.PrintF(TRANSV("%s was ripped apart by a Kleer"), (const char *) strPlayerName);
} else {
str.PrintF(TRANSV("%s was killed by a Kleer"), (const char *) strPlayerName);
}
return str;
}
virtual const CTFileName &GetComputerMessageName(void) const {
static DECLARE_CTFILENAME(fnm, "Data\\Messages\\Enemies\\Boneman.txt");
return fnm;
};
/* Entity info */
void *GetEntityInfo(void) {
return &eiBoneman;
};
/* Receive damage */
void ReceiveDamage(CEntity *penInflictor, enum DamageType dmtType,
FLOAT fDamageAmmount, const FLOAT3D &vHitPoint, const FLOAT3D &vDirection)
{
// boneman can't harm boneman
if (!IsOfClass(penInflictor, "Boneman")) {
CEnemyBase::ReceiveDamage(penInflictor, dmtType, fDamageAmmount, vHitPoint, vDirection);
}
};
void LeaveStain(BOOL bGrow)
{
// boneman doesn't leave bloody stain
}
// damage anim
INDEX AnimForDamage(FLOAT fDamage) {
INDEX iAnim;
switch (IRnd()%5) {
case 0: iAnim = BONEMAN_ANIM_WOUNDCRITICAL01; break;
case 1: iAnim = BONEMAN_ANIM_WOUNDCRITICAL02; break;
case 2: iAnim = BONEMAN_ANIM_WOUNDCRITICAL03; break;
case 3: iAnim = BONEMAN_ANIM_FALL01; break;
case 4: iAnim = BONEMAN_ANIM_FALL02; break;
default: iAnim = BONEMAN_ANIM_WOUNDCRITICAL01; //ASSERTALWAYS("Boneman unknown damage");
}
StartModelAnim(iAnim, 0);
DeactivateRunningSound();
return iAnim;
};
// death
INDEX AnimForDeath(void) {
INDEX iAnim;
switch (IRnd()%2) {
case 0: iAnim = BONEMAN_ANIM_DEATHTOBACK; break;
case 1: iAnim = BONEMAN_ANIM_DEATHTOFRONT; break;
default: iAnim = BONEMAN_ANIM_DEATHTOBACK; //ASSERTALWAYS("Boneman unknown death");
}
StartModelAnim(iAnim, 0);
DeactivateRunningSound();
return iAnim;
};
FLOAT WaitForDust(FLOAT3D &vStretch) {
if(GetModelObject()->GetAnim()==BONEMAN_ANIM_DEATHTOBACK)
{
vStretch=FLOAT3D(1,1,2)*1.0f;
return 0.48f;
}
else if(GetModelObject()->GetAnim()==BONEMAN_ANIM_DEATHTOFRONT)
{
vStretch=FLOAT3D(1,1,2)*0.75f;
return 0.48f;
}
return -1.0f;
};
void DeathNotify(void) {
ChangeCollisionBoxIndexWhenPossible(BONEMAN_COLLISION_BOX_DEATH);
};
// virtual anim functions
void StandingAnim(void) {
StartModelAnim(BONEMAN_ANIM_STANDLOOP, AOF_LOOPING|AOF_NORESTART);
DeactivateRunningSound();
};
void WalkingAnim(void) {
StartModelAnim(BONEMAN_ANIM_WALKLOOP, AOF_LOOPING|AOF_NORESTART);
DeactivateRunningSound();
};
void RunningAnim(void) {
StartModelAnim(BONEMAN_ANIM_RUNLOOP, AOF_LOOPING|AOF_NORESTART);
ActivateRunningSound();
};
void RotatingAnim(void) {
StartModelAnim(BONEMAN_ANIM_WALKLOOP, AOF_LOOPING|AOF_NORESTART);
DeactivateRunningSound();
};
// virtual sound functions
void IdleSound(void) {
PlaySound(m_soSound, SOUND_IDLE, SOF_3D);
};
void SightSound(void) {
PlaySound(m_soSound, SOUND_SIGHT, SOF_3D);
};
void WoundSound(void) {
PlaySound(m_soSound, SOUND_WOUND, SOF_3D);
};
void DeathSound(void) {
PlaySound(m_soSound, SOUND_DEATH, SOF_3D);
};
// running sounds
void ActivateRunningSound(void)
{
if (!m_bRunSoundPlaying) {
PlaySound(m_soFeet, SOUND_RUN, SOF_3D|SOF_LOOP);
m_bRunSoundPlaying = TRUE;
}
}
void DeactivateRunningSound(void)
{
m_soFeet.Stop();
m_bRunSoundPlaying = FALSE;
}
/************************************************************
* BLOW UP FUNCTIONS *
************************************************************/
// spawn body parts
void BlowUp(void) {
// get your size
FLOATaabbox3D box;
GetBoundingBox(box);
FLOAT fEntitySize = box.Size().MaxNorm();
FLOAT3D vNormalizedDamage = m_vDamage-m_vDamage*(m_fBlowUpAmount/m_vDamage.Length());
vNormalizedDamage /= Sqrt(vNormalizedDamage.Length());
vNormalizedDamage *= 0.75f;
FLOAT3D vBodySpeed = en_vCurrentTranslationAbsolute-en_vGravityDir*(en_vGravityDir%en_vCurrentTranslationAbsolute);
// spawn debris
Debris_Begin(EIBT_BONES, DPT_NONE, BET_NONE, fEntitySize, vNormalizedDamage, vBodySpeed, 5.0f, 2.0f);
Debris_Spawn(this, this, MODEL_BONEMAN_BODY, TEXTURE_BONEMAN, 0, 0, 0, 0, 0.0f,
FLOAT3D(FRnd()*0.6f+0.2f, FRnd()*0.6f+0.2f, FRnd()*0.6f+0.2f));
Debris_Spawn(this, this, MODEL_BONEMAN_HAND, TEXTURE_BONEMAN, 0, 0, 0, 0, 0.0f,
FLOAT3D(FRnd()*0.6f+0.2f, FRnd()*0.6f+0.2f, FRnd()*0.6f+0.2f));
Debris_Spawn(this, this, MODEL_BONEMAN_HAND, TEXTURE_BONEMAN, 0, 0, 0, 0, 0.0f,
FLOAT3D(FRnd()*0.6f+0.2f, FRnd()*0.6f+0.2f, FRnd()*0.6f+0.2f));
Debris_Spawn(this, this, MODEL_BONEMAN_LEGS, TEXTURE_BONEMAN, 0, 0, 0, 0, 0.0f,
FLOAT3D(FRnd()*0.6f+0.2f, FRnd()*0.6f+0.2f, FRnd()*0.6f+0.2f));
// hide yourself (must do this after spawning debris)
SwitchToEditorModel();
SetPhysicsFlags(EPF_MODEL_IMMATERIAL);
SetCollisionFlags(ECF_IMMATERIAL);
};
procedures:
/************************************************************
* A T T A C K E N E M Y *
************************************************************/
Fire(EVoid) : CEnemyBase::Fire {
// fire projectile
StartModelAnim(BONEMAN_ANIM_ATTACKCLOSELOOP, 0);
DeactivateRunningSound();
autowait(0.35f);
ShootProjectile(PRT_BONEMAN_FIRE, FIRE_RIGHT_HAND, ANGLE3D(0, 0, 0));
PlaySound(m_soSound, SOUND_FIRE, SOF_3D);
autowait(0.45f);
ShootProjectile(PRT_BONEMAN_FIRE, FIRE_LEFT_HAND, ANGLE3D(0, 0, 0));
PlaySound(m_soSound, SOUND_FIRE, SOF_3D);
autowait(FRnd()/3+0.6f);
return EReturn();
};
Hit(EVoid) : CEnemyBase::Hit {
// hit
if (CalcDist(m_penEnemy) < BONES_HIT) {
jump HitWithBones();
// jump
} else if (CalcDist(m_penEnemy) < 10.0f) {
jump JumpOnEnemy();
}
// run to enemy
m_fShootTime = _pTimer->CurrentTick() + 0.5f;
return EReturn();
};
// jump on enemy
JumpOnEnemy(EVoid) {
StartModelAnim(BONEMAN_ANIM_ATTACKFAR, 0);
DeactivateRunningSound();
// jump
FLOAT3D vDir = (m_penEnemy->GetPlacement().pl_PositionVector -
GetPlacement().pl_PositionVector).Normalize();
vDir *= !GetRotationMatrix();
vDir *= m_fCloseRunSpeed*1.5f;
vDir(2) = 2.5f;
SetDesiredTranslation(vDir);
PlaySound(m_soSound, SOUND_KICK, SOF_3D);
// animation - IGNORE DAMAGE WOUND -
SpawnReminder(this, 0.5f, 0);
m_iChargeHitAnimation = BONEMAN_ANIM_ATTACKFAR;
m_fChargeHitDamage = 20.0f;
m_fChargeHitAngle = 0.0f;
m_fChargeHitSpeed = 15.0f;
autocall CEnemyBase::ChargeHitEnemy() EReturn;
autowait(0.3f);
return EReturn();
};
// hit with bones
HitWithBones(EVoid) {
// attack with bones
StartModelAnim(BONEMAN_ANIM_ATTACKCLOSELOOP, 0);
DeactivateRunningSound();
// right hand
m_bFistHit = FALSE;
autowait(0.35f);
if (CalcDist(m_penEnemy)<BONES_HIT) { m_bFistHit = TRUE; }
PlaySound(m_soSound, SOUND_PUNCH, SOF_3D);
autowait(0.10f);
if (CalcDist(m_penEnemy)<BONES_HIT) { m_bFistHit = TRUE; }
if (m_bFistHit) {
FLOAT3D vDirection = m_penEnemy->GetPlacement().pl_PositionVector-GetPlacement().pl_PositionVector;
vDirection.Normalize();
// damage enemy
InflictDirectDamage(m_penEnemy, this, DMT_CLOSERANGE, 10.0f, FLOAT3D(0, 0, 0), vDirection);
// push target left
FLOAT3D vSpeed;
GetHeadingDirection(AngleDeg(90.0f), vSpeed);
vSpeed = vSpeed * 5.0f;
KickEntity(m_penEnemy, vSpeed);
}
// left hand
m_bFistHit = FALSE;
autowait(0.25f);
if (CalcDist(m_penEnemy)<BONES_HIT) { m_bFistHit = TRUE; }
PlaySound(m_soSound, SOUND_PUNCH, SOF_3D);
autowait(0.10f);
if (CalcDist(m_penEnemy)<BONES_HIT) { m_bFistHit = TRUE; }
if (m_bFistHit) {
// damage enemy
FLOAT3D vDirection = m_penEnemy->GetPlacement().pl_PositionVector-GetPlacement().pl_PositionVector;
vDirection.Normalize();
InflictDirectDamage(m_penEnemy, this, DMT_CLOSERANGE, 10.0f, FLOAT3D(0, 0, 0), vDirection);
// push target left
FLOAT3D vSpeed;
GetHeadingDirection(AngleDeg(-90.0f), vSpeed);
vSpeed = vSpeed * 5.0f;
KickEntity(m_penEnemy, vSpeed);
}
return EReturn();
};
/************************************************************
* M A I N *
************************************************************/
Main(EVoid) {
// declare yourself as a model
InitAsModel();
SetPhysicsFlags(EPF_MODEL_WALKING);
SetCollisionFlags(ECF_MODEL);
SetFlags(GetFlags()|ENF_ALIVE);
SetHealth(125.0f);
m_fMaxHealth = 125.0f;
en_fDensity = 2000.0f;
// set your appearance
SetModel(MODEL_BONEMAN);
SetModelMainTexture(TEXTURE_BONEMAN);
StandingAnim();
m_sptType = SPT_BONES;
// setup moving speed
m_fWalkSpeed = FRnd() + 2.5f;
m_aWalkRotateSpeed = FRnd()*25.0f + 45.0f;
m_fAttackRunSpeed = FRnd()*3.0f + 10.0f;
m_aAttackRotateSpeed = FRnd()*200 + 600.0f;
m_fCloseRunSpeed = FRnd() + 13.0f;
m_aCloseRotateSpeed = FRnd()*100 + 1000.0f;
// setup attack distances
m_fAttackDistance = 100.0f;
m_fCloseDistance = 30.0f;
m_fStopDistance = 2.0f;
m_fAttackFireTime = 3.0f;
m_fCloseFireTime = 2.0f;
m_fIgnoreRange = 200.0f;
// damage/explode properties
m_fBlowUpAmount = 70.0f;
m_fBodyParts = 4;
m_fDamageWounded = 80.0f;
m_iScore = 1000;
if (m_fStepHeight==-1) {
m_fStepHeight = 4.0f;
}
// set stretch factors for height and width
CEnemyBase::SizeModel();
m_soFeet.Set3DParameters(80.0f, 5.0f, 1.0f, 1.0f);
m_bRunSoundPlaying = FALSE;
// continue behavior in base class
jump CEnemyBase::MainLoop();
};
};
| 412 | 0.933293 | 1 | 0.933293 | game-dev | MEDIA | 0.994698 | game-dev | 0.525874 | 1 | 0.525874 |
magefree/mage | 1,955 | Mage.Sets/src/mage/cards/b/BjornaNightfallAlchemist.java | package mage.cards.b;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.common.SimpleActivatedAbility;
import mage.abilities.costs.common.SacrificeTargetCost;
import mage.abilities.costs.common.TapSourceCost;
import mage.abilities.effects.common.DamageTargetEffect;
import mage.abilities.effects.common.combat.GoadTargetEffect;
import mage.abilities.keyword.FriendsForeverAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.constants.SuperType;
import mage.filter.StaticFilters;
import mage.target.common.TargetControlledPermanent;
import mage.target.common.TargetCreaturePermanent;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class BjornaNightfallAlchemist extends CardImpl {
public BjornaNightfallAlchemist(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{U}{R}");
this.supertype.add(SuperType.LEGENDARY);
this.subtype.add(SubType.HUMAN);
this.power = new MageInt(1);
this.toughness = new MageInt(3);
// {T}, Sacrifice an artifact: Lucas, the Sharpshooter deals 1 damage to target creature. Goad that creature.
Ability ability = new SimpleActivatedAbility(new DamageTargetEffect(1), new TapSourceCost());
ability.addCost(new SacrificeTargetCost(StaticFilters.FILTER_CONTROLLED_PERMANENT_ARTIFACT_AN));
ability.addEffect(new GoadTargetEffect().setText("Goad that creature"));
ability.addTarget(new TargetCreaturePermanent());
this.addAbility(ability);
// Friends forever
this.addAbility(FriendsForeverAbility.getInstance());
}
private BjornaNightfallAlchemist(final BjornaNightfallAlchemist card) {
super(card);
}
@Override
public BjornaNightfallAlchemist copy() {
return new BjornaNightfallAlchemist(this);
}
}
| 412 | 0.922005 | 1 | 0.922005 | game-dev | MEDIA | 0.982091 | game-dev | 0.974404 | 1 | 0.974404 |
BiscuitDevelopment/SkyblockAddons | 7,387 | src/main/java/codes/biscuit/skyblockaddons/features/healingcircle/HealingCircle.java | package codes.biscuit.skyblockaddons.features.healingcircle;
import lombok.Getter;
import lombok.Setter;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@Getter @Setter
public class HealingCircle {
public static final float DIAMETER = 12;
public static final float RADIUS = 12 / 2F;
private List<HealingCircleParticle> healingCircleParticles = new ArrayList<>();
private long creation = System.currentTimeMillis();
private Point2D.Double cachedCenterPoint = null;
private double totalX;
private double totalZ;
private int totalParticles;
public HealingCircle(HealingCircleParticle healingCircleParticle) {
addPoint(healingCircleParticle);
}
public void addPoint(HealingCircleParticle healingCircleParticle) {
totalParticles++;
totalX += healingCircleParticle.getPoint().getX();
totalZ += healingCircleParticle.getPoint().getY();
healingCircleParticles.add(healingCircleParticle);
}
public double getAverageX() {
return totalX / (double) totalParticles;
}
public double getAverageZ() {
return totalZ / (double) totalParticles;
}
public double getParticlesPerSecond() {
int particlesPerSecond = 0;
long now = System.currentTimeMillis();
for (HealingCircleParticle healingCircleParticle : healingCircleParticles) {
if (now - healingCircleParticle.getCreation() < 1000) {
particlesPerSecond++;
}
}
return particlesPerSecond;
}
public Point2D.Double getCircleCenter() {
if (cachedCenterPoint != null) {
return cachedCenterPoint;
}
if (healingCircleParticles.size() < 3) {
return new Point2D.Double(Double.NaN, Double.NaN);
}
// The middle point, which is the first point for consistency. The circle will not appear
// until two other points exist, one that is left of this one, and one right.
Point2D.Double middlePoint = healingCircleParticles.get(0).getPoint();
// The first point, which can be anywhere on the circle as long as its a decent
// distance away from the middle.
Point2D.Double firstPoint = null;
for (HealingCircleParticle healingCircleParticle : healingCircleParticles) {
Point2D.Double point = healingCircleParticle.getPoint();
if (point != middlePoint && point.distance(middlePoint) > 2) {
firstPoint = point;
break;
}
}
if (firstPoint == null) {
return new Point2D.Double(Double.NaN, Double.NaN);
}
// The second point, which can be anywhere on the circle as long as its a decent
// distance away from the middle + its on the opposite side of the first point.
Point2D.Double secondPoint = null;
for (HealingCircleParticle healingCircleParticle : healingCircleParticles) {
Point2D.Double point = healingCircleParticle.getPoint();
if (point != middlePoint && point != firstPoint) {
double distanceToMiddle = point.distance(middlePoint);
// Make sure that the point is closer to the middle point than the first
// point, or else both points will be on the same side.
if (distanceToMiddle > 2 && point.distance(firstPoint) > distanceToMiddle) {
secondPoint = point;
break;
}
}
}
if (secondPoint == null) {
return new Point2D.Double(Double.NaN, Double.NaN);
}
Point2D.Double firstChordMidpoint = new Point2D.Double((middlePoint.x + firstPoint.x) / 2D, (middlePoint.y + firstPoint.y) / 2D);
Point2D.Double secondChordMidpoint = new Point2D.Double((middlePoint.x + secondPoint.x) / 2D, (middlePoint.y + secondPoint.y) / 2D);
Point2D.Double firstChordFirst = rotatePoint(middlePoint, firstChordMidpoint, 90);
Point2D.Double firstChordSecond = rotatePoint(firstPoint, firstChordMidpoint, 90);
Point2D.Double secondChordFirst = rotatePoint(middlePoint, secondChordMidpoint, 90);
Point2D.Double secondChordSecond = rotatePoint(secondPoint, secondChordMidpoint, 90);
Point2D.Double center = lineLineIntersection(firstChordFirst, firstChordSecond, secondChordFirst, secondChordSecond);
checkIfCenterIsPerfect(center);
return center;
}
public void checkIfCenterIsPerfect(Point2D.Double center) {
// Not large enough sample size to check
if (this.totalParticles < 25) {
return;
}
int perfectParticles = 0;
for (HealingCircleParticle healingCircleParticle : healingCircleParticles) {
Point2D.Double point = healingCircleParticle.getPoint();
double distance = point.distance(center);
if (distance > (DIAMETER - 1) / 2F && distance < (DIAMETER + 1) / 2F) {
perfectParticles++;
}
}
float percentagePerfect = perfectParticles / (float) totalParticles;
if (percentagePerfect > 0.75) {
this.cachedCenterPoint = center;
}
}
private static Point2D.Double rotatePoint(Point2D.Double point, Point2D.Double center, double degrees) {
double radians = Math.toRadians(degrees);
double newX = center.getX() + (point.getX() - center.getX()) * Math.cos(radians) - (point.getY() - center.getY()) * Math.sin(radians);
double newY = center.getY() + (point.getX() - center.getX()) * Math.sin(radians) + (point.getY() - center.getY()) * Math.cos(radians);
return new Point2D.Double(newX, newY);
}
private static Point2D.Double lineLineIntersection(Point2D.Double a, Point2D.Double b, Point2D.Double c, Point2D.Double d) {
// Line AB represented as a1x + b1y = c1
double a1 = b.y - a.y;
double b1 = a.x - b.x;
double c1 = a1 * (a.x) + b1 * (a.y);
// Line CD represented as a2x + b2y = c2
double a2 = d.y - c.y;
double b2 = c.x - d.x;
double c2 = a2 * (c.x) + b2 * (c.y);
double determinant = a1 * b2 - a2 * b1;
if (determinant == 0) {
// The lines are parallel.
return new Point2D.Double(Double.NaN, Double.NaN);
} else {
double x = (b2 * c1 - b1 * c2) / determinant;
double y = (a1 * c2 - a2 * c1) / determinant;
return new Point2D.Double(x, y);
}
}
public void removeOldParticles() {
Iterator<HealingCircleParticle> healingCircleParticleIterator = this.healingCircleParticles.iterator();
while (healingCircleParticleIterator.hasNext()) {
HealingCircleParticle healingCircleParticle = healingCircleParticleIterator.next();
if (System.currentTimeMillis() - healingCircleParticle.getCreation() > 10000) {
this.totalX -= healingCircleParticle.getPoint().getX();
this.totalZ -= healingCircleParticle.getPoint().getY();
this.totalParticles--;
healingCircleParticleIterator.remove();
}
}
}
public boolean hasCachedCenterPoint() {
return cachedCenterPoint != null;
}
}
| 412 | 0.823079 | 1 | 0.823079 | game-dev | MEDIA | 0.493474 | game-dev | 0.945373 | 1 | 0.945373 |
IlyaBlokh/ECS-Survivors | 1,367 | src/ecs-survivors/Assets/Code/Gameplay/Features/Hero/Behaviours/HeroAnimator.cs | using Code.Gameplay.Common.Visuals;
using DG.Tweening;
using UnityEngine;
namespace Code.Gameplay.Features.Hero.Behaviours
{
public class HeroAnimator : MonoBehaviour, IDamageTakenAnimator
{
private static readonly int OverlayIntensityProperty = Shader.PropertyToID("_OverlayIntensity");
private readonly int _isMovingHash = Animator.StringToHash("isMoving");
private readonly int _attackHash = Animator.StringToHash("attack");
private readonly int _diedHash = Animator.StringToHash("died");
public Animator Animator;
public SpriteRenderer SpriteRenderer;
private Material Material => SpriteRenderer.material;
public void PlayMove() => Animator.SetBool(_isMovingHash, true);
public void PlayIdle() => Animator.SetBool(_isMovingHash, false);
public void PlayAttack() => Animator.SetTrigger(_attackHash);
public void PlayDied() => Animator.SetTrigger(_diedHash);
public void PlayDamageTaken()
{
if (DOTween.IsTweening(Material))
return;
Material.DOFloat(0.5f, OverlayIntensityProperty, 0.15f)
.OnComplete(() =>
{
if (SpriteRenderer)
Material.DOFloat(0, OverlayIntensityProperty, 0.15f);
});
}
public void ResetAll()
{
Animator.ResetTrigger(_attackHash);
Animator.ResetTrigger(_diedHash);
}
}
} | 412 | 0.881264 | 1 | 0.881264 | game-dev | MEDIA | 0.984512 | game-dev | 0.96717 | 1 | 0.96717 |
b-crawl/bcrawl | 2,474 | crawl-ref/source/spl-goditem.h | #pragma once
#include "enchant-type.h"
#include "holy-word-source-type.h"
#include "spell-type.h"
#include "spl-cast.h"
#include "torment-source-type.h"
spret cast_healing(int pow, bool fail);
bool heal_monster(monster& patient, int amount);
/// List of monster enchantments which can be dispelled.
const enchant_type dispellable_enchantments[] =
{
ENCH_SLOW,
ENCH_HASTE,
ENCH_SWIFT,
ENCH_MIGHT,
ENCH_AGILE,
ENCH_FEAR,
ENCH_CONFUSION,
ENCH_CORONA,
ENCH_SILVER_CORONA,
ENCH_CHARM,
ENCH_PARALYSIS,
ENCH_PETRIFYING,
ENCH_PETRIFIED,
ENCH_REGENERATION,
ENCH_TP,
ENCH_INNER_FLAME,
ENCH_OZOCUBUS_ARMOUR,
ENCH_INJURY_BOND,
ENCH_DIMENSION_ANCHOR,
ENCH_TOXIC_RADIANCE,
ENCH_AGILE,
ENCH_BLACK_MARK,
ENCH_SHROUD,
ENCH_SAP_MAGIC,
ENCH_REPEL_MISSILES,
ENCH_DEFLECT_MISSILES,
ENCH_RESISTANCE,
ENCH_HEXED,
ENCH_PAIN_BOND,
ENCH_IDEALISED,
ENCH_INSANE,
ENCH_BOUND_SOUL,
};
bool player_is_debuffable();
void debuff_player();
bool monster_is_debuffable(const monster &mon);
void debuff_monster(monster &mon);
int detect_items(int pow);
int detect_creatures(int pow, bool telepathic = false);
bool remove_curse(bool alreadyknown = true, const string &pre_msg = "");
#if TAG_MAJOR_VERSION == 34
bool curse_item(bool armour, const string &pre_msg = "");
#endif
bool entomb(int pow);
bool cast_imprison(int pow, monster* mons, int source);
bool cast_smiting(int pow, monster* mons);
string unpacifiable_reason(const monster& mon);
string unpacifiable_reason(const monster_info& mi);
struct bolt;
void holy_word(int pow, holy_word_source_type source, const coord_def& where,
bool silent = false, actor *attacker = nullptr);
void holy_word_monsters(coord_def where, int pow, holy_word_source_type source,
actor *attacker = nullptr);
void holy_word_player(holy_word_source_type source);
void torment(actor *attacker, torment_source_type taux, const coord_def& where);
void torment_cell(coord_def where, actor *attacker, torment_source_type taux);
void torment_player(actor *attacker, torment_source_type taux);
void setup_cleansing_flame_beam(bolt &beam, int pow, int caster,
coord_def where, actor *attacker = nullptr);
void cleansing_flame(int pow, int caster, coord_def where,
actor *attacker = nullptr);
spret cast_random_effects(int pow, bolt& beam, bool fail);
| 412 | 0.901419 | 1 | 0.901419 | game-dev | MEDIA | 0.947898 | game-dev | 0.729329 | 1 | 0.729329 |
ChromeGaming/GameSphere | 10,229 | SinglePlayer - Games/ArmorAlley/script/UI/Tutorial.js | import { game } from '../core/Game.js';
import { utils } from '../core/utils.js';
import { TYPES, FPS } from '../core/global.js';
import { countFriendly, countSides } from '../core/logic.js';
import { TutorialStep } from './TutorialStep.js';
import { common } from '../core/common.js';
const Tutorial = () => {
let config, css, data, dom, exports;
function addStep(options) {
config.steps.push(TutorialStep(options));
}
function initDOM() {
dom.o = document.getElementById('tutorial');
dom.oList = document.getElementById('tutorial-list').getElementsByTagName('li');
dom.oTutorialWindow = document.getElementById('tutorial-window');
data.steps = dom.oList.length;
utils.css.add(game.dom.world, 'tutorial-mode');
}
function selectItem(i) {
dom.lastItem = dom.oList[i];
data.step = i;
document.getElementById('tutorial-body').innerHTML = dom.lastItem.innerHTML;
updateHighlightControls(data.step, true);
// animate immediately, twice; first to activate, second to check for completion. useful if this step has already been passed, etc.
if (data.step > 0 && config.steps[data.step]) {
config.steps[data.step].animate();
config.steps[data.step].animate();
}
}
function nextItem() {
updateHighlightControls(data.step, false);
selectItem(data.step + 1);
}
function updateHighlightControls(step, active) {
if (!config.steps[step]) return;
// mobile-only: data-for="bombs" (e.g.) attributes of nodes to highlight to user
const { highlightControls } = config.steps[step];
if (!highlightControls) return;
const oControls = document.getElementById('mobile-controls');
if (!oControls) return;
const query = highlightControls.map((type) => `[data-for="${type}"]`).join(',');
oControls.querySelectorAll(query).forEach((node) => utils.css.addOrRemove(node, active, css.getUserAttention));
}
function animate() {
// "runtime" for tutorial
if (data.frameCount % data.animateModulus === 0 && data.step !== null && config.steps[data.step]) {
config.steps[data.step].animate();
}
data.frameCount++;
}
function initTutorial() {
let temp;
initDOM();
utils.css.add(dom.o, css.active);
common.setFrameTimeout(() => utils.css.add(dom.oTutorialWindow, css.active), 1000);
addStep({
// introduction
highlightControls: ['guns', 'bombs'],
animate() {
// the player's helicopter.
const chopper = game.players.local, chopperData = chopper.data;
// condition for completion
return (
chopperData.ammo < chopperData.maxAmmo
&& chopperData.bombs < chopperData.maxBombs
);
},
complete() {
nextItem();
}
});
addStep({
// helicopter refuel/repair
animate() {
let chopper = game.players.local;
// player either landed and refueled, or died. ;)
return chopper.data.repairComplete;
},
complete() {
nextItem();
}
});
addStep({
// look, ma! bad guys!
activate() {
game.addObject(TYPES.tank, {
x: 1536,
isEnemy: true
});
game.addObject(TYPES.tank, {
x: 1536 + 70,
isEnemy: true
});
game.addObject(TYPES.tank, {
x: 1536 + 140,
isEnemy: true
});
game.addObject(TYPES.van, {
x: 1536 + 210,
isEnemy: true
});
},
animate() {
const counts = [countSides(TYPES.tank), countSides(TYPES.van)];
return (!counts[0].enemy && !counts[1].enemy);
},
complete() {
nextItem();
}
});
addStep({
// pick up a full load of infantry
highlightControls: ['inventory', 'infantry'],
animate() {
return (game.players.local.data.parachutes >= game.players.local.data.maxParachutes);
},
complete() {
nextItem();
}
});
addStep({
// claim a nearby enemy bunker
highlightControls: ['parachute-infantry'],
activate() {
let targetBunker, i, j;
for (i = 0, j = game.objects.bunker.length; i < j; i++) {
if (!game.objects.bunker[i].data.dead) {
targetBunker = game.objects.bunker[i];
break;
}
}
if (targetBunker) {
// ensure the first bunker is an enemy one.
targetBunker.capture(true);
// ... and has a balloon
targetBunker.repair();
// keep track of original bunker states
temp = countSides(TYPES.bunker);
} else {
// edge case: bunker has already been blown up, etc. bail.
temp = countSides(TYPES.bunker);
// next animate() call will pick this up and move to next step.
temp.enemy++;
}
},
animate() {
let bunkers = countSides(TYPES.bunker);
// a bunker was blown up, or claimed.
return (bunkers.enemy < temp.enemy);
},
complete() {
nextItem();
}
});
addStep({
// claim a nearby enemy Super Bunker
highlightControls: ['parachute-infantry'],
activate() {
let targetSuperBunker = game.objects[TYPES.superBunker][0];
if (targetSuperBunker) {
// make it an enemy unit, if not already.
targetSuperBunker.capture(true);
// and arm it with infantry, such that 3 infantry will claim it.
targetSuperBunker.data.energy = 2;
// keep track of original bunker states
temp = countSides(TYPES.superBunker);
} else {
// edge case: bunker has already been blown up, etc. bail.
temp = countSides(TYPES.superBunker);
// next animate() call will pick this up and move to next step.
temp.enemy++;
}
},
animate() {
let superBunkers = countSides(TYPES.superBunker);
// a Super Bunker was claimed.
return (superBunkers.enemy < temp.enemy);
},
complete() {
nextItem();
}
});
addStep({
// order a Missile launcher, Tank, Van
highlightControls: ['inventory', 'missile-launcher', 'tank', 'van'],
animate() {
let item, counts, isComplete;
// innocent until proven guilty.
isComplete = true;
counts = {
missileLaunchers: countFriendly(TYPES.missileLauncher),
tanks: countFriendly(TYPES.tank),
vans: countFriendly(TYPES.van)
};
for (item in counts) {
if (!counts[item]) {
isComplete = false;
}
}
return isComplete;
},
complete() {
nextItem();
}
});
addStep({
// destroy the enemy chopper!
activate() {
// make sure enemy helicopter is present
if (game.objects.helicopter.length < 2) {
// two screenfuls away, OR end of battlefield - whichever is less
game.addObject(TYPES.helicopter, {
isEnemy: true,
isCPU: true,
x: Math.min(game.players.local.data.x + (game.objects.view.data.browser.width * 2), game.objects.view.data.battleField.width - 64),
y: 72,
// give the player a serious advantage, here.
fireModulus: FPS / 3,
vX: 0
});
}
},
animate() {
return game.objects.helicopter[1].data.dead;
},
complete() {
nextItem();
}
});
addStep({
// defeat an incoming smart missile
activate() {
let missileX;
// dis-arm superBunker so it doesn't kill incoming missile launchers, etc.
game.objects[TYPES.superBunker][0].data.energy = 0;
missileX = Math.min(game.players.local.data.x + (game.objects.view.data.browser.width * 2), game.objects.view.data.battleField.width - 64);
// make ze missile launcher
game.addObject(TYPES.missileLauncher, {
x: missileX,
isEnemy: true
});
game.addObject(TYPES.missileLauncher, {
x: missileX + 64,
isEnemy: true
});
},
animate() {
return (countSides(TYPES.missileLauncher).enemy === 0 && countSides(TYPES.smartMissile).enemy === 0);
},
complete() {
nextItem();
}
});
addStep({
// rebuild the first friendly, dead turret
highlightControls: ['inventory', 'engineer'],
animate() {
const t = game.objects[TYPES.turret][0].data;
return (
!t.isEnemy
&& !t.dead
&& t.energy === t.energyMax
);
},
complete() {
nextItem();
}
});
addStep({
// destroy (or claim) the first enemy turret
activate() {
let turrets, engineer, complete;
turrets = game.objects[TYPES.turret];
engineer = null;
complete = true;
// bring the mid-level turrets[1] and [2] to life.
turrets[1].repair(engineer, complete);
turrets[2].repair(engineer, complete);
},
animate() {
const turrets = game.objects[TYPES.turret];
return (!turrets[1].data.isEnemy || turrets[1].data.dead || !turrets[2].data.isEnemy || turrets[2].data.dead);
},
complete() {
nextItem();
}
});
addStep({
// earn 50 funds
animate() {
return (game.objects[TYPES.endBunker][0].data.funds >= 50);
},
complete() {
nextItem();
}
});
// and begin
selectItem(0);
}
config = {
steps: []
};
css = {
active: 'active',
getUserAttention: 'get-user-attention'
};
data = {
frameCount: 0,
animateModulus: FPS / 2,
step: 0,
steps: 0
};
dom = {
o: null,
oList: null,
oTutorialWindow: null,
lastItem: null
};
exports = {
animate,
selectItem
};
initTutorial();
return exports;
};
export { Tutorial }; | 412 | 0.846283 | 1 | 0.846283 | game-dev | MEDIA | 0.875032 | game-dev | 0.950256 | 1 | 0.950256 |
ProjectIgnis/CardScripts | 1,429 | official/c34143852.lua | --H・C エクストラ・ソード
--Heroic Challenger - Extra Sword
local s,id=GetID()
function s.initial_effect(c)
--effect gain
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_BE_MATERIAL)
e1:SetCondition(s.efcon)
e1:SetOperation(s.efop)
c:RegisterEffect(e1)
end
function s.efcon(e,tp,eg,ep,ev,re,r,rp)
return r==REASON_XYZ
end
function s.efop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local rc=c:GetReasonCard()
local e1=Effect.CreateEffect(rc)
e1:SetDescription(aux.Stringid(id,0))
e1:SetCategory(CATEGORY_ATKCHANGE)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e1:SetCode(EVENT_SPSUMMON_SUCCESS)
e1:SetCondition(s.atkcon)
e1:SetOperation(s.atkop)
e1:SetReset(RESET_EVENT|RESETS_STANDARD)
rc:RegisterEffect(e1,true)
if not rc:IsType(TYPE_EFFECT) then
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_ADD_TYPE)
e2:SetValue(TYPE_EFFECT)
e2:SetReset(RESET_EVENT|RESETS_STANDARD)
rc:RegisterEffect(e2,true)
end
end
function s.atkcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsXyzSummoned()
end
function s.atkop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) and c:IsFaceup() then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(1000)
e1:SetReset(RESET_EVENT|RESETS_STANDARD_DISABLE)
c:RegisterEffect(e1)
end
end | 412 | 0.841944 | 1 | 0.841944 | game-dev | MEDIA | 0.829138 | game-dev | 0.671361 | 1 | 0.671361 |
chongdashu/unreal-mcp | 2,323 | MCPGameProject/Plugins/UnrealMCP/Source/UnrealMCP/Private/Commands/UnrealMCPProjectCommands.cpp | #include "Commands/UnrealMCPProjectCommands.h"
#include "Commands/UnrealMCPCommonUtils.h"
#include "GameFramework/InputSettings.h"
FUnrealMCPProjectCommands::FUnrealMCPProjectCommands()
{
}
TSharedPtr<FJsonObject> FUnrealMCPProjectCommands::HandleCommand(const FString& CommandType, const TSharedPtr<FJsonObject>& Params)
{
if (CommandType == TEXT("create_input_mapping"))
{
return HandleCreateInputMapping(Params);
}
return FUnrealMCPCommonUtils::CreateErrorResponse(FString::Printf(TEXT("Unknown project command: %s"), *CommandType));
}
TSharedPtr<FJsonObject> FUnrealMCPProjectCommands::HandleCreateInputMapping(const TSharedPtr<FJsonObject>& Params)
{
// Get required parameters
FString ActionName;
if (!Params->TryGetStringField(TEXT("action_name"), ActionName))
{
return FUnrealMCPCommonUtils::CreateErrorResponse(TEXT("Missing 'action_name' parameter"));
}
FString Key;
if (!Params->TryGetStringField(TEXT("key"), Key))
{
return FUnrealMCPCommonUtils::CreateErrorResponse(TEXT("Missing 'key' parameter"));
}
// Get the input settings
UInputSettings* InputSettings = GetMutableDefault<UInputSettings>();
if (!InputSettings)
{
return FUnrealMCPCommonUtils::CreateErrorResponse(TEXT("Failed to get input settings"));
}
// Create the input action mapping
FInputActionKeyMapping ActionMapping;
ActionMapping.ActionName = FName(*ActionName);
ActionMapping.Key = FKey(*Key);
// Add modifiers if provided
if (Params->HasField(TEXT("shift")))
{
ActionMapping.bShift = Params->GetBoolField(TEXT("shift"));
}
if (Params->HasField(TEXT("ctrl")))
{
ActionMapping.bCtrl = Params->GetBoolField(TEXT("ctrl"));
}
if (Params->HasField(TEXT("alt")))
{
ActionMapping.bAlt = Params->GetBoolField(TEXT("alt"));
}
if (Params->HasField(TEXT("cmd")))
{
ActionMapping.bCmd = Params->GetBoolField(TEXT("cmd"));
}
// Add the mapping
InputSettings->AddActionMapping(ActionMapping);
InputSettings->SaveConfig();
TSharedPtr<FJsonObject> ResultObj = MakeShared<FJsonObject>();
ResultObj->SetStringField(TEXT("action_name"), ActionName);
ResultObj->SetStringField(TEXT("key"), Key);
return ResultObj;
} | 412 | 0.841684 | 1 | 0.841684 | game-dev | MEDIA | 0.689386 | game-dev | 0.797036 | 1 | 0.797036 |
Apress/physically-based-shader-dev-for-unity-2017 | 3,390 | PostProcessingv2/Assets/PostProcessing/PostProcessing/Editor/PostProcessDebugEditor.cs | using UnityEngine;
using UnityEngine.Rendering.PostProcessing;
namespace UnityEditor.Rendering.PostProcessing
{
[CustomEditor(typeof(PostProcessDebug))]
public sealed class PostProcessDebugEditor : BaseEditor<PostProcessDebug>
{
SerializedProperty m_PostProcessLayer;
SerializedProperty m_LightMeterEnabled;
SerializedProperty m_HistogramEnabled;
SerializedProperty m_WaveformEnabled;
SerializedProperty m_VectorscopeEnabled;
SerializedObject m_Monitors;
SerializedProperty m_LightMeterShowCurves;
SerializedProperty m_HistogramChannel;
SerializedProperty m_WaveformExposure;
SerializedProperty m_VectorscopeExposure;
void OnEnable()
{
m_PostProcessLayer = FindProperty(x => x.postProcessLayer);
m_LightMeterEnabled = FindProperty(x => x.lightMeter);
m_HistogramEnabled = FindProperty(x => x.histogram);
m_WaveformEnabled = FindProperty(x => x.waveform);
m_VectorscopeEnabled = FindProperty(x => x.vectorscope);
if (m_PostProcessLayer.objectReferenceValue != null)
RebuildProperties();
}
void RebuildProperties()
{
if (m_PostProcessLayer.objectReferenceValue == null)
return;
m_Monitors = new SerializedObject(m_Target.postProcessLayer);
m_LightMeterShowCurves = m_Monitors.FindProperty("monitors.lightMeter.showCurves");
m_HistogramChannel = m_Monitors.FindProperty("monitors.histogram.channel");
m_WaveformExposure = m_Monitors.FindProperty("monitors.waveform.exposure");
m_VectorscopeExposure = m_Monitors.FindProperty("monitors.vectorscope.exposure");
}
public override void OnInspectorGUI()
{
serializedObject.Update();
using (var changed = new EditorGUI.ChangeCheckScope())
{
EditorGUILayout.PropertyField(m_PostProcessLayer);
if (changed.changed)
RebuildProperties();
}
if (m_PostProcessLayer.objectReferenceValue != null)
{
m_Monitors.Update();
DoMonitorGUI(EditorUtilities.GetContent("Light Meter"), m_LightMeterEnabled, m_LightMeterShowCurves);
DoMonitorGUI(EditorUtilities.GetContent("Histogram"), m_HistogramEnabled, m_HistogramChannel);
DoMonitorGUI(EditorUtilities.GetContent("Waveform"), m_WaveformEnabled, m_WaveformExposure);
DoMonitorGUI(EditorUtilities.GetContent("Vectoscope"), m_VectorscopeEnabled, m_VectorscopeExposure);
m_Monitors.ApplyModifiedProperties();
}
serializedObject.ApplyModifiedProperties();
}
void DoMonitorGUI(GUIContent content, SerializedProperty prop, params SerializedProperty[] settings)
{
EditorGUILayout.PropertyField(prop, content);
if (settings == null || settings.Length == 0)
return;
if (prop.boolValue)
{
EditorGUI.indentLevel++;
foreach (var p in settings)
EditorGUILayout.PropertyField(p);
EditorGUI.indentLevel--;
EditorGUILayout.Space();
}
}
}
}
| 412 | 0.714873 | 1 | 0.714873 | game-dev | MEDIA | 0.400494 | game-dev | 0.930876 | 1 | 0.930876 |
teeworlds/teeworlds | 5,510 | src/game/client/components/countryflags.cpp | /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
/* If you are missing that file, acquire a complete release at teeworlds.com. */
#include <base/math.h>
#include <base/system.h>
#include <engine/console.h>
#include <engine/graphics.h>
#include <engine/storage.h>
#include <engine/textrender.h>
#include <engine/shared/jsonparser.h>
#include <engine/shared/config.h>
#include "menus.h"
#include "countryflags.h"
void CCountryFlags::LoadCountryflagsIndexfile()
{
CJsonParser JsonParser;
const json_value *pJsonData = JsonParser.ParseFile("countryflags/index.json", Storage());
if(pJsonData == 0)
{
Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "countryflags", JsonParser.Error());
return;
}
// extract data
const json_value &rInit = (*pJsonData)["country codes"];
if(rInit.type == json_object)
{
enum
{
NUM_INDICES = 2,
};
const char *paIndices[NUM_INDICES] = {"custom", "ISO 3166-1"};
for(int Index = 0; Index < NUM_INDICES; ++Index)
{
const json_value &rStart = rInit[(const char *)paIndices[Index]];
if(rStart.type == json_array)
{
for(unsigned i = 0; i < rStart.u.array.length; ++i)
{
char aBuf[64];
// validate country code
int CountryCode = (json_int_t)rStart[i]["code"];
if(CountryCode < CODE_LB || CountryCode > CODE_UB)
{
str_format(aBuf, sizeof(aBuf), "country code '%i' not within valid code range [%i..%i]", CountryCode, CODE_LB, CODE_UB);
Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "countryflags", aBuf);
continue;
}
// add entry
const char *pCountryName = rStart[i]["id"];
CCountryFlag CountryFlag;
CountryFlag.m_CountryCode = CountryCode;
str_copy(CountryFlag.m_aCountryCodeString, pCountryName, sizeof(CountryFlag.m_aCountryCodeString));
if(Config()->m_ClLoadCountryFlags)
{
// load the graphic file
CImageInfo Info;
str_format(aBuf, sizeof(aBuf), "countryflags/%s.png", pCountryName);
if(!Graphics()->LoadPNG(&Info, aBuf, IStorage::TYPE_ALL))
{
char aMsg[64];
str_format(aMsg, sizeof(aMsg), "failed to load '%s'", aBuf);
Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "countryflags", aMsg);
continue;
}
CountryFlag.m_Texture = Graphics()->LoadTextureRaw(Info.m_Width, Info.m_Height, Info.m_Format, Info.m_pData, Info.m_Format, 0);
mem_free(Info.m_pData);
}
// blocked?
CountryFlag.m_Blocked = false;
const json_value Check = rStart[i]["blocked"];
if(Check.type == json_boolean && Check)
CountryFlag.m_Blocked = true;
m_aCountryFlags.add_unsorted(CountryFlag);
// print message
if(Config()->m_Debug)
{
str_format(aBuf, sizeof(aBuf), "loaded country flag '%s'", pCountryName);
Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "countryflags", aBuf);
}
}
}
}
}
// clean up
m_aCountryFlags.sort_range();
// find index of default item
int DefaultIndex = 0, Index = 0;
for(sorted_array<CCountryFlag>::range r = m_aCountryFlags.all(); !r.empty(); r.pop_front(), ++Index)
if(r.front().m_CountryCode == -1)
{
DefaultIndex = Index;
break;
}
// init LUT
if(DefaultIndex != 0)
for(int i = 0; i < CODE_RANGE; ++i)
m_CodeIndexLUT[i] = DefaultIndex;
else
mem_zero(m_CodeIndexLUT, sizeof(m_CodeIndexLUT));
for(int i = 0; i < m_aCountryFlags.size(); ++i)
m_CodeIndexLUT[maximum(0, (m_aCountryFlags[i].m_CountryCode-CODE_LB)%CODE_RANGE)] = i;
}
int CCountryFlags::GetInitAmount() const
{
return 10;
}
void CCountryFlags::OnInit()
{
// load country flags
m_aCountryFlags.clear();
LoadCountryflagsIndexfile();
if(!m_aCountryFlags.size())
{
Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "countryflags", "failed to load country flags. folder='countryflags/'");
CCountryFlag DummyEntry;
DummyEntry.m_CountryCode = -1;
DummyEntry.m_Blocked = false;
mem_zero(DummyEntry.m_aCountryCodeString, sizeof(DummyEntry.m_aCountryCodeString));
m_aCountryFlags.add(DummyEntry);
}
m_pClient->m_pMenus->RenderLoading(10);
}
int CCountryFlags::Num() const
{
return m_aCountryFlags.size();
}
const CCountryFlags::CCountryFlag *CCountryFlags::GetByCountryCode(int CountryCode) const
{
return GetByIndex(m_CodeIndexLUT[maximum(0, (CountryCode-CODE_LB)%CODE_RANGE)]);
}
const CCountryFlags::CCountryFlag *CCountryFlags::GetByIndex(int Index, bool SkipBlocked) const
{
if(SkipBlocked)
{
for(int i = 0; i < m_aCountryFlags.size(); i++)
if(!m_aCountryFlags[i].m_Blocked)
if(!Index--)
return &m_aCountryFlags[i];
}
return &m_aCountryFlags[maximum(0, Index%m_aCountryFlags.size())];
}
void CCountryFlags::Render(int CountryCode, const vec4 *pColor, float x, float y, float w, float h, bool AllowBlocked)
{
const CCountryFlag *pFlag = GetByCountryCode(CountryCode);
if(!AllowBlocked && pFlag->m_Blocked)
pFlag = GetByCountryCode(-1);
if(pFlag->m_Texture.IsValid())
{
Graphics()->TextureSet(pFlag->m_Texture);
Graphics()->QuadsBegin();
Graphics()->SetColor(pColor->r*pColor->a, pColor->g*pColor->a, pColor->b*pColor->a, pColor->a);
IGraphics::CQuadItem QuadItem(x, y, w, h);
Graphics()->QuadsDrawTL(&QuadItem, 1);
Graphics()->QuadsEnd();
}
else
{
static CTextCursor s_Cursor(10.0f);
s_Cursor.Reset();
s_Cursor.MoveTo(x+w/2, y+h/2);
s_Cursor.m_MaxLines = w;
s_Cursor.m_Align = TEXTALIGN_MC;
TextRender()->TextOutlined(&s_Cursor, pFlag->m_aCountryCodeString, -1);
}
}
| 412 | 0.875216 | 1 | 0.875216 | game-dev | MEDIA | 0.318184 | game-dev | 0.943834 | 1 | 0.943834 |
Huan912/SleepyHook-Plus-TW-CB2 | 3,488 | SleepyHook Plus/HLSDK/engine/custom.h | /***
*
* Copyright (c) 1996-2002, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
// Customization.h
#ifndef CUSTOM_H
#define CUSTOM_H
#ifdef _WIN32
#pragma once
#endif
#include "const.h"
#define MAX_QPATH 64 // Must match value in quakedefs.h
/////////////////
// Customization
// passed to pfnPlayerCustomization
// For automatic downloading.
typedef enum
{
t_sound = 0,
t_skin,
t_model,
t_decal,
t_generic,
t_eventscript,
t_world, // Fake type for world, is really t_model
} resourcetype_t;
typedef struct
{
int size;
} _resourceinfo_t;
typedef struct resourceinfo_s
{
_resourceinfo_t info[ 8 ];
} resourceinfo_t;
#define RES_FATALIFMISSING (1<<0) // Disconnect if we can't get this file.
#define RES_WASMISSING (1<<1) // Do we have the file locally, did we get it ok?
#define RES_CUSTOM (1<<2) // Is this resource one that corresponds to another player's customization
// or is it a server startup resource.
#define RES_REQUESTED (1<<3) // Already requested a download of this one
#define RES_PRECACHED (1<<4) // Already precached
#include "crc.h"
typedef struct resource_s
{
char szFileName[MAX_QPATH]; // File name to download/precache.
resourcetype_t type; // t_sound, t_skin, t_model, t_decal.
int nIndex; // For t_decals
int nDownloadSize; // Size in Bytes if this must be downloaded.
unsigned char ucFlags;
// For handling client to client resource propagation
unsigned char rgucMD5_hash[16]; // To determine if we already have it.
unsigned char playernum; // Which player index this resource is associated with, if it's a custom resource.
unsigned char rguc_reserved[ 32 ]; // For future expansion
struct resource_s *pNext; // Next in chain.
struct resource_s *pPrev;
} resource_t;
typedef struct customization_s
{
qboolean bInUse; // Is this customization in use;
resource_t resource; // The resource_t for this customization
qboolean bTranslated; // Has the raw data been translated into a useable format?
// (e.g., raw decal .wad make into texture_t *)
int nUserData1; // Customization specific data
int nUserData2; // Customization specific data
void *pInfo; // Buffer that holds the data structure that references the data (e.g., the cachewad_t)
void *pBuffer; // Buffer that holds the data for the customization (the raw .wad data)
struct customization_s *pNext; // Next in chain
} customization_t;
#define FCUST_FROMHPAK ( 1<<0 )
#define FCUST_WIPEDATA ( 1<<1 )
#define FCUST_IGNOREINIT ( 1<<2 )
void COM_ClearCustomizationList( struct customization_s *pHead, qboolean bCleanDecals);
qboolean COM_CreateCustomization( struct customization_s *pListHead, struct resource_s *pResource, int playernumber, int flags,
struct customization_s **pCustomization, int *nLumps );
int COM_SizeofResourceList ( struct resource_s *pList, struct resourceinfo_s *ri );
#endif // CUSTOM_H
| 412 | 0.883284 | 1 | 0.883284 | game-dev | MEDIA | 0.497138 | game-dev,graphics-rendering | 0.524546 | 1 | 0.524546 |
Dimbreath/AzurLaneData | 4,346 | zh-CN/mod/backyard/view/furnituredescwindow.lua | slot0 = class("FurnitureDescWindow")
function slot0.Ctor(slot0, slot1)
pg.DelegateInfo.New(slot0)
slot0._go = slot1
slot0.descPanel = tf(slot1)
slot0.maxFrame = findTF(slot0.descPanel, "max_panel")
slot0.maxPanel = findTF(slot0.maxFrame, "max")
slot0.maxIcon = findTF(slot0.maxPanel, "desc/iconframe/icon"):GetComponent(typeof(Image))
slot0.maxName = findTF(slot0.maxPanel, "desc/Text"):GetComponent(typeof(Text))
slot0.maxType = findTF(slot0.maxPanel, "desc/container/frame/type"):GetComponent(typeof(Text))
slot0.maxContent = findTF(slot0.maxPanel, "desc/container/frame/content"):GetComponent(typeof(Text))
slot0.maxComfortable = findTF(slot0.maxPanel, "desc/container/frame/comfortable_container/Text"):GetComponent(typeof(Text))
slot0.maxApproach = findTF(slot0.maxPanel, "desc/container/frame/approach_container/Text"):GetComponent(typeof(Text))
slot0.maxdate = findTF(slot0.maxPanel, "desc/container/frame/date_container/Text"):GetComponent(typeof(Text))
slot0.descPanelParent = slot0.descPanel.parent
slot0.descPanelVoiceBtn = findTF(slot0.maxPanel, "desc/container/frame/voice")
slot0.descPanelBgVoiceBtn = findTF(slot0.maxPanel, "desc/container/frame/bg_voice")
slot0.descPanelBgVoiceMark = findTF(slot0.maxPanel, "desc/container/frame/bg_voice/mark")
slot0:Init()
end
function slot0.Init(slot0)
onButton(slot0, slot0.descPanel, function ()
uv0:Close()
end, SFX_PANEL)
onButton(slot0, slot0.maxFrame, function ()
uv0:Close()
end, SFX_PANEL)
onButton(slot0, slot0.maxPanel:Find("ok_btn"), function ()
uv0:Close()
end, SFX_PANEL)
onButton(slot0, slot0.descPanelVoiceBtn, function ()
slot0, slot1 = uv0.furnitureVO:getVoice()
pg.CriMgr.GetInstance():PlaySoundEffect_V3(slot0)
uv0.curVoiceKey = slot0
print(slot0, slot1.action)
if uv0.onPlaySound then
uv0.onPlaySound(uv0.furnitureVO.id, true, slot1)
end
end, SFX_PANEL)
onButton(slot0, slot0.descPanelBgVoiceBtn, function ()
function slot0()
slot0, slot1 = uv0.furnitureVO:getVoice()
playBGM(slot0)
if uv0.onPlaySound then
uv0.onPlaySound(uv0.furnitureVO.id, true, slot1)
end
uv0.playData = {
id = uv0.furnitureVO.id,
effect = slot1.effect
}
setActive(uv0.descPanelBgVoiceMark, true)
end
if uv0.playData and uv0.playData.id == uv0.furnitureVO.id then
playBGM("backyard")
if uv0.onPlaySound then
uv0.onPlaySound(uv0.furnitureVO.id, false, {
action = "normal",
effect = uv0.playData.effect
})
end
setActive(uv0.descPanelBgVoiceMark, false)
uv0.playData = nil
elseif uv0.playData and uv0.playData.id ~= uv0.furnitureVO.id then
if uv0.onPlaySound then
uv0.onPlaySound(uv0.playData.id, false, {
action = "normal",
effect = uv0.playData.effect
})
end
uv0.playData = nil
slot0()
else
slot0()
end
end, SFX_PANEL)
end
function slot0.SetUp(slot0, slot1)
slot0.onPlaySound = slot1
end
function slot0.Show(slot0, slot1)
slot0.furnitureVO = slot1
slot3 = slot1:descVoiceType()
setActive(slot0.descPanelVoiceBtn, slot1:existVoice() and slot3 == BackYardConst.SOUND_TYPE_EFFECT)
setActive(slot0.descPanelBgVoiceBtn, slot2 and slot3 == BackYardConst.SOUND_TYPE_BG)
setActive(slot0.descPanel, true)
SetActive(slot0.maxFrame, false)
setActive(slot0.descPanelBgVoiceMark, slot0.playData and slot0.playData.id == slot1.id)
LoadSpriteAsync("FurnitureIcon/" .. slot1:getConfig("icon"), function (slot0)
if not uv0.exited then
uv0.maxIcon.sprite = slot0
end
end)
setActive(slot0.maxFrame, true)
slot0.maxName.text = shortenString(slot1:getConfig("name"), 6)
slot0.maxdate.text = slot1:getDate()
slot0.maxComfortable.text = "+" .. slot1:getConfig("comfortable")
slot0.maxContent.text = slot1:getConfig("describe")
slot0.maxApproach.text = slot1:getGainby()
slot0.maxType.text = slot1:getChineseType()
pg.UIMgr.GetInstance():BlurPanel(slot0.maxFrame)
end
function slot0.Close(slot0)
slot0:stopCV()
setActive(slot0.descPanel, false)
pg.UIMgr.GetInstance():UnblurPanel(slot0.maxFrame, slot0.descPanel)
end
function slot0.stopCV(slot0)
if slot0.curVoiceKey then
pg.CriMgr.GetInstance():UnloadSoundEffect_V3(slot0.curVoiceKey)
slot0.curVoiceKey = nil
end
end
function slot0.Destroy(slot0)
slot0.playData = nil
slot0.exited = true
slot0:Close()
pg.DelegateInfo.Dispose(slot0)
end
return slot0
| 412 | 0.645959 | 1 | 0.645959 | game-dev | MEDIA | 0.824026 | game-dev | 0.942004 | 1 | 0.942004 |
SimpleSSD/SimpleSSD-FullSystem | 3,289 | src/dev/storage/def.cc | /*
* Copyright (C) 2017 CAMELab
*
* This file is part of SimpleSSD.
*
* SimpleSSD 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.
*
* SimpleSSD 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 SimpleSSD. If not, see <http://www.gnu.org/licenses/>.
*/
#include "dev/storage/def.hh"
#undef panic
#undef warn
#undef info
#include "dev/storage/simplessd/util/simplessd.hh"
void ExitCallback::autoDestruct() { delete this; }
void ExitCallback::process() { releaseSimpleSSDEngine(); }
EventEngine::EventEngine(SimObject *s) : pObject(s), counter(0) {}
uint64_t EventEngine::getCurrentTick() { return curTick(); }
SimpleSSD::Event EventEngine::allocateEvent(SimpleSSD::EventFunction func) {
std::string name("SimpleSSD_Event_");
name += std::to_string(counter++);
auto iter = eventList.insert(
{counter, EventFunctionWrapper([func]() { func(curTick()); }, name)});
if (!iter.second) {
SimpleSSD::panic("Fail to allocate event");
}
return counter;
}
void EventEngine::scheduleEvent(SimpleSSD::Event eid, uint64_t tick) {
auto iter = eventList.find(eid);
if (pObject == nullptr) {
SimpleSSD::panic("SimObject not initialized");
}
if (iter != eventList.end()) {
uint64_t now = curTick();
if (tick < now) {
SimpleSSD::warn("Tried to schedule %" PRIu64
" < curTick() to event %" PRIu64
". Set tick as curTick().",
tick, eid);
tick = now;
}
if (iter->second.scheduled()) {
SimpleSSD::warn("Event %" PRIu64 " rescheduled from %" PRIu64
" to %" PRIu64,
eid, iter->second.when(), tick);
pObject->reschedule(iter->second, tick);
} else {
pObject->schedule(iter->second, tick);
}
} else {
SimpleSSD::panic("Event %" PRIu64 " does not exists", eid);
}
}
void EventEngine::descheduleEvent(SimpleSSD::Event eid) {
auto iter = eventList.find(eid);
if (pObject == nullptr) {
SimpleSSD::panic("SimObject not initialized");
}
if (iter != eventList.end()) {
if (iter->second.scheduled()) {
pObject->deschedule(iter->second);
}
} else {
SimpleSSD::panic("Event %" PRIu64 " does not exists", eid);
}
}
bool EventEngine::isScheduled(SimpleSSD::Event eid, uint64_t *pTick) {
bool ret = false;
auto iter = eventList.find(eid);
if (iter != eventList.end()) {
ret = iter->second.scheduled();
if (pTick) {
*pTick = iter->second.when();
}
} else {
SimpleSSD::panic("Event %" PRIu64 " does not exists", eid);
}
return ret;
}
void EventEngine::deallocateEvent(SimpleSSD::Event eid) {
auto iter = eventList.find(eid);
if (iter != eventList.end()) {
eventList.erase(iter);
} else {
SimpleSSD::panic("Event %" PRIu64 " does not exists", eid);
}
}
| 412 | 0.830744 | 1 | 0.830744 | game-dev | MEDIA | 0.881895 | game-dev | 0.961748 | 1 | 0.961748 |
ReadyTalk/avian | 9,067 | classpath/java/util/regex/CharacterMatcher.java | /* Copyright (c) 2008-2015, Avian Contributors
Permission to use, copy, modify, and/or distribute this software
for any purpose with or without fee is hereby granted, provided
that the above copyright notice and this permission notice appear
in all copies.
There is NO WARRANTY for this software. See license.txt for
details. */
package java.util.regex;
/**
* A class to match classes of characters.
* <p>
* This class is intended to be the working horse behind character classes
* such as {@code [a-z]}.
* </p>
* @author Johannes Schindelin
*/
class CharacterMatcher {
private boolean[] map;
private boolean inversePattern;
public static CharacterMatcher parse(String description) {
return parse(description.toCharArray());
}
public static CharacterMatcher parse(char[] description) {
Parser parser = new Parser(description);
CharacterMatcher result = parser.parseClass();
if (parser.getEndOffset() != description.length) {
throw new RuntimeException("Short character class @"
+ parser.getEndOffset() + ": " + new String(description));
}
return result;
}
public boolean matches(char c) {
int index = c;
return (map.length > index && map[index]) ^ inversePattern;
}
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("[");
if (inversePattern) {
builder.append("^");
}
for (int i = 0; i < map.length; ++ i) {
if (!map[i]) {
continue;
}
builder.append(i >= ' ' && i <= 0x7f ?
"" + (char)i : ("\\x" + Integer.toHexString(i)));
int j = i + 1;
while (j < map.length && map[j]) {
++ j;
}
-- j;
if (j > i) {
if (j > i + 1) {
builder.append('-');
}
builder.append(j >= ' ' && j <= 0x7f ?
"" + (char)j : ("\\x" + Integer.toHexString(j)));
i = j;
}
}
builder.append("]");
return builder.toString();
}
private static String specialClass(int c) {
if ('d' == c) {
return "[0-9]";
}
if ('D' == c) {
return "[^0-9]";
}
if ('s' == c) {
return "[ \\t\\n\\x0B\\f\\r]";
}
if ('S' == c) {
return "[^ \\t\\n\\x0B\\f\\r]";
}
if ('w' == c) {
return "[a-zA-Z_0-9]";
}
if ('W' == c) {
return "[^a-zA-Z_0-9]";
}
return null;
}
private CharacterMatcher(boolean[] map, boolean inversePattern) {
this.map = map;
this.inversePattern = inversePattern;
}
private void setMatch(int c) {
ensureCapacity(c + 1);
map[c] = true;
}
private void ensureCapacity(int length) {
if (map.length >= length) {
return;
}
int size = map.length;
if (size < 32) {
size = 32;
}
while (size < length) {
size <<= 1;
}
map = java.util.Arrays.copyOf(map, size);
}
private void merge(CharacterMatcher other) {
boolean inversePattern = this.inversePattern || other.inversePattern;
if ((map.length < other.map.length) ^ inversePattern) {
map = java.util.Arrays.copyOf(map, other.map.length);
}
for (int i = 0; i < map.length; ++ i) {
map[i] = (matches((char)i) || other.matches((char)i)) ^ inversePattern;
}
this.inversePattern = inversePattern;
}
private void intersect(CharacterMatcher other) {
boolean inversePattern = this.inversePattern && other.inversePattern;
if ((map.length > other.map.length) ^ inversePattern) {
map = java.util.Arrays.copyOf(map, other.map.length);
}
for (int i = 0; i < map.length; ++ i) {
map[i] = (matches((char)i) && other.matches((char)i)) ^ inversePattern;
}
this.inversePattern = inversePattern;
}
static class Parser {
private final char[] description;
private int offset;
public Parser(char[] description) {
this.description = description;
}
public int getEndOffset() {
return offset;
}
/**
* Parses an escaped character.
*
* @param start the offset <u>after</u> the backslash
* @return the escaped character, or -1 if no character was recognized
*/
public int parseEscapedCharacter(int start) {
offset = start;
return parseEscapedCharacter();
}
private int parseEscapedCharacter() {
if (offset == description.length) {
throw new IllegalArgumentException("Short escaped character");
}
char c = description[offset++];
if (c == '0') {
int len = digits(offset, 3, 8);
if (len == 3 && description[offset] > '3') {
--len;
}
c = (char)Integer.parseInt(new String(description, offset, len), 8);
offset += len;
return c;
}
if (c == 'x' || c == 'u') {
int len = digits(offset, 4, 16);
c = (char)Integer.parseInt(new String(description, offset, len), 16);
offset += len;
return c;
}
switch (c) {
case 'a':
return 0x0007;
case 'e':
return 0x001B;
case 'f':
return 0x000C;
case 'n':
return 0x000A;
case 'r':
return 0x000D;
case 't':
return 0x0009;
case '\\':
case '.':
case '*':
case '+':
case '?':
case '|':
case '[':
case ']':
case '{':
case '}':
case '(':
case ')':
case '^':
case '$':
return c;
}
return -1;
}
public int digits(int offset, int maxLength, int base) {
for (int i = 0; ; ++i) {
if (i == maxLength || offset + i >= description.length) {
return i;
}
int value = description[offset + i] - '0';
if (value < 0) {
return i;
}
if (base > 10 && value >= 10) {
value += 10 - (value >= 'a' - '0' ? 'a' - '0' : 'A' - '0');
}
if (value >= base) {
return i;
}
}
}
public CharacterMatcher parseClass(int start) {
offset = start;
return parseClass();
}
public CharacterMatcher parseClass() {
if (description[offset] != '[') {
if (description[offset] == '\\') {
String range = specialClass(description[++ offset]);
if (range != null) {
++ offset;
return CharacterMatcher.parse(range);
}
}
return null;
}
CharacterMatcher matcher = new CharacterMatcher(new boolean[0],
description[++ offset] == '^');
if (matcher.inversePattern) {
++ offset;
}
int previous = -1;
boolean firstCharacter = true;
for (;;) {
if (offset >= description.length) {
unsupported("short regex");
}
char c = description[offset++];
if (c == '-' && !firstCharacter && description[offset] != ']') {
if (previous < 0) {
unsupported("invalid range");
}
int rangeEnd = description[offset];
if ('\\' == rangeEnd) {
rangeEnd = parseEscapedCharacter();
if (rangeEnd < 0) {
unsupported("invalid range");
}
}
matcher.ensureCapacity(rangeEnd + 1);
for (int j = previous + 1; j <= rangeEnd; j++) {
matcher.map[j] = true;
}
} else if (c == '\\') {
int saved = offset;
previous = parseEscapedCharacter();
if (previous < 0) {
offset = saved - 1;
CharacterMatcher clazz = parseClass();
if (clazz == null) {
unsupported("escape");
}
matcher.merge(clazz);
} else {
matcher.setMatch(previous);
}
} else if (c == '[') {
Parser parser = new Parser(description);
CharacterMatcher other = parser.parseClass(offset - 1);
if (other == null) {
unsupported("invalid merge");
}
matcher.merge(other);
offset = parser.getEndOffset();
previous = -1;
} else if (c == '&') {
if (offset + 2 > description.length || description[offset] != '&'
|| description[offset + 1] != '[') {
unsupported("operation");
}
Parser parser = new Parser(description);
CharacterMatcher other = parser.parseClass(offset + 1);
if (other == null) {
unsupported("invalid intersection");
}
matcher.intersect(other);
offset = parser.getEndOffset();
previous = -1;
} else if (c == ']') {
break;
} else {
previous = c;
matcher.setMatch(previous);
}
firstCharacter = false;
}
return matcher;
}
private void unsupported(String msg) throws UnsupportedOperationException {
throw new UnsupportedOperationException("Unsupported " + msg + " @"
+ offset + ": "
+ new String(description, 0, description.length));
}
}
}
| 412 | 0.954625 | 1 | 0.954625 | game-dev | MEDIA | 0.212307 | game-dev | 0.964598 | 1 | 0.964598 |
MisterTea/HyperNEAT | 58,160 | NE/HyperNEAT/cliche-1.2/dama.c | /*______________________________________________________________________________
----------> name: dama, italian checkers
----------> author: martin fierz
----------> purpose: platform independent italian checkers engine
----------> version: 1.03
----------> date: 22nd september 2002
----------> description: dama.c contains a simple but fast checkers
engine and some routines to interface to checkerboard.
dama.c contains three main parts: interface, search and
move generation. these parts are separated in the code.
board representation: the standard checkers notation is
(white)
32 31 30 29
28 27 26 25
24 23 22 21
20 19 18 17
16 15 14 13
12 11 10 9
8 7 6 5
4 3 2 1
(black)
the internal representation of the board is different, it is a
array of int with length 46, the checkers board is numbered
like this:
(white)
37 38 39 40
32 33 34 35
28 29 30 31
23 24 25 26
19 20 21 22
14 15 16 17
10 11 12 13
5 6 7 8
(black)
let's say, you would like to teach the program that it is
important to keep a back rank guard. you can for instance
add the following (not very sophisticated) code for this:
if(b[6] & (BLACK|MAN)) eval++;
if(b[8] & (BLACK|MAN)) eval++;
if(b[37] & (WHITE|MAN)) eval--;
if(b[39] & (WHITE|MAN)) eval--;
the evaluation function is seen from the point of view of the
black player, so you increase the value v if you think the
position is good for black.
have fun!
questions, comments, suggestions to:
Martin Fierz
checkers@fierz.ch
*/
/*----------> includes */
#include <stdio.h>
#include <string.h>
#include <time.h>
#ifdef WIN32
#include <windows.h>
#else
#define WINAPI // empty on *nix
#endif
/*----------> platform stuff */
#ifdef WIN32
#define TICKS CLK_TCK
#else
#define TICKS CLOCKS_PER_SEC
#endif
/*----------> definitions */
#define OCCUPIED 0
#define WHITE 1
#define BLACK 2
#define MAN 4
#define KING 8
#define FREE 16
#define CHANGECOLOR 3
#define MAXDEPTH 99
#define MAXMOVES 24
/*----------> compile options */
#undef MUTE
#undef VERBOSE
#define STATISTICS
/* return values */
#define DRAW 0
#define WIN 1
#define LOSS 2
#define UNKNOWN 3
/*----------> structure definitions */
struct move2
{
short n;
int m[12];
};
struct coor /* coordinate structure for board coordinates */
{
int x;
int y;
};
static struct CBmove /* GLOBAL all the information you need about a move */
{
int jumps; /* how many jumps are there in this move? */
int newpiece; /* what type of piece appears on to */
int oldpiece; /* what disappears on from */
struct coor from,to; /* coordinates of the piece - in 8x8 notation!*/
struct coor path[12]; /* intermediate path coordinates of the moving piece */
struct coor del[12]; /* squares whose pieces are deleted after the move */
int delpiece[12]; /* what is on these squares */
} GCBmove;
/*----------> function prototypes */
/*----------> part I: interface to CheckerBoard: CheckerBoard requires that
at getmove and enginename are present in the dll. the
functions help, options and about are optional. if you
do not provide them, CheckerBoard will display a
MessageBox stating that this option is in fact not an option*/
/* required functions */
int WINAPI getmove(int b[8][8],int color, double maxtime, char str[255], int *playnow, int info, int unused, struct CBmove *move);
int WINAPI enginecommand(char command[256], char reply[256]);
int WINAPI islegal(int b[8][8], int color, int from, int to, struct CBmove *move);
static void setbestmove(struct move2 move);
static struct coor numbertocoor(int n);
static void movetonotation(struct move2 move,char str[80]);
/*----------> part II: search */
static int checkers(int b[46],int color, double maxtime, char *str);
static int alphabeta(int b[46],int depth, int alpha, int beta, int color);
static int firstalphabeta(int b[46],int depth, int alpha, int beta, int color,struct move2 *best);
static void domove(int b[46],struct move2 move);
static void undomove(int b[46],struct move2 move);
static int evaluation(int b[46], int color);
/*----------> part III: move generation */
static int generatemovelist(int b[46], struct move2 movelist[MAXMOVES], int color);
static int generatecapturelist(int b[46], struct move2 movelist[MAXMOVES], int color);
static void blackmancapture(int b[46], int *n, struct move2 movelist[MAXMOVES],int square);
static void blackkingcapture(int b[46], int *n, struct move2 movelist[MAXMOVES],int square);
static void whitemancapture(int b[46], int *n, struct move2 movelist[MAXMOVES],int square);
static void whitekingcapture(int b[46], int *n, struct move2 movelist[MAXMOVES],int square);
static int testcapture(int b[46], int color);
/*----------> globals */
#ifdef STATISTICS
static int alphabetas,generatemovelists,evaluations,generatecapturelists,testcaptures;
#endif
static int value[17]={0,0,0,0,0,1,256,0,0,16,4096,0,0,0,0,0,0};
static int *play;
/*-------------- PART 1: dll stuff -------------------------------------------*/
#ifdef WIN32
BOOL WINAPI DllEntryPoint (HANDLE hDLL, DWORD dwReason, LPVOID lpReserved)
{
/* in a dll you used to have LibMain instead of WinMain in windows programs, or main
in normal C programs
win32 replaces LibMain with DllEntryPoint.*/
switch (dwReason)
{
case DLL_PROCESS_ATTACH:
/* dll loaded. put initializations here! */
break;
case DLL_PROCESS_DETACH:
/* program is unloading dll. put clean up here! */
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
default:
break;
}
return TRUE;
}
#endif // WIN32
int WINAPI enginecommand(char str[256], char reply[256])
{
// answer to commands sent by CheckerBoard.
// Dama does not answer to some of the commands,
// eg it has no engine options.
char command[256],param1[256],param2[256];
sscanf(str,"%s %s %s",command,param1,param2);
// check for command keywords
// by default, return "i don't understand this"
sprintf(reply,"?");
if(strcmp(command,"name")==0)
{
sprintf(reply,"Dama Italiana 1.03");
return 1;
}
if(strcmp(command,"about")==0)
{
sprintf(reply,"Dama Italiana 1.02\n\n2001 by Martin Fierz");
return 1;
}
if(strcmp(command,"help")==0)
{
sprintf(reply,"damahelp.htm");
return 1;
}
if(strcmp(command,"set")==0)
{
if(strcmp(param1,"hashsize")==0)
{
return 0;
}
if(strcmp(param1,"book")==0)
{
return 0;
}
}
if(strcmp(command,"get")==0)
{
if(strcmp(param1,"hashsize")==0)
{
return 0;
}
if(strcmp(param1,"book")==0)
{
return 0;
}
if(strcmp(param1,"protocolversion")==0)
{
sprintf(reply,"2");
return 1;
}
if(strcmp(param1,"gametype")==0)
{
sprintf(reply,"32"); /* 22==ITALIAN 32==MAFIERZ */
return 1;
}
}
return 0;
}
int WINAPI islegal(int b[8][8], int color, int from, int to, struct CBmove *move)
{
/* islegal tells CheckerBoard if a move the user wants to make is legal or not */
/* to check this, we generate a movelist and compare the moves in the movelist to
the move the user wants to make with from&to */
int n,i,found=0,Lfrom,Lto;
struct move2 movelist[MAXMOVES];
int board[46];
int capture=0;
char Lstr[80];
/* initialize board */
for(i=0;i<46;i++)
board[i]=OCCUPIED;
for(i=5;i<=40;i++)
board[i]=FREE;
board[5]=b[0][0];board[6]=b[2][0];board[7]=b[4][0];board[8]=b[6][0];
board[10]=b[1][1];board[11]=b[3][1];board[12]=b[5][1];board[13]=b[7][1];
board[14]=b[0][2];board[15]=b[2][2];board[16]=b[4][2];board[17]=b[6][2];
board[19]=b[1][3];board[20]=b[3][3];board[21]=b[5][3];board[22]=b[7][3];
board[23]=b[0][4];board[24]=b[2][4];board[25]=b[4][4];board[26]=b[6][4];
board[28]=b[1][5];board[29]=b[3][5];board[30]=b[5][5];board[31]=b[7][5];
board[32]=b[0][6];board[33]=b[2][6];board[34]=b[4][6];board[35]=b[6][6];
board[37]=b[1][7];board[38]=b[3][7];board[39]=b[5][7];board[40]=b[7][7];
for(i=5;i<=40;i++)
if(board[i]==0) board[i]=FREE;
for(i=9;i<=36;i+=9)
board[i]=OCCUPIED;
/* board initialized */
n=generatecapturelist(board,movelist,color);
capture=n;
if(!n)
n=generatemovelist(board,movelist,color);
if(!n) return 0;
/* now we have a movelist - check if from and to are the same */
for(i=0;i<n;i++)
{
movetonotation(movelist[i],Lstr);
if(capture)
sscanf(Lstr,"%i%*c%i",&Lfrom,&Lto);
else
sscanf(Lstr,"%i%*c%i",&Lfrom,&Lto);
if(from==Lfrom && to==Lto)
{
found=1;
break;
}
}
if(found)
/* sets GCBmove to movelist[i] */
setbestmove(movelist[i]);
*move=GCBmove;
return found;
}
int WINAPI getmove(int b[8][8],int color, double maxtime, char str[255], int *playnow, int info, int unused, struct CBmove *move)
{
/* getmove is what checkerboard calls. you get the parameters:
b[8][8] is the current position. the values in the array are determined by
the #defined values of BLACK, WHITE, KING, MAN. a black king for
instance is represented by BLACK|KING.
color is the side to make a move. BLACK or WHITE.
maxtime is the time your program should use to make a move. this is
what you specify as level in checkerboard. so if you exceed
this time it's not too bad - just don't exceed it too much...
str is a pointer to the output string of the checkerboard status bar.
you can use sprintf(str,"information"); to print any information you
want into the status bar.
*playnow is a pointer to the playnow variable of checkerboard. if the user
would like your engine to play immediately, this value is nonzero,
else zero. you should respond to a nonzero value of *playnow by
interrupting your search IMMEDIATELY.
when programming for another version of checkers than english/american, you must
tell checkerboard what your move is with struct CBmove.
*/
int i;
int value;
int board[46];
/* initialize board */
for(i=0;i<46;i++)
board[i]=OCCUPIED;
for(i=5;i<=40;i++)
board[i]=FREE;
/* (white)
37 38 39 40
32 33 34 35
28 29 30 31
23 24 25 26
19 20 21 22
14 15 16 17
10 11 12 13
5 6 7 8
(black) */
board[5]=b[0][0];board[6]=b[2][0];board[7]=b[4][0];board[8]=b[6][0];
board[10]=b[1][1];board[11]=b[3][1];board[12]=b[5][1];board[13]=b[7][1];
board[14]=b[0][2];board[15]=b[2][2];board[16]=b[4][2];board[17]=b[6][2];
board[19]=b[1][3];board[20]=b[3][3];board[21]=b[5][3];board[22]=b[7][3];
board[23]=b[0][4];board[24]=b[2][4];board[25]=b[4][4];board[26]=b[6][4];
board[28]=b[1][5];board[29]=b[3][5];board[30]=b[5][5];board[31]=b[7][5];
board[32]=b[0][6];board[33]=b[2][6];board[34]=b[4][6];board[35]=b[6][6];
board[37]=b[1][7];board[38]=b[3][7];board[39]=b[5][7];board[40]=b[7][7];
for(i=5;i<=40;i++)
if(board[i]==0) board[i]=FREE;
for(i=9;i<=36;i+=9)
board[i]=OCCUPIED;
play=playnow;
value=checkers(board,color,maxtime,str);
for(i=5;i<=40;i++)
if(board[i]==FREE) board[i]=0;
/* return the board */
b[0][0]=board[5];b[2][0]=board[6];b[4][0]=board[7];b[6][0]=board[8];
b[1][1]=board[10];b[3][1]=board[11];b[5][1]=board[12];b[7][1]=board[13];
b[0][2]=board[14];b[2][2]=board[15];b[4][2]=board[16];b[6][2]=board[17];
b[1][3]=board[19];b[3][3]=board[20];b[5][3]=board[21];b[7][3]=board[22];
b[0][4]=board[23];b[2][4]=board[24];b[4][4]=board[25];b[6][4]=board[26];
b[1][5]=board[28];b[3][5]=board[29];b[5][5]=board[30];b[7][5]=board[31];
b[0][6]=board[32];b[2][6]=board[33];b[4][6]=board[34];b[6][6]=board[35];
b[1][7]=board[37];b[3][7]=board[38];b[5][7]=board[39];b[7][7]=board[40];
/* set the move */
*move=GCBmove;
if(color==BLACK)
{
if(value>4000) return WIN;
if(value<-4000) return LOSS;
}
if(color==WHITE)
{
if(value>4000) return LOSS;
if(value<-4000) return WIN;
}
return UNKNOWN;
}
struct coor numbertocoor(int n)
{
/* turns square number n into a coordinate for checkerboard */
/* (white)
37 38 39 40
32 33 34 35
28 29 30 31
23 24 25 26
19 20 21 22
14 15 16 17
10 11 12 13
5 6 7 8
(black) */
struct coor c;
switch(n)
{
case 5:
c.x=0;c.y=0;
break;
case 6:
c.x=2;c.y=0;
break;
case 7:
c.x=4;c.y=0;
break;
case 8:
c.x=6;c.y=0;
break;
case 10:
c.x=1;c.y=1;
break;
case 11:
c.x=3;c.y=1;
break;
case 12:
c.x=5;c.y=1;
break;
case 13:
c.x=7;c.y=1;
break;
/* (white)
37 38 39 40
32 33 34 35
28 29 30 31
23 24 25 26
19 20 21 22
14 15 16 17
10 11 12 13
5 6 7 8
(black) */
case 14:
c.x=0;c.y=2;
break;
case 15:
c.x=2;c.y=2;
break;
case 16:
c.x=4;c.y=2;
break;
case 17:
c.x=6;c.y=2;
break;
case 19:
c.x=1;c.y=3;
break;
case 20:
c.x=3;c.y=3;
break;
case 21:
c.x=5;c.y=3;
break;
case 22:
c.x=7;c.y=3;
break;
/* (white)
37 38 39 40
32 33 34 35
28 29 30 31
23 24 25 26
19 20 21 22
14 15 16 17
10 11 12 13
5 6 7 8
(black) */
case 23:
c.x=0;c.y=4;
break;
case 24:
c.x=2;c.y=4;
break;
case 25:
c.x=4;c.y=4;
break;
case 26:
c.x=6;c.y=4;
break;
case 28:
c.x=1;c.y=5;
break;
case 29:
c.x=3;c.y=5;
break;
case 30:
c.x=5;c.y=5;
break;
case 31:
c.x=7;c.y=5;
break;
/* (white)
37 38 39 40
32 33 34 35
28 29 30 31
23 24 25 26
19 20 21 22
14 15 16 17
10 11 12 13
5 6 7 8
(black) */
case 32:
c.x=0;c.y=6;
break;
case 33:
c.x=2;c.y=6;
break;
case 34:
c.x=4;c.y=6;
break;
case 35:
c.x=6;c.y=6;
break;
case 37:
c.x=1;c.y=7;
break;
case 38:
c.x=3;c.y=7;
break;
case 39:
c.x=5;c.y=7;
break;
case 40:
c.x=7;c.y=7;
break;
}
/* (white)
37 38 39 40
32 33 34 35
28 29 30 31
23 24 25 26
19 20 21 22
14 15 16 17
10 11 12 13
5 6 7 8
(black) */
return c;
}
void movetonotation(struct move2 move,char str[80])
{
/* adapted for italian checkers!*/
/* (white)
37 38 39 40
32 33 34 35
28 29 30 31
23 24 25 26
19 20 21 22
14 15 16 17
10 11 12 13
5 6 7 8
(black)
/* (white)
........
5 6 7 8
1 2 3 4
*/
int from,to;
char c;
from=move.m[0]%256;
to=move.m[1]%256;
from=from-(from/9);
to=to-(to/9);
from-=4;
to-=4;
c='-';
if(move.n>2) c='x';
sprintf(str,"%2li%c%2li",from,c,to);
}
/*-------------- PART II: SEARCH ---------------------------------------------*/
int checkers(int b[46],int color, double maxtime, char *str)
/*----------> purpose: entry point to checkers. find a move on board b for color
----------> in the time specified by maxtime, write the best move in
----------> board, returns information on the search in str
----------> returns 1 if a move is found & executed, 0, if there is
----------> move in this position.
----------> version: 1.1
----------> date: 9th october 98 */
{
int i,numberofmoves;
double start;
int eval;
struct move2 best,lastbest,movelist[MAXMOVES];
char str2[255];
#ifdef STATISTICS
alphabetas=0;
generatemovelists=0;
generatecapturelists=0;
evaluations=0;
#endif
/*--------> check if there is only one move */
numberofmoves=generatecapturelist(b,movelist,color);
if(numberofmoves==0) numberofmoves=generatemovelist(b,movelist,color);
/* set the best move to default movelist[0] - if it's a forced move we will return immediately*/
setbestmove(movelist[0]);
// XXX
if(numberofmoves==1) {domove(b,movelist[0]);sprintf(str,"forced move");return(firstalphabeta(b,1,-10000,10000,color,&best));}
if(numberofmoves==0) {sprintf(str,"no legal moves in this position");return(-5000);}
start=clock();
eval=firstalphabeta(b,1,-10000,10000,color,&best);
for(i=2;(i<=MAXDEPTH) && ( (clock()-start)/TICKS < maxtime );i++)
{
lastbest=best;
eval=firstalphabeta(b,i,-10000,10000,color,&best);
movetonotation(best,str2);
#ifndef MUTE
sprintf(str,"best:%s time %2.2fs, depth %2li, value %4li",str2,(clock()-start)/TICKS,i,eval);
#ifdef STATISTICS
sprintf(str2," nodes %li",
alphabetas);
strcat(str,str2);
#endif
#endif
if(*play) break;
if(eval==5000) break;
if(eval==-5000) break;
}
i--;
if(*play)
movetonotation(lastbest,str2);
else
movetonotation(best,str2);
sprintf(str,"best:%s time %2.2f, depth %2li, value %4li, nodes %li",str2,(clock()-start)/TICKS,i,eval,alphabetas);
if(*play)
best=lastbest;
domove(b,best);
/* set the CBmove */
setbestmove(best);
return eval;
}
void setbestmove(struct move2 move)
{
int i;
int jumps;
int from, to;
struct coor c1,c2;
jumps=move.n-2;
from=move.m[0]%256;
to=move.m[1]%256;
GCBmove.from=numbertocoor(from);
GCBmove.to=numbertocoor(to);
GCBmove.jumps=jumps;
GCBmove.newpiece=((move.m[1]>>16)%256);
GCBmove.oldpiece=((move.m[0]>>8)%256);
for(i=2;i<move.n;i++)
{
GCBmove.delpiece[i-2]=((move.m[i]>>8)%256);
GCBmove.del[i-2]=numbertocoor(move.m[i]%256);
}
if(jumps>1)
/* more than one jump - need to calculate intermediate squares*/
{
/* set square where we start to c1 */
c1=numbertocoor(from);
for(i=2;i<move.n;i++)
{
c2=numbertocoor(move.m[i]%256);
/* c2 is the piece we jump */
/* => we land on the next square?! */
if(c2.x>c1.x) c2.x++;
else c2.x--;
if(c2.y>c1.y) c2.y++;
else c2.y--;
/* now c2 holds the square after the jumped piece - this is our path square */
GCBmove.path[i-1]=c2;
c1=c2;
}
}
else
{
GCBmove.path[1]=numbertocoor(to);
}
//for(i=1;i<move.n;i++)
// GCBmove.path[i]=numbertocoor(to);
}
int firstalphabeta(int b[46], int depth, int alpha, int beta, int color, struct move2 *best)
/*----------> purpose: search the game tree and find the best move.
----------> version: 1.0
----------> date: 25th october 97 */
{
int i;
int value;
int numberofmoves;
int capture;
struct move2 movelist[MAXMOVES];
#ifdef STATISTICS
alphabetas++;
#endif
if (*play) return 0;
/*----------> test if captures are possible */
capture=testcapture(b,color);
/*----------> recursion termination if no captures and depth=0*/
if(depth==0)
{
if(capture==0)
return(evaluation(b,color));
else
depth=1;
}
/*----------> generate all possible moves in the position */
if(capture==0)
{
numberofmoves=generatemovelist(b,movelist,color);
/*----------> if there are no possible moves, we lose: */
if(numberofmoves==0) {if (color==BLACK) return(-5000); else return(5000);}
}
else
numberofmoves=generatecapturelist(b,movelist,color);
/*----------> for all moves: execute the move, search tree, undo move. */
for(i=0;i<numberofmoves;i++)
{
domove(b,movelist[i]);
value=alphabeta(b,depth-1,alpha,beta,(color^CHANGECOLOR));
undomove(b,movelist[i]);
if(color == BLACK)
{
if(value>=beta) return(value);
if(value>alpha) {alpha=value;*best=movelist[i];}
}
if(color == WHITE)
{
if(value<=alpha) return(value);
if(value<beta) {beta=value;*best=movelist[i];}
}
}
if(color == BLACK)
return(alpha);
return(beta);
}
int alphabeta(int b[46], int depth, int alpha, int beta, int color)
/*----------> purpose: search the game tree and find the best move.
----------> version: 1.0
----------> date: 24th october 97 */
{
int i;
int value;
int capture;
int numberofmoves;
struct move2 movelist[MAXMOVES];
#ifdef STATISTICS
alphabetas++;
#endif
if (*play) return 0;
/*----------> test if captures are possible */
capture=testcapture(b,color);
/*----------> recursion termination if no captures and depth=0*/
if(depth==0)
{
if(capture==0)
return(evaluation(b,color));
else
depth=1;
}
/*----------> generate all possible moves in the position */
if(capture==0)
{
numberofmoves=generatemovelist(b,movelist,color);
/*----------> if there are no possible moves, we lose: */
if(numberofmoves==0) {if (color==BLACK) return(-5000); else return(5000);}
}
else
numberofmoves=generatecapturelist(b,movelist,color);
/*----------> for all moves: execute the move, search tree, undo move. */
for(i=0;i<numberofmoves;i++)
{
domove(b,movelist[i]);
value=alphabeta(b,depth-1,alpha,beta,color^CHANGECOLOR);
undomove(b,movelist[i]);
if(color == BLACK)
{
if(value>=beta) return(value);
if(value>alpha) alpha=value;
}
if(color == WHITE)
{
if(value<=alpha) return(value);
if(value<beta) beta=value;
}
}
if(color == BLACK)
return(alpha);
return(beta);
}
void domove(int b[46],struct move2 move)
/*----------> purpose: execute move on board
----------> version: 1.1
----------> date: 25th october 97 */
{
int square,after;
int i;
for(i=0;i<move.n;i++)
{
square=(move.m[i] % 256);
after=((move.m[i]>>16) % 256);
b[square]=after;
}
}
void undomove(int b[46],struct move2 move)
/*----------> purpose:
----------> version: 1.1
----------> date: 25th october 97 */
{
int square,before;
int i;
for(i=0;i<move.n;i++)
{
square=(move.m[i] % 256);
before=((move.m[i]>>8) % 256);
b[square]=before;
}
}
int evaluation(int b[46], int color)
/*----------> purpose:
----------> version: 1.1
----------> date: 18th april 98 */
{
int i;
int eval;
int v1,v2;
int nbm,nbk,nwm,nwk;
int nbmc=0,nbkc=0,nwmc=0,nwkc=0;
int nbme=0,nbke=0,nwme=0,nwke=0;
int code=0;
static int value[17]={0,0,0,0,0,1,256,0,0,16,4096,0,0,0,0,0,0};
static int edge[14]={5,6,7,8,13,14,22,23,31,32,37,38,39,40};
static int center[8]={15,16,20,21,24,25,29,30};
static int row[41]={0,0,0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,0,3,3,3,3,4,4,4,4,0,5,5,5,5,6,6,6,6,0,7,7,7,7};
static int safeedge[4]={8,13,32,37};
int tempo=0;
int nm,nk;
const int turn=2; //color to move gets +turn
const int brv=3; //multiplier for back rank
const int kcv=5; //multiplier for kings in center
const int mcv=1; //multiplier for men in center
const int mev=1; //multiplier for men on edge
const int kev=5; //multiplier for kings on edge
const int cramp=5; //multiplier for cramp
const int opening=-2; // multipliers for tempo
const int midgame=-1;
const int endgame=2;
const int intactdoublecorner=3;
int backrank;
int stonesinsystem=0;
#ifdef STATISTICS
evaluations++;
#endif
for(i=5;i<=40;i++)
code+=value[b[i]];
nwm = code % 16;
nwk = (code>>4) % 16;
nbm = (code>>8) % 16;
nbk = (code>>12) % 16;
v1=100*nbm+160*nbk;
v2=100*nwm+160*nwk;
eval=v1-v2; /*material values*/
eval+=(250*(v1-v2))/(v1+v2); /*favor exchanges if in material plus*/
nm=nbm+nwm;
nk=nbk+nwk;
/*--------- fine evaluation below -------------*/
if(color == BLACK) eval+=turn;
else eval-=turn;
/* (white)
37 38 39 40
32 33 34 35
28 29 30 31
23 24 25 26
19 20 21 22
14 15 16 17
10 11 12 13
5 6 7 8
(black) */
/* cramp */
if(b[23]==(BLACK|MAN) && b[28]==(WHITE|MAN)) eval+=cramp;
if(b[22]==(WHITE|MAN) && b[17]==(BLACK|MAN)) eval-=cramp;
/* back rank guard */
code=0;
if(b[5] & MAN) code++;
if(b[6] & MAN) code+=2;
if(b[7] & MAN) code+=4;
if(b[8] & MAN) code+=8;
switch (code)
{
case 0: code=0;break;
case 1: code=-1;break;
case 2: code=1;break;
case 3: code=0;break;
case 4: code=1;break;
case 5: code=1;break;
case 6: code=2;break;
case 7: code=1;break;
case 8: code=1;break;
case 9: code=0;break;
case 10: code=7;break;
case 11: code=4;break;
case 12: code=2;break;
case 13: code=2;break;
case 14: code=9;break;
case 15: code=8;break;
}
backrank=code;
code=0;
if(b[37] & MAN) code+=8;
if(b[38] & MAN) code+=4;
if(b[39] & MAN) code+=2;
if(b[40] & MAN) code++;
switch (code)
{
case 0: code=0;break;
case 1: code=-1;break;
case 2: code=1;break;
case 3: code=0;break;
case 4: code=1;break;
case 5: code=1;break;
case 6: code=2;break;
case 7: code=1;break;
case 8: code=1;break;
case 9: code=0;break;
case 10: code=7;break;
case 11: code=4;break;
case 12: code=2;break;
case 13: code=2;break;
case 14: code=9;break;
case 15: code=8;break;
}
backrank-=code;
eval+=brv*backrank;
/* intact double corner */
if(b[8]==(BLACK|MAN))
{
if(b[12]==(BLACK|MAN) || b[13]==(BLACK|MAN))
eval+=intactdoublecorner;
}
if(b[37]==(WHITE|MAN))
{
if(b[32]==(WHITE|MAN) || b[33]==(WHITE|MAN))
eval-=intactdoublecorner;
}
/* (white)
37 38 39 40
32 33 34 35
28 29 30 31
23 24 25 26
19 20 21 22
14 15 16 17
10 11 12 13
5 6 7 8
(black) */
/* center control */
for(i=0;i<8;i++)
{
if(b[center[i]] != FREE)
{
if(b[center[i]] == (BLACK|MAN)) nbmc++;
if(b[center[i]] == (BLACK|KING)) nbkc++;
if(b[center[i]] == (WHITE|MAN)) nwmc++;
if(b[center[i]] == (WHITE|KING)) nwkc++;
}
}
eval+=(nbmc-nwmc)*mcv;
eval+=(nbkc-nwkc)*kcv;
/*edge*/
for(i=0;i<14;i++)
{
if(b[edge[i]] != FREE)
{
if(b[edge[i]] == (BLACK|MAN)) nbme++;
if(b[edge[i]] == (BLACK|KING)) nbke++;
if(b[edge[i]] == (WHITE|MAN)) nwme++;
if(b[edge[i]] == (WHITE|KING)) nwke++;
}
}
eval-=(nbme-nwme)*mev;
eval-=(nbke-nwke)*kev;
/* tempo */
for(i=5;i<41;i++)
{
if(b[i]== (BLACK | MAN))
tempo+=row[i];
if(b[i]== (WHITE | MAN))
tempo-=7-row[i];
}
if(nm>=16) eval+=opening*tempo;
if((nm<=15) && (nm>=12)) eval+=midgame*tempo;
if(nm<9) eval+=endgame*tempo;
for(i=0;i<4;i++)
{
if(nbk+nbm>nwk+nwm && nwk<3)
{
if(b[safeedge[i]]== (WHITE|KING))
eval-=15;
}
if(nwk+nwm>nbk+nbm && nbk<3)
{
if(b[safeedge[i]]==(BLACK|KING))
eval+=15;
}
}
return(eval);
}
/*-------------- PART III: MOVE GENERATION -----------------------------------*/
int generatemovelist(int b[46], struct move2 movelist[MAXMOVES], int color)
/*----------> purpose:generates all moves. no captures. returns number of moves
----------> version: 1.0
----------> date: 25th october 97 */
{
int n=0,m;
int i;
#ifdef STATISTICS
generatemovelists++;
#endif
if(color == BLACK)
{
for(i=5;i<=40;i++)
{
if( (b[i]&BLACK) !=0 )
{
if( (b[i]&MAN) !=0 )
{
if( (b[i+4] & FREE) !=0 )
{
movelist[n].n=2;
if(i>=32) m=(BLACK|KING); else m=(BLACK|MAN); m=m<<8;
m+=FREE;m=m<<8;
m+=i+4;
movelist[n].m[1]=m;
m=FREE;m=m<<8;
m+=(BLACK|MAN);m=m<<8;
m+=i;
movelist[n].m[0]=m;
n++;
}
if( (b[i+5] & FREE) !=0 )
{
movelist[n].n=2;
if(i>=32) m=(BLACK|KING); else m=(BLACK|MAN); m=m<<8;
m+=FREE;m=m<<8;
m+=i+5;
movelist[n].m[1]=m;
m=FREE;m=m<<8;
m+=(BLACK|MAN);m=m<<8;
m+=i;
movelist[n].m[0]=m;
n++;
}
}
if( (b[i]&KING) !=0 )
{
if( (b[i+4] & FREE) !=0 )
{
movelist[n].n=2;
m=(BLACK|KING);m=m<<8;
m+=FREE;m=m<<8;
m+=i+4;
movelist[n].m[1]=m;
m=FREE;m=m<<8;
m+=(BLACK|KING);m=m<<8;
m+=i;
movelist[n].m[0]=m;
n++;
}
if( (b[i+5] & FREE) !=0 )
{
movelist[n].n=2;
m=(BLACK|KING);m=m<<8;
m+=FREE;m=m<<8;
m+=i+5;
movelist[n].m[1]=m;
m=FREE;m=m<<8;
m+=(BLACK|KING);m=m<<8;
m+=i;
movelist[n].m[0]=m;
n++;
}
if( (b[i-4] & FREE) !=0 )
{
movelist[n].n=2;
m=(BLACK|KING);m=m<<8;
m+=FREE;m=m<<8;
m+=i-4;
movelist[n].m[1]=m;
m=FREE;m=m<<8;
m+=(BLACK|KING);m=m<<8;
m+=i;
movelist[n].m[0]=m;
n++;
}
if( (b[i-5] & FREE) !=0 )
{
movelist[n].n=2;
m=(BLACK|KING);m=m<<8;
m+=FREE;m=m<<8;
m+=i-5;
movelist[n].m[1]=m;
m=FREE;m=m<<8;
m+=(BLACK|KING);m=m<<8;
m+=i;
movelist[n].m[0]=m;
n++;
}
}
}
}
}
else /* color = WHITE */
{
for(i=5;i<=40;i++)
{
if( (b[i]&WHITE) !=0 )
{
if( (b[i]&MAN) !=0 )
{
if( (b[i-4] & FREE) !=0 )
{
movelist[n].n=2;
if(i<=13) m=(WHITE|KING); else m=(WHITE|MAN);m=m<<8;
m+=FREE;m=m<<8;
m+=i-4;
movelist[n].m[1]=m;
m=FREE;m=m<<8;
m+=(WHITE|MAN);m=m<<8;
m+=i;
movelist[n].m[0]=m;
n++;
}
if( (b[i-5] & FREE) !=0 )
{
movelist[n].n=2;
if(i<=13) m=(WHITE|KING); else m=(WHITE|MAN);m=m<<8;
m+=FREE;m=m<<8;
m+=i-5;
movelist[n].m[1]=m;
m=FREE;m=m<<8;
m+=(WHITE|MAN);m=m<<8;
m+=i;
movelist[n].m[0]=m;
n++;
}
}
if( (b[i]&KING) !=0 ) /* or else */
{
if( (b[i+4] & FREE) !=0 )
{
movelist[n].n=2;
m=(WHITE|KING);m=m<<8;
m+=FREE;m=m<<8;
m+=i+4;
movelist[n].m[1]=m;
m=FREE;m=m<<8;
m+=(WHITE|KING);m=m<<8;
m+=i;
movelist[n].m[0]=m;
n++;
}
if( (b[i+5] & FREE) !=0 )
{
movelist[n].n=2;
m=(WHITE|KING);m=m<<8;
m+=FREE;m=m<<8;
m+=i+5;
movelist[n].m[1]=m;
m=FREE;m=m<<8;
m+=(WHITE|KING);m=m<<8;
m+=i;
movelist[n].m[0]=m;
n++;
}
if( (b[i-4] & FREE) !=0 )
{
movelist[n].n=2;
m=(WHITE|KING);m=m<<8;
m+=FREE;m=m<<8;
m+=i-4;
movelist[n].m[1]=m;
m=FREE;m=m<<8;
m+=(WHITE|KING);m=m<<8;
m+=i;
movelist[n].m[0]=m;
n++;
}
if( (b[i-5] & FREE) !=0 )
{
movelist[n].n=2;
m=(WHITE|KING);m=m<<8;
m+=FREE;m=m<<8;
m+=i-5;
movelist[n].m[1]=m;
m=FREE;m=m<<8;
m+=(WHITE|KING);m=m<<8;
m+=i;
movelist[n].m[0]=m;
n++;
}
}
}
}
}
return(n);
}
int generatecapturelist(int b[46], struct move2 movelist[MAXMOVES], int color)
/*----------> purpose: generate all possible captures
----------> version: 1.0
----------> date: 11th march 01 */
{
int n=0;
int m;
int i,j;
int tmp,max;
int n2;
int ismove[MAXMOVES];
#ifdef STATISTICS
generatecapturelists++;
#endif
if(color == BLACK)
{
for(i=5;i<=40;i++)
{
if( (b[i] & BLACK) !=0)
{
if( (b[i] & MAN) !=0)
{
if( (b[i+4] == (WHITE|MAN)) )
{
if( (b[i+8] & FREE) !=0)
{
movelist[n].n=3;
if(i>=28) m=(BLACK|KING); else m=(BLACK|MAN);m=m<<8;
m+=FREE;m=m<<8;
m+=i+8;
movelist[n].m[1]=m;
m=FREE;m=m<<8;
m+=(BLACK|MAN);m=m<<8;
m+=i;
movelist[n].m[0]=m;
m=FREE;m=m<<8;
m+=b[i+4];m=m<<8;
m+=i+4;
movelist[n].m[2]=m;
blackmancapture(b, &n, movelist, i+8);
}
}
if( (b[i+5] == (WHITE|MAN)) )
{
if( (b[i+10] & FREE) !=0)
{
movelist[n].n=3;
if(i>=28) m=(BLACK|KING); else m=(BLACK|MAN);m=m<<8;
m+=FREE;m=m<<8;
m+=i+10;
movelist[n].m[1]=m;
m=FREE;m=m<<8;
m+=(BLACK|MAN);m=m<<8;
m+=i;
movelist[n].m[0]=m;
m=FREE;m=m<<8;
m+=b[i+5];m=m<<8;
m+=i+5;
movelist[n].m[2]=m;
blackmancapture(b, &n, movelist, i+10);
}
}
}
else /* b[i] is a KING */
{
if( (b[i+4] & WHITE) !=0)
{
if( (b[i+8] & FREE) !=0)
{
movelist[n].n=3;
m=(BLACK|KING);m=m<<8;
m+=FREE;m=m<<8;
m+=i+8;
movelist[n].m[1]=m;
m=FREE;m=m<<8;
m+=(BLACK|KING);m=m<<8;
m+=i;
movelist[n].m[0]=m;
m=FREE;m=m<<8;
m+=b[i+4];m=m<<8;
m+=i+4;
movelist[n].m[2]=m;
tmp=b[i+4];
b[i+4]=FREE;
blackkingcapture(b, &n, movelist, i+8);
b[i+4]=tmp;
}
}
if( (b[i+5] & WHITE) !=0)
{
if( (b[i+10] & FREE) !=0)
{
movelist[n].n=3;
m=(BLACK|KING);m=m<<8;
m+=FREE;m=m<<8;
m+=i+10;
movelist[n].m[1]=m;
m=FREE;m=m<<8;
m+=(BLACK|KING);m=m<<8;
m+=i;
movelist[n].m[0]=m;
m=FREE;m=m<<8;
m+=b[i+5];m=m<<8;
m+=i+5;
movelist[n].m[2]=m;
tmp=b[i+5];
b[i+5]=FREE;
blackkingcapture(b, &n, movelist, i+10);
b[i+5]=tmp;
}
}
if( (b[i-4] & WHITE) !=0)
{
if( (b[i-8] & FREE) !=0)
{
movelist[n].n=3;
m=(BLACK|KING);m=m<<8;
m+=FREE;m=m<<8;
m+=i-8;
movelist[n].m[1]=m;
m=FREE;m=m<<8;
m+=(BLACK|KING);m=m<<8;
m+=i;
movelist[n].m[0]=m;
m=FREE;m=m<<8;
m+=b[i-4];m=m<<8;
m+=i-4;
movelist[n].m[2]=m;
tmp=b[i-4];
b[i-4]=FREE;
blackkingcapture(b, &n, movelist, i-8);
b[i-4]=tmp;
}
}
if( (b[i-5] & WHITE) !=0)
{
if( (b[i-10] & FREE) !=0)
{
movelist[n].n=3;
m=(BLACK|KING);m=m<<8;
m+=FREE;m=m<<8;
m+=i-10;
movelist[n].m[1]=m;
m=FREE;m=m<<8;
m+=(BLACK|KING);m=m<<8;
m+=i;
movelist[n].m[0]=m;
m=FREE;m=m<<8;
m+=b[i-5];m=m<<8;
m+=i-5;
movelist[n].m[2]=m;
tmp=b[i-5];
b[i-5]=FREE;
blackkingcapture(b, &n, movelist, i-10);
b[i-5]=tmp;
}
}
}
}
}
}
else /* color is WHITE */
{
for(i=5;i<=40;i++)
{
if( (b[i] & WHITE) !=0)
{
if( (b[i] & MAN) !=0)
{
if( (b[i-4] == (BLACK|MAN)) )
{
if( (b[i-8] & FREE) !=0)
{
movelist[n].n=3;
if(i<=17) m=(WHITE|KING); else m=(WHITE|MAN);m=m<<8;
m+=FREE;m=m<<8;
m+=i-8;
movelist[n].m[1]=m;
m=FREE;m=m<<8;
m+=(WHITE|MAN);m=m<<8;
m+=i;
movelist[n].m[0]=m;
m=FREE;m=m<<8;
m+=b[i-4];m=m<<8;
m+=i-4;
movelist[n].m[2]=m;
whitemancapture(b, &n, movelist, i-8);
}
}
if( (b[i-5] == (BLACK|MAN)) )
{
if( (b[i-10] & FREE) !=0)
{
movelist[n].n=3;
if(i<=17) m=(WHITE|KING); else m=(WHITE|MAN);m=m<<8;
m+=FREE;m=m<<8;
m+=i-10;
movelist[n].m[1]=m;
m=FREE;m=m<<8;
m+=(WHITE|MAN);m=m<<8;
m+=i;
movelist[n].m[0]=m;
m=FREE;m=m<<8;
m+=b[i-5];m=m<<8;
m+=i-5;
movelist[n].m[2]=m;
whitemancapture(b, &n, movelist, i-10);
}
}
}
else /* b[i] is a KING */
{
if( (b[i+4] & BLACK) !=0)
{
if( (b[i+8] & FREE) !=0)
{
movelist[n].n=3;
m=(WHITE|KING);m=m<<8;
m+=FREE;m=m<<8;
m+=i+8;
movelist[n].m[1]=m;
m=FREE;m=m<<8;
m+=(WHITE|KING);m=m<<8;
m+=i;
movelist[n].m[0]=m;
m=FREE;m=m<<8;
m+=b[i+4];m=m<<8;
m+=i+4;
movelist[n].m[2]=m;
tmp=b[i+4];
b[i+4]=FREE;
whitekingcapture(b, &n, movelist, i+8);
b[i+4]=tmp;
}
}
if( (b[i+5] & BLACK) !=0)
{
if( (b[i+10] & FREE) !=0)
{
movelist[n].n=3;
m=(WHITE|KING);m=m<<8;
m+=FREE;m=m<<8;
m+=i+10;
movelist[n].m[1]=m;
m=FREE;m=m<<8;
m+=(WHITE|KING);m=m<<8;
m+=i;
movelist[n].m[0]=m;
m=FREE;m=m<<8;
m+=b[i+5];m=m<<8;
m+=i+5;
movelist[n].m[2]=m;
tmp=b[i+5];
b[i+5]=FREE;
whitekingcapture(b, &n, movelist, i+10);
b[i+5]=tmp;
}
}
if( (b[i-4] & BLACK) !=0)
{
if( (b[i-8] & FREE) !=0)
{
movelist[n].n=3;
m=(WHITE|KING);m=m<<8;
m+=FREE;m=m<<8;
m+=i-8;
movelist[n].m[1]=m;
m=FREE;m=m<<8;
m+=(WHITE|KING);m=m<<8;
m+=i;
movelist[n].m[0]=m;
m=FREE;m=m<<8;
m+=b[i-4];m=m<<8;
m+=i-4;
movelist[n].m[2]=m;
tmp=b[i-4];
b[i-4]=FREE;
whitekingcapture(b, &n, movelist, i-8);
b[i-4]=tmp;
}
}
if( (b[i-5] & BLACK) !=0)
{
if( (b[i-10] & FREE) !=0)
{
movelist[n].n=3;
m=(WHITE|KING);m=m<<8;
m+=FREE;m=m<<8;
m+=i-10;
movelist[n].m[1]=m;
m=FREE;m=m<<8;
m+=(WHITE|KING);m=m<<8;
m+=i;
movelist[n].m[0]=m;
m=FREE;m=m<<8;
m+=b[i-5];m=m<<8;
m+=i-5;
movelist[n].m[2]=m;
tmp=b[i-5];
b[i-5]=FREE;
whitekingcapture(b, &n, movelist, i-10);
b[i-5]=tmp;
}
}
}
}
}
}
/* this is dama italiana: clean up capture list.
rules: -> the maximum number of pieces must be captured
-> if that is possible with a man or a king, it must be done with the king
-> if there are multiple possibilites, it must take as many kings as possible
-> if there are multiple possibilites, it must take a king as early as possible*/
/* capture max */
for(i=0;i<n;i++)
ismove[i]=1;
max=0;
for(i=0;i<n;i++)
{
if(movelist[i].n > max)
max=movelist[i].n;
}
for(i=0;i<n;i++)
{
if(movelist[i].n < max)
{
ismove[i]=0;
}
}
/* capture with king if multiple possibilities*/
max=0;
for(i=0;i<n;i++)
{
if(!ismove[i]) continue;
if( ((movelist[i].m[0]>>8) % 256) & KING)
max=1;
}
if(max==1)
{
for(i=0;i<n;i++)
{
if(!( ((movelist[i].m[0]>>8) % 256) & KING))
ismove[i]=0;
}
}
/* capture maximum number of kings */
max=0;
for(i=0;i<n;i++)
{
if(!ismove[i]) continue;
tmp=0;
for(j=2;j<movelist[i].n;j++)
{
if( ((movelist[i].m[j]>>8)%256) & KING)
tmp++;
}
if (tmp>max) max=tmp;
}
if(max>0)
{
for(i=0;i<n;i++)
{
if(!ismove[i]) continue;
tmp=0;
for(j=2;j<movelist[i].n;j++)
{
if( ((movelist[i].m[j]>>8)%256) & KING)
tmp++;
}
if(tmp<max) ismove[i]=0;
}
}
/* capture king as early as possible */
/* for all moves: tmp is the earliest jump */
/* max is the smallest of the earliest jumps*/
max=100;
for(i=0;i<n;i++)
{
if(!ismove[i]) continue;
tmp=0;
for(j=movelist[i].n-1;j>=2;j--)
{
if(((movelist[i].m[j]>>8)%256) &KING)
tmp=j;
}
if(tmp<max) max=tmp;
}
for(i=0;i<n;i++)
{
if(!ismove[i]) continue;
tmp=0;
for(j=movelist[i].n-1;j>=2;j--)
{
if(((movelist[i].m[j]>>8)%256) &KING)
tmp=j;
}
if(tmp>max)
ismove[i]=0;
}
/* clean up movelist */
n2=0;
for(i=0;i<n;i++)
{
if(ismove[i])
{
movelist[n2]=movelist[i];
n2++;
}
}
return(n2);
}
void blackmancapture(int b[46], int *n, struct move2 movelist[MAXMOVES],int i)
{
int m;
int found=0;
struct move2 move,orgmove;
orgmove=movelist[*n];
move=orgmove;
if( (b[i+4] == (WHITE|MAN)) )
{
if( (b[i+8] & FREE) !=0)
{
move.n++;
if(i>=28) m=(BLACK|KING); else m=(BLACK|MAN);m=m<<8;
m+=FREE;m=m<<8;
m+=(i+8);
move.m[1]=m;
m=FREE;m=m<<8;
m+=b[i+4];m=m<<8;
m+=(i+4);
move.m[move.n-1]=m;
found=1;
movelist[*n]=move;
blackmancapture(b, n, movelist, i+8);
}
}
move=orgmove;
if( (b[i+5] == (WHITE|MAN)) )
{
if( (b[i+10] & FREE) !=0)
{
move.n++;
if(i>=28) m=(BLACK|KING); else m=(BLACK|MAN);m=m<<8;
m+=FREE;m=m<<8;
m+=(i+10);
move.m[1]=m;
m=FREE;m=m<<8;
m+=b[i+5];m=m<<8;
m+=(i+5);
move.m[move.n-1]=m;
found=1;
movelist[*n]=move;
blackmancapture(b, n, movelist, i+10);
}
}
if(!found) (*n)++;
}
void blackkingcapture(int b[46], int *n, struct move2 movelist[MAXMOVES],int i)
{
int m;
int tmp;
int found=0;
struct move2 move,orgmove;
orgmove=movelist[*n];
move=orgmove;
if( (b[i-4] & WHITE) !=0)
{
if( (b[i-8] & FREE) !=0)
{
move.n++;
m=(BLACK|KING);m=m<<8;
m+=FREE;m=m<<8;
m+=i-8;
move.m[1]=m;
m=FREE;m=m<<8;
m+=b[i-4];m=m<<8;
m+=i-4;
move.m[move.n-1]=m;
found=1;
movelist[*n]=move;
tmp=b[i-4];
b[i-4]=FREE;
blackkingcapture(b, n, movelist, i-8);
b[i-4]=tmp;
}
}
move=orgmove;
if( (b[i-5] & WHITE) !=0)
{
if( (b[i-10] & FREE) !=0)
{
move.n++;
m=(BLACK|KING);m=m<<8;
m+=FREE;m=m<<8;
m+=i-10;
move.m[1]=m;
m=FREE;m=m<<8;
m+=b[i-5];m=m<<8;
m+=i-5;
move.m[move.n-1]=m;
found=1;
movelist[*n]=move;
tmp=b[i-5];
b[i-5]=FREE;
blackkingcapture(b, n, movelist, i-10);
b[i-5]=tmp;
}
}
move = orgmove;
if( (b[i+4] & WHITE) !=0)
{
if( (b[i+8] & FREE) !=0)
{
move.n++;
m=(BLACK|KING);m=m<<8;
m+=FREE;m=m<<8;
m+=i+8;
move.m[1]=m;
m=FREE;m=m<<8;
m+=b[i+4];m=m<<8;
m+=i+4;
move.m[move.n-1]=m;
found=1;
movelist[*n]=move;
tmp=b[i+4];
b[i+4]=FREE;
blackkingcapture(b, n, movelist, i+8);
b[i+4]=tmp;
}
}
move=orgmove;
if( (b[i+5] & WHITE) !=0)
{
if( (b[i+10] & FREE) !=0)
{
move.n++;
m=(BLACK|KING);m=m<<8;
m+=FREE;m=m<<8;
m+=i+10;
move.m[1]=m;
m=FREE;m=m<<8;
m+=b[i+5];m=m<<8;
m+=i+5;
move.m[move.n-1]=m;
found=1;
movelist[*n]=move;
tmp=b[i+5];
b[i+5]=FREE;
blackkingcapture(b, n, movelist, i+10);
b[i+5]=tmp;
}
}
if(!found) (*n)++;
}
void whitemancapture(int b[46], int *n, struct move2 movelist[MAXMOVES],int i)
{
int m;
int found=0;
struct move2 move,orgmove;
orgmove=movelist[*n];
move=orgmove;
if( (b[i-4] == (BLACK|MAN)) )
{
if( (b[i-8] & FREE) !=0)
{
move.n++;
if(i<=17) m=(WHITE|KING); else m=(WHITE|MAN);m=m<<8;
m+=FREE;m=m<<8;
m+=i-8;
move.m[1]=m;
m=FREE;m=m<<8;
m+=b[i-4];m=m<<8;
m+=i-4;
move.m[move.n-1]=m;
found=1;
movelist[*n]=move;
whitemancapture(b, n, movelist, i-8);
}
}
move=orgmove;
if( (b[i-5] == (BLACK|MAN)) )
{
if( (b[i-10] & FREE) !=0)
{
move.n++;
if(i<=17) m=(WHITE|KING); else m=(WHITE|MAN);m=m<<8;
m+=FREE;m=m<<8;
m+=i-10;
move.m[1]=m;
m=FREE;m=m<<8;
m+=b[i-5];m=m<<8;
m+=i-5;
move.m[move.n-1]=m;
found=1;
movelist[*n]=move;
whitemancapture(b, n, movelist, i-10);
}
}
if(!found) (*n)++;
}
void whitekingcapture(int b[46], int *n, struct move2 movelist[MAXMOVES],int i)
{
int m;
int tmp;
int found=0;
struct move2 move,orgmove;
orgmove=movelist[*n];
move=orgmove;
if( (b[i-4] & BLACK) !=0)
{
if( (b[i-8] & FREE) !=0)
{
move.n++;
m=(WHITE|KING);m=m<<8;
m+=FREE;m=m<<8;
m+=i-8;
move.m[1]=m;
m=FREE;m=m<<8;
m+=b[i-4];m=m<<8;
m+=i-4;
move.m[move.n-1]=m;
found=1;
movelist[*n]=move;
tmp=b[i-4];
b[i-4]=FREE;
whitekingcapture(b, n, movelist, i-8);
b[i-4]=tmp;
}
}
move=orgmove;
if( (b[i-5] & BLACK) !=0)
{
if( (b[i-10] & FREE) !=0)
{
move.n++;
m=(WHITE|KING);m=m<<8;
m+=FREE;m=m<<8;
m+=i-10;
move.m[1]=m;
m=FREE;m=m<<8;
m+=b[i-5];m=m<<8;
m+=i-5;
move.m[move.n-1]=m;
found=1;
movelist[*n]=move;
tmp=b[i-5];
b[i-5]=FREE;
whitekingcapture(b, n, movelist, i-10);
b[i-5]=tmp;
}
}
move=orgmove;
if( (b[i+4] & BLACK) !=0)
{
if( (b[i+8] & FREE) !=0)
{
move.n++;
m=(WHITE|KING);m=m<<8;
m+=FREE;m=m<<8;
m+=i+8;
move.m[1]=m;
m=FREE;m=m<<8;
m+=b[i+4];m=m<<8;
m+=i+4;
move.m[move.n-1]=m;
found=1;
movelist[*n]=move;
tmp=b[i+4];
b[i+4]=FREE;
whitekingcapture(b, n, movelist, i+8);
b[i+4]=tmp;
}
}
move=orgmove;
if( (b[i+5] & BLACK) !=0)
{
if( (b[i+10] & FREE) !=0)
{
move.n++;
m=(WHITE|KING);m=m<<8;
m+=FREE;m=m<<8;
m+=i+10;
move.m[1]=m;
m=FREE;m=m<<8;
m+=b[i+5];m=m<<8;
m+=i+5;
move.m[move.n-1]=m;
found=1;
movelist[*n]=move;
tmp=b[i+5];
b[i+5]=FREE;
whitekingcapture(b, n, movelist, i+10);
b[i+5]=tmp;
}
}
if(!found) (*n)++;
}
int testcapture(int b[46], int color)
/*----------> purpose: test if color has a capture on b
----------> version: 1.0
----------> date: 25th october 97 */
{
int i;
#ifdef STATISTICS
testcaptures++;
#endif
if(color == BLACK)
{
for(i=5;i<=40;i++)
{
if( (b[i] & BLACK) !=0)
{
if( (b[i] & MAN) !=0)
{
if( (b[i+4] == (WHITE|MAN)) )
{
if( (b[i+8] & FREE) !=0)
return(1);
}
if( (b[i+5] == (WHITE|MAN)) )
{
if( (b[i+10] & FREE) !=0)
return(1);
}
}
else /* b[i] is a KING */
{
if( (b[i+4] & WHITE) !=0)
{
if( (b[i+8] & FREE) !=0)
return(1);
}
if( (b[i+5] & WHITE) !=0)
{
if( (b[i+10] & FREE) !=0)
return(1);
}
if( (b[i-4] & WHITE) !=0)
{
if( (b[i-8] & FREE) !=0)
return(1);
}
if( (b[i-5] & WHITE) !=0)
{
if( (b[i-10] & FREE) !=0)
return(1);
}
}
}
}
}
else /* color is WHITE */
{
for(i=5;i<=40;i++)
{
if( (b[i] & WHITE) !=0)
{
if( (b[i] & MAN) !=0)
{
if( (b[i-4] == (BLACK|MAN)) )
{
if( (b[i-8] & FREE) !=0)
return(1);
}
if( (b[i-5] == (BLACK|MAN)) )
{
if( (b[i-10] & FREE) !=0)
return(1);
}
}
else /* b[i] is a KING */
{
if( (b[i+4] & BLACK) !=0)
{
if( (b[i+8] & FREE) !=0)
return(1);
}
if( (b[i+5] & BLACK) !=0)
{
if( (b[i+10] & FREE) !=0)
return(1);
}
if( (b[i-4] & BLACK) !=0)
{
if( (b[i-8] & FREE) !=0)
return(1);
}
if( (b[i-5] & BLACK) !=0)
{
if( (b[i-10] & FREE) !=0)
return(1);
}
}
}
}
}
return(0);
}
| 412 | 0.876334 | 1 | 0.876334 | game-dev | MEDIA | 0.819876 | game-dev | 0.910392 | 1 | 0.910392 |
Decathlon/tzatziki | 4,017 | tzatziki-mapper/src/main/java/com/decathlon/tzatziki/utils/Mapper.java | package com.decathlon.tzatziki.utils;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.stream.Collectors;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class Mapper {
private static boolean convertDotPropertiesToObject = true;
public static void shouldConvertDotPropertiesToObject(boolean shouldConvertDotPropertiesToObject) {
convertDotPropertiesToObject = shouldConvertDotPropertiesToObject;
}
private static final MapperDelegate delegate = ServiceLoader.load(MapperDelegate.class)
.findFirst()
.orElseThrow();
public static <E> E read(String content) {
content = toYaml(content);
return delegate.read(content);
}
public static <E> List<E> readAsAListOf(String content, Class<E> clazz) {
content = toYaml(content);
if (clazz == Type.class) clazz = (Class<E>) Class.class;
return delegate.readAsAListOf(content, clazz);
}
public static <E> E read(String content, Class<E> clazz) {
if (clazz == Type.class) clazz = (Class<E>) Class.class;
if (clazz == String.class) return (E) content;
return read(content, (Type) clazz);
}
public static <E> E read(String content, Type type) {
content = toYaml(content);
return delegate.read(content, type);
}
public static String toJson(Object object) {
return delegate.toJson(object);
}
public static String toNonDefaultJson(Object object) {
return delegate.toNonDefaultJson(object);
}
public static String toYaml(Object object) {
if (object instanceof String content && convertDotPropertiesToObject) {
if (isList(content)) content = toYaml(delegate.read(content, List.class));
else if (isJson(content)) content = toYaml(delegate.read(content, Map.class));
content = dotNotationToYamlObject(content);
object = content;
}
return delegate.toYaml(object);
}
private static String dotNotationToYamlObject(String content) {
List<String> lines = content.lines().collect(Collectors.toList());
for (int idx = 0; idx < lines.size(); idx++) {
String line;
String matchOnlyIfNonRegexFlag = "(?![ \"']*\\?e)";
String captureDotNotation = "(?>([ \\-]*))" + matchOnlyIfNonRegexFlag + "([^.:]+)\\.((?>[^:]+)(?<!\\d{4}-\\d{2}-\\d{2}T\\d{2}):" + matchOnlyIfNonRegexFlag + ".*)";
while ((line = lines.get(idx)).matches(captureDotNotation)) {
String rootObjectIndent = line.replaceAll(captureDotNotation, "$1").replace("-", " ");
String subObjectIndent = " " + rootObjectIndent;
lines.set(idx, line.replaceAll(captureDotNotation, "$1$2:"));
lines.add(idx + 1, line.replaceAll(captureDotNotation, subObjectIndent + "$3"));
for (int subIdx = idx + 2; subIdx < lines.size() && (lines.get(subIdx).startsWith(subObjectIndent) || lines.get(subIdx).startsWith(rootObjectIndent + "-")); subIdx++) {
lines.set(subIdx, " " + lines.get(subIdx));
}
}
}
return lines.stream().collect(Collectors.joining("\n"));
}
public static boolean isJson(String value) {
return firstNonWhitespaceCharacterIs(value, '{', '[');
}
public static boolean isList(String content) {
return firstNonWhitespaceCharacterIs(content, '[', '-');
}
public static boolean firstNonWhitespaceCharacterIs(String text, Character... c) {
Set<Character> characters = Set.of(c);
for (int i = 0; i < text.length(); i++) {
char charAt = text.charAt(i);
if (charAt != ' ' && charAt != '\n') {
return characters.contains(charAt);
}
}
return false;
}
}
| 412 | 0.835193 | 1 | 0.835193 | game-dev | MEDIA | 0.285103 | game-dev | 0.967618 | 1 | 0.967618 |
wynand1004/Projects | 3,938 | Platformer/platformer_demo.py | # Platformer Coding using Pygame
# Python 3.x Compatible
# Windows, MacOSX, and Linux Compatible
# by @TokyoEdtech
import pygame
import sys
import math
import random
pygame.init()
pygame.display.set_caption("Platformer Demo! by @TokyoEdtech")
clock = pygame.time.Clock()
WIDTH = 1200
HEIGHT = 800
GRAVITY = 1
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
# Create the screen
screen = pygame.display.set_mode((WIDTH, HEIGHT))
# Create classes
class Sprite():
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.dx = 0
self.dy = 0
self.width = width
self.height = height
self.color = WHITE
self.friction = 0.8
def goto(self, x, y):
self.x = x
self.y = y
def render(self):
pygame.draw.rect(screen, self.color, pygame.Rect(int(self.x-self.width/2.0), int(self.y-self.height/2.0), self.width, self.height))
def is_aabb_collision(self, other):
# Axis Aligned Bounding Box
x_collision = (math.fabs(self.x - other.x) * 2) < (self.width + other.width)
y_collision = (math.fabs(self.y - other.y) * 2) < (self.height + other.height)
return (x_collision and y_collision)
class Player(Sprite):
def __init__(self, x, y, width, height):
Sprite.__init__(self, x, y, width, height)
self.color = GREEN
def left(self):
self.dx -= 6
if self.dx < -12:
self.dx = -12
def right(self):
self.dx += 6
if self.dx > 12:
self.dx = 12
def jump(self):
self.dy -= 24
def move(self):
self.x = self.x + self.dx
self.y += self.dy
self.dy += GRAVITY
# Create font
# Create sounds
# Create game objects
player = Player(600, 0, 20, 40)
blocks = [Sprite(600, 200, 400, 20), Sprite(600, 400, 600, 20), Sprite(600, 600, 1000, 20), Sprite(1000, 500, 100, 200), Sprite(200, 500, 100, 200)]
# Main game loop
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
# Keyboard events
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player.left()
elif event.key == pygame.K_RIGHT:
player.right()
elif event.key == pygame.K_SPACE:
for block in blocks:
if player.is_aabb_collision(block):
player.jump()
break
# Move/Update objects
player.move()
# Check for collisions
for block in blocks:
if player.is_aabb_collision(block):
# Player is to the left
if player.x < block.x - block.width/2.0 and player.dx > 0:
player.dx = 0
player.x = block.x - block.width/2.0 - player.width/2.0
# Player is to the right
elif player.x > block.x + block.width/2.0 and player.dx < 0:
player.dx = 0
player.x = block.x + block.width/2.0 + player.width/2.0
# Player is above
elif player.y < block.y:
player.dy = 0
player.y = block.y - block.height/2.0 - player.height/2.0 + 1
player.dx *= block.friction
#Player is below
elif player.y > block.y:
player.dy = 0
player.y = block.y + block.height/2.0 + player.height/2.0
player.dx *= block.friction
# Border check the player
if player.y > 800:
player.goto(600, 0)
# Render (Draw stuff)
# Fill the background color
screen.fill(BLACK)
# Render objects
player.render()
for block in blocks:
block.render()
# Flip the display
pygame.display.flip()
# Set the FPS
clock.tick(30)
| 412 | 0.77177 | 1 | 0.77177 | game-dev | MEDIA | 0.767188 | game-dev | 0.772901 | 1 | 0.772901 |
damarindra/Unity-Dungeon-Generator | 3,326 | Assets/Delaunay/Unity-delaunay/Delaunay/HalfedgePriorityQueue.cs | using UnityEngine;
using System.Collections.Generic;
using Delaunay.Utils;
namespace Delaunay
{
internal sealed class HalfedgePriorityQueue: Utils.IDisposable // also known as heap
{
private Halfedge[] _hash;
private int _count;
private int _minBucket;
private int _hashsize;
private float _ymin;
private float _deltay;
public HalfedgePriorityQueue (float ymin, float deltay, int sqrt_nsites)
{
_ymin = ymin;
_deltay = deltay;
_hashsize = 4 * sqrt_nsites;
Initialize ();
}
public void Dispose ()
{
// get rid of dummies
for (int i = 0; i < _hashsize; ++i) {
_hash [i].Dispose ();
_hash [i] = null;
}
_hash = null;
}
private void Initialize ()
{
int i;
_count = 0;
_minBucket = 0;
_hash = new Halfedge[_hashsize];
// dummy Halfedge at the top of each hash
for (i = 0; i < _hashsize; ++i) {
_hash [i] = Halfedge.CreateDummy ();
_hash [i].nextInPriorityQueue = null;
}
}
public void Insert (Halfedge halfEdge)
{
Halfedge previous, next;
int insertionBucket = Bucket (halfEdge);
if (insertionBucket < _minBucket) {
_minBucket = insertionBucket;
}
previous = _hash [insertionBucket];
while ((next = previous.nextInPriorityQueue) != null
&& (halfEdge.ystar > next.ystar || (halfEdge.ystar == next.ystar && halfEdge.vertex.x > next.vertex.x))) {
previous = next;
}
halfEdge.nextInPriorityQueue = previous.nextInPriorityQueue;
previous.nextInPriorityQueue = halfEdge;
++_count;
}
public void Remove (Halfedge halfEdge)
{
Halfedge previous;
int removalBucket = Bucket (halfEdge);
if (halfEdge.vertex != null) {
previous = _hash [removalBucket];
while (previous.nextInPriorityQueue != halfEdge) {
previous = previous.nextInPriorityQueue;
}
previous.nextInPriorityQueue = halfEdge.nextInPriorityQueue;
_count--;
halfEdge.vertex = null;
halfEdge.nextInPriorityQueue = null;
halfEdge.Dispose ();
}
}
private int Bucket (Halfedge halfEdge)
{
int theBucket = (int)((halfEdge.ystar - _ymin) / _deltay * _hashsize);
if (theBucket < 0)
theBucket = 0;
if (theBucket >= _hashsize)
theBucket = _hashsize - 1;
return theBucket;
}
private bool IsEmpty (int bucket)
{
return (_hash [bucket].nextInPriorityQueue == null);
}
/**
* move _minBucket until it contains an actual Halfedge (not just the dummy at the top);
*
*/
private void AdjustMinBucket ()
{
while (_minBucket < _hashsize - 1 && IsEmpty(_minBucket)) {
++_minBucket;
}
}
public bool Empty ()
{
return _count == 0;
}
/**
* @return coordinates of the Halfedge's vertex in V*, the transformed Voronoi diagram
*
*/
public Vector2 Min ()
{
AdjustMinBucket ();
Halfedge answer = _hash [_minBucket].nextInPriorityQueue;
return new Vector2 (answer.vertex.x, answer.ystar);
}
/**
* remove and return the min Halfedge
* @return
*
*/
public Halfedge ExtractMin ()
{
Halfedge answer;
// get the first real Halfedge in _minBucket
answer = _hash [_minBucket].nextInPriorityQueue;
_hash [_minBucket].nextInPriorityQueue = answer.nextInPriorityQueue;
_count--;
answer.nextInPriorityQueue = null;
return answer;
}
}
} | 412 | 0.871343 | 1 | 0.871343 | game-dev | MEDIA | 0.182558 | game-dev | 0.964433 | 1 | 0.964433 |
Xeno69/Domination | 1,399 | co30_Domination.Altis/missions/ma3t/x_m23.sqf | // by Xeno
//#define __DEBUG__
#include "..\..\x_setup.sqf"
d_x_sm_pos = "d_sm_23" call d_fnc_smmapos; // Officer, GSM Station
d_x_sm_type = "normal"; // "convoy"
if (hasInterface) then {
d_cur_sm_txt = localize "STR_DOM_MISSIONSTRING_1813";
d_current_mission_resolved_text = localize "STR_DOM_MISSIONSTRING_729";
};
if (isServer) then {
d_x_sm_pos params ["_poss"];
private _fortress = createVehicle [d_sm_fortress, _poss, [], 0, "NONE"];
_fortress setPos _poss;
d_x_sm_vec_rem_ar pushBack _fortress;
sleep 2.123;
private _ogroup = [d_side_enemy] call d_fnc_creategroup;
private _sm_vec = _ogroup createUnit [d_soldier_officer, _poss, [], 0, "NONE"];
[_sm_vec] joinSilent _ogroup;
_ogroup deleteGroupWhenEmpty true;
_sm_vec call d_fnc_removenvgoggles_fak;
_sm_vec call d_fnc_addkillednormal;
d_x_sm_rem_ar pushBack _sm_vec;
sleep 2.123;
private _bpos = getPosATL _fortress;
_bpos set [2, 1];
_sm_vec setFormDir ((direction _fortress) + 90);
_sm_vec setPos _bpos;
["aa", 1, "tracked_apc", 1, "tank", 1, _poss, 1, 450, true] spawn d_fnc_CreateArmor;
sleep 2.123;
["specops", 2, "allmen", 2, _poss, 300, true] spawn d_fnc_CreateInf;
sleep 2.123;
private _leadero = leader _ogroup;
_leadero setRank "COLONEL";
_ogroup allowFleeing 0;
_ogroup setbehaviour "AWARE";
_leadero disableAI "PATH";
if (d_with_dynsim == 0) then {
[_sm_vec, 1] spawn d_fnc_enabledynsim;
};
};
| 412 | 0.786133 | 1 | 0.786133 | game-dev | MEDIA | 0.942162 | game-dev | 0.547594 | 1 | 0.547594 |
avaraline/Avara | 3,450 | platform/ios/SDL2.xcframework/ios-arm64_x86_64-simulator/SDL2.framework/Headers/SDL_gesture.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2025 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* # CategoryGesture
*
* Include file for SDL gesture event handling.
*/
#ifndef SDL_gesture_h_
#define SDL_gesture_h_
#include <SDL2/SDL_stdinc.h>
#include <SDL2/SDL_error.h>
#include <SDL2/SDL_video.h>
#include <SDL2/SDL_touch.h>
#include <SDL2/begin_code.h>
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
typedef Sint64 SDL_GestureID;
/* Function prototypes */
/**
* Begin recording a gesture on a specified touch device or all touch devices.
*
* If the parameter `touchId` is -1 (i.e., all devices), this function will
* always return 1, regardless of whether there actually are any devices.
*
* \param touchId the touch device id, or -1 for all touch devices.
* \returns 1 on success or 0 if the specified device could not be found.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_GetTouchDevice
*/
extern DECLSPEC int SDLCALL SDL_RecordGesture(SDL_TouchID touchId);
/**
* Save all currently loaded Dollar Gesture templates.
*
* \param dst a SDL_RWops to save to.
* \returns the number of saved templates on success or 0 on failure; call
* SDL_GetError() for more information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_LoadDollarTemplates
* \sa SDL_SaveDollarTemplate
*/
extern DECLSPEC int SDLCALL SDL_SaveAllDollarTemplates(SDL_RWops *dst);
/**
* Save a currently loaded Dollar Gesture template.
*
* \param gestureId a gesture id.
* \param dst a SDL_RWops to save to.
* \returns 1 on success or 0 on failure; call SDL_GetError() for more
* information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_LoadDollarTemplates
* \sa SDL_SaveAllDollarTemplates
*/
extern DECLSPEC int SDLCALL SDL_SaveDollarTemplate(SDL_GestureID gestureId,SDL_RWops *dst);
/**
* Load Dollar Gesture templates from a file.
*
* \param touchId a touch id.
* \param src a SDL_RWops to load from.
* \returns the number of loaded templates on success or a negative error code
* (or 0) on failure; call SDL_GetError() for more information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_SaveAllDollarTemplates
* \sa SDL_SaveDollarTemplate
*/
extern DECLSPEC int SDLCALL SDL_LoadDollarTemplates(SDL_TouchID touchId, SDL_RWops *src);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include <SDL2/close_code.h>
#endif /* SDL_gesture_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 412 | 0.894858 | 1 | 0.894858 | game-dev | MEDIA | 0.879625 | game-dev | 0.559319 | 1 | 0.559319 |
dpjudas/VkDoom | 9,464 | src/maploader/maploader.h | #pragma once
#include "nodebuild.h"
#include "g_levellocals.h"
#include "files.h"
struct FStrifeDialogueNode;
struct FStrifeDialogueReply;
struct Response;
struct EDMapthing
{
int recordnum;
int tid;
int type;
double height;
int args[5];
uint16_t skillfilter;
uint32_t flags;
};
struct EDLinedef
{
int recordnum;
int special;
int tag;
int id;
int args[5];
double alpha;
uint32_t flags;
uint32_t activation;
};
struct EDSector
{
int recordnum;
uint32_t flags;
uint32_t flagsRemove;
uint32_t flagsAdd;
int damageamount;
int damageinterval;
FName damagetype;
uint8_t leaky;
uint8_t leakyadd;
uint8_t leakyremove;
int floorterrain;
int ceilingterrain;
uint32_t color;
uint32_t damageflags;
uint32_t damageflagsAdd;
uint32_t damageflagsRemove;
bool flagsSet;
bool damageflagsSet;
bool colorSet;
// colormaptop//bottom cannot be used because ZDoom has no corresponding properties.
double xoffs[2], yoffs[2];
DAngle angle[2];
uint32_t portalflags[2];
double Overlayalpha[2];
};
struct sidei_t // [RH] Only keep BOOM sidedef init stuff around for init
{
union
{
// Used when unpacking sidedefs and assigning
// properties based on linedefs.
struct
{
short tag, special;
short alpha;
uint32_t map;
} a;
// Used when grouping sidedefs into loops.
struct
{
uint32_t first, next;
char lineside;
} b;
};
};
struct FMissingCount
{
int Count = 0;
};
typedef TMap<FString,FMissingCount> FMissingTextureTracker;
struct FLevelLocals;
struct MapData;
class MapLoader
{
friend class UDMFParser;
friend class USDFParser;
void *level; // this is to hide the global variable and produce an error for referencing it.
public:
FLevelLocals *Level;
private:
int firstglvertex; // helpers for loading GL nodes from GWA files.
bool format5;
TMap<unsigned, unsigned> MapThingsUserDataIndex; // from mapthing idx -> user data idx
TArray<FUDMFKey> MapThingsUserData;
int sidecount = 0;
TArray<int> linemap;
TArray<sidei_t> sidetemp;
public: // for the scripted compatibility system these two members need to be public.
TArray<FMapThing> MapThingsConverted;
bool ForceNodeBuild = false;
// This needs to be public to fetch this from DLevelPostProcessor native functions
TArray<vertexdata_t> vertexdatas;
private:
// Extradata loader
TMap<int, EDLinedef> EDLines;
TMap<int, EDSector> EDSectors;
TMap<int, EDMapthing> EDThings;
// Polyobject init
TArray<int32_t> KnownPolySides;
FName CheckCompatibility(MapData *map);
void PostProcessLevel(FName checksum);
// Slopes
void SlopeLineToPoint(int lineid, const DVector3 &pos, bool slopeCeil);
void CopyPlane(int tag, sector_t *dest, bool copyCeil);
void CopyPlane(int tag, const DVector2 &pos, bool copyCeil);
void SetSlope(secplane_t *plane, bool setCeil, int xyangi, int zangi, const DVector3 &pos);
void VavoomSlope(sector_t * sec, int id, const DVector3 &pos, int which);
void SetSlopesFromVertexHeights(FMapThing *firstmt, FMapThing *lastmt, const int *oldvertextable);
void AlignPlane(sector_t *sec, line_t *line, int which);
// Extradata
void InitED();
void ProcessEDMapthing(FMapThing *mt, int recordnum);
void ProcessEDLinedef(line_t *line, int recordnum);
void ProcessEDSector(sector_t *sec, int recordnum);
void parseEDLinedef(FScanner &sc, TMap<int, EDLinedef> &EDLines);
// Polyobjects
void InitSideLists();
void IterFindPolySides(FPolyObj *po, side_t *side);
void SpawnPolyobj(int index, int tag, int type, int damage);
void TranslateToStartSpot(int tag, const DVector2 &origin);
void InitPolyBlockMap(void);
// GL nodes
int checkGLVertex(int num);
int checkGLVertex3(int num);
int CheckForMissingSegs();
bool LoadGLVertexes(FileReader &lump);
bool LoadGLSegs(FileReader &lump);
bool LoadGLSubsectors(FileReader &lump);
bool LoadNodes(FileReader &lump);
bool DoLoadGLNodes(FileReader * lumps);
void CreateCachedNodes(MapData *map);
// Render info
void PrepareSectorData();
void PrepareTransparentDoors(sector_t * sector);
void InitVertexData();
void GetSideVertices(int sdnum, DVector2 *v1, DVector2 *v2);
void PrepareSegs();
void FloodSectorStacks();
void InitRenderInfo();
void FixMinisegReferences();
void FixHoles();
void ReportUnpairedMinisegs();
void CalcIndices();
// Strife dialogue
void LoadStrifeConversations (MapData *map, const char *mapname);
bool LoadScriptFile (const char *name, bool include, int type);
bool LoadScriptFile(const char *name, int lumpnum, FileReader &lump, int numnodes, bool include, int type);
FStrifeDialogueNode *ReadRetailNode (const char *name, FileReader &lump, uint32_t &prevSpeakerType);
FStrifeDialogueNode *ReadTeaserNode (const char *name, FileReader &lump, uint32_t &prevSpeakerType);
void ParseReplies (const char *name, int pos, FStrifeDialogueReply **replyptr, Response *responses);
bool ParseUSDF(int lumpnum, FileReader &lump, int lumplen);
// Specials
void SpawnSpecials();
void InitSectorSpecial(sector_t *sector, int special);
void SpawnLights(sector_t *sector);
void CreateScroller(EScroll type, double dx, double dy, sector_t *sect, side_t* side, int accel, EScrollPos scrollpos = EScrollPos::scw_all, int scrollmode = 15/*SCROLL_All*/);
void SpawnScrollers();
void SpawnFriction();
void SpawnPushers();
AActor *GetPushThing (int s);
void SpawnPortal(line_t *line, int sectortag, int plane, int bytealpha, int linked);
void CopyPortal(int sectortag, int plane, unsigned pnum, double alpha, bool tolines);
void SetPortal(sector_t *sector, int plane, unsigned pnum, double alpha);
void SpawnLinePortal(line_t* line);
void SetupPortals();
void SpawnSkybox(AActor *origin);
void SetupFloorPortal (AActor *point);
void SetupCeilingPortal (AActor *point);
void TranslateTeleportThings();
int Set3DFloor(line_t * line, int param, int param2, int alpha);
void Spawn3DFloors ();
void SetTexture(side_t *side, int position, const char *name, FMissingTextureTracker &track);
void SetTexture(side_t* side, int position, const FString& name, FMissingTextureTracker& track)
{
SetTexture(side, position, name.GetChars(), track);
}
void SetTexture(sector_t *sector, int index, int position, const char *name, FMissingTextureTracker &track, bool truncate);
void SetTexture(side_t *side, int position, uint32_t *blend, const char *name);
void SetTextureNoErr(side_t *side, int position, uint32_t *color, const char *name, bool *validcolor, bool isFog);
void FloodZone(sector_t *sec, int zonenum);
void LoadGLZSegs(FileReader &data, int type);
void LoadZSegs(FileReader &data);
void LoadZNodes(FileReader &data, int glnodes);
void SetLineID(int i, line_t *ld);
void SaveLineSpecial(line_t *ld);
void FinishLoadingLineDef(line_t *ld, int alpha);
void SetSideNum(side_t **sidenum_p, uint16_t sidenum);
void AllocateSideDefs(MapData *map, int count);
void ProcessSideTextures(bool checktranmap, side_t *sd, sector_t *sec, intmapsidedef_t *msd, int special, int tag, short *alpha, FMissingTextureTracker &missingtex);
void SetMapThingUserData(AActor *actor, unsigned udi);
void CreateBlockMap();
void PO_Init(void);
// During map init the items' own Index functions should not be used.
inline int Index(vertex_t *v) const
{
return int(v - &Level->vertexes[0]);
}
inline int Index(side_t *v) const
{
return int(v - &Level->sides[0]);
}
inline int Index(line_t *v) const
{
return int(v - &Level->lines[0]);
}
inline int Index(seg_t *v) const
{
return int(v - &Level->segs[0]);
}
inline int Index(subsector_t *v) const
{
return int(v - &Level->subsectors[0]);
}
inline int Index(node_t *v) const
{
return int(v - &Level->nodes[0]);
}
inline int Index(sector_t *v) const
{
return int(v - &Level->sectors[0]);
}
public:
void LoadMapinfoACSLump();
void ProcessEDSectors();
void FloodZones();
void LoadVertexes(MapData * map);
bool LoadExtendedNodes(FileReader &dalump, uint32_t id);
template<class segtype> bool LoadSegs(MapData * map);
template<class subsectortype, class segtype> bool LoadSubsectors(MapData * map);
template<class nodetype, class subsectortype> bool LoadNodes(MapData * map);
bool LoadGLNodes(MapData * map);
bool CheckCachedNodes(MapData *map);
bool CheckNodes(MapData * map, bool rebuilt, int buildtime);
bool CheckForGLNodes();
void LoadSectors(MapData *map, FMissingTextureTracker &missingtex);
void LoadThings(MapData * map);
void LoadThings2(MapData * map);
void SpawnThings(int position);
void FinishLoadingLineDefs();
void LoadLineDefs(MapData * map);
void LoadLineDefs2(MapData * map);
void LoopSidedefs(bool firstloop);
void LoadSideDefs2(MapData *map, FMissingTextureTracker &missingtex);
void LoadBlockMap(MapData * map);
void LoadReject(MapData * map, bool junk);
void LoadBehavior(MapData * map);
void GetPolySpots(MapData * map, TArray<FNodeBuilder::FPolyStart> &spots, TArray<FNodeBuilder::FPolyStart> &anchors);
void GroupLines(bool buildmap);
void ParseTextMap(MapData *map, FMissingTextureTracker &missingtex);
void SummarizeMissingTextures(const FMissingTextureTracker &missing);
void SetRenderSector();
void SpawnSlopeMakers(FMapThing *firstmt, FMapThing *lastmt, const int *oldvertextable);
void SetSlopes();
void CopySlopes();
void InitLightmapTiles(MapData* map);
void InitLevelMesh(MapData* map);
bool LoadLightmap(MapData* map);
void LoadLevel(MapData *map, const char *lumpname, int position);
MapLoader(FLevelLocals *lev)
{
Level = lev;
}
};
| 412 | 0.964351 | 1 | 0.964351 | game-dev | MEDIA | 0.642363 | game-dev | 0.619903 | 1 | 0.619903 |
H4PM/Elywing | 5,990 | src/pocketmine/entity/Projectile.php | <?php
/*
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*/
namespace pocketmine\entity;
use pocketmine\event\entity\EntityCombustByEntityEvent;
use pocketmine\event\entity\EntityDamageByChildEntityEvent;
use pocketmine\event\entity\EntityDamageByEntityEvent;
use pocketmine\event\entity\EntityDamageEvent;
use pocketmine\event\entity\ProjectileHitEvent;
use pocketmine\item\Potion;
use pocketmine\level\format\Chunk;
use pocketmine\level\MovingObjectPosition;
use pocketmine\math\Vector3;
use pocketmine\nbt\tag\CompoundTag;
use pocketmine\nbt\tag\ShortTag;
abstract class Projectile extends Entity{
const DATA_SHOOTER_ID = 17;
/** @var Entity */
public $shootingEntity = null;
protected $damage = 0;
public $hadCollision = false;
public function __construct(Chunk $chunk, CompoundTag $nbt, Entity $shootingEntity = null){
$this->shootingEntity = $shootingEntity;
if($shootingEntity !== null){
$this->setDataProperty(self::DATA_SHOOTER_ID, self::DATA_TYPE_LONG, $shootingEntity->getId());
}
parent::__construct($chunk, $nbt);
}
public function attack($damage, EntityDamageEvent $source){
if($source->getCause() === EntityDamageEvent::CAUSE_VOID){
parent::attack($damage, $source);
}
}
protected function initEntity(){
parent::initEntity();
$this->setMaxHealth(1);
$this->setHealth(1);
if(isset($this->namedtag->Age)){
$this->age = $this->namedtag["Age"];
}
}
public function canCollideWith(Entity $entity){
return $entity instanceof Living and !$this->onGround;
}
public function saveNBT(){
parent::saveNBT();
$this->namedtag->Age = new ShortTag("Age", $this->age);
}
public function onUpdate($currentTick){
if($this->closed){
return false;
}
$tickDiff = $currentTick - $this->lastUpdate;
if($tickDiff <= 0 and !$this->justCreated){
return true;
}
$this->lastUpdate = $currentTick;
$hasUpdate = $this->entityBaseTick($tickDiff);
if($this->isAlive()){
$movingObjectPosition = null;
if(!$this->isCollided){
$this->motionY -= $this->gravity;
}
$moveVector = new Vector3($this->x + $this->motionX, $this->y + $this->motionY, $this->z + $this->motionZ);
$list = $this->getLevel()->getCollidingEntities($this->boundingBox->addCoord($this->motionX, $this->motionY, $this->motionZ)->expand(1, 1, 1), $this);
$nearDistance = PHP_INT_MAX;
$nearEntity = null;
foreach($list as $entity){
if(/*!$entity->canCollideWith($this) or */
($entity === $this->shootingEntity and $this->ticksLived < 5)
){
continue;
}
$axisalignedbb = $entity->boundingBox->grow(0.3, 0.3, 0.3);
$ob = $axisalignedbb->calculateIntercept($this, $moveVector);
if($ob === null){
continue;
}
$distance = $this->distanceSquared($ob->hitVector);
if($distance < $nearDistance){
$nearDistance = $distance;
$nearEntity = $entity;
}
}
if($nearEntity !== null){
$movingObjectPosition = MovingObjectPosition::fromEntity($nearEntity);
}
if($movingObjectPosition !== null){
if($movingObjectPosition->entityHit !== null){
$this->server->getPluginManager()->callEvent(new ProjectileHitEvent($this));
$motion = sqrt($this->motionX ** 2 + $this->motionY ** 2 + $this->motionZ ** 2);
$damage = ceil($motion * $this->damage);
if($this instanceof Arrow and $this->isCritical()){
$damage += mt_rand(0, (int) ($damage / 2) + 1);
}
if($this->shootingEntity === null){
$ev = new EntityDamageByEntityEvent($this, $movingObjectPosition->entityHit, EntityDamageEvent::CAUSE_PROJECTILE, $damage);
}else{
$ev = new EntityDamageByChildEntityEvent($this->shootingEntity, $this, $movingObjectPosition->entityHit, EntityDamageEvent::CAUSE_PROJECTILE, $damage);
}
if($movingObjectPosition->entityHit->attack($ev->getFinalDamage(), $ev) === true){
if($this instanceof Arrow and $this->getPotionId() != 0){
foreach(Potion::getEffectsById($this->getPotionId() - 1) as $effect){
$movingObjectPosition->entityHit->addEffect($effect->setDuration($effect->getDuration() / 8));
}
}
$ev->useArmors();
}
$this->hadCollision = true;
if($this->fireTicks > 0){
$ev = new EntityCombustByEntityEvent($this, $movingObjectPosition->entityHit, 5);
$this->server->getPluginManager()->callEvent($ev);
if(!$ev->isCancelled()){
$movingObjectPosition->entityHit->setOnFire($ev->getDuration());
}
}
$this->kill();
return true;
}
}
$this->move($this->motionX, $this->motionY, $this->motionZ);
if($this->isCollided and !$this->hadCollision){
$this->hadCollision = true;
$this->motionX = 0;
$this->motionY = 0;
$this->motionZ = 0;
$this->server->getPluginManager()->callEvent(new ProjectileHitEvent($this));
}elseif(!$this->isCollided and $this->hadCollision){
$this->hadCollision = false;
}
if(!$this->onGround or abs($this->motionX) > 0.00001 or abs($this->motionY) > 0.00001 or abs($this->motionZ) > 0.00001){
$f = sqrt(($this->motionX ** 2) + ($this->motionZ ** 2));
$this->yaw = (atan2($this->motionX, $this->motionZ) * 180 / M_PI);
$this->pitch = (atan2($this->motionY, $f) * 180 / M_PI);
$hasUpdate = true;
}
$this->updateMovement();
}
return $hasUpdate;
}
} | 412 | 0.90438 | 1 | 0.90438 | game-dev | MEDIA | 0.934651 | game-dev | 0.939676 | 1 | 0.939676 |
jotesoft/sudachi_yzm | 8,748 | src/hid_core/resources/touch_screen/gesture_handler.cpp | // SPDX-FileCopyrightText: Copyright 2024 yuzu Emulator Project
// SPDX-License-Identifier: GPL-3.0-or-later
#include "common/math_util.h"
#include "hid_core/resources/touch_screen/gesture_handler.h"
namespace Service::HID {
constexpr f32 Square(s32 num) {
return static_cast<f32>(num * num);
}
GestureHandler::GestureHandler() {}
GestureHandler::~GestureHandler() {}
void GestureHandler::SetTouchState(std::span<TouchState> touch_state, u32 count, s64 timestamp) {
gesture = {};
gesture.active_points = std::min(MaxPoints, static_cast<std::size_t>(count));
for (size_t id = 0; id < gesture.active_points; ++id) {
const auto& [active_x, active_y] = touch_state[id].position;
gesture.points[id] = {
.x = static_cast<s32>(active_x),
.y = static_cast<s32>(active_y),
};
gesture.mid_point.x += static_cast<s32>(gesture.points[id].x / gesture.active_points);
gesture.mid_point.y += static_cast<s32>(gesture.points[id].y / gesture.active_points);
}
for (size_t id = 0; id < gesture.active_points; ++id) {
const f32 distance = std::sqrt(Square(gesture.mid_point.x - gesture.points[id].x) +
Square(gesture.mid_point.y - gesture.points[id].y));
gesture.average_distance += distance / static_cast<f32>(gesture.active_points);
}
gesture.angle = std::atan2(static_cast<f32>(gesture.mid_point.y - gesture.points[0].y),
static_cast<f32>(gesture.mid_point.x - gesture.points[0].x));
gesture.detection_count = last_gesture.detection_count;
if (last_update_timestamp > timestamp) {
timestamp = last_tap_timestamp;
}
time_difference = static_cast<f32>(timestamp - last_update_timestamp) / (1000 * 1000 * 1000);
}
bool GestureHandler::NeedsUpdate() {
if (force_update) {
force_update = false;
return true;
}
// Update if coordinates change
for (size_t id = 0; id < MaxPoints; id++) {
if (gesture.points[id] != last_gesture.points[id]) {
return true;
}
}
// Update on press and hold event after 0.5 seconds
if (last_gesture_state.type == GestureType::Touch && last_gesture_state.point_count == 1 &&
time_difference > PressDelay) {
return enable_press_and_tap;
}
return false;
}
void GestureHandler::UpdateGestureState(GestureState& next_state, s64 timestamp) {
last_update_timestamp = timestamp;
GestureType type = GestureType::Idle;
GestureAttribute attributes{};
// Reset next state to default
next_state.sampling_number = last_gesture_state.sampling_number + 1;
next_state.delta = {};
next_state.vel_x = 0;
next_state.vel_y = 0;
next_state.direction = GestureDirection::None;
next_state.rotation_angle = 0;
next_state.scale = 0;
if (gesture.active_points > 0) {
if (last_gesture.active_points == 0) {
NewGesture(type, attributes);
} else {
UpdateExistingGesture(next_state, type);
}
} else {
EndGesture(next_state, type, attributes);
}
// Apply attributes
next_state.detection_count = gesture.detection_count;
next_state.type = type;
next_state.attributes = attributes;
next_state.pos = gesture.mid_point;
next_state.point_count = static_cast<s32>(gesture.active_points);
next_state.points = gesture.points;
last_gesture = gesture;
last_gesture_state = next_state;
}
void GestureHandler::NewGesture(GestureType& type, GestureAttribute& attributes) {
gesture.detection_count++;
type = GestureType::Touch;
// New touch after cancel is not considered new
if (last_gesture_state.type != GestureType::Cancel) {
attributes.is_new_touch.Assign(1);
enable_press_and_tap = true;
}
}
void GestureHandler::UpdateExistingGesture(GestureState& next_state, GestureType& type) {
// Promote to pan type if touch moved
for (size_t id = 0; id < MaxPoints; id++) {
if (gesture.points[id] != last_gesture.points[id]) {
type = GestureType::Pan;
break;
}
}
// Number of fingers changed cancel the last event and clear data
if (gesture.active_points != last_gesture.active_points) {
type = GestureType::Cancel;
enable_press_and_tap = false;
gesture.active_points = 0;
gesture.mid_point = {};
gesture.points.fill({});
return;
}
// Calculate extra parameters of panning
if (type == GestureType::Pan) {
UpdatePanEvent(next_state, type);
return;
}
// Promote to press type
if (last_gesture_state.type == GestureType::Touch) {
type = GestureType::Press;
}
}
void GestureHandler::EndGesture(GestureState& next_state, GestureType& type,
GestureAttribute& attributes) {
if (last_gesture.active_points != 0) {
switch (last_gesture_state.type) {
case GestureType::Touch:
if (enable_press_and_tap) {
SetTapEvent(type, attributes);
return;
}
type = GestureType::Cancel;
force_update = true;
break;
case GestureType::Press:
case GestureType::Tap:
case GestureType::Swipe:
case GestureType::Pinch:
case GestureType::Rotate:
type = GestureType::Complete;
force_update = true;
break;
case GestureType::Pan:
EndPanEvent(next_state, type);
break;
default:
break;
}
return;
}
if (last_gesture_state.type == GestureType::Complete ||
last_gesture_state.type == GestureType::Cancel) {
gesture.detection_count++;
}
}
void GestureHandler::SetTapEvent(GestureType& type, GestureAttribute& attributes) {
type = GestureType::Tap;
gesture = last_gesture;
force_update = true;
f32 tap_time_difference =
static_cast<f32>(last_update_timestamp - last_tap_timestamp) / (1000 * 1000 * 1000);
last_tap_timestamp = last_update_timestamp;
if (tap_time_difference < DoubleTapDelay) {
attributes.is_double_tap.Assign(1);
}
}
void GestureHandler::UpdatePanEvent(GestureState& next_state, GestureType& type) {
next_state.delta = gesture.mid_point - last_gesture_state.pos;
next_state.vel_x = static_cast<f32>(next_state.delta.x) / time_difference;
next_state.vel_y = static_cast<f32>(next_state.delta.y) / time_difference;
last_pan_time_difference = time_difference;
// Promote to pinch type
if (std::abs(gesture.average_distance - last_gesture.average_distance) > PinchThreshold) {
type = GestureType::Pinch;
next_state.scale = gesture.average_distance / last_gesture.average_distance;
}
const f32 angle_between_two_lines = std::atan((gesture.angle - last_gesture.angle) /
(1 + (gesture.angle * last_gesture.angle)));
// Promote to rotate type
if (std::abs(angle_between_two_lines) > AngleThreshold) {
type = GestureType::Rotate;
next_state.scale = 0;
next_state.rotation_angle = angle_between_two_lines * 180.0f / Common::PI;
}
}
void GestureHandler::EndPanEvent(GestureState& next_state, GestureType& type) {
next_state.vel_x =
static_cast<f32>(last_gesture_state.delta.x) / (last_pan_time_difference + time_difference);
next_state.vel_y =
static_cast<f32>(last_gesture_state.delta.y) / (last_pan_time_difference + time_difference);
const f32 curr_vel =
std::sqrt((next_state.vel_x * next_state.vel_x) + (next_state.vel_y * next_state.vel_y));
// Set swipe event with parameters
if (curr_vel > SwipeThreshold) {
SetSwipeEvent(next_state, type);
return;
}
// End panning without swipe
type = GestureType::Complete;
next_state.vel_x = 0;
next_state.vel_y = 0;
force_update = true;
}
void GestureHandler::SetSwipeEvent(GestureState& next_state, GestureType& type) {
type = GestureType::Swipe;
gesture = last_gesture;
force_update = true;
next_state.delta = last_gesture_state.delta;
if (std::abs(next_state.delta.x) > std::abs(next_state.delta.y)) {
if (next_state.delta.x > 0) {
next_state.direction = GestureDirection::Right;
return;
}
next_state.direction = GestureDirection::Left;
return;
}
if (next_state.delta.y > 0) {
next_state.direction = GestureDirection::Down;
return;
}
next_state.direction = GestureDirection::Up;
}
} // namespace Service::HID
| 412 | 0.858388 | 1 | 0.858388 | game-dev | MEDIA | 0.255895 | game-dev | 0.832412 | 1 | 0.832412 |
paynebc/tunefish | 40,347 | src/tunefish4/JuceLibraryCode/modules/juce_audio_processors/format_types/VST3_SDK/base/source/fstring.h | //------------------------------------------------------------------------
// Project : SDK Base
// Version : 1.0
//
// Category : Helpers
// Filename : base/source/fstring.h
// Created by : Steinberg, 2008
// Description : String class
//
//-----------------------------------------------------------------------------
// LICENSE
// (c) 2019, Steinberg Media Technologies GmbH, All Rights Reserved
//-----------------------------------------------------------------------------
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of the Steinberg Media Technologies nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
//-----------------------------------------------------------------------------
#pragma once
#include "pluginterfaces/base/ftypes.h"
#include "pluginterfaces/base/fstrdefs.h"
#include "pluginterfaces/base/istringresult.h"
#include "pluginterfaces/base/ipersistent.h"
#include "base/source/fobject.h"
#include <stdarg.h>
namespace Steinberg {
class FVariant;
class String;
#ifdef UNICODE
static const bool kWideStringDefault = true;
#else
static const bool kWideStringDefault = false;
#endif
static const uint16 kBomUtf16 = 0xFEFF; ///< UTF16 Byte Order Mark
static const char8* const kBomUtf8 = "\xEF\xBB\xBF"; ///< UTF8 Byte Order Mark
static const int32 kBomUtf8Length = 3;
enum MBCodePage
{
kCP_ANSI = 0, ///< Default ANSI codepage.
kCP_MAC_ROMAN = 2, ///< Default Mac codepage.
kCP_ANSI_WEL = 1252, ///< West European Latin Encoding.
kCP_MAC_CEE = 10029, ///< Mac Central European Encoding.
kCP_Utf8 = 65001, ///< UTF8 Encoding.
kCP_ShiftJIS = 932, ///< Shifted Japan Industrial Standard Encoding.
kCP_US_ASCII = 20127, ///< US-ASCII (7-bit).
kCP_Default = kCP_ANSI ///< Default ANSI codepage.
};
enum UnicodeNormalization
{
kUnicodeNormC, ///< Unicode normalization Form C, canonical composition.
kUnicodeNormD, ///< Unicode normalization Form D, canonical decomposition.
kUnicodeNormKC, ///< Unicode normalization form KC, compatibility composition.
kUnicodeNormKD ///< Unicode normalization form KD, compatibility decomposition.
};
//------------------------------------------------------------------------
// Helper functions to create hash codes from string data.
//------------------------------------------------------------------------
extern uint32 hashString8 (const char8* s, uint32 m);
extern uint32 hashString16 (const char16* s, uint32 m);
inline uint32 hashString (const tchar* s, uint32 m)
{
#ifdef UNICODE
return hashString16 (s, m);
#else
return hashString8 (s, m);
#endif
}
//-----------------------------------------------------------------------------
/** Invariant String.
@ingroup adt
A base class which provides methods to work with its
member string. Neither of the operations allows modifying the member string and
that is why all operation are declared as const.
There are operations for access, comparison, find, numbers and conversion.
Almost all operations exist in three versions for char8, char16 and the
polymorphic type tchar. The type tchar can either be char8 or char16 depending
on whether UNICODE is activated or not.*/
//-----------------------------------------------------------------------------
class ConstString
{
public:
//-----------------------------------------------------------------------------
ConstString (const char8* str, int32 length = -1); ///< Assign from string of type char8 (length=-1: all)
ConstString (const char16* str, int32 length = -1); ///< Assign from string of type char16 (length=-1: all)
ConstString (const ConstString& str, int32 offset = 0, int32 length = -1); ///< Copy constructor (length=-1: all).
ConstString (const FVariant& var); ///< Assign a string from FVariant
ConstString ();
virtual ~ConstString () {} ///< Destructor.
// access -----------------------------------------------------------------
virtual int32 length () const {return static_cast<int32> (len);} ///< Return length of string
inline bool isEmpty () const {return buffer == 0 || len == 0;} ///< Return true if string is empty
operator const char8* () const {return text8 ();} ///< Returns pointer to string of type char8 (no modification allowed)
operator const char16* () const {return text16 ();} ///< Returns pointer to string of type char16(no modification allowed)
inline tchar operator[] (short idx) const {return getChar (static_cast<uint32> (idx));} ///< Returns character at 'idx'
inline tchar operator[] (long idx) const {return getChar (static_cast<uint32> (idx));}
inline tchar operator[] (int idx) const {return getChar (static_cast<uint32> (idx));}
inline tchar operator[] (unsigned short idx) const {return getChar (idx);}
inline tchar operator[] (unsigned long idx) const {return getChar (static_cast<uint32> (idx));}
inline tchar operator[] (unsigned int idx) const {return getChar (idx);}
inline virtual const char8* text8 () const; ///< Returns pointer to string of type char8
inline virtual const char16* text16 () const; ///< Returns pointer to string of type char16
inline virtual const tchar* text () const; ///< Returns pointer to string of type tchar
inline virtual const void* ptr () const {return buffer;} ///< Returns pointer to string of type void
inline virtual char8 getChar8 (uint32 index) const; ///< Returns character of type char16 at 'index'
inline virtual char16 getChar16 (uint32 index) const; ///< Returns character of type char8 at 'index'
inline tchar getChar (uint32 index) const; ///< Returns character of type tchar at 'index'
inline tchar getCharAt (uint32 index) const; ///< Returns character of type tchar at 'index', no conversion!
bool testChar8 (uint32 index, char8 c) const; ///< Returns true if character is equal at position 'index'
bool testChar16 (uint32 index, char16 c) const;
inline bool testChar (uint32 index, char8 c) const {return testChar8 (index, c);}
inline bool testChar (uint32 index, char16 c) const {return testChar16 (index, c);}
bool extract (String& result, uint32 idx, int32 n = -1) const; ///< Get n characters long substring starting at index (n=-1: until end)
int32 copyTo8 (char8* str, uint32 idx = 0, int32 n = -1) const;
int32 copyTo16 (char16* str, uint32 idx = 0, int32 n = -1) const;
int32 copyTo (tchar* str, uint32 idx = 0, int32 n = -1) const;
void copyTo (IStringResult* result) const; ///< Copies whole member string
void copyTo (IString& string) const; ///< Copies whole member string
inline uint32 hash (uint32 tsize) const
{
return isWide ? hashString16 (buffer16, tsize) : hashString8 (buffer8, tsize) ;
}
//-------------------------------------------------------------------------
// compare ----------------------------------------------------------------
enum CompareMode
{
kCaseSensitive, ///< Comparison is done with regard to character's case
kCaseInsensitive ///< Comparison is done without regard to character's case
};
int32 compareAt (uint32 index, const ConstString& str, int32 n = -1, CompareMode m = kCaseSensitive) const; ///< Compare n characters of str with n characters of this starting at index (return: see above)
int32 compare (const ConstString& str, int32 n, CompareMode m = kCaseSensitive) const; ///< Compare n characters of str with n characters of this (return: see above)
int32 compare (const ConstString& str, CompareMode m = kCaseSensitive) const; ///< Compare all characters of str with this (return: see above)
int32 naturalCompare (const ConstString& str, CompareMode mode = kCaseSensitive) const;
bool startsWith (const ConstString& str, CompareMode m = kCaseSensitive) const; ///< Check if this starts with str
bool endsWith (const ConstString& str, CompareMode m = kCaseSensitive) const; ///< Check if this ends with str
bool contains (const ConstString& str, CompareMode m = kCaseSensitive) const; ///< Check if this contains str
// static methods
static bool isCharSpace (char8 character); ///< Returns true if character is a space
static bool isCharSpace (char16 character); ///< @copydoc isCharSpace(const char8)
static bool isCharAlpha (char8 character); ///< Returns true if character is an alphabetic character
static bool isCharAlpha (char16 character); ///< @copydoc isCharAlpha(const char8)
static bool isCharAlphaNum (char8 character); ///< Returns true if character is an alphanumeric character
static bool isCharAlphaNum (char16 character); ///< @copydoc isCharAlphaNum(const char8)
static bool isCharDigit (char8 character); ///< Returns true if character is a number
static bool isCharDigit (char16 character); ///< @copydoc isCharDigit(const char8)
static bool isCharAscii (char8 character); ///< Returns true if character is in ASCII range
static bool isCharAscii (char16 character); ///< Returns true if character is in ASCII range
static bool isCharUpper (char8 character);
static bool isCharUpper (char16 character);
static bool isCharLower (char8 character);
static bool isCharLower (char16 character);
//-------------------------------------------------------------------------
/** @name Find first occurrence of n characters of str in this (n=-1: all) ending at endIndex (endIndex = -1: all)*/
///@{
inline int32 findFirst (const ConstString& str, int32 n = -1, CompareMode m = kCaseSensitive, int32 endIndex = -1) const {return findNext (0, str, n, m, endIndex);}
inline int32 findFirst (char8 c, CompareMode m = kCaseSensitive, int32 endIndex = -1) const {return findNext (0, c, m, endIndex);}
inline int32 findFirst (char16 c, CompareMode m = kCaseSensitive, int32 endIndex = -1) const {return findNext (0, c, m, endIndex);}
///@}
/** @name Find next occurrence of n characters of str starting at startIndex in this (n=-1: all) ending at endIndex (endIndex = -1: all)*/
///@{
int32 findNext (int32 startIndex, const ConstString& str, int32 n = -1, CompareMode = kCaseSensitive, int32 endIndex = -1) const;
int32 findNext (int32 startIndex, char8 c, CompareMode = kCaseSensitive, int32 endIndex = -1) const;
int32 findNext (int32 startIndex, char16 c, CompareMode = kCaseSensitive, int32 endIndex = -1) const;
///@}
/** @name Find previous occurrence of n characters of str starting at startIndex in this (n=-1: all) */
///@{
int32 findPrev (int32 startIndex, const ConstString& str, int32 n = -1, CompareMode = kCaseSensitive) const;
int32 findPrev (int32 startIndex, char8 c, CompareMode = kCaseSensitive) const;
int32 findPrev (int32 startIndex, char16 c, CompareMode = kCaseSensitive) const;
///@}
inline int32 findLast (const ConstString& str, int32 n = -1, CompareMode m = kCaseSensitive) const {return findPrev (-1, str, n, m);} ///< Find last occurrence of n characters of str in this (n=-1: all)
inline int32 findLast (char8 c, CompareMode m = kCaseSensitive) const {return findPrev (-1, c, m);}
inline int32 findLast (char16 c, CompareMode m = kCaseSensitive) const {return findPrev (-1, c, m);}
int32 countOccurences (char8 c, uint32 startIndex, CompareMode = kCaseSensitive) const; ///< Counts occurences of c within this starting at index
int32 countOccurences (char16 c, uint32 startIndex, CompareMode = kCaseSensitive) const;
int32 getFirstDifferent (const ConstString& str, CompareMode = kCaseSensitive) const; ///< Returns position of first different character
//-------------------------------------------------------------------------
// numbers ----------------------------------------------------------------
bool isDigit (uint32 index) const; ///< Returns true if character at position is a digit
bool scanFloat (double& value, uint32 offset = 0, bool scanToEnd = true) const; ///< Converts string to double value starting at offset
bool scanInt64 (int64& value, uint32 offset = 0, bool scanToEnd = true) const; ///< Converts string to int64 value starting at offset
bool scanUInt64 (uint64& value, uint32 offset = 0, bool scanToEnd = true) const; ///< Converts string to uint64 value starting at offset
bool scanInt32 (int32& value, uint32 offset = 0, bool scanToEnd = true) const; ///< Converts string to int32 value starting at offset
bool scanUInt32 (uint32& value, uint32 offset = 0, bool scanToEnd = true) const; ///< Converts string to uint32 value starting at offset
bool scanHex (uint8& value, uint32 offset = 0, bool scanToEnd = true) const; ///< Converts string to hex/uint8 value starting at offset
int32 getTrailingNumberIndex (uint32 width = 0) const; ///< Returns start index of trailing number
int64 getTrailingNumber (int64 fallback = 0) const; ///< Returns result of scanInt64 or the fallback
int64 getNumber () const; ///< Returns result of scanInt64
// static methods
static bool scanInt64_8 (const char8* text, int64& value, bool scanToEnd = true); ///< Converts string of type char8 to int64 value
static bool scanInt64_16 (const char16* text, int64& value, bool scanToEnd = true); ///< Converts string of type char16 to int64 value
static bool scanInt64 (const tchar* text, int64& value, bool scanToEnd = true); ///< Converts string of type tchar to int64 value
static bool scanUInt64_8 (const char8* text, uint64& value, bool scanToEnd = true); ///< Converts string of type char8 to uint64 value
static bool scanUInt64_16 (const char16* text, uint64& value, bool scanToEnd = true); ///< Converts string of type char16 to uint64 value
static bool scanUInt64 (const tchar* text, uint64& value, bool scanToEnd = true); ///< Converts string of type tchar to uint64 value
static bool scanInt32_8 (const char8* text, int32& value, bool scanToEnd = true); ///< Converts string of type char8 to int32 value
static bool scanInt32_16 (const char16* text, int32& value, bool scanToEnd = true); ///< Converts string of type char16 to int32 value
static bool scanInt32 (const tchar* text, int32& value, bool scanToEnd = true); ///< Converts string of type tchar to int32 value
static bool scanUInt32_8 (const char8* text, uint32& value, bool scanToEnd = true); ///< Converts string of type char8 to int32 value
static bool scanUInt32_16 (const char16* text, uint32& value, bool scanToEnd = true); ///< Converts string of type char16 to int32 value
static bool scanUInt32 (const tchar* text, uint32& value, bool scanToEnd = true); ///< Converts string of type tchar to int32 value
static bool scanHex_8 (const char8* text, uint8& value, bool scanToEnd = true); ///< Converts string of type char8 to hex/unit8 value
static bool scanHex_16 (const char16* text, uint8& value, bool scanToEnd = true); ///< Converts string of type char16 to hex/unit8 value
static bool scanHex (const tchar* text, uint8& value, bool scanToEnd = true); ///< Converts string of type tchar to hex/unit8 value
//-------------------------------------------------------------------------
// conversion -------------------------------------------------------------
void toVariant (FVariant& var) const;
static char8 toLower (char8 c); ///< Converts to lower case
static char8 toUpper (char8 c); ///< Converts to upper case
static char16 toLower (char16 c);
static char16 toUpper (char16 c);
static int32 multiByteToWideString (char16* dest, const char8* source, int32 wcharCount, uint32 sourceCodePage = kCP_Default); ///< If dest is zero, this returns the maximum number of bytes needed to convert source
static int32 wideStringToMultiByte (char8* dest, const char16* source, int32 char8Count, uint32 destCodePage = kCP_Default); ///< If dest is zero, this returns the maximum number of bytes needed to convert source
bool isWideString () const {return isWide != 0;} ///< Returns true if string is wide
bool isAsciiString () const; ///< Checks if all characters in string are in ascii range
bool isNormalized (UnicodeNormalization = kUnicodeNormC); ///< On PC only kUnicodeNormC is working
#if SMTG_OS_MACOS
virtual void* toCFStringRef (uint32 encoding = 0xFFFF, bool mutableCFString = false) const; ///< CFString conversion
#endif
//-------------------------------------------------------------------------
//-----------------------------------------------------------------------------
protected:
union
{
void* buffer;
char8* buffer8;
char16* buffer16;
};
uint32 len : 30;
uint32 isWide : 1;
};
//-----------------------------------------------------------------------------
/** String.
@ingroup adt
Extends class ConstString by operations which allow modifications.
\see ConstString */
//-----------------------------------------------------------------------------
class String : public ConstString
{
public:
//-----------------------------------------------------------------------------
String ();
String (const char8* str, MBCodePage codepage, int32 n = -1, bool isTerminated = true); ///< assign n characters of str and convert to wide string by using the specified codepage
String (const char8* str, int32 n = -1, bool isTerminated = true); ///< assign n characters of str (-1: all)
String (const char16* str, int32 n = -1, bool isTerminated = true); ///< assign n characters of str (-1: all)
String (const String& str, int32 n = -1); ///< assign n characters of str (-1: all)
String (const ConstString& str, int32 n = -1); ///< assign n characters of str (-1: all)
String (const FVariant& var); ///< assign from FVariant
String (IString* str); ///< assign from IString
~String ();
#if SMTG_CPP11_STDLIBSUPPORT
String (String&& str);
String& operator= (String&& str);
#endif
// access------------------------------------------------------------------
void updateLength (); ///< Call this when the string is truncated outside (not recommended though)
virtual const char8* text8 () const SMTG_OVERRIDE;
virtual const char16* text16 () const SMTG_OVERRIDE;
virtual char8 getChar8 (uint32 index) const SMTG_OVERRIDE;
virtual char16 getChar16 (uint32 index) const SMTG_OVERRIDE;
bool setChar8 (uint32 index, char8 c);
bool setChar16 (uint32 index, char16 c);
inline bool setChar (uint32 index, char8 c) {return setChar8 (index, c);}
inline bool setChar (uint32 index, char16 c) {return setChar16 (index, c);}
//-------------------------------------------------------------------------
// assignment--------------------------------------------------------------
String& operator= (const char8* str) {return assign (str);} ///< Assign from a string of type char8
String& operator= (const char16* str) {return assign (str);}
String& operator= (const ConstString& str) {return assign (str);}
String& operator= (const String& str) {return assign (str);}
String& operator= (char8 c) {return assign (c);}
String& operator= (char16 c) {return assign (c);}
String& assign (const ConstString& str, int32 n = -1); ///< Assign n characters of str (-1: all)
String& assign (const char8* str, int32 n = -1, bool isTerminated = true); ///< Assign n characters of str (-1: all)
String& assign (const char16* str, int32 n = -1, bool isTerminated = true); ///< Assign n characters of str (-1: all)
String& assign (char8 c, int32 n = 1);
String& assign (char16 c, int32 n = 1);
//-------------------------------------------------------------------------
// concat------------------------------------------------------------------
String& append (const ConstString& str, int32 n = -1); ///< Append n characters of str to this (n=-1: all)
String& append (const char8* str, int32 n = -1); ///< Append n characters of str to this (n=-1: all)
String& append (const char16* str, int32 n = -1); ///< Append n characters of str to this (n=-1: all)
String& append (const char8 c, int32 n = 1); ///< Append char c n times
String& append (const char16 c, int32 n = 1); ///< Append char c n times
String& insertAt (uint32 idx, const ConstString& str, int32 n = -1); ///< Insert n characters of str at position idx (n=-1: all)
String& insertAt (uint32 idx, const char8* str, int32 n = -1); ///< Insert n characters of str at position idx (n=-1: all)
String& insertAt (uint32 idx, const char16* str, int32 n = -1); ///< Insert n characters of str at position idx (n=-1: all)
String& insertAt (uint32 idx, char8 c) {char8 str[] = {c, 0}; return insertAt (idx, str, 1);}
String& insertAt (uint32 idx, char16 c) {char16 str[] = {c, 0}; return insertAt (idx, str, 1);}
String& operator+= (const String& str) {return append (str);}
String& operator+= (const ConstString& str) {return append (str);}
String& operator+= (const char8* str) {return append (str);}
String& operator+= (const char16* str) {return append (str);}
String& operator+= (const char8 c) {return append (c);}
String& operator+= (const char16 c) {return append (c);}
//-------------------------------------------------------------------------
// replace-----------------------------------------------------------------
String& replace (uint32 idx, int32 n1, const ConstString& str, int32 n2 = -1); ///< Replace n1 characters of this (starting at idx) with n2 characters of str (n1,n2=-1: until end)
String& replace (uint32 idx, int32 n1, const char8* str, int32 n2 = -1); ///< Replace n1 characters of this (starting at idx) with n2 characters of str (n1,n2=-1: until end)
String& replace (uint32 idx, int32 n1, const char16* str, int32 n2 = -1); ///< Replace n1 characters of this (starting at idx) with n2 characters of str (n1,n2=-1: until end)
int32 replace (const char8* toReplace, const char8* toReplaceWith, bool all = false, CompareMode m = kCaseSensitive); ///< Replace find string with replace string - returns number of replacements
int32 replace (const char16* toReplace, const char16* toReplaceWith, bool all = false, CompareMode m = kCaseSensitive); ///< Replace find string with replace string - returns number of replacements
bool replaceChars8 (const char8* toReplace, char8 toReplaceBy); ///< Returns true when any replacement was done
bool replaceChars16 (const char16* toReplace, char16 toReplaceBy);
inline bool replaceChars8 (char8 toReplace, char8 toReplaceBy) {char8 str[] = {toReplace, 0}; return replaceChars8 (str, toReplaceBy);}
inline bool replaceChars16 (char16 toReplace, char16 toReplaceBy) {char16 str[] = {toReplace, 0}; return replaceChars16 (str, toReplaceBy);}
inline bool replaceChars (char8 toReplace, char8 toReplaceBy) {return replaceChars8 (toReplace, toReplaceBy);}
inline bool replaceChars (char16 toReplace, char16 toReplaceBy) {return replaceChars16 (toReplace, toReplaceBy);}
inline bool replaceChars (const char8* toReplace, char8 toReplaceBy) {return replaceChars8 (toReplace, toReplaceBy);}
inline bool replaceChars (const char16* toReplace, char16 toReplaceBy) {return replaceChars16 (toReplace, toReplaceBy);}
//-------------------------------------------------------------------------
// remove------------------------------------------------------------------
String& remove (uint32 index = 0, int32 n = -1); ///< Remove n characters from string starting at index (n=-1: until end)
enum CharGroup {kSpace, kNotAlphaNum, kNotAlpha};
bool trim (CharGroup mode = kSpace); ///< Trim lead/trail.
void removeChars (CharGroup mode = kSpace); ///< Removes all of group.
bool removeChars8 (const char8* which); ///< Remove all occurrences of each char in 'which'
bool removeChars16 (const char16* which); ///< Remove all occurrences of each char in 'which'
inline bool removeChars8 (const char8 which) {char8 str[] = {which, 0}; return removeChars8 (str); }
inline bool removeChars16 (const char16 which) {char16 str[] = {which, 0}; return removeChars16 (str); }
inline bool removeChars (const char8* which) {return removeChars8 (which);}
inline bool removeChars (const char16* which) {return removeChars16 (which);}
inline bool removeChars (const char8 which) {return removeChars8 (which);}
inline bool removeChars (const char16 which) {return removeChars16 (which);}
bool removeSubString (const ConstString& subString, bool allOccurences = true);
//-------------------------------------------------------------------------
// print-------------------------------------------------------------------
String& printf (const char8* format, ...); ///< Print formatted data into string
String& printf (const char16* format, ...); ///< Print formatted data into string
String& vprintf (const char8* format, va_list args);
String& vprintf (const char16* format, va_list args);
//-------------------------------------------------------------------------
// numbers-----------------------------------------------------------------
String& printInt64 (int64 value);
String& printFloat (double value);
/** Increment the trailing number if present else start with minNumber, width specifies the string width format (width 2 for number 3 is 03),
applyOnlyFormat set to true will only format the string to the given width without incrementing the founded trailing number */
bool incrementTrailingNumber (uint32 width = 2, tchar separator = STR (' '), uint32 minNumber = 1, bool applyOnlyFormat = false);
//-------------------------------------------------------------------------
// conversion--------------------------------------------------------------
bool fromVariant (const FVariant& var); ///< Assigns string from FVariant
void toVariant (FVariant& var) const;
bool fromAttributes (IAttributes* a, IAttrID attrID); ///< Assigns string from FAttributes
bool toAttributes (IAttributes* a, IAttrID attrID);
void swapContent (String& s); ///< Swaps ownership of the strings pointed to
void take (String& str); ///< Take ownership of the string of 'str'
void take (void* _buffer, bool wide); ///< Take ownership of buffer
void* pass ();
void passToVariant (FVariant& var); ///< Pass ownership of buffer to Variant - sets Variant ownership
void toLower (uint32 index); ///< Lower case the character.
void toLower (); ///< Lower case the string.
void toUpper (uint32 index); ///< Upper case the character.
void toUpper (); ///< Upper case the string.
unsigned char* toPascalString (unsigned char* buf); ///< Pascal string conversion
const String& fromPascalString (const unsigned char* buf); ///< Pascal string conversion
bool toWideString (uint32 sourceCodePage = kCP_Default); ///< Converts to wide string according to sourceCodePage
bool toMultiByte (uint32 destCodePage = kCP_Default);
void fromUTF8 (const char8* utf8String); ///< Assigns from UTF8 string
bool normalize (UnicodeNormalization = kUnicodeNormC); ///< On PC only kUnicodeNormC is working
#if SMTG_OS_MACOS
virtual bool fromCFStringRef (const void*, uint32 encoding = 0xFFFF); ///< CFString conversion
#endif
//-------------------------------------------------------------------------
//-----------------------------------------------------------------------------
protected:
bool resize (uint32 newSize, bool wide, bool fill = false);
private:
void tryFreeBuffer ();
bool checkToMultiByte (uint32 destCodePage = kCP_Default) const; // to remove debug code from inline - const_cast inside!!!
};
// String concatenation functions.
inline String operator+ (const ConstString& s1, const ConstString& s2) {return String (s1).append (s2);}
inline String operator+ (const ConstString& s1, const char8* s2) {return String (s1).append (s2);}
inline String operator+ (const ConstString& s1, const char16* s2) {return String (s1).append (s2);}
inline String operator+ (const char8* s1, const ConstString& s2) {return String (s1).append (s2);}
inline String operator+ (const char16* s1, const ConstString& s2) {return String (s1).append (s2);}
inline String operator+ (const ConstString& s1, const String& s2) {return String (s1).append (s2);}
inline String operator+ (const String& s1, const ConstString& s2) {return String (s1).append (s2);}
inline String operator+ (const String& s1, const String& s2) {return String (s1).append (s2);}
inline String operator+ (const String& s1, const char8* s2) {return String (s1).append (s2);}
inline String operator+ (const String& s1, const char16* s2) {return String (s1).append (s2);}
inline String operator+ (const char8* s1, const String& s2) {return String (s1).append (s2);}
inline String operator+ (const char16* s1, const String& s2) {return String (s1).append (s2);}
//-----------------------------------------------------------------------------
// ConstString
//-----------------------------------------------------------------------------
inline const tchar* ConstString::text () const
{
#ifdef UNICODE
return text16 ();
#else
return text8 ();
#endif
}
//-----------------------------------------------------------------------------
inline const char8* ConstString::text8 () const
{
return (!isWide && buffer8) ? buffer8: kEmptyString8;
}
//-----------------------------------------------------------------------------
inline const char16* ConstString::text16 () const
{
return (isWide && buffer16) ? buffer16 : kEmptyString16;
}
//-----------------------------------------------------------------------------
inline char8 ConstString::getChar8 (uint32 index) const
{
if (index < len && buffer8 && !isWide)
return buffer8[index];
return 0;
}
//-----------------------------------------------------------------------------
inline char16 ConstString::getChar16 (uint32 index) const
{
if (index < len && buffer16 && isWide)
return buffer16[index];
return 0;
}
//-----------------------------------------------------------------------------
inline tchar ConstString::getChar (uint32 index) const
{
#ifdef UNICODE
return getChar16 (index);
#else
return getChar8 (index);
#endif
}
//-----------------------------------------------------------------------------
inline tchar ConstString::getCharAt (uint32 index) const
{
#ifdef UNICODE
if (isWide)
return getChar16 (index);
#endif
return static_cast<tchar> (getChar8 (index));
}
//-----------------------------------------------------------------------------
inline int64 ConstString::getNumber () const
{
int64 tmp = 0;
scanInt64 (tmp);
return tmp;
}
//-----------------------------------------------------------------------------
inline bool ConstString::scanInt32_8 (const char8* text, int32& value, bool scanToEnd)
{
int64 tmp;
if (scanInt64_8 (text, tmp, scanToEnd))
{
value = (int32)tmp;
return true;
}
return false;
}
//-----------------------------------------------------------------------------
inline bool ConstString::scanInt32_16 (const char16* text, int32& value, bool scanToEnd)
{
int64 tmp;
if (scanInt64_16 (text, tmp, scanToEnd))
{
value = (int32)tmp;
return true;
}
return false;
}
//-----------------------------------------------------------------------------
inline bool ConstString::scanInt32 (const tchar* text, int32& value, bool scanToEnd)
{
int64 tmp;
if (scanInt64 (text, tmp, scanToEnd))
{
value = (int32)tmp;
return true;
}
return false;
}
//-----------------------------------------------------------------------------
inline bool ConstString::scanUInt32_8 (const char8* text, uint32& value, bool scanToEnd)
{
uint64 tmp;
if (scanUInt64_8 (text, tmp, scanToEnd))
{
value = (uint32)tmp;
return true;
}
return false;
}
//-----------------------------------------------------------------------------
inline bool ConstString::scanUInt32_16 (const char16* text, uint32& value, bool scanToEnd)
{
uint64 tmp;
if (scanUInt64_16 (text, tmp, scanToEnd))
{
value = (uint32)tmp;
return true;
}
return false;
}
//-----------------------------------------------------------------------------
inline bool ConstString::scanUInt32 (const tchar* text, uint32& value, bool scanToEnd)
{
uint64 tmp;
if (scanUInt64 (text, tmp, scanToEnd))
{
value = (uint32)tmp;
return true;
}
return false;
}
//-----------------------------------------------------------------------------
inline const char8* String::text8 () const
{
if (isWide && !isEmpty ())
checkToMultiByte (); // this should be avoided, since it can lead to information loss
return ConstString::text8 ();
}
//-----------------------------------------------------------------------------
inline const char16* String::text16 () const
{
if (!isWide && !isEmpty ())
{
const_cast<String&> (*this).toWideString ();
}
return ConstString::text16 ();
}
//-----------------------------------------------------------------------------
inline char8 String::getChar8 (uint32 index) const
{
if (isWide && !isEmpty ())
checkToMultiByte (); // this should be avoided, since it can lead to information loss
return ConstString::getChar8 (index);
}
//-----------------------------------------------------------------------------
inline char16 String::getChar16 (uint32 index) const
{
if (!isWide && !isEmpty ())
{
const_cast<String&> (*this).toWideString ();
}
return ConstString::getChar16 (index);
}
//-----------------------------------------------------------------------------
inline bool operator< (const ConstString& s1, const ConstString& s2) {return (s1.compare (s2) < 0) ? true : false;}
inline bool operator<= (const ConstString& s1, const ConstString& s2) {return (s1.compare (s2) <= 0) ? true : false;}
inline bool operator> (const ConstString& s1, const ConstString& s2) {return (s1.compare (s2) > 0) ? true : false;}
inline bool operator>= (const ConstString& s1, const ConstString& s2) {return (s1.compare (s2) >= 0) ? true : false;}
inline bool operator== (const ConstString& s1, const ConstString& s2) {return (s1.compare (s2) == 0) ? true : false;}
inline bool operator!= (const ConstString& s1, const ConstString& s2) {return (s1.compare (s2) != 0) ? true : false;}
inline bool operator< (const ConstString& s1, const char8* s2) {return (s1.compare (s2) < 0) ? true : false;}
inline bool operator<= (const ConstString& s1, const char8* s2) {return (s1.compare (s2) <= 0) ? true : false;}
inline bool operator> (const ConstString& s1, const char8* s2) {return (s1.compare (s2) > 0) ? true : false;}
inline bool operator>= (const ConstString& s1, const char8* s2) {return (s1.compare (s2) >= 0) ? true : false;}
inline bool operator== (const ConstString& s1, const char8* s2) {return (s1.compare (s2) == 0) ? true : false;}
inline bool operator!= (const ConstString& s1, const char8* s2) {return (s1.compare (s2) != 0) ? true : false;}
inline bool operator< (const char8* s1, const ConstString& s2) {return (s2.compare (s1) > 0) ? true : false;}
inline bool operator<= (const char8* s1, const ConstString& s2) {return (s2.compare (s1) >= 0) ? true : false;}
inline bool operator> (const char8* s1, const ConstString& s2) {return (s2.compare (s1) < 0) ? true : false;}
inline bool operator>= (const char8* s1, const ConstString& s2) {return (s2.compare (s1) <= 0) ? true : false;}
inline bool operator== (const char8* s1, const ConstString& s2) {return (s2.compare (s1) == 0) ? true : false;}
inline bool operator!= (const char8* s1, const ConstString& s2) {return (s2.compare (s1) != 0) ? true : false;}
inline bool operator< (const ConstString& s1, const char16* s2) {return (s1.compare (s2) < 0) ? true : false;}
inline bool operator<= (const ConstString& s1, const char16* s2) {return (s1.compare (s2) <= 0) ? true : false;}
inline bool operator> (const ConstString& s1, const char16* s2) {return (s1.compare (s2) > 0) ? true : false;}
inline bool operator>= (const ConstString& s1, const char16* s2) {return (s1.compare (s2) >= 0) ? true : false;}
inline bool operator== (const ConstString& s1, const char16* s2) {return (s1.compare (s2) == 0) ? true : false;}
inline bool operator!= (const ConstString& s1, const char16* s2) {return (s1.compare (s2) != 0) ? true : false;}
inline bool operator< (const char16* s1, const ConstString& s2) {return (s2.compare (s1) > 0) ? true : false;}
inline bool operator<= (const char16* s1, const ConstString& s2) {return (s2.compare (s1) >= 0) ? true : false;}
inline bool operator> (const char16* s1, const ConstString& s2) {return (s2.compare (s1) < 0) ? true : false;}
inline bool operator>= (const char16* s1, const ConstString& s2) {return (s2.compare (s1) <= 0) ? true : false;}
inline bool operator== (const char16* s1, const ConstString& s2) {return (s2.compare (s1) == 0) ? true : false;}
inline bool operator!= (const char16* s1, const ConstString& s2) {return (s2.compare (s1) != 0) ? true : false;}
// The following functions will only work with European Numbers!
// (e.g. Arabic, Tibetan, and Khmer digits are not supported)
extern int32 strnatcmp8 (const char8* s1, const char8* s2, bool caseSensitive = true);
extern int32 strnatcmp16 (const char16* s1, const char16* s2, bool caseSensitive = true);
inline int32 strnatcmp (const tchar* s1, const tchar* s2, bool caseSensitive = true)
{
#ifdef UNICODE
return strnatcmp16 (s1, s2, caseSensitive);
#else
return strnatcmp8 (s1, s2, caseSensitive);
#endif
}
//-----------------------------------------------------------------------------
/** StringObject implements IStringResult and IString methods.
It can therefore be exchanged with other Steinberg objects using one or both of these
interfaces.
\see String, ConstString
*/
//-----------------------------------------------------------------------------
class StringObject : public FObject, public String, public IStringResult, public IString
{
public:
//-----------------------------------------------------------------------------
StringObject () {}
StringObject (const char16* str, int32 n = -1, bool isTerminated = true) : String (str, n, isTerminated) {}
StringObject (const char8* str, int32 n = -1, bool isTerminated = true) : String (str, n, isTerminated) {}
StringObject (const StringObject& str, int32 n = -1) : String (str, n) {}
StringObject (const String& str, int32 n = -1) : String (str, n) {}
StringObject (const FVariant& var) : String (var) {}
using String::operator=;
// IStringResult ----------------------------------------------------------
virtual void PLUGIN_API setText (const char8* text) SMTG_OVERRIDE;
//-------------------------------------------------------------------------
// IString-----------------------------------------------------------------
virtual void PLUGIN_API setText8 (const char8* text) SMTG_OVERRIDE;
virtual void PLUGIN_API setText16 (const char16* text) SMTG_OVERRIDE;
virtual const char8* PLUGIN_API getText8 () SMTG_OVERRIDE;
virtual const char16* PLUGIN_API getText16 () SMTG_OVERRIDE;
virtual void PLUGIN_API take (void* s, bool _isWide) SMTG_OVERRIDE;
virtual bool PLUGIN_API isWideString () const SMTG_OVERRIDE;
//-------------------------------------------------------------------------
OBJ_METHODS (StringObject, FObject)
FUNKNOWN_METHODS2 (IStringResult, IString, FObject)
};
//------------------------------------------------------------------------
} // namespace Steinberg
| 412 | 0.979524 | 1 | 0.979524 | game-dev | MEDIA | 0.197848 | game-dev | 0.741988 | 1 | 0.741988 |
io12/qemu-libretro | 3,664 | backends/rng-random.c | /*
* QEMU Random Number Generator Backend
*
* Copyright IBM, Corp. 2012
*
* Authors:
* Anthony Liguori <aliguori@us.ibm.com>
*
* This work is licensed under the terms of the GNU GPL, version 2 or later.
* See the COPYING file in the top-level directory.
*/
#include "qemu/osdep.h"
#include "sysemu/rng-random.h"
#include "sysemu/rng.h"
#include "qapi/error.h"
#include "qapi/qmp/qerror.h"
#include "qemu/main-loop.h"
#include "qemu/module.h"
struct RngRandom
{
RngBackend parent;
int fd;
char *filename;
};
/**
* A simple and incomplete backend to request entropy from /dev/random.
*
* This backend exposes an additional "filename" property that can be used to
* set the filename to use to open the backend.
*/
static void entropy_available(void *opaque)
{
RngRandom *s = RNG_RANDOM(opaque);
while (!QSIMPLEQ_EMPTY(&s->parent.requests)) {
RngRequest *req = QSIMPLEQ_FIRST(&s->parent.requests);
ssize_t len;
len = read(s->fd, req->data, req->size);
if (len < 0 && errno == EAGAIN) {
return;
}
g_assert(len != -1);
req->receive_entropy(req->opaque, req->data, len);
rng_backend_finalize_request(&s->parent, req);
}
/* We've drained all requests, the fd handler can be reset. */
qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
}
static void rng_random_request_entropy(RngBackend *b, RngRequest *req)
{
RngRandom *s = RNG_RANDOM(b);
if (QSIMPLEQ_EMPTY(&s->parent.requests)) {
/* If there are no pending requests yet, we need to
* install our fd handler. */
qemu_set_fd_handler(s->fd, entropy_available, NULL, s);
}
}
static void rng_random_opened(RngBackend *b, Error **errp)
{
RngRandom *s = RNG_RANDOM(b);
if (s->filename == NULL) {
error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
"filename", "a valid filename");
} else {
s->fd = qemu_open(s->filename, O_RDONLY | O_NONBLOCK, errp);
}
}
static char *rng_random_get_filename(Object *obj, Error **errp)
{
RngRandom *s = RNG_RANDOM(obj);
return g_strdup(s->filename);
}
static void rng_random_set_filename(Object *obj, const char *filename,
Error **errp)
{
RngBackend *b = RNG_BACKEND(obj);
RngRandom *s = RNG_RANDOM(obj);
if (b->opened) {
error_setg(errp, "Property 'filename' can no longer be set");
return;
}
g_free(s->filename);
s->filename = g_strdup(filename);
}
static void rng_random_init(Object *obj)
{
RngRandom *s = RNG_RANDOM(obj);
s->filename = g_strdup("/dev/urandom");
s->fd = -1;
}
static void rng_random_finalize(Object *obj)
{
RngRandom *s = RNG_RANDOM(obj);
if (s->fd != -1) {
qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
qemu_close(s->fd);
}
g_free(s->filename);
}
static void rng_random_class_init(ObjectClass *klass, void *data)
{
RngBackendClass *rbc = RNG_BACKEND_CLASS(klass);
rbc->request_entropy = rng_random_request_entropy;
rbc->opened = rng_random_opened;
object_class_property_add_str(klass, "filename",
rng_random_get_filename,
rng_random_set_filename);
}
static const TypeInfo rng_random_info = {
.name = TYPE_RNG_RANDOM,
.parent = TYPE_RNG_BACKEND,
.instance_size = sizeof(RngRandom),
.class_init = rng_random_class_init,
.instance_init = rng_random_init,
.instance_finalize = rng_random_finalize,
};
static void register_types(void)
{
type_register_static(&rng_random_info);
}
type_init(register_types);
| 412 | 0.961613 | 1 | 0.961613 | game-dev | MEDIA | 0.337141 | game-dev | 0.923302 | 1 | 0.923302 |
enz/pentobi | 8,143 | pentobi/AnalyzeGameModel.cpp | //-----------------------------------------------------------------------------
/** @file pentobi/AnalyzeGameModel.cpp
@author Markus Enzenberger
@copyright GNU General Public License version 3 or later */
//-----------------------------------------------------------------------------
#include "AnalyzeGameModel.h"
#include <QPromise>
#include <QSettings>
#include <QtConcurrentRun>
#include "libboardgame_base/SgfUtil.h"
using namespace Qt::StringLiterals;
using libboardgame_base::ArrayList;
//-----------------------------------------------------------------------------
AnalyzeGameElement::AnalyzeGameElement(QObject* parent, int moveColor,
double value)
: QObject(parent),
m_moveColor(moveColor),
m_value(value)
{
}
//-----------------------------------------------------------------------------
AnalyzeGameModel::AnalyzeGameModel(QObject* parent)
: QObject(parent)
{
connect(&m_watcher, &QFutureWatcher<void>::finished, this, [this]
{
updateElements();
// Set isRunning after updating elements because in GameViewDesktop
// either isRunning must be true or elements.length > 0 to show the
// analysis and we don't want it to disappear if a game with one move
// was analyzed.
setIsRunning(false);
});
connect(&m_watcher,
&QFutureWatcher<void>::resultReadyAt, this, [this](int index)
{
updateElements(m_watcher.resultAt(index));
});
}
AnalyzeGameModel::~AnalyzeGameModel()
{
cancel();
}
void AnalyzeGameModel::autoSave(GameModel* gameModel)
{
auto& bd = gameModel->getGame().get_board();
QVariantList list;
auto variant = bd.get_variant();
auto nuMoves = m_analyzeGame.get_nu_moves();
QSettings settings;
if (nuMoves == 0 || m_analyzeGame.get_variant() != variant)
settings.remove("analyzeGame"_L1);
else
{
list.append(to_string_id(variant));
list.append(nuMoves);
for (unsigned i = 0; i < nuMoves; ++i)
{
auto mv = m_analyzeGame.get_move(i);
list.append(mv.color.to_int());
list.append(bd.to_string(mv.move).c_str());
list.append(m_analyzeGame.get_value(i));
}
settings.setValue("analyzeGame"_L1, QVariant::fromValue(list));
}
}
void AnalyzeGameModel::cancel()
{
if (! m_isRunning)
return;
m_search->abort();
m_watcher.waitForFinished();
setIsRunning(false);
}
void AnalyzeGameModel::clear()
{
cancel();
if (m_elements.empty())
return;
m_analyzeGame.clear();
m_markMoveNumber = -1;
m_elements.clear();
emit elementsChanged();
}
QQmlListProperty<AnalyzeGameElement> AnalyzeGameModel::elements()
{
return {this, &m_elements};
}
AnalyzeGameModel::ColorValueList AnalyzeGameModel::getColorValueList() const
{
auto nuMoves = m_analyzeGame.get_nu_moves();
ColorValueList result;
result.reserve(nuMoves);
for (unsigned i = 0; i < nuMoves; ++i)
{
auto moveColor = m_analyzeGame.get_move(i).color.to_int();
// Values of search are supposed to be win/loss probabilities but can
// be slightly outside [0..1] (see libpentobi_mcts::State).
auto value = max(0., min(1., m_analyzeGame.get_value(i)));
result.push_back({moveColor, value});
}
return result;
}
void AnalyzeGameModel::gotoMove(GameModel* gameModel, int moveNumber)
{
if (moveNumber < 0)
return;
auto n = static_cast<unsigned>(moveNumber);
if (n >= m_analyzeGame.get_nu_moves())
return;
auto& game = gameModel->getGame();
if (game.get_variant() != m_analyzeGame.get_variant())
return;
auto& tree = game.get_tree();
auto node = &tree.get_root();
if (tree.has_move(*node))
{
// Move in root node not supported.
setMarkMoveNumber(-1);
return;
}
for (unsigned i = 0; i < n; ++i)
{
auto mv = m_analyzeGame.get_move(i);
bool found = false;
for (auto& child : node->get_children())
if (tree.get_move(child) == mv)
{
found = true;
node = &child;
break;
}
if (! found)
{
setMarkMoveNumber(-1);
return;
}
}
gameModel->gotoNode(*node);
setMarkMoveNumber(moveNumber);
}
void AnalyzeGameModel::loadAutoSave(GameModel* gameModel)
{
QSettings settings;
auto list = settings.value("analyzeGame"_L1).value<QVariantList>();
qsizetype size = list.size();
qsizetype index = 0;
if (index >= size)
return;
auto variant = list[index++].toString();
auto& bd = gameModel->getGame().get_board();
if (variant != to_string_id(bd.get_variant()))
return;
if (index >= size)
return;
auto nuMoves = list[index++].toUInt();
vector<ColorMove> moves;
vector<double> values;
for (unsigned i = 0; i < nuMoves; ++i)
{
if (index >= size)
return;
auto color = list[index++].toUInt();
if (color >= bd.get_nu_colors())
return;
if (index >= size)
return;
auto moveString = list[index++].toString();
Move mv;
if (! bd.from_string(mv, moveString.toLatin1().constData()))
return;
if (index >= size)
return;
auto value = list[index++].toDouble();
moves.emplace_back(Color(static_cast<Color::IntType>(color)), mv);
values.push_back(value);
}
m_analyzeGame.set(bd.get_variant(), moves, values);
updateElements();
}
void AnalyzeGameModel::markCurrentMove(GameModel* gameModel)
{
auto& game = gameModel->getGame();
auto& node = game.get_current();
int moveNumber = -1;
if (is_main_variation(node))
{
ArrayList<ColorMove, Board::max_moves> moves;
auto& tree = game.get_tree();
auto current = &find_root(node);
while (current)
{
auto mv = tree.get_move(*current);
if (! mv.is_null() && moves.size() < Board::max_moves)
moves.push_back(mv);
if (current == &node)
break;
current = current->get_first_child_or_null();
}
if (moves.size() <= m_analyzeGame.get_nu_moves())
{
for (unsigned i = 0; i < moves.size(); ++i)
if (moves[i] != m_analyzeGame.get_move(i))
return;
moveNumber = static_cast<int>(moves.size());
}
}
setMarkMoveNumber(moveNumber);
}
void AnalyzeGameModel::setIsRunning(bool isRunning)
{
if (m_isRunning == isRunning)
return;
m_isRunning = isRunning;
emit isRunningChanged();
}
void AnalyzeGameModel::setMarkMoveNumber(int markMoveNumber)
{
if (m_markMoveNumber == markMoveNumber)
return;
m_markMoveNumber = markMoveNumber;
emit markMoveNumberChanged();
}
void AnalyzeGameModel::start(GameModel* gameModel, PlayerModel* playerModel,
int nuSimulations)
{
if (nuSimulations <= 0)
return;
m_markMoveNumber = -1;
m_nuSimulations = static_cast<size_t>(nuSimulations);
cancel();
setIsRunning(true);
m_search = &playerModel->getSearch();
auto future = QtConcurrent::run(
[this, gameModel](QPromise<ColorValueList>& promise) {
m_analyzeGame.run(gameModel->getGame(), *this->m_search,
this->m_nuSimulations,
[this, &promise]() {
promise.addResult(getColorValueList());
});
});
m_watcher.setFuture(future);
}
void AnalyzeGameModel::updateElements()
{
updateElements(getColorValueList());
}
void AnalyzeGameModel::updateElements(const ColorValueList& colorValueList)
{
m_elements.clear();
for (auto& i : colorValueList)
m_elements.append(new AnalyzeGameElement(this, i.first, i.second));
emit elementsChanged();
}
//-----------------------------------------------------------------------------
| 412 | 0.892719 | 1 | 0.892719 | game-dev | MEDIA | 0.834231 | game-dev | 0.975519 | 1 | 0.975519 |
FabricMC/fabric | 7,350 | fabric-model-loading-api-v1/src/testmodClient/java/net/fabricmc/fabric/test/model/loading/ModelTestModClient.java | /*
* Copyright (c) 2016, 2017, 2018, 2019 FabricMC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.fabricmc.fabric.test.model.loading;
import java.util.function.Predicate;
import org.jetbrains.annotations.Nullable;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.block.CropBlock;
import net.minecraft.block.HorizontalConnectingBlock;
import net.minecraft.client.render.entity.PlayerEntityRenderer;
import net.minecraft.client.render.model.BlockStateModel;
import net.minecraft.client.render.model.MissingModel;
import net.minecraft.client.render.model.SimpleBlockStateModel;
import net.minecraft.client.render.model.json.ModelVariant;
import net.minecraft.resource.ResourceType;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.util.math.random.Random;
import net.minecraft.world.BlockRenderView;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.model.loading.v1.ExtraModelKey;
import net.fabricmc.fabric.api.client.model.loading.v1.ModelLoadingPlugin;
import net.fabricmc.fabric.api.client.model.loading.v1.ModelModifier;
import net.fabricmc.fabric.api.client.model.loading.v1.SimpleUnbakedExtraModel;
import net.fabricmc.fabric.api.client.model.loading.v1.wrapper.WrapperBlockStateModel;
import net.fabricmc.fabric.api.client.rendering.v1.LivingEntityFeatureRendererRegistrationCallback;
import net.fabricmc.fabric.api.renderer.v1.mesh.QuadEmitter;
import net.fabricmc.fabric.api.resource.v1.ResourceLoader;
import net.fabricmc.fabric.api.resource.v1.reloader.ResourceReloaderKeys;
public class ModelTestModClient implements ClientModInitializer {
public static final String ID = "fabric-model-loading-api-v1-testmod";
public static final Identifier HALF_RED_SAND_MODEL_ID = id("half_red_sand");
public static final ExtraModelKey<BlockStateModel> HALF_RED_SAND_MODEL_KEY = ExtraModelKey.create(HALF_RED_SAND_MODEL_ID::toString);
public static final Identifier WHEAT_STAGE0_MODEL_ID = Identifier.ofVanilla("block/wheat_stage0");
public static final Identifier WHEAT_STAGE7_MODEL_ID = Identifier.ofVanilla("block/wheat_stage7");
public static final Identifier BROWN_GLAZED_TERRACOTTA_MODEL_ID = Identifier.ofVanilla("block/brown_glazed_terracotta");
@Override
public void onInitializeClient() {
ModelLoadingPlugin.register(pluginContext -> {
pluginContext.addModel(HALF_RED_SAND_MODEL_KEY, SimpleUnbakedExtraModel.blockStateModel(HALF_RED_SAND_MODEL_ID));
// Make wheat stages 1->6 use the same model as stage 0. This can be done with resource packs, this is just a test.
pluginContext.registerBlockStateResolver(Blocks.WHEAT, context -> {
BlockState state = context.block().getDefaultState();
BlockStateModel.UnbakedGrouped wheatStage0Model = simpleUnbakedGroupedBlockStateModel(WHEAT_STAGE0_MODEL_ID);
BlockStateModel.UnbakedGrouped wheatStage7Model = simpleUnbakedGroupedBlockStateModel(WHEAT_STAGE7_MODEL_ID);
for (int age = 0; age <= 6; age++) {
context.setModel(state.with(CropBlock.AGE, age), wheatStage0Model);
}
context.setModel(state.with(CropBlock.AGE, 7), wheatStage7Model);
});
// FIXME
// Replace the brown glazed terracotta model with a missing model without affecting child models.
// Since 1.21.4, the item model is not a child model, so it is also affected.
//pluginContext.modifyModelOnLoad().register(ModelModifier.WRAP_PHASE, (model, context) -> {
// if (context.id().equals(BROWN_GLAZED_TERRACOTTA_MODEL_ID)) {
// return new WrapperUnbakedModel(model) {
// @Override
// public void resolve(Resolver resolver) {
// super.resolve(resolver);
// resolver.resolve(MissingModel.ID);
// }
//
// @Override
// public BakedModel bake(ModelTextures textures, Baker baker, ModelBakeSettings settings, boolean ambientOcclusion, boolean isSideLit, ModelTransformation transformation) {
// return baker.bake(MissingModel.ID, settings);
// }
// };
// }
//
// return model;
//});
// Make oak fences with west: true and everything else false appear to be a missing model visually.
BlockState westOakFence = Blocks.OAK_FENCE.getDefaultState().with(HorizontalConnectingBlock.WEST, true);
pluginContext.modifyBlockModelOnLoad().register(ModelModifier.OVERRIDE_PHASE, (model, context) -> {
if (context.state() == westOakFence) {
return simpleUnbakedGroupedBlockStateModel(MissingModel.ID);
}
return model;
});
// Remove bottom face of gold blocks
BlockState goldBlock = Blocks.GOLD_BLOCK.getDefaultState();
pluginContext.modifyBlockModelAfterBake().register(ModelModifier.WRAP_PHASE, (model, context) -> {
if (context.state() == goldBlock) {
return new DownQuadRemovingModel(model);
}
return model;
});
});
ResourceLoader resourceLoader = ResourceLoader.get(ResourceType.CLIENT_RESOURCES);
resourceLoader.registerReloader(SpecificModelReloadListener.ID, SpecificModelReloadListener.INSTANCE);
resourceLoader.addReloaderOrdering(ResourceReloaderKeys.Client.MODELS, SpecificModelReloadListener.ID);
LivingEntityFeatureRendererRegistrationCallback.EVENT.register((entityType, entityRenderer, registrationHelper, context) -> {
if (entityRenderer instanceof PlayerEntityRenderer playerRenderer) {
registrationHelper.register(new BakedModelFeatureRenderer<>(playerRenderer, SpecificModelReloadListener.INSTANCE::getSpecificModel));
}
});
}
public static Identifier id(String path) {
return Identifier.of(ID, path);
}
private static BlockStateModel.UnbakedGrouped simpleUnbakedGroupedBlockStateModel(Identifier model) {
return new SimpleBlockStateModel.Unbaked(new ModelVariant(model)).cached();
}
private static class DownQuadRemovingModel extends WrapperBlockStateModel {
DownQuadRemovingModel(BlockStateModel model) {
super(model);
}
@Override
public void emitQuads(QuadEmitter emitter, BlockRenderView blockView, BlockPos pos, BlockState state, Random random, Predicate<@Nullable Direction> cullTest) {
emitter.pushTransform(q -> q.cullFace() != Direction.DOWN);
// Modify the cullTest as an example of how to achieve maximum performance
super.emitQuads(emitter, blockView, pos, state, random, cullFace -> {
if (cullFace == Direction.DOWN) {
return true;
}
return cullTest.test(cullFace);
});
emitter.popTransform();
}
@Override
@Nullable
public Object createGeometryKey(BlockRenderView blockView, BlockPos pos, BlockState state, Random random) {
Object subkey = wrapped.createGeometryKey(blockView, pos, state, random);
if (subkey == null) {
return subkey;
}
record Key(Object subkey) {
}
return new Key(subkey);
}
}
}
| 412 | 0.828342 | 1 | 0.828342 | game-dev | MEDIA | 0.748113 | game-dev,graphics-rendering | 0.883152 | 1 | 0.883152 |
stefanvranjes/Vigilante2Unity | 1,313 | Assets/Scripts/Particle2.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Particle2 : VigObject
{
protected override void Start()
{
base.Start();
}
protected override void Update()
{
base.Update();
}
public override uint OnCollision(HitDetection hit)
{
uint uVar1;
VigObject oVar2;
Vehicle vVar2;
Vector3Int local_18;
Vector3Int local_10;
oVar2 = hit.self;
uVar1 = 0;
if (oVar2.type == 2)
{
vVar2 = (Vehicle)oVar2;
Utilities.FUN_2A168(out local_18, vTransform.position, vVar2.vTransform.position);
local_10 = new Vector3Int(local_18.x * 12, local_18.y * 6, local_18.z * 12);
vVar2.FUN_2B370(local_10, vTransform.position);
uVar1 = 0;
if (vVar2.id < 0)
{
GameManager.instance.FUN_15B00(~vVar2.id, 255, 2, 128);
uVar1 = 0;
}
}
return uVar1;
}
//FUN_4E03C
public override uint UpdateW(int arg1, VigObject arg2)
{
uint uVar1;
uVar1 = 0;
if (arg1 == 5)
{
GameManager.instance.FUN_309A0(this);
uVar1 = 0xfffffffe;
}
return uVar1;
}
}
| 412 | 0.887837 | 1 | 0.887837 | game-dev | MEDIA | 0.744325 | game-dev | 0.965167 | 1 | 0.965167 |
Deadlineem/Chronix | 3,025 | src/views/network/missions/hunt_the_beast.hpp | #include "core/scr_globals.hpp"
#include "script_local.hpp"
#include "services/tunables/tunables_service.hpp"
#include "util/math.hpp"
#include "util/scripts.hpp"
#include "util/teleport.hpp"
#include "views/view.hpp"
namespace big
{
int get_land_mark_beast_is_closest_to(player_ptr player, script_local land_mark_list, int num_landmarks)
{
if (!player->get_ped() || !player->get_ped()->m_navigation)
return -1;
int closest_index = 0;
Vector3 transformed_vector = Vector3(player->get_ped()->m_navigation->get_position()->x,
player->get_ped()->m_navigation->get_position()->y,
player->get_ped()->m_navigation->get_position()->z);
float distance = math::distance_between_vectors(transformed_vector, *land_mark_list.at(0, 3).as<Vector3*>());
for (int i = 1; i < num_landmarks; i++)
{
float new_distance = math::distance_between_vectors(transformed_vector, *land_mark_list.at(i, 3).as<Vector3*>());
if (new_distance < distance)
{
distance = new_distance;
closest_index = i;
}
}
return closest_index;
}
inline void render_hunt_the_beast_ui()
{
if (auto hunt_the_beast_script_thread = gta_util::find_script_thread("am_hunt_the_beast"_J))
{
auto beast_player_index =
*script_local(hunt_the_beast_script_thread, scr_locals::am_hunt_the_beast::broadcast_idx).at(1).at(6).as<uint32_t*>();
if (auto beast = g_player_service->get_by_id(beast_player_index))
{
ImGui::Text(std::format("{} {}", g_player_service->get_by_id(beast_player_index).get()->get_name(), "VIEW_NET_MISSIONS_IS_THE_BEAST"_T).c_str());
ImGui::SameLine();
components::button("VIEW_NET_MISSIONS_SET_AS_SELECTED"_T, [beast] {
g_player_service->set_selected(beast);
});
ImGui::Spacing();
auto beast_land_mark_list =
script_local(hunt_the_beast_script_thread, scr_locals::am_hunt_the_beast::broadcast_idx).at(1).at(19);
static int* num_landmarks = nullptr;
if (!num_landmarks)
num_landmarks = g_tunables_service->get_tunable<int*>("HUNT_THE_BEAST_NUMBER_OF_ACTIVE_LANDMARKS"_J);
if (ImGui::BeginListBox("##beastlandmarks", ImVec2(400, 300)))
{
for (int i = 0; i < (num_landmarks ? *num_landmarks : 10); i++)
{
auto script_local_land_mark = *beast_land_mark_list.at(i, 3).as<Vector3*>();
auto label = std::vformat("VIEW_NET_MISSIONS_TP_TO_LANDMARK"_T, std::make_format_args(i, script_local_land_mark.x, script_local_land_mark.y, script_local_land_mark.z));
if (ImGui::Selectable(label.c_str(), i == get_land_mark_beast_is_closest_to(g_player_service->get_by_id(beast_player_index), beast_land_mark_list, num_landmarks ? *num_landmarks : 10)))
{
g_fiber_pool->queue_job([script_local_land_mark, beast] {
teleport::teleport_player_to_coords(g.player.spectating ? beast : g_player_service->get_self(), script_local_land_mark);
});
}
}
ImGui::EndListBox();
}
}
else
{
ImGui::Text("Hunt the beast event is active...");
}
}
}
}
| 412 | 0.893697 | 1 | 0.893697 | game-dev | MEDIA | 0.975011 | game-dev | 0.896844 | 1 | 0.896844 |
Sorapointa/Sorapointa-Protos | 1,599 | proto/PlayerEyePointStateNotify.proto | // Sorapointa - A server software re-implementation for a certain anime game, and avoid sorapointa.
// Copyright (C) 2022 Sorapointa Team
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
syntax = "proto3";
import "CylinderRegionSize.proto";
import "PolygonRegionSize.proto";
import "Vector.proto";
option java_package = "org.sorapointa.proto";
message PlayerEyePointStateNotify {
// enum CmdId {
// option allow_alias = true;
// NONE = 0;
// CMD_ID = 3079;
// ENET_CHANNEL_ID = 0;
// ENET_IS_RELIABLE = 1;
// }
Vector eye_point_pos = 12;
bool Unk3300_KFOHOBLMMLB = 9;
uint32 Unk3300_GNFJIOEGHOE = 1;
uint32 Unk3300_BIHEKNFDDDI = 8;
int32 fix_lod_level = 11;
bool Unk3300_NIPFCFCBFAE = 14;
uint32 Unk3300_JGEMKKJAHKA = 13;
uint32 Unk3300_EOPFNBBBGPK = 6;
oneof region_size {
float sphere_radius = 1413;
Vector cubic_size = 1362;
CylinderRegionSize cylinder_size = 1250;
PolygonRegionSize polygon_size = 608;
}
}
| 412 | 0.765796 | 1 | 0.765796 | game-dev | MEDIA | 0.804396 | game-dev | 0.657574 | 1 | 0.657574 |
Electrical-Age/ElectricalAge | 2,804 | src/main/java/mods/eln/sixnode/electricallightsensor/ElectricalLightSensorDescriptor.java | package mods.eln.sixnode.electricallightsensor;
import mods.eln.Eln;
import mods.eln.misc.*;
import mods.eln.misc.Obj3D.Obj3DPart;
import mods.eln.node.six.SixNodeDescriptor;
import mods.eln.wiki.Data;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import org.lwjgl.opengl.GL11;
import java.util.Collections;
import java.util.List;
import static mods.eln.i18n.I18N.tr;
public class ElectricalLightSensorDescriptor extends SixNodeDescriptor {
private Obj3DPart main;
public boolean dayLightOnly;
public float[] pinDistance;
Obj3D obj;
public ElectricalLightSensorDescriptor(String name, Obj3D obj, boolean dayLightOnly) {
super(name, ElectricalLightSensorElement.class, ElectricalLightSensorRender.class);
this.obj = obj;
this.dayLightOnly = dayLightOnly;
if (obj != null) {
main = obj.getPart("main");
pinDistance = Utils.getSixNodePinDistance(main);
}
voltageLevelColor = VoltageLevelColor.SignalVoltage;
}
void draw() {
if (main != null) main.draw();
}
@Override
public void setParent(Item item, int damage) {
super.setParent(item, damage);
Data.addSignal(newItemStack());
}
@Override
public void addInformation(ItemStack itemStack, EntityPlayer entityPlayer, List list, boolean par4) {
super.addInformation(itemStack, entityPlayer, list, par4);
if (dayLightOnly) {
Collections.addAll(list, tr("Provides an electrical voltage\nwhich is proportional to\nthe intensity of daylight.").split("\n"));
list.add(tr("0V at night, %1$V at noon.", Utils.plotValue(Eln.SVU)));
} else {
Collections.addAll(list, tr("Provides an electrical voltage\nin the presence of light.").split("\n"));
}
}
@Override
public boolean handleRenderType(ItemStack item, ItemRenderType type) {
return true;
}
@Override
public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) {
return type != ItemRenderType.INVENTORY;
}
@Override
public boolean shouldUseRenderHelperEln(ItemRenderType type, ItemStack item, ItemRendererHelper helper) {
return type != ItemRenderType.INVENTORY;
}
@Override
public void renderItem(ItemRenderType type, ItemStack item, Object... data) {
if (type == ItemRenderType.INVENTORY) {
super.renderItem(type, item, data);
} else {
GL11.glScalef(2f, 2f, 2f);
draw();
}
}
@Override
public LRDU getFrontFromPlace(Direction side, EntityPlayer player) {
return super.getFrontFromPlace(side, player).right();
}
}
| 412 | 0.898112 | 1 | 0.898112 | game-dev | MEDIA | 0.917529 | game-dev | 0.989726 | 1 | 0.989726 |
magefree/mage | 3,199 | Mage.Sets/src/mage/cards/e/EvilTwin.java | package mage.cards.e;
import mage.MageInt;
import mage.MageObject;
import mage.abilities.Ability;
import mage.abilities.common.EntersBattlefieldAbility;
import mage.abilities.common.SimpleActivatedAbility;
import mage.abilities.costs.common.TapSourceCost;
import mage.abilities.costs.mana.ManaCostsImpl;
import mage.abilities.effects.Effect;
import mage.abilities.effects.common.CopyPermanentEffect;
import mage.abilities.effects.common.DestroyTargetEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.constants.Zone;
import mage.filter.StaticFilters;
import mage.filter.common.FilterCreaturePermanent;
import mage.filter.predicate.ObjectSourcePlayer;
import mage.filter.predicate.ObjectSourcePlayerPredicate;
import mage.game.Game;
import mage.game.permanent.Permanent;
import mage.target.TargetPermanent;
import mage.target.common.TargetCreaturePermanent;
import mage.util.CardUtil;
import mage.util.functions.CopyApplier;
import java.util.UUID;
/**
* @author BetaSteward
*/
public final class EvilTwin extends CardImpl {
public EvilTwin(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{2}{U}{B}");
this.subtype.add(SubType.SHAPESHIFTER);
this.power = new MageInt(0);
this.toughness = new MageInt(0);
// You may have Evil Twin enter the battlefield as a copy of any creature on the battlefield, except it has "{U}{B}, {T}: Destroy target creature with the same name as this creature."
Effect effect = new CopyPermanentEffect(StaticFilters.FILTER_PERMANENT_CREATURE, new EvilTwinCopyApplier());
effect.setText("as a copy of any creature on the battlefield, except it has \"{U}{B}, {T}: Destroy target creature with the same name as this creature.\"");
this.addAbility(new EntersBattlefieldAbility(effect, true));
}
private EvilTwin(final EvilTwin card) {
super(card);
}
@Override
public EvilTwin copy() {
return new EvilTwin(this);
}
}
class EvilTwinCopyApplier extends CopyApplier {
private static final FilterCreaturePermanent filter = new FilterCreaturePermanent("creature with the same name as this creature");
static {
filter.add(new EvilTwinPredicate());
}
@Override
public boolean apply(Game game, MageObject blueprint, Ability source, UUID copyToObjectId) {
Ability ability = new SimpleActivatedAbility(new DestroyTargetEffect(), new ManaCostsImpl<>("{U}{B}"));
ability.addCost(new TapSourceCost());
ability.addTarget(new TargetPermanent(filter));
blueprint.getAbilities().add(ability);
return true;
}
}
class EvilTwinPredicate implements ObjectSourcePlayerPredicate<Permanent> {
@Override
public boolean apply(ObjectSourcePlayer<Permanent> input, Game game) {
Permanent permanent = input.getObject();
Permanent twin = input.getSource().getSourcePermanentIfItStillExists(game);
return CardUtil.haveSameNames(permanent, twin);
}
@Override
public String toString() {
return "SameNameAsSource";
}
}
| 412 | 0.963243 | 1 | 0.963243 | game-dev | MEDIA | 0.966168 | game-dev | 0.990552 | 1 | 0.990552 |
laicasaane/simple_setup_ecs_2d | 2,218 | Assets/Code/Systems.Initialization/SpawnGroup/SpawnSpritePresenterSystem.cs | using Unity.Collections;
using Unity.Entities;
using UnityEngine;
namespace SimpleSetupEcs2d
{
[UpdateInGroup(typeof(SpawnSystemGroup))]
[UpdateAfter(typeof(SpawnSpriteCharacterSystem))]
public sealed partial class SpawnSpritePresenterSystem : SystemBase
{
private EntityQuery _poolerQuery;
private EntityQuery _presenterQuery;
protected override void OnCreate()
{
_poolerQuery = SystemAPI.QueryBuilder()
.WithAll<SpritePresenterPoolerRef>()
.Build();
_presenterQuery = SystemAPI.QueryBuilder()
.WithAllRW<NeedsInitPresenterTag>()
.WithAllRW<GameObjectInfo>()
.WithAllRW<SpriteRendererRef>()
.Build();
RequireForUpdate(_poolerQuery);
RequireForUpdate(_presenterQuery);
}
protected override void OnUpdate()
{
var pool = _poolerQuery.GetSingleton<SpritePresenterPoolerRef>().poolerRef.Value.Pool;
var entities = _presenterQuery.ToEntityArray(Allocator.Temp);
var length = entities.Length;
var pooledObjects = new NativeList<PooledGameObject>(length, Allocator.Temp);
if (pool.TryRent(length, ref pooledObjects, true))
{
var em = EntityManager;
for (var i = 0; i < length; i++)
{
var entity = entities[i];
ref readonly var obj = ref pooledObjects.ElementAt(i);
var go = Resources.InstanceIDToObject(obj.instanceId) as GameObject;
var renderer = go.GetComponent<SpriteRenderer>();
go.name = entity.ToString();
em.SetComponentData(entity, new GameObjectInfo { value = obj });
em.SetComponentData(entity, new SpriteRendererRef { value = renderer });
em.SetComponentEnabled<NeedsInitPresenterTag>(entity, false);
}
}
// Dependency has been completed by _presenterQuery.ToEntityArray
// so we have to reset it here.
Dependency = default;
}
}
}
| 412 | 0.760409 | 1 | 0.760409 | game-dev | MEDIA | 0.975773 | game-dev | 0.852145 | 1 | 0.852145 |
Draakoor/h2m-gscscripts | 4,485 | user_scripts/mp/snipers_only.gsc | #include common_scripts\utility;
#include maps\mp\_utility;
#include maps\mp\gametypes\_hud_util;
#include maps\mp\gametypes\_gamelogic;
init()
{
if (getDvarInt("sniperport") == 1) {
level thread onPlayerConnect();
level.OriginalCallbackPlayerDamage = level.callbackPlayerDamage;
level.callbackPlayerDamage = ::CodeCallback_PlayerDamage;
}
}
onPlayerConnect()
{
while (true)
{
level waittill("connected", player);
player thread onPlayerSpawned();
}
}
onPlayerSpawned()
{
self endon("disconnect");
while (true)
{
self waittill("spawned_player");
self thread applyGameMode();
self thread ammoLoop();
}
}
restrictWeapons()
{
self takeWeapon("h2_semtex_mp");
self takeweapon("h1_fraggrenade_mp");
self takeweapon("h1_claymore_mp");
self takeweapon("h1_c4_mp");
self takeWeapon("h1_flashgrenade_mp");
self takeWeapon("h1_concussiongrenade_mp");
self takeWeapon("h1_smokegrenade_mp");
self takeweapon("h2m_weapon_c4");
self takeweapon("h2m_weapon_claymore");
//blast shield is not removed maybe buggy
self takeweapon("specialty_blastshield");
self maps\mp\_utility::_unsetperk("specialty_blastshield");
weapon = self getCurrentWeapon();
// Check for weapon attachments and allowed weapons
if (
weapon != self.secondaryWeapon &&
(
isSubStr(weapon, "thermal") ||
isSubStr(weapon, "heartbeat") ||
isSubStr(weapon, "acog") ||
!(
isSubStr(weapon, "cheytac") ||
isSubStr(weapon, "barrett") ||
isSubStr(weapon, "wa2000") ||
isSubStr(weapon, "m21") ||
isSubStr(weapon, "as50") ||
isSubStr(weapon, "msr") ||
isSubStr(weapon, "m40a3") ||
isSubStr(weapon, "throwingknife") ||
isSubStr(weapon, "briefcase_bomb") ||
isSubStr(weapon, "tacticalinsertion")
)
)
)
{
self takeWeapon(weapon);
self giveWeapon("h2_cheytac_mp");
//throwing knife doesnt work
self setlethalweapon("iw9_throwknife_mp");
self giveWeapon ("iw9_throwknife_mp");
// wait .1 second as switchToWeapon doesn't seem to work when called directly after giveWeapon
wait(.1);
self switchToWeapon("h2_cheytac_mp");
//should give some sniper perks
self maps\mp\_utility::giveperk("specialty_fastreload", 0);
self maps\mp\_utility::giveperk("specialty_quickdraw", 0);
self maps\mp\_utility::giveperk("specialty_longersprint", 0);
self maps\mp\_utility::giveperk("specialty_fastmantle", 0);
self maps\mp\_utility::giveperk("specialty_lightweight", 0);
self maps\mp\_utility::giveperk("specialty_fastsprintrecovery", 0);
self maps\mp\_utility::giveperk("specialty_bulletdamage", 0);
self maps\mp\_utility::giveperk("specialty_armorpiercing", 0);
self maps\mp\_utility::giveperk("specialty_extendedmelee", 0);
self maps\mp\_utility::giveperk("specialty_falldamage", 0);
self maps\mp\_utility::giveperk("specialty_bulletaccuracy", 0);
self maps\mp\_utility::giveperk("specialty_holdbreath", 0);
}
}
applyGameMode()
{
for (count=0;count<15;count++)
{
self restrictWeapons();
wait(3);
}
}
ammoLoop()
{
while (true)
{
self waittill("weapon_fired");
ammoWeapon = self getCurrentWeapon();
if (ammoWeapon != self.secondaryWeapon)
{
self giveMaxAmmo(ammoWeapon);
}
}
}
isSniper( weapon )
{
return (
isSubstr( weapon, "h2_cheytac")
|| isSubstr( weapon, "h2_barrett" )
|| isSubstr( weapon, "h2_wa2000" )
|| isSubstr( weapon, "h2_m21" )
|| isSubstr( weapon, "h2_m40a3" )
|| isSubstr( weapon, "h2_as50" )
|| isSubstr( weapon, "h2_d25s" )
|| IsSubStr( weapon, "h2_msr")
|| IsSubStr( weapon, "briefcase_bomb")
//|| isSubstr( weapon, "h1_febsnp" )
//|| isSubstr( weapon, "h1_junsnp" )
);
}
CodeCallback_PlayerDamage(eInflictor, eAttacker, iDamage, iDFlags, sMeansOfDeath, sWeapon, vPoint, vDir, sHitLoc, timeOffset)
{
self endon("disconnect");
if(sMeansOfDeath == "MOD_TRIGGER_HURT" || sMeansOfDeath == "MOD_HIT_BY_OBJECT" || sMeansOfDeath == "MOD_FALLING" || sMeansOfDeath == "MOD_MELEE")
{
return;
}
else
{
if( isSniper( sWeapon ) )
{
iDamage = 999;
}
else
return;
[[level.OriginalCallbackPlayerDamage]](eInflictor, eAttacker, iDamage, iDFlags, sMeansOfDeath, sWeapon, vPoint, vDir, sHitLoc, timeOffset);
}
}
| 412 | 0.925563 | 1 | 0.925563 | game-dev | MEDIA | 0.987633 | game-dev | 0.726862 | 1 | 0.726862 |
bnjmn/weka | 6,855 | weka/src/main/java/weka/core/SingleIndex.java | /*
* 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/>.
*/
/*
* SingleIndex.java
* Copyright (C) 2003-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import java.io.Serializable;
/**
* Class representing a single cardinal number. The number is set by a
* string representation such as: <P>
*
* <code>
* first
* last
* 1
* 3
* </code> <P>
* The number is internally converted from 1-based to 0-based (so methods that
* set or get numbers not in string format should use 0-based numbers).
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @version $Revision$
*/
public class SingleIndex
implements Serializable, RevisionHandler, CustomDisplayStringProvider {
/** for serialization. */
static final long serialVersionUID = 5285169134430839303L;
/** Record the string representation of the number. */
protected /*@non_null spec_public@*/ String m_IndexString = "";
/** The selected index. */
protected /*@ spec_public @*/ int m_SelectedIndex = -1;
/** Store the maximum value permitted. -1 indicates that no upper
value has been set */
protected /*@ spec_public @*/ int m_Upper = -1;
/**
* Default constructor.
*
*/
//@ assignable m_IndexString, m_SelectedIndex, m_Upper;
//@ ensures m_SelectedIndex == -1;
//@ ensures m_Upper == -1;
public SingleIndex() {
}
/**
* Constructor to set initial index.
*
* @param index the initial index
* @throws IllegalArgumentException if the index is invalid
*/
//@ assignable m_IndexString, m_SelectedIndex, m_Upper;
//@ ensures m_IndexString == index;
//@ ensures m_SelectedIndex == -1;
//@ ensures m_Upper == -1;
public SingleIndex(/*@non_null@*/ String index) {
setSingleIndex(index);
}
/**
* Sets the value of "last".
*
* @param newUpper the value of "last"
*/
//@ assignable m_Upper, m_IndexString, m_SelectedIndex;
//@ ensures newUpper < 0 ==> m_Upper == \old(m_Upper);
//@ ensures newUpper >= 0 ==> m_Upper == newUpper;
public void setUpper(int newUpper) {
if (newUpper >= 0) {
m_Upper = newUpper;
setValue();
}
}
/**
* Gets the string representing the selected range of values.
*
* @return the range selection string
*/
//@ ensures \result == m_IndexString;
public /*@pure@*/ String getSingleIndex() {
return m_IndexString;
}
/**
* Sets the index from a string representation. Note that setUpper()
* must be called for the value to be actually set
*
* @param index the index set
* @throws IllegalArgumentException if the index was not well formed
*/
//@ assignable m_IndexString, m_SelectedIndex;
//@ ensures m_IndexString == index;
//@ ensures m_SelectedIndex == -1;
public void setSingleIndex(/*@non_null@*/ String index) {
m_IndexString = index;
m_SelectedIndex = -1;
}
/**
* Constructs a representation of the current range. Being a string
* representation, the numbers are based from 1.
*
* @return the string representation of the current range
*/
//@ also signals (RuntimeException e) \old(m_Upper) < 0;
//@ ensures \result != null;
public /*@pure@*/ String toString() {
if (m_IndexString.equals("")) {
return "No index set";
}
if (m_Upper == -1) {
throw new RuntimeException("Upper limit has not been specified");
}
return m_IndexString;
}
/**
* Gets the selected index.
*
* @return the selected index
* @throws RuntimeException if the upper limit of the index hasn't been defined
*/
//@ requires m_Upper >= 0;
//@ requires m_IndexString.length() > 0;
//@ ensures \result == m_SelectedIndex;
public /*@pure@*/ int getIndex() {
if (m_IndexString.equals("")) {
throw new RuntimeException("No index set");
}
if (m_Upper == -1) {
throw new RuntimeException("No upper limit has been specified for index");
}
return m_SelectedIndex;
}
/**
* Creates a string representation of the given index.
*
* @param index the index to turn into a string.
* Since the index will typically come from a program, indices are assumed
* from 0, and thus will have 1 added in the String representation.
* @return the string representation
*/
//@ requires index >= 0;
public static /*@pure non_null@*/ String indexToString(int index) {
return "" + (index + 1);
}
/**
* Translates a single string selection into it's internal 0-based equivalent.
*/
//@ assignable m_SelectedIndex, m_IndexString;
protected void setValue() {
if (m_IndexString.equals("")) {
throw new RuntimeException("No index set");
}
if (m_IndexString.toLowerCase().equals("first")) {
m_SelectedIndex = 0;
} else if (m_IndexString.toLowerCase().equals("last")) {
m_SelectedIndex = m_Upper;
} else {
m_SelectedIndex = Integer.parseInt(m_IndexString) - 1;
if (m_SelectedIndex < 0) {
m_IndexString = "";
throw new IllegalArgumentException("Index must be greater than zero");
}
if (m_SelectedIndex > m_Upper) {
m_IndexString = "";
throw new IllegalArgumentException("Index is too large");
}
}
}
/**
* Returns the revision string.
*
* @return the revision
*/
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Returns the custom display string.
*
* @return the string
*/
public String toDisplay() {
return getSingleIndex();
}
/**
* Main method for testing this class.
*
* @param argv one parameter: a test index specification
*/
//@ requires \nonnullelements(argv);
public static void main(/*@non_null@*/ String [] argv) {
try {
if (argv.length == 0) {
throw new Exception("Usage: SingleIndex <indexspec>");
}
SingleIndex singleIndex = new SingleIndex();
singleIndex.setSingleIndex(argv[0]);
singleIndex.setUpper(9);
System.out.println("Input: " + argv[0] + "\n"
+ singleIndex.toString());
int selectedIndex = singleIndex.getIndex();
System.out.println(selectedIndex + "");
} catch (Exception ex) {
ex.printStackTrace();
System.out.println(ex.getMessage());
}
}
}
| 412 | 0.966905 | 1 | 0.966905 | game-dev | MEDIA | 0.255078 | game-dev | 0.949362 | 1 | 0.949362 |
FreeFalcon/freefalcon-central | 10,245 | src/vu2/src/vudriver.cpp | /** @file vudriver.cpp
* Implementation of classes which drive units in Vu
* Must not depend on any falclib file
* Rewrite: sfr
*/
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include "vu2.h"
/** number of update renews per second */
#define RENEWS_PER_SECOND (2)
/** maximum number of position updates sent per update per client by server */
#define MAX_SERVER_SENDS_PER_UPDATE (40)
/** maximum number of position updates sent per update per client by client */
#define MAX_CLIENT_SENDS_PER_UPDATE (5)
// tolerance for a position update generation
/** if unit moves more than this qty in any axis, an update can be generated. Unit used: feet */
#define MOVE_TOLERANCE (1.0f)
/** if unit turns more than this qty in any axis, update can be generated. In radians */
#define TURN_TOLERANCE (2*PI / 10.0f)
// useful constants
#define VU_TICS_PER_SEC_INV (1.0f/VU_TICS_PER_SECOND)
// useful function
/** returns time interval in seconds between the 2 timestamps. Returns negative if last_timestamp is bigger */
inline double GetDT(VU_TIME timestamp, VU_TIME last_timestamp)
{
// look out here, time is unsigned, hence the check
if (timestamp > last_timestamp)
{
return ((SM_SCALAR)(timestamp - last_timestamp)) * VU_TICS_PER_SEC_INV;
}
else
{
return -(((SM_SCALAR)(last_timestamp - timestamp)) * VU_TICS_PER_SEC_INV);
}
}
//////////////
// VUDRIVER //
//////////////
VuDriver::VuDriver(VuEntity* entity) : entity_(entity)
{
//lastUpdateGameTime_ = 0;
lastUpdateGameTime_ = entity->LastUpdateTime();
}
VuDriver::~VuDriver()
{
}
/*
void VuDriver::AlignTimeAdd(VU_TIME dt){
lastUpdateGameTime_ += dt;
}
void VuDriver::AlignTimeSubtract(VU_TIME dt){
lastUpdateGameTime_ -= dt;
}
*/
void VuDriver::ResetLastUpdateTime(VU_TIME time)
{
lastUpdateGameTime_ = time;
entity_->SetUpdateTime(time);
}
//////////////////
// VUDEADRECKON //
//////////////////
VuDeadReckon::VuDeadReckon(VuEntity* entity) : VuDriver(entity)
{
VuDeadReckon::Reset();
ResetLastUpdateTime(0);
}
VuDeadReckon::~VuDeadReckon()
{
}
void VuDeadReckon::Reset()
{
// get unit position and heading
d_drx_ = entity_->XDelta();
d_dry_ = entity_->YDelta();
d_drz_ = entity_->ZDelta();
drx_ = entity_->XPos();
dry_ = entity_->YPos();
drz_ = entity_->ZPos();
dryaw_ = entity_->Yaw();
drpitch_ = entity_->Pitch();
drroll_ = entity_->Roll();
}
void VuDeadReckon::NoExec(VU_TIME time)
{
ResetLastUpdateTime(time);
}
void VuDeadReckon::ExecDR(VU_TIME timestamp)
{
BIG_SCALAR dt =
(lastUpdateGameTime_ == 0) ? 0 : static_cast<BIG_SCALAR>(GetDT(timestamp, lastUpdateGameTime_))
;
// if update was not enough to change the value, we zero it...
// this is a float precision problem
BIG_SCALAR bu; // values before update
BIG_SCALAR pval[3], dpval[3], tval[3], dtval[3]; // value and increment
pval[0] = drx_;
pval[1] = dry_;
pval[2] = drz_;
dpval[0] = d_drx_;
dpval[1] = d_dry_;
dpval[2] = d_drz_;
tval[0] = dryaw_;
tval[1] = drpitch_;
tval[2] = drroll_;
dtval[0] = d_dryaw_;
dtval[1] = d_drpitch_;
dtval[2] = d_drroll_;
for (unsigned int i = 0; i < 3; ++i)
{
// position
BIG_SCALAR inc = dt * dpval[i];
bu = pval[i];
pval[i] += inc;
if (bu == pval[i])
{
dpval[i] = 0; // if increment was not enough to update, set speed to 0
}
// turn
inc = dt * dtval[i];
bu = tval[i];
tval[i] += inc;
if (bu == tval[i])
{
dtval[i] = 0; // if increment was not enough to update, set speed to 0
}
// keeps turn between -PI and +PI
if (tval[i] > VU_PI)
{
tval[i] -= VU_TWOPI;
}
else if (tval[i] < -VU_PI)
{
tval[i] += VU_TWOPI;
}
}
drx_ = pval[0];
dry_ = pval[1];
drz_ = pval[2];
d_drx_ = dpval[0];
d_dry_ = dpval[1];
d_drz_ = dpval[2];
dryaw_ = tval[0];
drpitch_ = tval[1];
drroll_ = tval[2];
d_dryaw_ = dtval[0];
d_drpitch_ = dtval[1];
d_drroll_ = dtval[2];
entity_->SetPosition(drx_, dry_, drz_);
entity_->SetDelta(d_drx_, d_dry_, d_drz_);
entity_->SetYPR(dryaw_, drpitch_, drroll_);
entity_->SetYPRDelta(d_dryaw_, d_drpitch_, d_drroll_);
/*
val = bu = drx_;
inc = dt*d_drx_;
drx_ = val + inc;
if (bu == drx_){ d_drx_ = 0; } // if increment was not enough to update, set speed to 0
val = bu = dry_;
inc = dt*d_dry_;
dry_ = val + inc;
if (bu == dry_){ d_dry_ = 0; }
val = bu = drz_;
inc = dt*d_drz_;
drz_ = val + inc;
if (bu == drz_){ d_drz_ = 0; }
// sfr: we should use AGL instead of 0 here, since some places can be below 0...
//if (drz_ > 0.0f){
// // z is inverted (- is up)
// drz_ = 0.0f;
//}
//entity update
entity_->SetPosition(
static_cast<SM_SCALAR>(drx_),
static_cast<SM_SCALAR>(dry_),
static_cast<SM_SCALAR>(drz_)
);
entity_->SetDelta(d_drx_, d_dry_, d_drz_);
*/
ResetLastUpdateTime(timestamp);
}
//////////////////
// VUDELAYSLAVE //
//////////////////
VuDelaySlave::VuDelaySlave(VuEntity *entity) : VuDeadReckon(entity)
{
VuDelaySlave::Reset();
}
void VuDelaySlave::Reset()
{
VuDeadReckon::Reset();
predictedTime_ = 0;//vuxGameTime;
lastRemoteUpdateTime_ = 0;
}
void VuDelaySlave::NoExec(VU_TIME timestamp)
{
VuDeadReckon::NoExec(timestamp);
}
void VuDelaySlave::Exec(VU_TIME timestamp)
{
// check if prediction is recent
if (predictedTime_ > timestamp)
{
// speed is already set by handle, execute dead reckon
ExecDR(timestamp);
}
// our prediction is far past, this prolly means we didnt receive
// an update for this units for sometime
else
{
VuDelaySlave::NoExec(timestamp);
}
}
VU_ERRCODE VuDelaySlave::Handle(VuPositionUpdateEvent* event)
{
// here we just set position
// only accept events newer than last update
if (event->updateTime_ < lastRemoteUpdateTime_)
{
return VU_NO_OP;
}
// we do not receive any dYPR data
entity_->SetPosition(event->x_, event->y_, event->z_);
entity_->SetDelta(event->dx_, event->dy_, event->dz_);
entity_->SetYPR(event->yaw_, event->pitch_, event->roll_);
return VU_SUCCESS;
}
//////////////
// VUMASTER //
//////////////
// static variable
int VuMaster::toSend = 0;
/** returns maximum number of sends for entity. */
namespace
{
unsigned int MaxSends()
{
if (vuLocalGame->OwnerId() == vuLocalSession)
{
return MAX_SERVER_SENDS_PER_UPDATE * (vuLocalGame->SessionCount() - 1);
}
else
{
return MAX_CLIENT_SENDS_PER_UPDATE * (vuLocalGame->SessionCount() - 1);
}
}
}
void VuMaster::ResetToSendIfTime()
{
VU_TIME lastSend = 0;
VU_TIME now = vuxGameTime;
// every half second, renews position updates allowed
if (now >= lastSend + (VU_TICS_PER_SECOND / RENEWS_PER_SECOND))
{
lastSend = now;
toSend = static_cast<int>(MaxSends());
}
}
unsigned int VuMaster::SendsPerPlayer()
{
int otherPlayers = vuLocalSessionEntity->Game()->SessionCount() - 1;
// avoids division by zero
return ((otherPlayers > 0) and (toSend > 0)) ? (MaxSends() / otherPlayers) : 0;
}
VuMaster::VuMaster(VuEntity* entity) : VuDeadReckon(entity)
{
updateSentRealTime_ = 0;
xsent_ = entity_->XPos();
ysent_ = entity_->YPos();
zsent_ = entity_->ZPos();
dxsent_ = entity->XDelta();
dxsent_ = entity->YDelta();
dxsent_ = entity->ZDelta();
yawsent_ = entity_->Yaw();
pitchsent_ = entity_->Pitch();
rollsent_ = entity_->Roll();
}
VuMaster::~VuMaster()
{
}
VU_ERRCODE VuMaster::GeneratePositionUpdate(bool reliable, bool oob, VU_TIME time, VuSessionEntity *target)
{
// send message
VuPositionUpdateEvent *event = new VuPositionUpdateEvent(entity_, target);
if (reliable)
{
event->RequestReliableTransmit();
}
if (oob)
{
event->RequestOutOfBandTransmit();
}
if (VuMessageQueue::PostVuMessage(event) <= 0)
{
return VU_ERROR; // send failed
}
// update sent
xsent_ = entity_->XPos();
ysent_ = entity_->YPos();
zsent_ = entity_->ZPos();
yawsent_ = entity_->Yaw();
pitchsent_ = entity_->Pitch();
rollsent_ = entity_->Roll();
updateSentRealTime_ = vuxRealTime;
return VU_SUCCESS;
}
inline bool VuMaster::ToleranceReached()
{
return
(abs(entity_->XPos() - xsent_) >= MOVE_TOLERANCE) or
(abs(entity_->YPos() - ysent_) >= MOVE_TOLERANCE) or
(abs(entity_->ZPos() - zsent_) >= MOVE_TOLERANCE) or
(abs(entity_->Yaw() - yawsent_) >= TURN_TOLERANCE) or
(abs(entity_->Pitch() - pitchsent_) >= TURN_TOLERANCE) or
(abs(entity_->Roll() - rollsent_) >= TURN_TOLERANCE)
;
}
void VuMaster::Exec(VU_TIME timestamp)
{
ResetToSendIfTime();
// exec model, if fails, exec DR
if ( not ExecModel(timestamp))
{
ExecDR(timestamp);
}
// unit updated
ResetLastUpdateTime(timestamp);
//bool sent = false;
VU_TIME timeDelta = vuxRealTime - updateSentRealTime_;
VuSessionsIterator iter(vuLocalGame);
for (VuSessionEntity *s = iter.GetFirst(); s not_eq NULL; s = iter.GetNext())
{
// dont send to ourselves
if (s == vuLocalSessionEntity)
{
continue;
}
// check if we should send position to this session
SEND_SCORE score = SendScore(s, timeDelta);
if (score.first >= SEND_OOB)
{
s->EnqueueOobPositionUpdate(entity_);
--toSend;
}
else if ((score.first == ENQUEUE_SEND) and (toSend > 0))
{
// enqeue send, dont decrement to sent (will be done during enqueued sends)
// do this to optimize enqueued PU (they wont be sent if OOB)
s->EnqueuePositionUpdate(score.second, entity_);
}
}
}
| 412 | 0.95182 | 1 | 0.95182 | game-dev | MEDIA | 0.478176 | game-dev | 0.987192 | 1 | 0.987192 |
GregTechCEu/GregTech | 6,700 | src/test/java/gregtech/common/metatileentities/storage/QuantumTankTest.java | package gregtech.common.metatileentities.storage;
import gregtech.Bootstrap;
import gregtech.api.GTValues;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidUtil;
import net.minecraftforge.fluids.capability.IFluidHandler;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static gregtech.api.capability.GregtechDataCodes.UPDATE_FLUID_AMOUNT;
import static gregtech.api.util.GTUtility.gregtechId;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
public class QuantumTankTest {
private static FluidStack WATER;
private static FluidStack LAVA;
private static ItemStack BUCKET_WATER;
private static ItemStack BUCKET_LAVA;
@BeforeAll
public static void bootstrap() {
Bootstrap.perform();
WATER = new FluidStack(FluidRegistry.WATER, 1000);
LAVA = new FluidStack(FluidRegistry.LAVA, 1000);
BUCKET_WATER = FluidUtil.getFilledBucket(WATER);
BUCKET_LAVA = FluidUtil.getFilledBucket(LAVA);
}
@Test
public void Test_Valid() {
for (var quantumTank : createInstances()) {
assertThat(quantumTank, is(notNullValue()));
}
}
@Test
public void Test_Insertion() {
for (var quantumTank : createInstances()) {
IFluidHandler handler = quantumTank.getFluidInventory();
int filled = handler.fill(WATER.copy(), false);
assertThat("Not all fluid was inserted!", filled == 1000);
handler.fill(WATER.copy(), true);
assertThat("Quantum tank was not fully filled!", quantumTank.fluidTank.getFluidAmount() == 1000);
filled = handler.fill(LAVA.copy(), true);
assertThat("Quantum tank inserted fluid different from it's internal fluid!", filled == 0);
// todo test here to check inserting via filled fluid containers
}
}
@Test
public void Test_Voiding() {
for (var quantumTank : createInstances()) {
IFluidHandler handler = quantumTank.getFluidInventory();
FluidStack resource = WATER.copy();
resource.amount = Integer.MAX_VALUE;
int inserted = handler.fill(resource, true);
assertThat("Quantum Tank accepted too much fluid!",
inserted == handler.getTankProperties()[0].getCapacity());
quantumTank.setVoiding(true);
inserted = handler.fill(resource, true);
assertThat("Fluid was not properly voided!", inserted == resource.amount);
inserted = handler.fill(LAVA.copy(), true);
assertThat("Quantum tank voided the wrong fluid!", inserted == 0);
}
}
@Test
public void Test_Extraction() {
for (var quantumTank : createInstances()) {
IFluidHandler handler = quantumTank.getFluidInventory();
FluidStack inTank = LAVA.copy();
inTank.amount = 5000;
handler.fill(inTank, true);
FluidStack extracted = handler.drain(2500, true);
assertThat("extracted was null!", extracted != null);
assertThat("Too much/little fluid was extracted!", extracted.amount == 2500);
inTank = handler.getTankProperties()[0].getContents();
assertThat("tank contents was null!", inTank != null);
assertThat("Too much/little fluid in quantum tank!", inTank.amount == 2500);
// todo tests for extracting with an empty fluid container
}
}
private QuantumTankWrapper[] createInstances() {
QuantumTankWrapper[] quantumTanks = new QuantumTankWrapper[10];
for (int i = 0; i < 5; i++) {
String voltageName = GTValues.VN[i + 1].toLowerCase();
quantumTanks[i] = new QuantumTankWrapper(gregtechId("super_tank." + voltageName), i + 1,
4000000 * (int) Math.pow(2, i));
}
for (int i = 5; i < quantumTanks.length; i++) {
String voltageName = GTValues.VN[i].toLowerCase();
int capacity = i == GTValues.UHV ? Integer.MAX_VALUE : 4000000 * (int) Math.pow(2, i);
quantumTanks[i] = new QuantumTankWrapper(gregtechId("quantum_tank." + voltageName), i, capacity);
}
return quantumTanks;
}
private static class QuantumTankWrapper extends MetaTileEntityQuantumTank {
public QuantumTankWrapper(ResourceLocation metaTileEntityId, int tier, int maxFluidCapacity) {
super(metaTileEntityId, tier, maxFluidCapacity);
}
@Override
protected void setVoiding(boolean isVoiding) {
this.voiding = isVoiding;
}
private void fakeUpdate(boolean isRemote) {
EnumFacing currentOutputFacing = getOutputFacing();
if (!isRemote) {
fillContainerFromInternalTank();
fillInternalTankFromFluidContainer();
if (isAutoOutputFluids()) {
pushFluidsIntoNearbyHandlers(currentOutputFacing);
}
FluidStack currentFluid = fluidTank.getFluid();
if (previousFluid == null) {
// tank was empty, but now is not
if (currentFluid != null) {
updatePreviousFluid(currentFluid);
}
} else {
if (currentFluid == null) {
// tank had fluid, but now is empty
updatePreviousFluid(null);
} else if (previousFluid.getFluid().equals(currentFluid.getFluid()) &&
previousFluid.amount != currentFluid.amount) {
// tank has fluid with changed amount
previousFluid.amount = currentFluid.amount;
writeCustomData(UPDATE_FLUID_AMOUNT, buf -> buf.writeInt(currentFluid.amount));
} else
if (!previousFluid.equals(currentFluid)) {
// tank has a different fluid from before
updatePreviousFluid(currentFluid);
}
}
}
}
@Override
protected void updatePreviousFluid(FluidStack currentFluid) {
previousFluid = currentFluid == null ? null : currentFluid.copy();
}
}
}
| 412 | 0.844918 | 1 | 0.844918 | game-dev | MEDIA | 0.718084 | game-dev | 0.896755 | 1 | 0.896755 |
iliak/dungeoneye | 2,920 | Game/AutoMap.cs | #region Licence
//
//This file is part of ArcEngine.
//Copyright (C)2008-2011 Adrien Hémery ( iliak@mimicprod.net )
//
//ArcEngine 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
//any later version.
//
//ArcEngine 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 Foobar. If not, see <http://www.gnu.org/licenses/>.
//
#endregion
using System.Drawing;
using System.Windows.Forms;
using ArcEngine;
using ArcEngine.Asset;
using ArcEngine.Graphic;
using ArcEngine.Input;
using ArcEngine.Utility.ScreenManager;
using DungeonEye.Gui;
namespace DungeonEye
{
public class AutoMap : GameScreenBase
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="batch">SpriteBatch to use</param>
public AutoMap(SpriteBatch batch)
{
Batch = batch;
}
/// <summary>
///
/// </summary>
public override void LoadContent()
{
Trace.WriteDebugLine("[AutoMap] : LoadContent()");
Tileset = ResourceManager.CreateAsset<TileSet>("AutoMap");
}
/// <summary>
/// Unload content
/// </summary>
public override void UnloadContent()
{
Trace.WriteDebugLine("[AutoMap] : UnloadContent()");
//Font = null;
Batch = null;
if (Tileset != null)
Tileset.Dispose();
Tileset = null;
}
#region Update & draw
/// <summary>
/// Update logic
/// </summary>
/// <param name="time"></param>
/// <param name="hasFocus"></param>
/// <param name="isCovered"></param>
public override void Update(GameTime time, bool hasFocus, bool isCovered)
{
if (Keyboard.IsNewKeyPress(Keys.Escape) || Keyboard.IsNewKeyPress(Keys.Tab))
ExitScreen();
}
/// <summary>
///
/// </summary>
public override void Draw()
{
// Clears the background
Display.ClearBuffers();
Batch.Begin();
// Background
Batch.DrawTile(Tileset, 1, Point.Empty, Color.White);
for (int y = 0; y < 20; y++)
for (int x = 0; x < 30; x++)
Batch.DrawTile(Tileset, 3, new Point(68 + x * 12, 90 + y * 12));
// Some WIP
Batch.DrawString(GUI.MenuFont, new Vector2(100, 100), Color.White, "TODO...");
// Draw the cursor or the item in the hand
Batch.DrawTile(Tileset, 0, Mouse.Location, Color.White);
Batch.End();
}
#endregion
#region Properties
/// <summary>
/// Tileset
/// </summary>
TileSet Tileset;
/// <summary>
/// Font
/// </summary>
//BitmapFont Font;
/// <summary>
/// Spritebatch
/// </summary>
SpriteBatch Batch;
#endregion
}
}
| 412 | 0.824109 | 1 | 0.824109 | game-dev | MEDIA | 0.923977 | game-dev | 0.943116 | 1 | 0.943116 |
SAT-R/sa2 | 4,953 | src/game/stage/boss_results_transition.c | #include "global.h"
#include "core.h"
#include "flags.h"
#include "task.h"
#include "lib/m4a/m4a.h"
#include "game/cheese.h"
#include "game/save.h"
#include "game/stage/player.h"
#include "game/stage/camera.h"
#include "game/cutscenes/level_endings.h"
#include "game/stage/screen_fade.h"
#include "game/stage/results.h"
#include "game/time_attack/results.h"
#include "game/stage/boss_results_transition.h"
#include "constants/songs.h"
#include "constants/zones.h"
// Seven unknown x/y positions
const u16 gUnknown_080D6DE4[][2] = {
{ 3800, 177 }, { 11864, 145 }, { 16088, 177 }, { 21080, 153 }, { 27000, 150 }, { 36058, 201 }, { 40000, 225 },
};
typedef struct {
/* 0x00 */ ScreenFade ts;
/* 0x0C */ s16 unkC;
/* 0x0C */ s16 unkE;
/* 0x10 */ u8 unk10;
/* 0x11 */ u8 unk11;
} StageResultsInit; /* size: 0x14 */
void Task_802F06C(void);
void Task_802ED98(void)
{
StageResultsInit *sri = TASK_DATA(gCurTask);
ScreenFade *ts = &sri->ts;
if (UpdateScreenFade(ts) == SCREEN_FADE_COMPLETE) {
TaskDestroy(gCurTask);
if (gGameMode == GAME_MODE_BOSS_TIME_ATTACK) {
CreateTimeAttackResults(gCourseTime);
return;
}
if (IS_FINAL_STAGE(gCurrentLevel)) {
return;
}
if ((gSelectedCharacter == CHARACTER_SONIC) && gLoadedSaveGame->unlockedLevels[CHARACTER_SONIC] <= gCurrentLevel) {
switch (LEVEL_TO_ZONE(gCurrentLevel)) {
case ZONE_1: {
// This case is never executed.
// The boss_1 module does the transition to Cream
// explicitly.
CreateStageResultsCutscene(COURSE_END_UNLOCK_CREAM);
} break;
case ZONE_3: {
CreateStageResultsCutscene(COURSE_END_UNLOCK_TAILS);
} break;
case ZONE_5: {
CreateStageResultsCutscene(COURSE_END_UNLOCK_KNUCKLES);
} break;
default: {
CreateStageResults(gCourseTime, gRingCount, gSpecialRingCount);
} break;
}
return;
} else {
CreateStageResults(gCourseTime, gRingCount, gSpecialRingCount);
return;
}
}
}
void Task_802EE78(void)
{
StageResultsInit *sri = TASK_DATA(gCurTask);
ScreenFade *ts = &sri->ts;
UpdateScreenFade(ts);
if (++sri->unk10 > 8) {
ts->brightness = Q(0);
ts->flags = 2;
ts->speed = 0;
ts->bldCnt = (BLDCNT_EFFECT_LIGHTEN | BLDCNT_TGT1_ALL);
ts->bldAlpha = 0;
if (gCurrentLevel != LEVEL_INDEX(ZONE_7, ACT_BOSS)) {
gFlags &= ~FLAGS_EXECUTE_HBLANK_COPY;
}
if (IS_FINAL_STAGE(gCurrentLevel)) {
u32 x, y;
x = gUnknown_080D6DE4[sri->unk11][0];
x -= I(gPlayer.qWorldX);
y = gUnknown_080D6DE4[sri->unk11][1];
y -= I(gPlayer.qWorldY);
gPlayer.qWorldX += Q(x);
gPlayer.qWorldY += Q(y);
gCamera.x += x;
gCamera.y += y;
gCamera.unk20 += x;
gCamera.unk24 += y;
gCamera.unk10 += x;
gCamera.unk14 += y;
if (gCheese != NULL) {
gCheese->posX += Q(x);
gCheese->posY += Q(y);
}
gBossIndex++;
}
gCurTask->main = Task_802F06C;
}
}
void sub_802EF68(s16 p0, s16 p1, u8 p2)
{
struct Task *t = TaskCreate(Task_802EE78, sizeof(StageResultsInit), 0x6080, 0, NULL);
StageResultsInit *sri = TASK_DATA(t);
ScreenFade *ts = &sri->ts;
sri->unk10 = 0;
sri->unkC = p0;
sri->unkE = p1;
sri->unk11 = p2;
ts->window = 0;
ts->brightness = Q(8.0);
ts->flags = 1;
ts->speed = Q(3. / 4.);
ts->bldCnt = (BLDCNT_EFFECT_LIGHTEN | BLDCNT_TGT1_ALL);
ts->bldAlpha = 0;
m4aSongNumStart(SE_333);
}
void InitHBlankBgOffsets(u16 xOffset)
{
if (gBgOffsetsHBlank == &gBgOffsetsBuffer) {
#if DISPLAY_WIDTH > 255
DmaFill32(3, xOffset, &gBgOffsetsBuffer[0][0], sizeof(gBgOffsetsBuffer[0]));
#else
DmaFill16(3, xOffset, &gBgOffsetsBuffer[0][0], sizeof(gBgOffsetsBuffer[0]));
#endif
} else {
#if DISPLAY_WIDTH > 255
DmaFill32(3, xOffset, &gBgOffsetsBuffer[1][0], sizeof(gBgOffsetsBuffer[1]));
#else
DmaFill16(3, xOffset, &gBgOffsetsBuffer[1][0], sizeof(gBgOffsetsBuffer[1]));
#endif
}
}
// Unused
void SetBgOffsetsInRange(u16 value, int_vcount from, int_vcount to)
{
u16 *offsets = gBgOffsetsHBlank;
offsets += from;
for (; from < to; from++) {
*offsets++ = value;
}
}
void Task_802F06C(void)
{
StageResultsInit *sri = TASK_DATA(gCurTask);
ScreenFade *ts = &sri->ts;
UpdateScreenFade(ts);
if (++sri->unk10 > ZONE_TIME_TO_INT(0, 2)) {
ts->speed = 60;
gCurTask->main = Task_802ED98;
}
} | 412 | 0.782136 | 1 | 0.782136 | game-dev | MEDIA | 0.764482 | game-dev | 0.844757 | 1 | 0.844757 |
Straw1997/UnityCustomShaderGUI | 9,434 | CustomShaderGUI/Library/PackageCache/com.unity.render-pipelines.core@10.2.2/Runtime/Common/ObjectPools.cs | using System;
using System.Collections.Generic;
using UnityEngine.Events;
namespace UnityEngine.Rendering
{
/// <summary>
/// Generic object pool.
/// </summary>
/// <typeparam name="T">Type of the object pool.</typeparam>
public class ObjectPool<T> where T : new()
{
readonly Stack<T> m_Stack = new Stack<T>();
readonly UnityAction<T> m_ActionOnGet;
readonly UnityAction<T> m_ActionOnRelease;
readonly bool m_CollectionCheck = true;
/// <summary>
/// Number of objects in the pool.
/// </summary>
public int countAll { get; private set; }
/// <summary>
/// Number of active objects in the pool.
/// </summary>
public int countActive { get { return countAll - countInactive; } }
/// <summary>
/// Number of inactive objects in the pool.
/// </summary>
public int countInactive { get { return m_Stack.Count; } }
/// <summary>
/// Constructor.
/// </summary>
/// <param name="actionOnGet">Action on get.</param>
/// <param name="actionOnRelease">Action on release.</param>
/// <param name="collectionCheck">True if collection integrity should be checked.</param>
public ObjectPool(UnityAction<T> actionOnGet, UnityAction<T> actionOnRelease, bool collectionCheck = true)
{
m_ActionOnGet = actionOnGet;
m_ActionOnRelease = actionOnRelease;
m_CollectionCheck = collectionCheck;
}
/// <summary>
/// Get an object from the pool.
/// </summary>
/// <returns>A new object from the pool.</returns>
public T Get()
{
T element;
if (m_Stack.Count == 0)
{
element = new T();
countAll++;
}
else
{
element = m_Stack.Pop();
}
if (m_ActionOnGet != null)
m_ActionOnGet(element);
return element;
}
/// <summary>
/// Pooled object.
/// </summary>
public struct PooledObject : IDisposable
{
readonly T m_ToReturn;
readonly ObjectPool<T> m_Pool;
internal PooledObject(T value, ObjectPool<T> pool)
{
m_ToReturn = value;
m_Pool = pool;
}
/// <summary>
/// Disposable pattern implementation.
/// </summary>
void IDisposable.Dispose() => m_Pool.Release(m_ToReturn);
}
/// <summary>
/// Get et new PooledObject.
/// </summary>
/// <param name="v">Output new typed object.</param>
/// <returns>New PooledObject</returns>
public PooledObject Get(out T v) => new PooledObject(v = Get(), this);
/// <summary>
/// Release an object to the pool.
/// </summary>
/// <param name="element">Object to release.</param>
public void Release(T element)
{
#if UNITY_EDITOR // keep heavy checks in editor
if (m_CollectionCheck && m_Stack.Count > 0)
{
if (m_Stack.Contains(element))
Debug.LogError("Internal error. Trying to destroy object that is already released to pool.");
}
#endif
if (m_ActionOnRelease != null)
m_ActionOnRelease(element);
m_Stack.Push(element);
}
}
/// <summary>
/// Generic pool.
/// </summary>
/// <typeparam name="T">Type of the objects in the pull.</typeparam>
public static class GenericPool<T>
where T : new()
{
// Object pool to avoid allocations.
static readonly ObjectPool<T> s_Pool = new ObjectPool<T>(null, null);
/// <summary>
/// Get a new object.
/// </summary>
/// <returns>A new object from the pool.</returns>
public static T Get() => s_Pool.Get();
/// <summary>
/// Get a new PooledObject
/// </summary>
/// <param name="value">Output typed object.</param>
/// <returns>A new PooledObject.</returns>
public static ObjectPool<T>.PooledObject Get(out T value) => s_Pool.Get(out value);
/// <summary>
/// Release an object to the pool.
/// </summary>
/// <param name="toRelease">Object to release.</param>
public static void Release(T toRelease) => s_Pool.Release(toRelease);
}
/// <summary>
/// Generic pool without collection checks.
/// This class is an alternative for the GenericPool for object that allocate memory when they are being compared.
/// It is the case for the CullingResult class from Unity, and because of this in HDRP HDCullingResults generates garbage whenever we use ==, .Equals or ReferenceEquals.
/// This pool doesn't do any of these comparison because we don't check if the stack already contains the element before releasing it.
/// </summary>
/// <typeparam name="T">Type of the objects in the pull.</typeparam>
public static class UnsafeGenericPool<T>
where T : new()
{
// Object pool to avoid allocations.
static readonly ObjectPool<T> s_Pool = new ObjectPool<T>(null, null, false);
/// <summary>
/// Get a new object.
/// </summary>
/// <returns>A new object from the pool.</returns>
public static T Get() => s_Pool.Get();
/// <summary>
/// Get a new PooledObject
/// </summary>
/// <param name="value">Output typed object.</param>
/// <returns>A new PooledObject.</returns>
public static ObjectPool<T>.PooledObject Get(out T value) => s_Pool.Get(out value);
/// <summary>
/// Release an object to the pool.
/// </summary>
/// <param name="toRelease">Object to release.</param>
public static void Release(T toRelease) => s_Pool.Release(toRelease);
}
/// <summary>
/// List Pool.
/// </summary>
/// <typeparam name="T">Type of the objects in the pooled lists.</typeparam>
public static class ListPool<T>
{
// Object pool to avoid allocations.
static readonly ObjectPool<List<T>> s_Pool = new ObjectPool<List<T>>(null, l => l.Clear());
/// <summary>
/// Get a new List
/// </summary>
/// <returns>A new List</returns>
public static List<T> Get() => s_Pool.Get();
/// <summary>
/// Get a new list PooledObject.
/// </summary>
/// <param name="value">Output typed List.</param>
/// <returns>A new List PooledObject.</returns>
public static ObjectPool<List<T>>.PooledObject Get(out List<T> value) => s_Pool.Get(out value);
/// <summary>
/// Release an object to the pool.
/// </summary>
/// <param name="toRelease">List to release.</param>
public static void Release(List<T> toRelease) => s_Pool.Release(toRelease);
}
/// <summary>
/// HashSet Pool.
/// </summary>
/// <typeparam name="T">Type of the objects in the pooled hashsets.</typeparam>
public static class HashSetPool<T>
{
// Object pool to avoid allocations.
static readonly ObjectPool<HashSet<T>> s_Pool = new ObjectPool<HashSet<T>>(null, l => l.Clear());
/// <summary>
/// Get a new HashSet
/// </summary>
/// <returns>A new HashSet</returns>
public static HashSet<T> Get() => s_Pool.Get();
/// <summary>
/// Get a new list PooledObject.
/// </summary>
/// <param name="value">Output typed HashSet.</param>
/// <returns>A new HashSet PooledObject.</returns>
public static ObjectPool<HashSet<T>>.PooledObject Get(out HashSet<T> value) => s_Pool.Get(out value);
/// <summary>
/// Release an object to the pool.
/// </summary>
/// <param name="toRelease">hashSet to release.</param>
public static void Release(HashSet<T> toRelease) => s_Pool.Release(toRelease);
}
/// <summary>
/// Dictionary Pool.
/// </summary>
/// <typeparam name="TKey">Key type.</typeparam>
/// <typeparam name="TValue">Value type.</typeparam>
public static class DictionaryPool<TKey, TValue>
{
// Object pool to avoid allocations.
static readonly ObjectPool<Dictionary<TKey, TValue>> s_Pool
= new ObjectPool<Dictionary<TKey, TValue>>(null, l => l.Clear());
/// <summary>
/// Get a new Dictionary
/// </summary>
/// <returns>A new Dictionary</returns>
public static Dictionary<TKey, TValue> Get() => s_Pool.Get();
/// <summary>
/// Get a new dictionary PooledObject.
/// </summary>
/// <param name="value">Output typed Dictionary.</param>
/// <returns>A new Dictionary PooledObject.</returns>
public static ObjectPool<Dictionary<TKey, TValue>>.PooledObject Get(out Dictionary<TKey, TValue> value)
=> s_Pool.Get(out value);
/// <summary>
/// Release an object to the pool.
/// </summary>
/// <param name="toRelease">Dictionary to release.</param>
public static void Release(Dictionary<TKey, TValue> toRelease) => s_Pool.Release(toRelease);
}
}
| 412 | 0.801587 | 1 | 0.801587 | game-dev | MEDIA | 0.729449 | game-dev | 0.890127 | 1 | 0.890127 |
eliemichel/TownBuilder | 13,673 | Packages/LilyXwfc/Library/WaveFunctionCollapse.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace LilyXwfc
{
/**
* Collapse methods exist in two versions, the default one, more efficient,
* and a coroutine version (returning enumerators) for visualization.
* This is also used to test implementations.
*/
public class WaveFunctionCollapse
{
readonly WaveFunctionSystem system;
/**
* If setting non uniform initial states, e.g. because setting boundary
* constraints, we propagate from all states before any observation to
* limit the chances of inconsistent state.
*/
readonly bool skipInitialConditions;
/**
* Use backtracking when reaching an inconsistent state, i.e. roll back
* to the last choice and do another one. This converges faster because
* otherwise the solving is restarted from scratch and enables the
* detection of unsolvable systems, but requires memory to store
* (in so called checkpoints) the whole state before each observation.
* TODO: add an option to save only a few checkpoints.
*/
readonly bool useBacktracking;
bool isInconsistent = false; // becomes true when a variable with empty superposed state is found
// for backtracking, we store the state from time to time, as well as the choices (to avoid making them again)
Stack<SuperposedState[]> checkpoints;
Stack<Observation> obervations;
// For debug only
WaveVariable currentIndex = WaveVariable.Null;
public WaveVariable CurrentIndex { get { return currentIndex; } }
/**
* Turn skipInitialConditions on if you have no initial condition, to
* avoid trying to propagate all variables before doing any
* observation.
*/
public WaveFunctionCollapse(WaveFunctionSystem system, bool skipInitialConditions = false, bool useBacktracking = true)
{
this.system = system;
this.skipInitialConditions = skipInitialConditions;
this.useBacktracking = useBacktracking;
}
void Reset()
{
checkpoints = new Stack<SuperposedState[]>();
obervations = new Stack<Observation>();
isInconsistent = false;
}
/**
* Before doing any observation, we propagate from any variable that
* was initialized with a non uniform distribution.
*/
bool PropagateFromInitialConditions()
{
foreach (var x in system.Variables())
{
//if (system.GetWave(x).Equals(equiprobable)) continue;
if (!Propagate(x)) return false;
}
return true;
}
/**
* Return false if the system could not be solved in maxSteps steps
*/
public bool Collapse(int maxSteps = 20)
{
Reset();
if (!skipInitialConditions)
{
if (!PropagateFromInitialConditions())
{
Debug.Log("System is not solvable");
return false;
}
}
WaveVariable lastChangedVariable = Observe();
for (int i = 0; i < maxSteps && !lastChangedVariable.IsNull(); ++i)
{
if (Propagate(lastChangedVariable))
{
lastChangedVariable = Observe();
}
else
{
if (useBacktracking)
{
Debug.Log("Inconsistent state reached at step #" + i + ", backtracking.");
lastChangedVariable = Backtrack();
if (lastChangedVariable.IsNull())
{
Debug.Log("System is not solvable");
}
}
else
{
Debug.Log("Inconsistent state reached at step #" + i + ", restarting.");
system.Reset();
return Collapse(maxSteps - i - 1);
}
}
}
return lastChangedVariable.IsNull();
}
/**
* Rollback the system to before a previous choice and remove the last
* choice from the possible values (since it lead to an inconsistent
* state).
* Return the variable of the last choice, that must be propagated
* because since we removed a possible value its neighbors might be
* affected before doing any further observation.
*/
public WaveVariable Backtrack()
{
if (checkpoints.Count == 0)
{
// Cannot backtrack, we are already back to the initial state,
// this means that the system is unsolvable.
return WaveVariable.Null;
}
// Restore the system state from the last checkpoint.
PopCheckpoint();
// Avoid doing the same choice again, if possible
var lastChoice = obervations.Pop();
if (lastChoice.Prevent(system))
{
return lastChoice.variable;
}
else
{
// If it cannot be prevented, recursively backtrack to the previous point
return Backtrack();
}
}
/**
* Save the current state of the system.
* You must push a choice to 'obervations' each time you call this.
*/
void PushCheckpoint()
{
var state = new SuperposedState[system.VariableCount];
int i = 0;
foreach (var x in system.Variables())
{
state[i++] = system.GetWave(x);
}
checkpoints.Push(state);
}
/**
* Get the last saved state and remove it from the checkpoint stack.
* You must pop a choice from 'obervations' each time you call this.
*/
void PopCheckpoint()
{
var state = checkpoints.Pop();
int i = 0;
foreach (var x in system.Variables())
{
system.SetWave(x, state[i++]);
}
}
public IEnumerator<bool> CollapseCoroutine(int maxSteps = 20)
{
Reset();
if (!skipInitialConditions)
{
foreach (var x in system.Variables())
{
currentIndex = x; yield return x.IsNull();
for (var it = PropagateCoroutine(x); it.MoveNext();)
{
yield return x.IsNull();
}
}
}
WaveVariable idx = Observe();
for (int i = 0; i < maxSteps && !idx.IsNull() && !isInconsistent; ++i)
{
Debug.Log("#################### Propagate from " + idx);
for (var it = PropagateCoroutine(idx); it.MoveNext();)
{
currentIndex = idx; yield return idx.IsNull();
}
// Backtracking
while (isInconsistent)
{
if (useBacktracking)
{
Debug.Assert(checkpoints.Count > 0);
Debug.Log("Inconsistent state reached at step #" + i + ", backtracking.");
isInconsistent = false;
PopCheckpoint();
// Avoid doing the same choice again
var lastChoice = obervations.Pop();
isInconsistent = !lastChoice.Prevent(system);
}
else
{
Debug.Log("Inconsistent state reached at step #" + i + ", restarting.");
system.Reset();
isInconsistent = false;
}
}
currentIndex = idx; yield return idx.IsNull();
idx = Observe();
}
currentIndex = idx; yield return idx.IsNull();
}
/**
* Propagate a change that has been made to the wave function at a
* given index to its neighbors, recursively, and return false if there
* was an inconsistent state found.
*/
bool Propagate(WaveVariable idx)
{
// 1. build neighborhood
var neighborhood = system.OutgoingConnections(idx);
// 2. For each neighbor
for (int i = 0; i < neighborhood.Count; ++i)
{
WaveVariable nidx = neighborhood[i].destination;
int connectionType = neighborhood[i].type;
BMesh.Loop loop = neighborhood[i].loop;
// 2a. Test all combinations
SuperposedState neighborState = system.GetWave(nidx);
// Build a mask
SuperposedState allowed = system.rules.AllowedStates(system.GetWave(idx), loop, neighborState);
// Apply the mask to the neighbor
SuperposedState newNeighborState = neighborState.MaskBy(allowed);
system.SetWave(nidx, newNeighborState);
bool changed = !newNeighborState.Equals(neighborState);
if (changed)
{
if (newNeighborState.Components().Count == 0)
{
// Inconsistency, abort
isInconsistent = true;
return false;
}
// 2b. Recursive call
if (!Propagate(nidx)) return false;
}
}
return true;
}
IEnumerator PropagateCoroutine(WaveVariable idx)
{
Debug.Log("Propagate(" + idx + ") (state = " + system.GetWave(idx) + ") -->");
// 1. build neighborhood
var neighborhood = system.OutgoingConnections(idx);
// 2. For each neighbor
for (int i = 0; i < neighborhood.Count; ++i)
{
WaveVariable nidx = neighborhood[i].destination;
int connectionType = neighborhood[i].type;
BMesh.Loop loop = neighborhood[i].loop;
Debug.Log("neighbor (" + nidx + "), in direction #" + connectionType + " (state = " + system.GetWave(nidx) + ")");
// 2a. Test all combinations
SuperposedState neighborState = system.GetWave(nidx);
// Build a mask
SuperposedState allowed = system.rules.AllowedStates(system.GetWave(idx), loop, neighborState);
// Apply the mask to the neighbor
SuperposedState newNeighborState = neighborState.MaskBy(allowed);
system.SetWave(nidx, newNeighborState);
bool changed = !newNeighborState.Equals(neighborState);
if (changed)
{
if (newNeighborState.Components().Count == 0)
{
// Inconsistency, abort (This is where we could decide to backtrack)
isInconsistent = true;
yield break;
}
// 2b. Recursive call
currentIndex = nidx; yield return null;
for (var it = PropagateCoroutine(nidx); it.MoveNext();)
{
yield return null;
}
}
}
Debug.Log("<-- Propagate(" + idx + ")");
}
/**
* Observe the less entropic superposed state and return its index
*/
WaveVariable Observe()
{
// 1. Find less entropic state
float minEntropy = Mathf.Infinity;
List<WaveVariable> argminEntropy = new List<WaveVariable>(); // indices of minimal non null entropy
foreach (WaveVariable idx in system.Variables())
{
SuperposedState s = system.GetWave(idx);
float entropy = s.Entropy();
Debug.Assert(entropy == 0 || s.Components().Count > 1);
if (entropy > 0 && entropy < minEntropy)
{
minEntropy = entropy;
argminEntropy.Clear();
}
if (entropy == minEntropy)
{
argminEntropy.Add(idx);
}
}
if (argminEntropy.Count == 0)
{
//Debug.Log("No more superposed state.");
return WaveVariable.Null;
}
// 2. Save state for backtracking
if (useBacktracking)
PushCheckpoint();
// 3. Decohere state
//Debug.Log("min entropy: " + minEntropy + " found in " + argminEntropy.Count + " states");
int r = Random.Range(0, argminEntropy.Count);
var selected = argminEntropy[r];
var wave = system.GetWave(selected);
wave.Observe();
system.SetWave(selected, wave);
// 4. Save choice for backtracking
if (useBacktracking)
obervations.Push(new Observation(selected, wave));
return selected;
}
}
}
| 412 | 0.925355 | 1 | 0.925355 | game-dev | MEDIA | 0.77745 | game-dev | 0.98246 | 1 | 0.98246 |
ronaldoussoren/pyobjc | 1,634 | pyobjc-framework-GameplayKit/PyObjCTest/test_gkobstacle.py | from PyObjCTools.TestSupport import TestCase, min_os_level
import GameplayKit # noqa: F401
from objc import simd
class TestGKObstacle(TestCase):
def testMethods(self):
self.assertResultHasType(
GameplayKit.GKCircleObstacle.position, simd.vector_float2.__typestr__
)
self.assertArgHasType(
GameplayKit.GKCircleObstacle.setPosition_, 0, simd.vector_float2.__typestr__
)
self.assertArgHasType(
GameplayKit.GKPolygonObstacle.obstacleWithPoints_count_,
0,
b"n^" + simd.vector_float2.__typestr__,
)
self.assertArgIsIn(GameplayKit.GKPolygonObstacle.obstacleWithPoints_count_, 0)
self.assertArgSizeInArg(
GameplayKit.GKPolygonObstacle.obstacleWithPoints_count_, 0, 1
)
self.assertArgHasType(
GameplayKit.GKPolygonObstacle.initWithPoints_count_,
0,
b"n^" + simd.vector_float2.__typestr__,
)
self.assertArgIsIn(GameplayKit.GKPolygonObstacle.initWithPoints_count_, 0)
self.assertArgSizeInArg(
GameplayKit.GKPolygonObstacle.initWithPoints_count_, 0, 1
)
self.assertResultHasType(
GameplayKit.GKPolygonObstacle.vertexAtIndex_, simd.vector_float2.__typestr__
)
@min_os_level("10.12")
def test_methods10_12(self):
self.assertResultHasType(
GameplayKit.GKSphereObstacle.position, simd.vector_float3.__typestr__
)
self.assertArgHasType(
GameplayKit.GKSphereObstacle.setPosition_, 0, simd.vector_float3.__typestr__
)
| 412 | 0.718089 | 1 | 0.718089 | game-dev | MEDIA | 0.751857 | game-dev,testing-qa | 0.624619 | 1 | 0.624619 |
Mezy/UhcCore | 9,955 | src/main/java/com/gmail/val59000mc/utils/VersionUtils_1_8.java | package com.gmail.val59000mc.utils;
import com.gmail.val59000mc.game.GameManager;
import com.gmail.val59000mc.maploader.MapLoader;
import com.gmail.val59000mc.players.UhcPlayer;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import io.papermc.lib.PaperLib;
import org.apache.commons.lang.Validate;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.Chest;
import org.bukkit.block.Skull;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerPortalEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.Recipe;
import org.bukkit.inventory.ShapedRecipe;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.potion.PotionData;
import org.bukkit.scoreboard.NameTagVisibility;
import org.bukkit.scoreboard.Objective;
import org.bukkit.scoreboard.Scoreboard;
import org.bukkit.scoreboard.Team;
import javax.annotation.Nullable;
import java.lang.reflect.Method;
import java.util.*;
@SuppressWarnings("deprecation")
public class VersionUtils_1_8 extends VersionUtils{
@Override
public ShapedRecipe createShapedRecipe(ItemStack craft, String craftKey) {
return new ShapedRecipe(craft);
}
@Override
public ItemStack createPlayerSkull(String name, UUID uuid) {
ItemStack item = UniversalMaterial.PLAYER_HEAD.getStack();
SkullMeta im = (SkullMeta) item.getItemMeta();
im.setOwner(name);
item.setItemMeta(im);
return item;
}
@Override
public void setSkullOwner(Skull skull, UhcPlayer player) {
skull.setOwner(player.getName());
}
@Override
public Objective registerObjective(Scoreboard scoreboard, String name, String criteria) {
return scoreboard.registerNewObjective(name, criteria);
}
@Override
public void setPlayerMaxHealth(Player player, double maxHealth) {
player.setMaxHealth(maxHealth);
}
@Override
public void setGameRuleValue(World world, String gameRule, Object value) {
world.setGameRuleValue(gameRule, value.toString());
}
@Override
public boolean hasEye(Block block) {
return block.getData() > 3;
}
@Override
public void setEye(Block block, boolean eye){
byte data = block.getData();
if (eye && data < 4){
data += 4;
}else if (!eye && data > 3){
data -= 4;
}
setBlockData(block, data);
}
@Override
public void setEndPortalFrameOrientation(Block block, BlockFace blockFace){
byte data = -1;
switch (blockFace){
case NORTH:
data = 2;
break;
case EAST:
data = 3;
break;
case SOUTH:
data = 0;
break;
case WEST:
data = 1;
break;
}
setBlockData(block, data);
}
private void setBlockData(Block block, byte data){
try {
Method setData = NMSUtils.getMethod(Block.class, "setData",1);
setData.invoke(block, data);
}catch (ReflectiveOperationException ex){
ex.printStackTrace();
}
}
@Override
public void setTeamNameTagVisibility(Team team, boolean value){
team.setNameTagVisibility(value?NameTagVisibility.ALWAYS:NameTagVisibility.NEVER);
}
@Override
public void setChestName(Chest chest, String name){
try {
Class craftChest = NMSUtils.getNMSClass("block.CraftChest");
Method getTileEntity = NMSUtils.getMethod(craftChest, "getTileEntity");
Object tileChest = getTileEntity.invoke(chest);
Method a = NMSUtils.getMethod(tileChest.getClass(), "a", String.class);
a.invoke(tileChest, name);
}catch (Exception ex){ // todo find a way to change the chest name on other versions up to 1.11
Bukkit.getLogger().severe("[UhcCore] Failed to rename chest! Are you on 1.9-1.11?");
ex.printStackTrace();
}
}
@Override
public JsonObject getBasePotionEffect(PotionMeta potionMeta){
return null;
}
@Override
public PotionMeta setBasePotionEffect(PotionMeta potionMeta, PotionData potionData){
return potionMeta;
}
@Nullable
@Override
public Color getPotionColor(PotionMeta potionMeta){
return null;
}
@Override
public PotionMeta setPotionColor(PotionMeta potionMeta, Color color){
return potionMeta;
}
@Override
public void setChestSide(Chest chest, boolean left) {
// Not needed on 1.8
}
@Override
public void removeRecipe(ItemStack item, Recipe recipe){
Iterator<Recipe> iterator = Bukkit.recipeIterator();
try {
while (iterator.hasNext()){
if (iterator.next().getResult().isSimilar(item)){
iterator.remove();
Bukkit.getLogger().info("[UhcCore] Removed recipe for item "+JsonItemUtils.getItemJson(item));
}
}
}catch (Exception ex){
Bukkit.getLogger().warning("[UhcCore] Failed to remove recipe for item "+JsonItemUtils.getItemJson(item)+"!");
ex.printStackTrace();
}
}
@Override
public void handleNetherPortalEvent(PlayerPortalEvent event){
if (event.getTo() != null){
return;
}
Location loc = event.getFrom();
MapLoader mapLoader = GameManager.getGameManager().getMapLoader();
try{
Class<?> travelAgent = Class.forName("org.bukkit.TravelAgent");
Method getPortalTravelAgent = NMSUtils.getMethod(event.getClass(), "getPortalTravelAgent");
Method findOrCreate = NMSUtils.getMethod(travelAgent, "findOrCreate", Location.class);
Object travelAgentInstance = getPortalTravelAgent.invoke(event);
if (event.getFrom().getWorld().getEnvironment() == World.Environment.NETHER){
loc.setWorld(mapLoader.getUhcWorld(World.Environment.NORMAL));
loc.setX(loc.getX() * 2d);
loc.setZ(loc.getZ() * 2d);
Location to = (Location) findOrCreate.invoke(travelAgentInstance, loc);
Validate.notNull(to, "TravelAgent returned null location!");
event.setTo(to);
}else{
loc.setWorld(mapLoader.getUhcWorld(World.Environment.NETHER));
loc.setX(loc.getX() / 2d);
loc.setZ(loc.getZ() / 2d);
Location to = (Location) findOrCreate.invoke(travelAgentInstance, loc);
Validate.notNull(to, "TravelAgent returned null location!");
event.setTo(to);
}
}catch (ReflectiveOperationException ex){
ex.printStackTrace();
}
}
@Nullable
@Override
public JsonObject getItemAttributes(ItemMeta meta){
return null;
}
@Override
public ItemMeta applyItemAttributes(ItemMeta meta, JsonObject attributes){
return meta;
}
@Override
public String getEnchantmentKey(Enchantment enchantment){
return enchantment.getName();
}
@Nullable
@Override
public Enchantment getEnchantmentFromKey(String key){
return Enchantment.getByName(key);
}
@Override
public void setEntityAI(LivingEntity entity, boolean b){
try{
// Get Minecraft entity class
Object mcEntity = NMSUtils.getHandle(entity);
Method getNBTTag = NMSUtils.getMethod(mcEntity.getClass(), "getNBTTag");
Class NBTTagCompound = NMSUtils.getNMSClass("NBTTagCompound");
// Get NBT tag of zombie
Object tag = getNBTTag.invoke(mcEntity);
if (tag == null){
tag = NBTTagCompound.newInstance();
}
// Methods to apply NBT data to the zombie
Method c = NMSUtils.getMethod(mcEntity.getClass(), "c", NBTTagCompound);
Method f = NMSUtils.getMethod(mcEntity.getClass(), "f", NBTTagCompound);
// Method to set NBT values
Method setInt = NMSUtils.getMethod(NBTTagCompound, "setInt", String.class, int.class);
c.invoke(mcEntity, tag);
setInt.invoke(tag, "NoAI", b?0:1);
f.invoke(mcEntity, tag);
}catch (Exception ex){
// This will only work on 1.8 (Not 1.9-1.11, 0.5% of servers)
ex.printStackTrace();
}
}
@Override
public List<Material> getItemList() {
// Arrays.asList() returns a AbstractList where no objects can be removed from.
return new ArrayList<>(Arrays.asList(Material.values()));
}
@Nullable
@Override
public JsonArray getSuspiciousStewEffects(ItemMeta meta){
return null;
}
@Override
public ItemMeta applySuspiciousStewEffects(ItemMeta meta, JsonArray effects){
return meta;
}
@Override
public void setItemUnbreakable(ItemMeta meta, boolean b){
if (!PaperLib.isSpigot()){
return; // Unable to set item as unbreakable on a none spigot server.
}
try {
Method spigot = NMSUtils.getMethod(meta.getClass(), "spigot");
Object spigotInstance = spigot.invoke(meta);
Method setUnbreakable = NMSUtils.getMethod(spigotInstance.getClass(), "setUnbreakable", boolean.class);
setUnbreakable.invoke(spigotInstance, b);
}catch (ReflectiveOperationException ex){
ex.printStackTrace();
}
}
@Override
public void killPlayer(Player player) {
player.damage(player.getHealth());
}
} | 412 | 0.960221 | 1 | 0.960221 | game-dev | MEDIA | 0.992413 | game-dev | 0.976884 | 1 | 0.976884 |
twhl-community/halflife-unified-sdk | 27,700 | src/game/server/entities/NPCs/aliens/bigmomma.cpp | /***
*
* Copyright (c) 1996-2001, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* This source code contains proprietary and confidential information of
* Valve LLC and its suppliers. Access to this code is restricted to
* persons who have executed a written SDK license with Valve. Any access,
* use or distribution of this code by or to any unlicensed person is illegal.
*
****/
#include "cbase.h"
#define SF_INFOBM_RUN 0x0001
#define SF_INFOBM_WAIT 0x0002
/**
* @brief AI Nodes for Big Momma
*/
class CInfoBM : public CPointEntity
{
DECLARE_CLASS(CInfoBM, CPointEntity);
DECLARE_DATAMAP();
public:
void Spawn() override;
bool KeyValue(KeyValueData* pkvd) override;
// name in pev->targetname
// next in pev->target
// radius in pev->scale
// health in pev->health
// Reach target in pev->message
// Reach delay in pev->speed
// Reach sequence in pev->netname
string_t m_preSequence;
};
LINK_ENTITY_TO_CLASS(info_bigmomma, CInfoBM);
BEGIN_DATAMAP(CInfoBM)
DEFINE_FIELD(m_preSequence, FIELD_STRING),
END_DATAMAP();
void CInfoBM::Spawn()
{
}
bool CInfoBM::KeyValue(KeyValueData* pkvd)
{
if (FStrEq(pkvd->szKeyName, "radius"))
{
pev->scale = atof(pkvd->szValue);
return true;
}
else if (FStrEq(pkvd->szKeyName, "reachdelay"))
{
pev->speed = atof(pkvd->szValue);
return true;
}
else if (FStrEq(pkvd->szKeyName, "reachtarget"))
{
pev->message = ALLOC_STRING(pkvd->szValue);
return true;
}
else if (FStrEq(pkvd->szKeyName, "reachsequence"))
{
pev->netname = ALLOC_STRING(pkvd->szValue);
return true;
}
else if (FStrEq(pkvd->szKeyName, "presequence"))
{
m_preSequence = ALLOC_STRING(pkvd->szValue);
return true;
}
return CPointEntity::KeyValue(pkvd);
}
/**
* @brief Mortar shot entity
*/
class CBMortar : public CBaseEntity
{
DECLARE_CLASS(CBMortar, CBaseEntity);
DECLARE_DATAMAP();
public:
void Spawn() override;
static CBMortar* Shoot(CBaseEntity* owner, Vector vecStart, Vector vecVelocity);
void Touch(CBaseEntity* pOther) override;
void Animate();
int m_maxFrame;
};
LINK_ENTITY_TO_CLASS(bmortar, CBMortar);
BEGIN_DATAMAP(CBMortar)
DEFINE_FIELD(m_maxFrame, FIELD_INTEGER),
DEFINE_FUNCTION(Animate),
END_DATAMAP();
#define BIG_AE_STEP1 1 // Footstep left
#define BIG_AE_STEP2 2 // Footstep right
#define BIG_AE_STEP3 3 // Footstep back left
#define BIG_AE_STEP4 4 // Footstep back right
#define BIG_AE_SACK 5 // Sack slosh
#define BIG_AE_DEATHSOUND 6 // Death sound
#define BIG_AE_MELEE_ATTACKBR 8 // Leg attack
#define BIG_AE_MELEE_ATTACKBL 9 // Leg attack
#define BIG_AE_MELEE_ATTACK1 10 // Leg attack
#define BIG_AE_MORTAR_ATTACK1 11 // Launch a mortar
#define BIG_AE_LAY_CRAB 12 // Lay a headcrab
#define BIG_AE_JUMP_FORWARD 13 // Jump up and forward
#define BIG_AE_SCREAM 14 // alert sound
#define BIG_AE_PAIN_SOUND 15 // pain sound
#define BIG_AE_ATTACK_SOUND 16 // attack sound
#define BIG_AE_BIRTH_SOUND 17 // birth sound
#define BIG_AE_EARLY_TARGET 50 // Fire target early
// User defined conditions
#define bits_COND_NODE_SEQUENCE (bits_COND_SPECIAL1) // pev->netname contains the name of a sequence to play
// Attack distance constants
#define BIG_ATTACKDIST 170
#define BIG_MORTARDIST 800
#define BIG_MAXCHILDREN 20 // Max # of live headcrab children
#define bits_MEMORY_CHILDPAIR (bits_MEMORY_CUSTOM1)
#define bits_MEMORY_ADVANCE_NODE (bits_MEMORY_CUSTOM2)
#define bits_MEMORY_COMPLETED_NODE (bits_MEMORY_CUSTOM3)
#define bits_MEMORY_FIRED_NODE (bits_MEMORY_CUSTOM4)
int gSpitSprite, gSpitDebrisSprite;
Vector VecCheckSplatToss(CBaseEntity* entity, const Vector& vecSpot1, Vector vecSpot2, float maxHeight);
void MortarSpray(const Vector& position, const Vector& direction, int spriteModel, int count);
#define BIG_CHILDCLASS "monster_babycrab"
class CBigMomma : public CBaseMonster
{
DECLARE_CLASS(CBigMomma, CBaseMonster);
DECLARE_DATAMAP();
DECLARE_CUSTOM_SCHEDULES();
public:
void OnCreate() override;
void Spawn() override;
void Precache() override;
bool KeyValue(KeyValueData* pkvd) override;
void Activate() override;
bool TakeDamage(CBaseEntity* inflictor, CBaseEntity* attacker, float flDamage, int bitsDamageType) override;
bool HasAlienGibs() override { return true; }
void RunTask(const Task_t* pTask) override;
void StartTask(const Task_t* pTask) override;
const Schedule_t* GetSchedule() override;
const Schedule_t* GetScheduleOfType(int Type) override;
void TraceAttack(CBaseEntity* attacker, float flDamage, Vector vecDir, TraceResult* ptr, int bitsDamageType) override;
void NodeStart(string_t iszNextNode);
void NodeReach();
bool ShouldGoToNode();
void SetYawSpeed() override;
void HandleAnimEvent(MonsterEvent_t* pEvent) override;
void LayHeadcrab();
string_t GetNodeSequence()
{
CBaseEntity* pTarget = m_hTargetEnt;
if (pTarget)
{
return pTarget->pev->netname; // netname holds node sequence
}
return string_t::Null;
}
string_t GetNodePresequence()
{
CInfoBM* pTarget = m_hTargetEnt.Get<CInfoBM>();
if (pTarget)
{
return pTarget->m_preSequence;
}
return string_t::Null;
}
float GetNodeDelay()
{
CBaseEntity* pTarget = m_hTargetEnt;
if (pTarget)
{
return pTarget->pev->speed; // Speed holds node delay
}
return 0;
}
float GetNodeRange()
{
CBaseEntity* pTarget = m_hTargetEnt;
if (pTarget)
{
return pTarget->pev->scale; // Scale holds node delay
}
return 1e6;
}
float GetNodeYaw()
{
CBaseEntity* pTarget = m_hTargetEnt;
if (pTarget)
{
if (pTarget->pev->angles.y != 0)
return pTarget->pev->angles.y;
}
return pev->angles.y;
}
// Restart the crab count on each new level
void OverrideReset() override
{
m_crabCount = 0;
}
void DeathNotice(CBaseEntity* child) override;
bool CanLayCrab()
{
if (m_crabTime < gpGlobals->time && m_crabCount < BIG_MAXCHILDREN)
{
// Don't spawn crabs inside each other
Vector mins = pev->origin - Vector(32, 32, 0);
Vector maxs = pev->origin + Vector(32, 32, 0);
CBaseEntity* pList[2];
int count = UTIL_EntitiesInBox(pList, 2, mins, maxs, FL_MONSTER);
for (int i = 0; i < count; i++)
{
if (pList[i] != this) // Don't hurt yourself!
return false;
}
return true;
}
return false;
}
void LaunchMortar();
void SetObjectCollisionBox() override
{
pev->absmin = pev->origin + Vector(-95, -95, 0);
pev->absmax = pev->origin + Vector(95, 95, 190);
}
bool CheckMeleeAttack1(float flDot, float flDist) override; // Slash
bool CheckMeleeAttack2(float flDot, float flDist) override; // Lay a crab
bool CheckRangeAttack1(float flDot, float flDist) override; // Mortar launch
static const char* pChildDieSounds[];
static const char* pSackSounds[];
static const char* pDeathSounds[];
static const char* pAttackSounds[];
static const char* pAttackHitSounds[];
static const char* pBirthSounds[];
static const char* pAlertSounds[];
static const char* pPainSounds[];
static const char* pFootSounds[];
private:
float m_nodeTime;
float m_crabTime;
float m_mortarTime;
float m_painSoundTime;
int m_crabCount;
};
LINK_ENTITY_TO_CLASS(monster_bigmomma, CBigMomma);
BEGIN_DATAMAP(CBigMomma)
DEFINE_FIELD(m_nodeTime, FIELD_TIME),
DEFINE_FIELD(m_crabTime, FIELD_TIME),
DEFINE_FIELD(m_mortarTime, FIELD_TIME),
DEFINE_FIELD(m_painSoundTime, FIELD_TIME),
DEFINE_FIELD(m_crabCount, FIELD_INTEGER),
END_DATAMAP();
const char* CBigMomma::pChildDieSounds[] =
{
"gonarch/gon_childdie1.wav",
"gonarch/gon_childdie2.wav",
"gonarch/gon_childdie3.wav",
};
const char* CBigMomma::pSackSounds[] =
{
"gonarch/gon_sack1.wav",
"gonarch/gon_sack2.wav",
"gonarch/gon_sack3.wav",
};
const char* CBigMomma::pDeathSounds[] =
{
"gonarch/gon_die1.wav",
};
const char* CBigMomma::pAttackSounds[] =
{
"gonarch/gon_attack1.wav",
"gonarch/gon_attack2.wav",
"gonarch/gon_attack3.wav",
};
const char* CBigMomma::pAttackHitSounds[] =
{
"zombie/claw_strike1.wav",
"zombie/claw_strike2.wav",
"zombie/claw_strike3.wav",
};
const char* CBigMomma::pBirthSounds[] =
{
"gonarch/gon_birth1.wav",
"gonarch/gon_birth2.wav",
"gonarch/gon_birth3.wav",
};
const char* CBigMomma::pAlertSounds[] =
{
"gonarch/gon_alert1.wav",
"gonarch/gon_alert2.wav",
"gonarch/gon_alert3.wav",
};
const char* CBigMomma::pPainSounds[] =
{
"gonarch/gon_pain2.wav",
"gonarch/gon_pain4.wav",
"gonarch/gon_pain5.wav",
};
const char* CBigMomma::pFootSounds[] =
{
"gonarch/gon_step1.wav",
"gonarch/gon_step2.wav",
"gonarch/gon_step3.wav",
};
void CBigMomma::OnCreate()
{
CBaseMonster::OnCreate();
pev->health = 150 * GetSkillFloat("bigmomma_health_factor"sv);
pev->model = MAKE_STRING("models/big_mom.mdl");
SetClassification("alien_monster");
}
bool CBigMomma::KeyValue(KeyValueData* pkvd)
{
#if 0
if (FStrEq(pkvd->szKeyName, "volume"))
{
m_volume = atof(pkvd->szValue);
return true;
}
#endif
return CBaseMonster::KeyValue(pkvd);
}
void CBigMomma::SetYawSpeed()
{
int ys;
switch (m_Activity)
{
case ACT_IDLE:
ys = 100;
break;
default:
ys = 90;
}
pev->yaw_speed = ys;
}
void CBigMomma::HandleAnimEvent(MonsterEvent_t* pEvent)
{
switch (pEvent->event)
{
case BIG_AE_MELEE_ATTACKBR:
case BIG_AE_MELEE_ATTACKBL:
case BIG_AE_MELEE_ATTACK1:
{
Vector forward, right;
AngleVectors(pev->angles, &forward, &right, nullptr);
Vector center = pev->origin + forward * 128;
Vector mins = center - Vector(64, 64, 0);
Vector maxs = center + Vector(64, 64, 64);
CBaseEntity* pList[8];
int count = UTIL_EntitiesInBox(pList, 8, mins, maxs, FL_MONSTER | FL_CLIENT);
CBaseEntity* pHurt = nullptr;
for (int i = 0; i < count && !pHurt; i++)
{
if (pList[i] != this)
{
if (pList[i]->pev->owner != edict())
pHurt = pList[i];
}
}
if (pHurt)
{
pHurt->TakeDamage(this, this, GetSkillFloat("bigmomma_dmg_slash"sv), DMG_CRUSH | DMG_SLASH);
pHurt->pev->punchangle.x = 15;
switch (pEvent->event)
{
case BIG_AE_MELEE_ATTACKBR:
pHurt->pev->velocity = pHurt->pev->velocity + (forward * 150) + Vector(0, 0, 250) - (right * 200);
break;
case BIG_AE_MELEE_ATTACKBL:
pHurt->pev->velocity = pHurt->pev->velocity + (forward * 150) + Vector(0, 0, 250) + (right * 200);
break;
case BIG_AE_MELEE_ATTACK1:
pHurt->pev->velocity = pHurt->pev->velocity + (forward * 220) + Vector(0, 0, 200);
break;
}
pHurt->pev->flags &= ~FL_ONGROUND;
EmitSoundDyn(CHAN_WEAPON, RANDOM_SOUND_ARRAY(pAttackHitSounds), 1.0, ATTN_NORM, 0, 100 + RANDOM_LONG(-5, 5));
}
}
break;
case BIG_AE_SCREAM:
EMIT_SOUND_ARRAY_DYN(CHAN_VOICE, pAlertSounds);
break;
case BIG_AE_PAIN_SOUND:
EMIT_SOUND_ARRAY_DYN(CHAN_VOICE, pPainSounds);
break;
case BIG_AE_ATTACK_SOUND:
EMIT_SOUND_ARRAY_DYN(CHAN_WEAPON, pAttackSounds);
break;
case BIG_AE_BIRTH_SOUND:
EMIT_SOUND_ARRAY_DYN(CHAN_BODY, pBirthSounds);
break;
case BIG_AE_SACK:
if (RANDOM_LONG(0, 100) < 30)
EMIT_SOUND_ARRAY_DYN(CHAN_BODY, pSackSounds);
break;
case BIG_AE_DEATHSOUND:
EMIT_SOUND_ARRAY_DYN(CHAN_VOICE, pDeathSounds);
break;
case BIG_AE_STEP1: // Footstep left
case BIG_AE_STEP3: // Footstep back left
EMIT_SOUND_ARRAY_DYN(CHAN_ITEM, pFootSounds);
break;
case BIG_AE_STEP4: // Footstep back right
case BIG_AE_STEP2: // Footstep right
EMIT_SOUND_ARRAY_DYN(CHAN_BODY, pFootSounds);
break;
case BIG_AE_MORTAR_ATTACK1:
LaunchMortar();
break;
case BIG_AE_LAY_CRAB:
LayHeadcrab();
break;
case BIG_AE_JUMP_FORWARD:
ClearBits(pev->flags, FL_ONGROUND);
SetOrigin(pev->origin + Vector(0, 0, 1)); // take him off ground so engine doesn't instantly reset onground
UTIL_MakeVectors(pev->angles);
pev->velocity = (gpGlobals->v_forward * 200) + gpGlobals->v_up * 500;
break;
case BIG_AE_EARLY_TARGET:
{
CBaseEntity* pTarget = m_hTargetEnt;
if (pTarget && !FStringNull(pTarget->pev->message))
FireTargets(STRING(pTarget->pev->message), this, this, USE_TOGGLE, 0);
Remember(bits_MEMORY_FIRED_NODE);
}
break;
default:
CBaseMonster::HandleAnimEvent(pEvent);
break;
}
}
void CBigMomma::TraceAttack(CBaseEntity* attacker, float flDamage, Vector vecDir, TraceResult* ptr, int bitsDamageType)
{
if (ptr->iHitgroup != 1)
{
// didn't hit the sack?
if (pev->dmgtime != gpGlobals->time || (RANDOM_LONG(0, 10) < 1))
{
UTIL_Ricochet(ptr->vecEndPos, RANDOM_FLOAT(1, 2));
pev->dmgtime = gpGlobals->time;
}
flDamage = 0.1; // don't hurt the monster much, but allow bits_COND_LIGHT_DAMAGE to be generated
}
else if (gpGlobals->time > m_painSoundTime)
{
m_painSoundTime = gpGlobals->time + RANDOM_LONG(1, 3);
EMIT_SOUND_ARRAY_DYN(CHAN_VOICE, pPainSounds);
}
CBaseMonster::TraceAttack(attacker, flDamage, vecDir, ptr, bitsDamageType);
}
bool CBigMomma::TakeDamage(CBaseEntity* inflictor, CBaseEntity* attacker, float flDamage, int bitsDamageType)
{
// Don't take any acid damage -- BigMomma's mortar is acid
if ((bitsDamageType & DMG_ACID) != 0)
flDamage = 0;
if (!HasMemory(bits_MEMORY_PATH_FINISHED))
{
if (pev->health <= flDamage)
{
pev->health = flDamage + 1;
Remember(bits_MEMORY_ADVANCE_NODE | bits_MEMORY_COMPLETED_NODE);
AILogger->debug("BM: Finished node health!!!");
}
}
return CBaseMonster::TakeDamage(inflictor, attacker, flDamage, bitsDamageType);
}
void CBigMomma::LayHeadcrab()
{
CBaseEntity* pChild = CBaseEntity::Create(BIG_CHILDCLASS, pev->origin, pev->angles, this, false);
MaybeSetChildClassification(pChild);
DispatchSpawn(pChild->edict());
pChild->pev->spawnflags |= SF_MONSTER_FALL_TO_GROUND;
// Is this the second crab in a pair?
if (HasMemory(bits_MEMORY_CHILDPAIR))
{
m_crabTime = gpGlobals->time + RANDOM_FLOAT(5, 10);
Forget(bits_MEMORY_CHILDPAIR);
}
else
{
m_crabTime = gpGlobals->time + RANDOM_FLOAT(0.5, 2.5);
Remember(bits_MEMORY_CHILDPAIR);
}
TraceResult tr;
UTIL_TraceLine(pev->origin, pev->origin - Vector(0, 0, 100), ignore_monsters, edict(), &tr);
UTIL_DecalTrace(&tr, DECAL_MOMMABIRTH);
EmitSoundDyn(CHAN_WEAPON, RANDOM_SOUND_ARRAY(pBirthSounds), 1.0, ATTN_NORM, 0, 100 + RANDOM_LONG(-5, 5));
m_crabCount++;
}
void CBigMomma::DeathNotice(CBaseEntity* child)
{
if (m_crabCount > 0) // Some babies may cross a transition, but we reset the count then
m_crabCount--;
if (IsAlive())
{
// Make the "my baby's dead" noise!
EMIT_SOUND_ARRAY_DYN(CHAN_WEAPON, pChildDieSounds);
}
}
void CBigMomma::LaunchMortar()
{
m_mortarTime = gpGlobals->time + RANDOM_FLOAT(2, 15);
Vector startPos = pev->origin;
startPos.z += 180;
EmitSoundDyn(CHAN_WEAPON, RANDOM_SOUND_ARRAY(pSackSounds), 1.0, ATTN_NORM, 0, 100 + RANDOM_LONG(-5, 5));
CBMortar* pBomb = CBMortar::Shoot(this, startPos, pev->movedir);
pBomb->pev->gravity = 1.0;
MortarSpray(startPos, Vector(0, 0, 1), gSpitSprite, 24);
}
void CBigMomma::Spawn()
{
Precache();
SetModel(STRING(pev->model));
SetSize(Vector(-32, -32, 0), Vector(32, 32, 64));
pev->solid = SOLID_SLIDEBOX;
pev->movetype = MOVETYPE_STEP;
m_bloodColor = BLOOD_COLOR_GREEN;
pev->view_ofs = Vector(0, 0, 128); // position of the eyes relative to monster's origin.
m_flFieldOfView = 0.3; // indicates the width of this monster's forward view cone ( as a dotproduct result )
m_MonsterState = MONSTERSTATE_NONE;
MonsterInit();
}
void CBigMomma::Precache()
{
PrecacheModel(STRING(pev->model));
PRECACHE_SOUND_ARRAY(pChildDieSounds);
PRECACHE_SOUND_ARRAY(pSackSounds);
PRECACHE_SOUND_ARRAY(pDeathSounds);
PRECACHE_SOUND_ARRAY(pAttackSounds);
PRECACHE_SOUND_ARRAY(pAttackHitSounds);
PRECACHE_SOUND_ARRAY(pBirthSounds);
PRECACHE_SOUND_ARRAY(pAlertSounds);
PRECACHE_SOUND_ARRAY(pPainSounds);
PRECACHE_SOUND_ARRAY(pFootSounds);
UTIL_PrecacheOther(BIG_CHILDCLASS);
// TEMP: Squid
PrecacheModel("sprites/mommaspit.spr"); // spit projectile.
gSpitSprite = PrecacheModel("sprites/mommaspout.spr"); // client side spittle.
gSpitDebrisSprite = PrecacheModel("sprites/mommablob.spr");
PrecacheSound("bullchicken/bc_acid1.wav");
PrecacheSound("bullchicken/bc_spithit1.wav");
PrecacheSound("bullchicken/bc_spithit2.wav");
}
void CBigMomma::Activate()
{
if (m_hTargetEnt == nullptr)
Remember(bits_MEMORY_ADVANCE_NODE); // Start 'er up
}
void CBigMomma::NodeStart(string_t iszNextNode)
{
pev->netname = iszNextNode;
CBaseEntity* pTarget = nullptr;
if (!FStringNull(pev->netname))
{
pTarget = UTIL_FindEntityByTargetname(nullptr, STRING(pev->netname));
}
if (!pTarget)
{
AILogger->debug("BM: Finished the path!!");
Remember(bits_MEMORY_PATH_FINISHED);
return;
}
Remember(bits_MEMORY_ON_PATH);
m_hTargetEnt = pTarget;
}
void CBigMomma::NodeReach()
{
CBaseEntity* pTarget = m_hTargetEnt;
Forget(bits_MEMORY_ADVANCE_NODE);
if (!pTarget)
return;
if (0 != pTarget->pev->health)
pev->max_health = pev->health = pTarget->pev->health * GetSkillFloat("bigmomma_health_factor"sv);
if (!HasMemory(bits_MEMORY_FIRED_NODE))
{
if (!FStringNull(pTarget->pev->message))
FireTargets(STRING(pTarget->pev->message), this, this, USE_TOGGLE, 0);
}
Forget(bits_MEMORY_FIRED_NODE);
pev->netname = pTarget->pev->target;
if (pTarget->pev->health == 0)
Remember(bits_MEMORY_ADVANCE_NODE); // Move on if no health at this node
}
bool CBigMomma::CheckMeleeAttack1(float flDot, float flDist)
{
if (flDot >= 0.7)
{
if (flDist <= BIG_ATTACKDIST)
return true;
}
return false;
}
bool CBigMomma::CheckMeleeAttack2(float flDot, float flDist)
{
return CanLayCrab();
}
bool CBigMomma::CheckRangeAttack1(float flDot, float flDist)
{
if (flDist <= BIG_MORTARDIST && m_mortarTime < gpGlobals->time)
{
CBaseEntity* pEnemy = m_hEnemy;
if (pEnemy)
{
Vector startPos = pev->origin;
startPos.z += 180;
pev->movedir = VecCheckSplatToss(this, startPos, pEnemy->BodyTarget(pev->origin), RANDOM_FLOAT(150, 500));
if (pev->movedir != g_vecZero)
return true;
}
}
return false;
}
enum
{
SCHED_BIG_NODE = LAST_COMMON_SCHEDULE + 1,
SCHED_NODE_FAIL,
};
enum
{
TASK_MOVE_TO_NODE_RANGE = LAST_COMMON_TASK + 1, // Move within node range
TASK_FIND_NODE, // Find my next node
TASK_PLAY_NODE_PRESEQUENCE, // Play node pre-script
TASK_PLAY_NODE_SEQUENCE, // Play node script
TASK_PROCESS_NODE, // Fire targets, etc.
TASK_WAIT_NODE, // Wait at the node
TASK_NODE_DELAY, // Delay walking toward node for a bit. You've failed to get there
TASK_NODE_YAW, // Get the best facing direction for this node
};
Task_t tlBigNode[] =
{
{TASK_SET_FAIL_SCHEDULE, (float)SCHED_NODE_FAIL},
{TASK_STOP_MOVING, (float)0},
{TASK_FIND_NODE, (float)0}, // Find my next node
{TASK_PLAY_NODE_PRESEQUENCE, (float)0}, // Play the pre-approach sequence if any
{TASK_MOVE_TO_NODE_RANGE, (float)0}, // Move within node range
{TASK_STOP_MOVING, (float)0},
{TASK_NODE_YAW, (float)0},
{TASK_FACE_IDEAL, (float)0},
{TASK_WAIT_NODE, (float)0}, // Wait for node delay
{TASK_PLAY_NODE_SEQUENCE, (float)0}, // Play the sequence if one exists
{TASK_PROCESS_NODE, (float)0}, // Fire targets, etc.
{TASK_SET_ACTIVITY, (float)ACT_IDLE},
};
Schedule_t slBigNode[] =
{
{tlBigNode,
std::size(tlBigNode),
0,
0,
"Big Node"},
};
Task_t tlNodeFail[] =
{
{TASK_NODE_DELAY, (float)10}, // Try to do something else for 10 seconds
{TASK_SET_ACTIVITY, (float)ACT_IDLE},
};
Schedule_t slNodeFail[] =
{
{tlNodeFail,
std::size(tlNodeFail),
0,
0,
"NodeFail"},
};
BEGIN_CUSTOM_SCHEDULES(CBigMomma)
slBigNode,
slNodeFail
END_CUSTOM_SCHEDULES();
const Schedule_t* CBigMomma::GetScheduleOfType(int Type)
{
switch (Type)
{
case SCHED_BIG_NODE:
return slBigNode;
break;
case SCHED_NODE_FAIL:
return slNodeFail;
break;
}
return CBaseMonster::GetScheduleOfType(Type);
}
bool CBigMomma::ShouldGoToNode()
{
if (HasMemory(bits_MEMORY_ADVANCE_NODE))
{
if (m_nodeTime < gpGlobals->time)
return true;
}
return false;
}
const Schedule_t* CBigMomma::GetSchedule()
{
if (ShouldGoToNode())
{
return GetScheduleOfType(SCHED_BIG_NODE);
}
return CBaseMonster::GetSchedule();
}
void CBigMomma::StartTask(const Task_t* pTask)
{
switch (pTask->iTask)
{
case TASK_FIND_NODE:
{
CBaseEntity* pTarget = m_hTargetEnt;
if (!HasMemory(bits_MEMORY_ADVANCE_NODE))
{
if (pTarget)
pev->netname = m_hTargetEnt->pev->target;
}
NodeStart(pev->netname);
TaskComplete();
AILogger->debug("BM: Found node {}", STRING(pev->netname));
}
break;
case TASK_NODE_DELAY:
m_nodeTime = gpGlobals->time + pTask->flData;
TaskComplete();
AILogger->debug("BM: FAIL! Delay {:.2f}", pTask->flData);
break;
case TASK_PROCESS_NODE:
AILogger->debug("BM: Reached node {}", STRING(pev->netname));
NodeReach();
TaskComplete();
break;
case TASK_PLAY_NODE_PRESEQUENCE:
case TASK_PLAY_NODE_SEQUENCE:
{
string_t sequence;
if (pTask->iTask == TASK_PLAY_NODE_SEQUENCE)
sequence = GetNodeSequence();
else
sequence = GetNodePresequence();
AILogger->debug("BM: Playing node sequence {}", STRING(sequence));
if (!FStringNull(sequence))
{
const int sequenceIndex = LookupSequence(STRING(sequence));
if (sequenceIndex != -1)
{
pev->sequence = sequenceIndex;
pev->frame = 0;
ResetSequenceInfo();
AILogger->debug("BM: Sequence {}", STRING(GetNodeSequence()));
return;
}
}
TaskComplete();
}
break;
case TASK_NODE_YAW:
pev->ideal_yaw = GetNodeYaw();
TaskComplete();
break;
case TASK_WAIT_NODE:
m_flWait = gpGlobals->time + GetNodeDelay();
if ((m_hTargetEnt->pev->spawnflags & SF_INFOBM_WAIT) != 0)
AILogger->debug("BM: Wait at node {} forever", STRING(pev->netname));
else
AILogger->debug("BM: Wait at node {} for {:.2f}", STRING(pev->netname), GetNodeDelay());
break;
case TASK_MOVE_TO_NODE_RANGE:
{
CBaseEntity* pTarget = m_hTargetEnt;
if (!pTarget)
TaskFail();
else
{
if ((pTarget->pev->origin - pev->origin).Length() < GetNodeRange())
TaskComplete();
else
{
Activity act = ACT_WALK;
if ((pTarget->pev->spawnflags & SF_INFOBM_RUN) != 0)
act = ACT_RUN;
m_vecMoveGoal = pTarget->pev->origin;
if (!MoveToTarget(act, 2))
{
TaskFail();
}
}
}
}
AILogger->debug("BM: Moving to node {}", STRING(pev->netname));
break;
case TASK_MELEE_ATTACK1:
// Play an attack sound here
EmitSound(CHAN_VOICE, RANDOM_SOUND_ARRAY(pAttackSounds), 1.0, ATTN_NORM);
CBaseMonster::StartTask(pTask);
break;
default:
CBaseMonster::StartTask(pTask);
break;
}
}
void CBigMomma::RunTask(const Task_t* pTask)
{
switch (pTask->iTask)
{
case TASK_MOVE_TO_NODE_RANGE:
{
float distance;
if (m_hTargetEnt == nullptr)
TaskFail();
else
{
distance = (m_vecMoveGoal - pev->origin).Length2D();
// Set the appropriate activity based on an overlapping range
// overlap the range to prevent oscillation
if ((distance < GetNodeRange()) || MovementIsComplete())
{
AILogger->debug("BM: Reached node!");
TaskComplete();
RouteClear(); // Stop moving
}
}
}
break;
case TASK_WAIT_NODE:
if (m_hTargetEnt != nullptr && (m_hTargetEnt->pev->spawnflags & SF_INFOBM_WAIT) != 0)
return;
if (gpGlobals->time > m_flWaitFinished)
TaskComplete();
AILogger->debug("BM: The WAIT is over!");
break;
case TASK_PLAY_NODE_PRESEQUENCE:
case TASK_PLAY_NODE_SEQUENCE:
if (m_fSequenceFinished)
{
m_Activity = ACT_RESET;
TaskComplete();
}
break;
default:
CBaseMonster::RunTask(pTask);
break;
}
}
Vector VecCheckSplatToss(CBaseEntity* entity, const Vector& vecSpot1, Vector vecSpot2, float maxHeight)
{
TraceResult tr;
Vector vecMidPoint; // halfway point between Spot1 and Spot2
Vector vecApex; // highest point
Vector vecGrenadeVel;
float flGravity = g_psv_gravity->value;
// calculate the midpoint and apex of the 'triangle'
vecMidPoint = vecSpot1 + (vecSpot2 - vecSpot1) * 0.5;
UTIL_TraceLine(vecMidPoint, vecMidPoint + Vector(0, 0, maxHeight), ignore_monsters, entity->edict(), &tr);
vecApex = tr.vecEndPos;
UTIL_TraceLine(vecSpot1, vecApex, dont_ignore_monsters, entity->edict(), &tr);
if (tr.flFraction != 1.0)
{
// fail!
return g_vecZero;
}
// Don't worry about actually hitting the target, this won't hurt us!
// How high should the grenade travel (subtract 15 so the grenade doesn't hit the ceiling)?
float height = (vecApex.z - vecSpot1.z) - 15;
// How fast does the grenade need to travel to reach that height given gravity?
float speed = sqrt(2 * flGravity * height);
// How much time does it take to get there?
float time = speed / flGravity;
vecGrenadeVel = (vecSpot2 - vecSpot1);
vecGrenadeVel.z = 0;
// Travel half the distance to the target in that time (apex is at the midpoint)
vecGrenadeVel = vecGrenadeVel * (0.5 / time);
// Speed to offset gravity at the desired height
vecGrenadeVel.z = speed;
return vecGrenadeVel;
}
void MortarSpray(const Vector& position, const Vector& direction, int spriteModel, int count)
{
MESSAGE_BEGIN(MSG_PVS, SVC_TEMPENTITY, position);
WRITE_BYTE(TE_SPRITE_SPRAY);
WRITE_COORD(position.x); // pos
WRITE_COORD(position.y);
WRITE_COORD(position.z);
WRITE_COORD(direction.x); // dir
WRITE_COORD(direction.y);
WRITE_COORD(direction.z);
WRITE_SHORT(spriteModel); // model
WRITE_BYTE(count); // count
WRITE_BYTE(130); // speed
WRITE_BYTE(80); // noise ( client will divide by 100 )
MESSAGE_END();
}
// UNDONE: right now this is pretty much a copy of the squid spit with minor changes to the way it does damage
void CBMortar::Spawn()
{
pev->movetype = MOVETYPE_TOSS;
pev->solid = SOLID_BBOX;
pev->rendermode = kRenderTransAlpha;
pev->renderamt = 255;
SetModel("sprites/mommaspit.spr");
pev->frame = 0;
pev->scale = 0.5;
SetSize(Vector(0, 0, 0), Vector(0, 0, 0));
m_maxFrame = (float)MODEL_FRAMES(pev->modelindex) - 1;
pev->dmgtime = gpGlobals->time + 0.4;
}
void CBMortar::Animate()
{
pev->nextthink = gpGlobals->time + 0.1;
if (gpGlobals->time > pev->dmgtime)
{
pev->dmgtime = gpGlobals->time + 0.2;
MortarSpray(pev->origin, -pev->velocity.Normalize(), gSpitSprite, 3);
}
if (0 != pev->frame++)
{
if (pev->frame > m_maxFrame)
{
pev->frame = 0;
}
}
}
CBMortar* CBMortar::Shoot(CBaseEntity* owner, Vector vecStart, Vector vecVelocity)
{
CBMortar* pSpit = g_EntityDictionary->Create<CBMortar>("bmortar");
pSpit->Spawn();
pSpit->SetOrigin(vecStart);
pSpit->pev->velocity = vecVelocity;
pSpit->SetOwner(owner);
pSpit->pev->scale = 2.5;
pSpit->SetThink(&CBMortar::Animate);
pSpit->pev->nextthink = gpGlobals->time + 0.1;
return pSpit;
}
void CBMortar::Touch(CBaseEntity* pOther)
{
TraceResult tr;
int iPitch;
// splat sound
iPitch = RANDOM_FLOAT(90, 110);
EmitSoundDyn(CHAN_VOICE, "bullchicken/bc_acid1.wav", 1, ATTN_NORM, 0, iPitch);
switch (RANDOM_LONG(0, 1))
{
case 0:
EmitSoundDyn(CHAN_WEAPON, "bullchicken/bc_spithit1.wav", 1, ATTN_NORM, 0, iPitch);
break;
case 1:
EmitSoundDyn(CHAN_WEAPON, "bullchicken/bc_spithit2.wav", 1, ATTN_NORM, 0, iPitch);
break;
}
if (pOther->IsBSPModel())
{
// make a splat on the wall
UTIL_TraceLine(pev->origin, pev->origin + pev->velocity * 10, dont_ignore_monsters, edict(), &tr);
UTIL_DecalTrace(&tr, DECAL_MOMMASPLAT);
}
else
{
tr.vecEndPos = pev->origin;
tr.vecPlaneNormal = -1 * pev->velocity.Normalize();
}
// make some flecks
MortarSpray(tr.vecEndPos, tr.vecPlaneNormal, gSpitSprite, 24);
auto owner = GetOwner();
RadiusDamage(pev->origin, this, owner, GetSkillFloat("bigmomma_dmg_blast"sv), GetSkillFloat("bigmomma_radius_blast"sv), DMG_ACID);
UTIL_Remove(this);
}
| 412 | 0.942928 | 1 | 0.942928 | game-dev | MEDIA | 0.972849 | game-dev | 0.857406 | 1 | 0.857406 |
thelaui/M.A.R.S. | 2,944 | src/Teams/DMTeam.cpp | /* DMTeam.cpp
Copyright (c) 2010 - 2011 by Felix Lauer and Simon Schneegans
This program is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option)
any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see <http://www.gnu.org/licenses/>. */
# include "Teams/DMTeam.hpp"
# include "Teams/teams.hpp"
# include "Players/Player.hpp"
# include "Items/items.hpp"
# include "Items/PowerUp.hpp"
# include "SpaceObjects/ships.hpp"
# include "Games/games.hpp"
void DMTeam::createJobs() {
checkEnemies();
checkPowerUps();
for (int i=0; i<botControllers_.size(); ++i) {
addJob(Job(Job::jLand, 4));
addJob(Job(Job::jCharge, 4));
}
}
void DMTeam::checkEnemies() {
std::vector<Ship*> ships = ships::getShips();
bool existAny(false);
for (std::vector<Ship*>::const_iterator it = ships.begin(); it != ships.end(); ++it)
if ((*it)->getOwner()->team() != this && (*it)->attackable()) {
existAny = true;
break;
}
if (existAny) {
for (int i=0; i<botControllers_.size(); ++i)
addJob(Job(Job::jAttackAny, 60));
}
else {
for (int i=0; i<botControllers_.size(); ++i)
addJob(Job(Job::jEscape, 6));
}
}
void DMTeam::checkPowerUps() {
std::vector<Ship*> ships = ships::getShips();
bool existAny(false);
for (std::vector<Ship*>::const_iterator it = ships.begin(); it != ships.end(); ++it)
if ((*it)->getOwner()->team() != this && (*it)->attackable()) {
existAny = true;
break;
}
powerUpLocations_.clear();
std::list<PowerUp*> const& powerUps = items::getPowerUps();
for (std::list<PowerUp*>::const_iterator it=powerUps.begin(); it!=powerUps.end(); ++it) {
if (!(*it)->isCollected()) {
powerUpLocations_.push_back((*it)->location());
switch ((*it)->type()) {
case items::puFuel: addJob(Job(Job::jGetPUFuel, 70, &powerUpLocations_.back())); break;
case items::puHealth: addJob(Job(Job::jGetPUHealth, 70, &powerUpLocations_.back())); break;
case items::puReverse: if (existAny) addJob(Job(Job::jGetPUReverse, 70, &powerUpLocations_.back())); break;
case items::puShield: addJob(Job(Job::jGetPUShield, 70, &powerUpLocations_.back())); break;
default: if (existAny) addJob(Job(Job::jGetPUSleep, 70, &powerUpLocations_.back())); break;
}
}
}
}
| 412 | 0.771469 | 1 | 0.771469 | game-dev | MEDIA | 0.850273 | game-dev | 0.914665 | 1 | 0.914665 |
CrossTheRoadElec/Phoenix5-Examples | 4,606 | Java Talon FX (Falcon 500)/Current Limit/src/main/java/frc/robot/sim/PhysicsSim.java | package frc.robot.sim;
import java.util.*;
import com.ctre.phoenix.motorcontrol.can.*;
/**
* Manages physics simulation for CTRE products.
*/
public class PhysicsSim {
private static final PhysicsSim sim = new PhysicsSim();
/**
* Gets the robot simulator instance.
*/
public static PhysicsSim getInstance() {
return sim;
}
/**
* Adds a TalonSRX controller to the simulator.
*
* @param talon
* The TalonSRX device
* @param accelToFullTime
* The time the motor takes to accelerate from 0 to full, in seconds
* @param fullVel
* The maximum motor velocity, in ticks per 100ms
*/
public void addTalonSRX(TalonSRX talon, final double accelToFullTime, final double fullVel) {
addTalonSRX(talon, accelToFullTime, fullVel, false);
}
/**
* Adds a TalonSRX controller to the simulator.
*
* @param talon
* The TalonSRX device
* @param accelToFullTime
* The time the motor takes to accelerate from 0 to full, in seconds
* @param fullVel
* The maximum motor velocity, in ticks per 100ms
* @param sensorPhase
* The phase of the TalonSRX sensors
*/
public void addTalonSRX(TalonSRX talon, final double accelToFullTime, final double fullVel, final boolean sensorPhase) {
if (talon != null) {
TalonSRXSimProfile simTalon = new TalonSRXSimProfile(talon, accelToFullTime, fullVel, sensorPhase);
_simProfiles.add(simTalon);
}
}
/**
* Adds a TalonFX controller to the simulator.
*
* @param falcon
* The TalonFX device
* @param accelToFullTime
* The time the motor takes to accelerate from 0 to full, in seconds
* @param fullVel
* The maximum motor velocity, in ticks per 100ms
*/
public void addTalonFX(TalonFX falcon, final double accelToFullTime, final double fullVel) {
addTalonFX(falcon, accelToFullTime, fullVel, false);
}
/**
* Adds a TalonFX controller to the simulator.
*
* @param falcon
* The TalonFX device
* @param accelToFullTime
* The time the motor takes to accelerate from 0 to full, in seconds
* @param fullVel
* The maximum motor velocity, in ticks per 100ms
* @param sensorPhase
* The phase of the TalonFX sensors
*/
public void addTalonFX(TalonFX falcon, final double accelToFullTime, final double fullVel, final boolean sensorPhase) {
if (falcon != null) {
TalonFXSimProfile simFalcon = new TalonFXSimProfile(falcon, accelToFullTime, fullVel, sensorPhase);
_simProfiles.add(simFalcon);
}
}
/**
* Adds a VictorSPX controller to the simulator.
*
* @param victor
* The VictorSPX device
*/
public void addVictorSPX(VictorSPX victor) {
if (victor != null) {
VictorSPXSimProfile simVictor = new VictorSPXSimProfile(victor);
_simProfiles.add(simVictor);
}
}
/**
* Runs the simulator:
* - enable the robot
* - simulate sensors
*/
public void run() {
// Simulate devices
for (SimProfile simProfile : _simProfiles) {
simProfile.run();
}
}
private final ArrayList<SimProfile> _simProfiles = new ArrayList<SimProfile>();
/* scales a random domain of [0, 2pi] to [min, max] while prioritizing the peaks */
static double random(double min, double max) {
return (max - min) / 2 * Math.sin(Math.IEEEremainder(Math.random(), 2 * 3.14159)) + (max + min) / 2;
}
static double random(double max) {
return random(0, max);
}
/**
* Holds information about a simulated device.
*/
static class SimProfile {
private long _lastTime;
private boolean _running = false;
/**
* Runs the simulation profile.
* Implemented by device-specific profiles.
*/
public void run() {}
/**
* Returns the time since last call, in milliseconds.
*/
protected double getPeriod() {
// set the start time if not yet running
if (!_running) {
_lastTime = System.nanoTime();
_running = true;
}
long now = System.nanoTime();
final double period = (now - _lastTime) / 1000000.;
_lastTime = now;
return period;
}
}
}
| 412 | 0.817323 | 1 | 0.817323 | game-dev | MEDIA | 0.846384 | game-dev | 0.963564 | 1 | 0.963564 |
PickleModifications/pickle_slapboxing | 1,970 | modules/table/server.lua | SlapTables = {}
GlobalState.SlapTables = SlapTables
function GenerateIndex()
local index = os.time()
repeat
index = os.time() .. "_" .. math.random(1, 1000)
until not SlapTables[index]
return index
end
function GenerateTableData(source, name, coords, heading, item)
return {
name = name,
coords = coords,
heading = heading,
source = source,
item = item,
activeMatch = false,
bets = {
home = {},
away = {}
},
turn = "home",
sides = {
home = nil,
away = nil
}
}
end
function CreateTable(source, name, coords, heading, item)
local index = GenerateIndex()
SlapTables[index] = GenerateTableData(source, name, coords, heading, item)
GlobalState.SlapTables = SlapTables
return index
end
function DestroyTable(index)
SlapTables[index] = nil
GlobalState.SlapTables = SlapTables
TriggerClientEvent("pickle_slapboxing:destroyTable", -1, index)
end
RegisterNetEvent("pickle_slapboxing:removeTable", function(index)
local source = source
local data = SlapTables[index]
if data.sides.home or data.sides.away then
return
end
if Config.CanRemoveTable(source, SlapTables[index]) then
ShowNotification(source, _L("table_removed"))
if SlapTables[index].item then
AddItem(source, SlapTables[index].item, 1)
end
DestroyTable(index)
else
ShowNotification(source, _L("table_fail_removed"))
end
end)
for k,v in pairs(Config.Items) do
RegisterUsableItem(k, function(source)
local ped = GetPlayerPed(source)
local data = lib.callback.await('pickle_slapboxing:requestPlayerData', source, vector3(0.0, 1.0, -1.0))
ShowNotification(source, _L("table_spawned"))
CreateTable(source, v.table, data.offset, data.heading, k)
RemoveItem(source, k, 1)
end)
end | 412 | 0.830562 | 1 | 0.830562 | game-dev | MEDIA | 0.523112 | game-dev | 0.90609 | 1 | 0.90609 |
kiwibrowser/src.next | 11,056 | third_party/blink/renderer/core/layout/multi_column_fragmentainer_group.h | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_MULTI_COLUMN_FRAGMENTAINER_GROUP_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_MULTI_COLUMN_FRAGMENTAINER_GROUP_H_
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/layout/layout_multi_column_flow_thread.h"
#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
// A group of columns, that are laid out in the inline progression direction,
// all with the same column height.
//
// When a multicol container is inside another fragmentation context, and said
// multicol container lives in multiple outer fragmentainers (pages / columns),
// we need to put these inner columns into separate groups, with one group per
// outer fragmentainer. Such a group of columns is what comprises a "row of
// column boxes" in spec lingo.
//
// Column balancing, when enabled, takes place within a column fragmentainer
// group.
//
// Each fragmentainer group may have its own actual column count (if there are
// unused columns because of forced breaks, for example). If there are multiple
// fragmentainer groups, the actual column count must not exceed the used column
// count (the one calculated based on column-count and column-width from CSS),
// or they'd overflow the outer fragmentainer in the inline direction. If we
// need more columns than what a group has room for, we'll create another group
// and put them there (and make them appear in the next outer fragmentainer).
class CORE_EXPORT MultiColumnFragmentainerGroup {
DISALLOW_NEW();
public:
explicit MultiColumnFragmentainerGroup(const LayoutMultiColumnSet&);
const LayoutMultiColumnSet& ColumnSet() const { return *column_set_; }
bool IsFirstGroup() const;
bool IsLastGroup() const;
// Position within the LayoutMultiColumnSet.
LayoutUnit LogicalTop() const { return logical_top_; }
void SetLogicalTop(LayoutUnit logical_top) { logical_top_ = logical_top; }
// Return the amount of block space that this fragmentainer group takes up in
// its containing LayoutMultiColumnSet.
LayoutUnit GroupLogicalHeight() const {
DCHECK(IsLogicalHeightKnown());
return logical_height_;
}
// Return the block size of a column (or fragmentainer) in this fragmentainer
// group. The spec says that this value must always be >= 1px, to ensure
// progress.
LayoutUnit ColumnLogicalHeight() const {
DCHECK(IsLogicalHeightKnown());
return std::max(LayoutUnit(1), logical_height_);
}
// Return whether we have some column height to work with. This doesn't have
// to be the final height. It will only return false in the first layout pass,
// and even then only if column height is auto and there's no way to even make
// a guess (i.e. when there are no usable constraints).
bool IsLogicalHeightKnown() const { return is_logical_height_known_; }
LayoutSize OffsetFromColumnSet() const;
// Return the block offset from the enclosing fragmentation context, if
// nested. In the coordinate space of the enclosing fragmentation context.
LayoutUnit BlockOffsetInEnclosingFragmentationContext() const;
// The top of our flow thread portion
LayoutUnit LogicalTopInFlowThread() const {
return logical_top_in_flow_thread_;
}
void SetLogicalTopInFlowThread(LayoutUnit logical_top_in_flow_thread) {
logical_top_in_flow_thread_ = logical_top_in_flow_thread;
}
// The bottom of our flow thread portion
LayoutUnit LogicalBottomInFlowThread() const {
return logical_bottom_in_flow_thread_;
}
void SetLogicalBottomInFlowThread(LayoutUnit logical_bottom_in_flow_thread) {
logical_bottom_in_flow_thread_ = logical_bottom_in_flow_thread;
}
void ExtendLogicalBottomInFlowThread(LayoutUnit block_size) {
logical_bottom_in_flow_thread_ += block_size;
}
// The height of the flow thread portion for the entire fragmentainer group.
LayoutUnit LogicalHeightInFlowThread() const {
// Due to negative margins, logical bottom may actually end up above logical
// top, but we never want to return negative logical heights.
return (logical_bottom_in_flow_thread_ - logical_top_in_flow_thread_)
.ClampNegativeToZero();
}
// The height of the flow thread portion for the specified fragmentainer.
// The last fragmentainer may not be using all available space.
LayoutUnit LogicalHeightInFlowThreadAt(unsigned column_index) const;
void ResetColumnHeight();
bool RecalculateColumnHeight(LayoutMultiColumnSet&);
LayoutSize FlowThreadTranslationAtOffset(LayoutUnit,
LayoutBox::PageBoundaryRule,
CoordinateSpaceConversion) const;
LayoutUnit ColumnLogicalTopForOffset(LayoutUnit offset_in_flow_thread) const;
// If SnapToColumnPolicy is SnapToColumn, visualPointToFlowThreadPoint() won't
// return points that lie outside the bounds of the columns: Before converting
// to a flow thread position, if the block direction coordinate is outside the
// column, snap to the bounds of the column, and reset the inline direction
// coordinate to the start position in the column. The effect of this is that
// if the block position is before the column rectangle, we'll get to the
// beginning of this column, while if the block position is after the column
// rectangle, we'll get to the beginning of the next column. This is behavior
// that positionForPoint() depends on.
enum SnapToColumnPolicy { kDontSnapToColumn, kSnapToColumn };
LayoutPoint VisualPointToFlowThreadPoint(
const LayoutPoint& visual_point,
SnapToColumnPolicy = kDontSnapToColumn) const;
LayoutRect FragmentsBoundingBox(
const LayoutRect& bounding_box_in_flow_thread) const;
LayoutRect FlowThreadPortionRectAt(unsigned column_index) const;
LayoutRect FlowThreadPortionOverflowRectAt(unsigned column_index) const;
// Get the first and the last column intersecting the specified block range.
// Note that |logicalBottomInFlowThread| is an exclusive endpoint.
void ColumnIntervalForBlockRangeInFlowThread(
LayoutUnit logical_top_in_flow_thread,
LayoutUnit logical_bottom_in_flow_thread,
unsigned& first_column,
unsigned& last_column) const;
// Get the first and the last column intersecting the specified visual
// rectangle.
void ColumnIntervalForVisualRect(const LayoutRect&,
unsigned& first_column,
unsigned& last_column) const;
LayoutRect CalculateOverflow() const;
unsigned ColumnIndexAtOffset(LayoutUnit offset_in_flow_thread,
LayoutBox::PageBoundaryRule) const;
// Like ColumnIndexAtOffset(), but with the return value clamped to actual
// column count. While there are legitimate reasons for dealing with columns
// out of bounds during layout, this should not happen when performing read
// operations on the tree (like painting and hit-testing).
unsigned ConstrainedColumnIndexAtOffset(LayoutUnit offset_in_flow_thread,
LayoutBox::PageBoundaryRule) const;
// The "CSS actual" value of column-count. This includes overflowing columns,
// if any.
// Returns 1 or greater, never 0.
unsigned ActualColumnCount() const;
void SetColumnBlockSizeFromNG(LayoutUnit);
void ExtendColumnBlockSizeFromNG(LayoutUnit);
void Trace(Visitor*) const;
private:
LayoutUnit HeightAdjustedForRowOffset(LayoutUnit height) const;
LayoutUnit CalculateMaxColumnHeight() const;
void SetAndConstrainColumnHeight(LayoutUnit);
LayoutUnit RebalanceColumnHeightIfNeeded() const;
LayoutRect ColumnRectAt(unsigned column_index) const;
LayoutUnit LogicalTopInFlowThreadAt(unsigned column_index) const {
return logical_top_in_flow_thread_ + column_index * ColumnLogicalHeight();
}
// Return the column that the specified visual point belongs to. Only the
// coordinate on the column progression axis is relevant. Every point belongs
// to a column, even if said point is not inside any of the columns.
unsigned ColumnIndexAtVisualPoint(const LayoutPoint& visual_point) const;
unsigned UnclampedActualColumnCount() const;
const Member<const LayoutMultiColumnSet> column_set_;
LayoutUnit logical_top_;
LayoutUnit logical_top_in_flow_thread_;
LayoutUnit logical_bottom_in_flow_thread_;
// Logical height of the group. This will also be the height of each column
// in this group, with the difference that, while the logical height can be
// 0, the height of a column must be >= 1px.
LayoutUnit logical_height_;
// Maximum logical height allowed.
LayoutUnit max_logical_height_;
bool is_logical_height_known_ = false;
};
// List of all fragmentainer groups within a column set. There will always be at
// least one group. Deleting the one group is not allowed (or possible). There
// will be more than one group if the owning column set lives in multiple outer
// fragmentainers (e.g. multicol inside paged media).
class CORE_EXPORT MultiColumnFragmentainerGroupList {
DISALLOW_NEW();
public:
explicit MultiColumnFragmentainerGroupList(LayoutMultiColumnSet&);
~MultiColumnFragmentainerGroupList();
// Add an additional fragmentainer group to the end of the list, and return
// it.
MultiColumnFragmentainerGroup& AddExtraGroup();
// Remove all fragmentainer groups but the first one.
void DeleteExtraGroups();
MultiColumnFragmentainerGroup& First() { return groups_.front(); }
const MultiColumnFragmentainerGroup& First() const { return groups_.front(); }
MultiColumnFragmentainerGroup& Last() { return groups_.back(); }
const MultiColumnFragmentainerGroup& Last() const { return groups_.back(); }
typedef HeapVector<MultiColumnFragmentainerGroup, 1>::iterator iterator;
typedef HeapVector<MultiColumnFragmentainerGroup, 1>::const_iterator
const_iterator;
iterator begin() { return groups_.begin(); }
const_iterator begin() const { return groups_.begin(); }
iterator end() { return groups_.end(); }
const_iterator end() const { return groups_.end(); }
wtf_size_t size() const { return groups_.size(); }
MultiColumnFragmentainerGroup& operator[](wtf_size_t i) {
return groups_.at(i);
}
const MultiColumnFragmentainerGroup& operator[](wtf_size_t i) const {
return groups_.at(i);
}
void Append(const MultiColumnFragmentainerGroup& group) {
groups_.push_back(group);
}
void Shrink(wtf_size_t size) { groups_.Shrink(size); }
void Trace(Visitor*) const;
private:
Member<LayoutMultiColumnSet> column_set_;
HeapVector<MultiColumnFragmentainerGroup, 1> groups_;
};
} // namespace blink
WTF_ALLOW_CLEAR_UNUSED_SLOTS_WITH_MEM_FUNCTIONS(
blink::MultiColumnFragmentainerGroup)
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_MULTI_COLUMN_FRAGMENTAINER_GROUP_H_
| 412 | 0.959143 | 1 | 0.959143 | game-dev | MEDIA | 0.10947 | game-dev | 0.828672 | 1 | 0.828672 |
MartinDrab/IRPMon | 11,839 | km-shared/allocator.c |
/**
* @file
*
* Implementation of a special memory allocator.
*
* The allocator records information
* about every memory allocation and deallocation, attempts to check validity of
* a heap, which should catch writing too many data to small buffers, and keeps
* an eye on memory leaks.
*
* Structure of every memory block allocated by the allocator looks as follows:
* - THE HEADER (allocator-specific information are stored here)
* - THE BLOCK (user gets pointer to beginning of this member)
* - THE FOOTER (contains signature in order to detect writing to small buffers)
*
* The allocator records the following information about every allocated block:
* - Type of memory pool
* - size
* - name of function that allocated it
* - line of code that allocated it
*/
#include <ntifs.h>
#include <fltKernel.h>
#include "preprocessor.h"
#include "allocator.h"
/************************************************************************/
/* GLOBAL VARIABLES */
/************************************************************************/
static const ULONG _poolTag = (ULONG)'MPRI';
/** Synchronizes access to list of paged memory blocks. */
static EX_PUSH_LOCK _pagedListLock;
/** synchronizes access to list of nonpaged memory blocks. */
static KSPIN_LOCK _nonPagedListLock;
/** Lists of memory blocks. One list for one memory pool. */
static LIST_ENTRY _poolLists[2];
/************************************************************************/
/* HELPER MACROS */
/************************************************************************/
/** Initializes header of an allocated block.
*
* @param header Address of the header.
* @param PoolType Type of the memory pool the block is allocated from.
* @param NumberOfbytes Size of the block requested by the caller, in bytes.
* @param Function Name of function where the allocation was performed.
* @param Line Number of source line that performed the allocation.
*/
#define BlockHeaderInitialize(Header, PoolType, NumberOfBytes, Function, Line) \
InitializeListHead(&Header->Entry); \
Header->PoolType = PoolType; \
Header->NumberOfBytes = NumberOfBytes; \
Header->Function = Function; \
Header->Line = Line; \
Header->Signature = BLOCK_HEADER_SIGNATURE
/** Initializes footer of an allocated block.
*
* @param Footer Address of the footer.
*/
#define BlockFooterInitialize(Footer) \
Footer->Signature = BLOCK_FOOTER_SIGNATURE
/************************************************************************/
/* HELPER ROUTINES */
/************************************************************************/
/** Locks list of allocated blocks of given memory pool.
*
* @param PoolType Type of memory pool.
* @param Irql Address of variable that, when locking list of nonpaged memory blocks,
* receives value of IRQL before the locking operation. The parameter is ignored when
* locking list of paged memory blocks.
*/
static void _PoolListLock(POOL_TYPE PoolType, PKIRQL Irql)
{
switch (PoolType) {
case NonPagedPool:
KeAcquireSpinLock(&_nonPagedListLock, Irql);
break;
case PagedPool:
FltAcquirePushLockExclusive(&_pagedListLock);
break;
default:
DEBUG_ERROR("Invalid memory pool type: %u", PoolType);
break;
}
return;
}
/** Unlocks list of allocated blocks of given pool type.
*
* @param PoolType Type of memory pool.
* @param Irql Value of IRQL which should be restored after the unlock operation is
* finished. The parameter is ignored when unlocking list of nonpaged memory blocks.
*/
static void _PoolUnlock(POOL_TYPE PoolType, KIRQL Irql)
{
switch (PoolType) {
case NonPagedPool:
KeReleaseSpinLock(&_nonPagedListLock, Irql);
break;
case PagedPool:
FltReleasePushLock(&_pagedListLock);
break;
default:
DEBUG_ERROR("Invalid memory pool type: %u", PoolType);
break;
}
return;
}
/** Checks whether given allocated block of memory is valid.
*
* @param Header Header of the block to check.
*
* @remark
* The routine does not return any value indicating whether the block is valid or not.
* Instead, it prints a debug message and issues a breakpoint when the block is invalid.
*/
static void _BlockValidityCheck(PDEBUG_BLOCK_HEADER Header)
{
BOOLEAN valid = FALSE;
PDEBUG_BLOCK_FOOTER footer = (PDEBUG_BLOCK_FOOTER)((PUCHAR)Header + sizeof(DEBUG_BLOCK_HEADER) + Header->NumberOfBytes);
// DEBUG_ENTER_FUNCTION("Header=0x%p", Header);
valid =
((Header->PoolType == PagedPool || Header->PoolType == NonPagedPool) &&
(Header->Signature == BLOCK_HEADER_SIGNATURE) &&
(footer->Signature == BLOCK_FOOTER_SIGNATURE));
if (!valid) {
DEBUG_ERROR("Block of memory is invalid: header=0x%p", Header);
}
// DEBUG_EXIT_FUNCTION_VOID();
return;
}
/** Checks validity of all blocks in one list.
*
* @param PoolType Type of memory pool which list of allocated blocks should be
* checked.
*/
static void _PoolValidityCheck(POOL_TYPE PoolType)
{
KIRQL Irql;
PDEBUG_BLOCK_HEADER header = NULL;
// DEBUG_ENTER_FUNCTION("PoolType=%u", PoolType);
_PoolListLock(PoolType, &Irql);
header = CONTAINING_RECORD(_poolLists[PoolType].Flink, DEBUG_BLOCK_HEADER, Entry);
while (&header->Entry != &_poolLists[PoolType]) {
_BlockValidityCheck(header);
header = CONTAINING_RECORD(header->Entry.Flink, DEBUG_BLOCK_HEADER, Entry);
}
_PoolUnlock(PoolType, Irql);
// DEBUG_EXIT_FUNCTION_VOID();
return;
}
/** Checks validity of blocks in all currently available lists of
* allocated memory blocks.
*
* @remark
* If called at IRQL >= DISPATCH_LEVEL, only the list of nonpaged memory
* blocks is checked. Otherwise, the paged one is also examined.
*/
static void _HeapValidityCheck(void)
{
// DEBUG_ENTER_FUNCTION_NO_ARGS();
_PoolValidityCheck(NonPagedPool);
// Check the paged pool heap only when we are running at IRQL
// lower enough.
if (KeGetCurrentIrql() < DISPATCH_LEVEL) {
_PoolValidityCheck(PagedPool);
}
// DEBUG_EXIT_FUNCTION_VOID();
return;
}
/** Finds memory blocks allocated in given pool, that were not freed and hence are
* a memory leaks.
*
* @param PoolType type of the memory pool.
*
* @remark
* The routine does not return these blocks. Instead, it prints debug messages and
* issues a breakpoint for every block found not to be freed.
*/
static void _PoolFindUnfreedMemory(POOL_TYPE PoolType)
{
PDEBUG_BLOCK_HEADER header = NULL;
// DEBUG_ENTER_FUNCTION("PoolType=%u", PoolType);
header = CONTAINING_RECORD(_poolLists[PoolType].Flink, DEBUG_BLOCK_HEADER, Entry);
while (&header->Entry != &_poolLists[PoolType]) {
DEBUG_PRINT_LOCATION("A block of allocated memory has been found: 0x%p", header + 1);
DEBUG_PRINT_LOCATION("Pool type: %s", header->PoolType == NonPagedPool ? "nonpaged" : "paged");
DEBUG_PRINT_LOCATION("Size: %u", header->NumberOfBytes);
DEBUG_PRINT_LOCATION("Allocated in function %s at line %u", header->Function, header->Line);
// __debugbreak();
header = CONTAINING_RECORD(header->Entry.Flink, DEBUG_BLOCK_HEADER, Entry);
}
// DEBUG_EXIT_FUNCTION_VOID();
return;
}
/** Finds allocated memory blocks that were not freed, hence they are part of a memory
* leak.
*/
static void _FindUnfreedMemory(void)
{
// DEBUG_ENTER_FUNCTION_NO_ARGS();
_PoolFindUnfreedMemory(NonPagedPool);
_PoolFindUnfreedMemory(PagedPool);
// DEBUG_EXIT_FUNCTION_VOID();
return;
}
/** Frees all memory used by the debug allocator for given pool type, including
* allocated memory blocks.
*
* @param PoolType Memory pool type.
*/
static void _PoolFree(POOL_TYPE PoolType)
{
PDEBUG_BLOCK_HEADER old = NULL;
PDEBUG_BLOCK_HEADER header = NULL;
DEBUG_ENTER_FUNCTION("PoolType=%u", PoolType);
header = CONTAINING_RECORD(_poolLists[PoolType].Flink, DEBUG_BLOCK_HEADER, Entry);
while (&header->Entry != &_poolLists[PoolType]) {
old = header;
header = CONTAINING_RECORD(header->Entry.Flink, DEBUG_BLOCK_HEADER, Entry);
ExFreePool(old);
}
DEBUG_EXIT_FUNCTION_VOID();
return;
}
/** Frees all memory used by the debug allocator, including
* allocated memory blocks.
*/
static void _PoolsFree(void)
{
DEBUG_ENTER_FUNCTION_NO_ARGS();
_PoolFree(NonPagedPool);
_PoolFree(PagedPool);
DEBUG_EXIT_FUNCTION_VOID();
return;
}
/************************************************************************/
/* PUBLIC ROUTINES */
/************************************************************************/
/** Allocates a block of memory and records the operation to the structures of the allocator.
*
* @param PoolType Type of memory pool from where the block should be allocated.
* @param NumberOfBytes Size of the block, in bytes.
* @param Function Name of routine that is calling the allocator.
* @param Line Line of code where the call occurred.
*
* @return
* Returns address of newly allocated block of memory. If the allocation fails,
* the function returns NULL.
*/
PVOID DebugAllocatorAlloc(POOL_TYPE PoolType, SIZE_T NumberOfBytes, PCHAR Function, ULONG Line)
{
KIRQL Irql;
PVOID ret = NULL;
PDEBUG_BLOCK_HEADER header = NULL;
PDEBUG_BLOCK_FOOTER footer = NULL;
SIZE_T wholeSize = sizeof(DEBUG_BLOCK_HEADER) + NumberOfBytes + sizeof(DEBUG_BLOCK_FOOTER);
// DEBUG_ENTER_FUNCTION("PoolType=%u; NumberOfBytes=%u; Function=%s; Line=%u", PoolType, NumberOfBytes, Function, Line);
_HeapValidityCheck();
ret = ExAllocatePoolWithTag(PoolType, wholeSize, _poolTag);
if (ret != NULL) {
header = (PDEBUG_BLOCK_HEADER)ret;
footer = (PDEBUG_BLOCK_FOOTER)((PUCHAR)ret + sizeof(DEBUG_BLOCK_HEADER) + NumberOfBytes);
BlockHeaderInitialize(header, PoolType, NumberOfBytes, Function, Line);
BlockFooterInitialize(footer);
_PoolListLock(PoolType, &Irql);
InsertTailList(&_poolLists[PoolType], &header->Entry);
_PoolUnlock(PoolType, Irql);
ret = (PVOID)((PUCHAR)ret + sizeof(DEBUG_BLOCK_HEADER));
}
// DEBUG_EXIT_FUNCTION("0x%p", ret);
return ret;
}
/** Frees a block of memory.
*
* @param Address of the block, returned by DebugAllocatorAlloc routine.
*/
void DebugAllocatorFree(PVOID Address)
{
KIRQL Irql;
PDEBUG_BLOCK_HEADER header = (PDEBUG_BLOCK_HEADER)((PUCHAR)Address - sizeof(DEBUG_BLOCK_HEADER));
// DEBUG_ENTER_FUNCTION("Address=0x%p", Address);
_BlockValidityCheck(header);
_HeapValidityCheck();
_PoolListLock(header->PoolType, &Irql);
RemoveEntryList(&header->Entry);
_PoolUnlock(header->PoolType, Irql);
ExFreePoolWithTag(header, _poolTag);
// DEBUG_EXIT_FUNCTION_VOID();
return;
}
/************************************************************************/
/* INITIALIZATION AND FINALIZACTION */
/************************************************************************/
/** Initializes the allocator.
*
* @return
* Always returns STATUS_SUCCESS.
*/
NTSTATUS DebugAllocatorModuleInit(void)
{
NTSTATUS status = STATUS_UNSUCCESSFUL;
DEBUG_ENTER_FUNCTION_NO_ARGS();
FltInitializePushLock(&_pagedListLock);
KeInitializeSpinLock(&_nonPagedListLock);
InitializeListHead(&_poolLists[0]);
InitializeListHead(&_poolLists[1]);
status = STATUS_SUCCESS;
DEBUG_EXIT_FUNCTION("0x%x", status);
return status;
}
/** Frees memory allocated by the allocator. The routine also attempts to find
* blocks of memory that were not freed. The routine is expected to be called
* just before the driver unloads.
*/
void DebugAllocatorModuleFinit(void)
{
DEBUG_ENTER_FUNCTION_NO_ARGS();
_HeapValidityCheck();
_FindUnfreedMemory();
_PoolsFree();
DEBUG_EXIT_FUNCTION_VOID();
return;
}
| 412 | 0.934136 | 1 | 0.934136 | game-dev | MEDIA | 0.355081 | game-dev | 0.654724 | 1 | 0.654724 |
RobertSkalko/Age-of-Exile | 3,691 | src/main/java/com/robertx22/age_of_exile/database/data/spells/spell_classes/SpellCtx.java | package com.robertx22.age_of_exile.database.data.spells.spell_classes;
import com.robertx22.age_of_exile.database.data.spells.components.EntityActivation;
import com.robertx22.age_of_exile.database.data.spells.entities.EntitySavedSpellData;
import com.robertx22.age_of_exile.database.data.value_calc.LevelProvider;
import com.robertx22.age_of_exile.uncommon.datasaving.Load;
import net.minecraft.entity.Entity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.vector.Vector3d;
import net.minecraft.world.World;
import java.util.Objects;
public class SpellCtx {
// the entity the effect came from, player summons fireball. fireball hits enemy, dmg comes from fireball
public Entity sourceEntity;
public World world;
public LivingEntity caster;
public LivingEntity target;
public BlockPos pos;
public Vector3d vecPos;
public final EntityActivation activation;
public final LevelProvider levelProvider;
public EntitySavedSpellData calculatedSpellData;
private SpellCtx(EntityActivation act, Entity sourceEntity, LivingEntity caster, LivingEntity target, BlockPos pos, Vector3d vec, EntitySavedSpellData calculatedSpellData) {
this.sourceEntity = sourceEntity;
this.caster = caster;
this.target = target;
this.pos = pos;
this.calculatedSpellData = calculatedSpellData;
this.world = caster.level;
this.vecPos = vec;
this.activation = act;
this.levelProvider = new LevelProvider(caster, calculatedSpellData.getSpell());
}
public static SpellCtx onCast(LivingEntity caster, EntitySavedSpellData data) {
Objects.requireNonNull(caster);
Objects.requireNonNull(data);
return new SpellCtx(EntityActivation.ON_CAST, caster, caster, caster, caster.blockPosition(), caster.position(), data);
}
public static SpellCtx onHit(LivingEntity caster, Entity sourceEntity, LivingEntity target, EntitySavedSpellData data) {
Objects.requireNonNull(caster);
Objects.requireNonNull(sourceEntity);
Objects.requireNonNull(data);
Load.spells(caster)
.onSpellHitTarget(sourceEntity, target);
return new SpellCtx(EntityActivation.ON_HIT, sourceEntity, caster, target, target.blockPosition(), target.position(), data);
}
public static SpellCtx onEntityHit(SpellCtx ctx, LivingEntity target) {
Objects.requireNonNull(ctx);
Objects.requireNonNull(target);
return new SpellCtx(EntityActivation.PER_ENTITY_HIT, ctx.sourceEntity, ctx.caster, target, target.blockPosition(), target.position(), ctx.calculatedSpellData);
}
public static SpellCtx onExpire(LivingEntity caster, Entity sourceEntity, EntitySavedSpellData data) {
Objects.requireNonNull(caster);
Objects.requireNonNull(sourceEntity);
Objects.requireNonNull(data);
LivingEntity target = sourceEntity instanceof LivingEntity ? (LivingEntity) sourceEntity : null;
return new SpellCtx(EntityActivation.ON_EXPIRE, sourceEntity, caster, target, sourceEntity.blockPosition(), sourceEntity.position(), data);
}
public static SpellCtx onTick(LivingEntity caster, Entity sourceEntity, EntitySavedSpellData data) {
Objects.requireNonNull(caster);
Objects.requireNonNull(sourceEntity);
Objects.requireNonNull(data);
LivingEntity target = sourceEntity instanceof LivingEntity ? (LivingEntity) sourceEntity : null;
return new SpellCtx(EntityActivation.ON_TICK, sourceEntity, caster, target, sourceEntity.blockPosition(), sourceEntity.position(), data);
}
}
| 412 | 0.515721 | 1 | 0.515721 | game-dev | MEDIA | 0.89687 | game-dev | 0.508217 | 1 | 0.508217 |
goonstation/goonstation-2016 | 20,978 | code/datums/limb.dm | /**
* Limb datums for arms. Describes all activity performed by the limb.
* Currently, this is basically attack_hand().
*
* Also serves as a future holder for any other special limb activity.
*/
/datum/limb
var/obj/item/parts/holder = null
New(var/obj/item/parts/holder)
src.holder = holder
// !!CAUTION!! it is allowed to delete the target here
// Mob is also passed as a convenience/redundancy.
proc/attack_hand(atom/target, var/mob/user, var/reach)
target.attack_hand(user)
proc/harm(mob/living/carbon/human/target, var/mob/living/user)
user.melee_attack_normal(target, 0, 0, DAMAGE_BLUNT)
proc/help(mob/living/carbon/human/target, var/mob/living/user)
user.do_help(target)
proc/disarm(mob/living/carbon/human/target, var/mob/living/user)
user.disarm(target)
proc/grab(mob/living/carbon/human/target, var/mob/living/user)
user.grab_other(target)
proc/attack_range(atom/target, var/mob/user, params)
return
proc/is_on_cooldown()
return 0
/datum/limb/hitscan
var/brute = 5
var/burn = 0
var/cooldown = 30
var/next_shot_at = 0
var/image/default_obscurer
attack_range(atom/target, var/mob/user, params)
if (next_shot_at > ticker.round_elapsed_ticks)
return
user.visible_message("<b style='color:red'>[user] fires at [target] with the [holder.name]!</b>")
playsound(user.loc, "sound/weapons/lasermed.ogg", 100, 1)
next_shot_at = ticker.round_elapsed_ticks + cooldown
if (ismob(target))
var/mob/MT = target
if (prob(30))
user.visible_message("<span style='color:red'>The shot misses!</span>")
else
MT.TakeDamageAccountArmor(user.zone_sel ? user.zone_sel.selecting : "All", brute, burn, 0, burn ? DAMAGE_BURN : DAMAGE_BLUNT)
spawn
var/datum/effects/system/spark_spread/s = unpool(/datum/effects/system/spark_spread)
s.set_up(3, 1, target)
s.start()
is_on_cooldown()
if (ticker.round_elapsed_ticks < next_shot_at)
return next_shot_at - ticker.round_elapsed_ticks
return 0
/datum/limb/railgun
var/cooldown = 50
var/next_shot_at = 0
var/image/default_obscurer
is_on_cooldown()
if (ticker.round_elapsed_ticks < next_shot_at)
return next_shot_at - ticker.round_elapsed_ticks
return 0
attack_range(atom/target, var/mob/user, params)
var/turf/start = user.loc
if (!isturf(start))
return
target = get_turf(target)
if (!target)
return
if (target == start)
return
if (next_shot_at > ticker.round_elapsed_ticks)
return
next_shot_at = ticker.round_elapsed_ticks + cooldown
playsound(user, "sound/effects/mag_warp.ogg", 50, 1)
spawn(rand(1,3)) // so it might miss, sometimes, maybe
var/obj/target_r = new/obj/railgun_trg_dummy(target)
playsound(user, "sound/weapons/railgun.ogg", 50, 1)
user.dir = get_dir(user, target)
var/list/affected = DrawLine(user, target_r, /obj/line_obj/railgun ,'icons/obj/projectiles.dmi',"WholeRailG",1,1,"HalfStartRailG","HalfEndRailG",OBJ_LAYER,1)
for(var/obj/O in affected)
O.anchored = 1 //Proc wont spawn the right object type so lets do that here.
O.name = "Energy"
var/turf/src_turf = O.loc
for(var/obj/machinery/vehicle/A in src_turf)
if(A == O || A == user) continue
A.meteorhit(O)
for(var/mob/living/M in src_turf)
if(M == O || M == user) continue
M.meteorhit(O)
for(var/turf/T in src_turf)
if(T == O) continue
T.meteorhit(O)
for(var/obj/machinery/colosseum_putt/A in src_turf)
if (A == O || A == user) continue
A.meteorhit(O)
sleep(3)
for (var/obj/O in affected)
pool(O)
if(istype(target_r, /obj/railgun_trg_dummy)) qdel(target_r)
/datum/limb/arcflash
var/wattage = 15000
var/cooldown = 60
var/next_shot_at = 0
var/image/default_obscurer
is_on_cooldown()
if (ticker.round_elapsed_ticks < next_shot_at)
return next_shot_at - ticker.round_elapsed_ticks
return 0
attack_range(atom/target, var/mob/user, params)
if (next_shot_at > ticker.round_elapsed_ticks)
return
next_shot_at = ticker.round_elapsed_ticks + cooldown
arcFlashTurf(user, get_turf(target), 15000)
/datum/limb/gun
var/datum/projectile/proj = null
var/cooldown = 30
var/reload_time = 200
var/shots = 4
var/current_shots = 0
var/reloading_str = "reloading"
var/reloaded_at = 0
var/next_shot_at = 0
var/image/default_obscurer
attack_range(atom/target, var/mob/user, params)
if (reloaded_at > ticker.round_elapsed_ticks && !current_shots)
boutput(user, "<span style='color:red'>The [holder.name] is [reloading_str]!</span>")
return
else if (current_shots <= 0)
current_shots = shots
if (next_shot_at > ticker.round_elapsed_ticks)
return
if (current_shots > 0)
current_shots--
var/pox = text2num(params["icon-x"]) - 16
var/poy = text2num(params["icon-y"]) - 16
shoot_projectile_ST_pixel(user, proj, target, pox, poy)
user.visible_message("<b style='color:red'>[user] fires at [target] with the [holder.name]!</b>")
next_shot_at = ticker.round_elapsed_ticks + cooldown
if (!current_shots)
reloaded_at = ticker.round_elapsed_ticks + reload_time
else
reloaded_at = ticker.round_elapsed_ticks + reload_time
is_on_cooldown()
if (ticker.round_elapsed_ticks < reloaded_at)
return reloaded_at - ticker.round_elapsed_ticks
return 0
arm38
proj = new/datum/projectile/bullet/revolver_38
shots = 3
current_shots = 3
cooldown = 30
reload_time = 200
abg
proj = new/datum/projectile/bullet/abg
shots = 6
current_shots = 6
cooldown = 30
reload_time = 300
phaser
proj = new/datum/projectile/laser/light
shots = 1
current_shots = 1
cooldown = 30
reload_time = 30
cutter
proj = new/datum/projectile/laser/drill/cutter
shots = 1
current_shots = 1
cooldown = 30
reload_time = 30
artillery
proj = new/datum/projectile/bullet/autocannon
shots = 1
current_shots = 1
cooldown = 50
reload_time = 50
disruptor
proj = new/datum/projectile/disruptor/high
shots = 1
current_shots = 1
cooldown = 40
reload_time = 40
glitch
proj = new/datum/projectile/bullet/glitch
shots = 1
current_shots = 1
cooldown = 40
reload_time = 40
fire_elemental
proj = new/datum/projectile/bullet/flare
shots = 1
current_shots = 1
cooldown = 40
reload_time = 40
/datum/limb/mouth
attack_hand(atom/target, var/mob/user, var/reach)
if (ismob(target))
..()
if (istype(target, /obj/item))
var/obj/item/potentially_food = target
if (potentially_food.edible)
potentially_food.Eat(user, user, 1)
help(mob/target, var/mob/user)
return
disarm(mob/target, var/mob/user)
return
grab(mob/target, var/mob/user)
return
harm(mob/target, var/mob/user)
if (!user || !target)
return 0
if (!target.melee_attack_test(user))
return
if (prob(80) || target.stunned || target.weakened || target.paralysis || target.stat || target.restrained())
var/obj/item/affecting = target.get_affecting(user)
var/datum/attackResults/msgs = user.calculate_melee_attack(target, affecting, 3, 8, 0)
user.attack_effects(target, affecting)
msgs.base_attack_message = "<b><span style='color:red'>[user] bites [target]!</span></b>"
msgs.played_sound = "sound/weapons/werewolf_attack1.ogg"
msgs.flush(0)
user.HealDamage("All", 2, 0)
else
user.visible_message("<b><span style='color:red'>[user] attempts to bite [target] but misses!</span></b>")
/datum/limb/item
attack_hand(atom/target, var/mob/user, var/reach)
if (holder && holder.remove_object && istype(holder.remove_object))
target.attackby(holder.remove_object, user)
if (target)
holder.remove_object.afterattack(target, src, reach)
/datum/limb/bear
attack_hand(atom/target, var/mob/living/user, var/reach)
if (!holder)
return
if (!istype(user))
target.attack_hand(user)
return
if (ismob(target))
..()
return
if (isobj(target))
switch (user.smash_through(target, list("window", "grille")))
if (0)
if (istype(target, /obj/item))
boutput(user, "<span style=\"color:red\">You try to pick [target] up but it wiggles out of your hand. Opposable thumbs would be nice.</span>")
return
else if (istype(target, /obj/machinery))
boutput(user, "<span style=\"color:red\">You're unlikely to be able to use [target]. You manage to scratch its surface though.</span>")
return
if (1)
return
..()
return
help(mob/target, var/mob/living/user)
user.show_message("<span style=\"color:red\">Nope. Not going to work. You're more likely to kill them.</span>")
disarm(mob/target, var/mob/living/user)
logTheThing("combat", user, target, "mauls %target% with bear limbs (disarm intent) at [log_loc(user)].")
user.visible_message("<span style=\"color:red\">[user] mauls [target] while trying to disarm them!</span>")
harm(target, user, 1)
grab(mob/target, var/mob/living/user)
logTheThing("combat", user, target, "mauls %target% with bear limbs (grab intent) at [log_loc(user)].")
user.visible_message("<span style=\"color:red\">[user] mauls [target] while trying to grab them!</span>")
harm(target, user, 1)
harm(mob/target, var/mob/living/user, var/no_logs = 0)
if (no_logs != 1)
logTheThing("combat", user, target, "mauls %target% with bear limbs at [log_loc(user)].")
var/obj/item/affecting = target.get_affecting(user)
var/datum/attackResults/msgs = user.calculate_melee_attack(target, affecting, 6, 10, 0)
user.attack_effects(target, affecting)
var/action = pick("maim", "maul", "mangle", "rip", "claw", "lacerate", "mutilate")
msgs.base_attack_message = "<b><span style='color:red'>[user] [action]s [target] with their [src.holder]!</span></b>"
msgs.played_sound = "sound/effects/bloody_stab.ogg"
msgs.damage_type = DAMAGE_CUT
msgs.flush(SUPPRESS_LOGS)
if (prob(60))
target.weakened += 2
/datum/limb/wendigo
attack_hand(atom/target, var/mob/living/user, var/reach)
if (!holder)
return
var/quality = src.holder.quality
if (!istype(user))
target.attack_hand(user)
return
if (isobj(target))
switch (user.smash_through(target, list("window", "grille", "door")))
if (0)
if (istype(target, /obj/item/reagent_containers))
if (prob(50 * quality))
user.visible_message("<span style=\"color:red\">[user] accidentally crushes [target]!</span>", "<span style=\"color:red\">You accidentally crush the [target]!</span>")
qdel(target)
return
else if (istype(target, /obj/item))
if (prob(45))
user.show_message("<span style=\"color:red\">[target] slips through your claws!</span>")
return
if (1)
return
..()
return
proc/accident(mob/target, mob/living/user)
if (prob(25))
logTheThing("combat", user, target, "accidentally harms %target% with wendigo limbs at [log_loc(user)].")
user.visible_message("<span style=\"color:red\"><b>[user] accidentally claws [target] while trying to [user.a_intent] them!</b></span>", "<span style=\"color:red\"><b>You accidentally claw [target] while trying to [user.a_intent] them!</b></span>")
harm(target, user, 1)
return 1
return 0
help(mob/target, var/mob/living/user)
if (accident(target, user))
return
else
..()
disarm(mob/target, var/mob/living/user)
if (accident(target, user))
return
else
..()
grab(mob/target, var/mob/living/user)
if (accident(target, user))
return
else
..()
harm(mob/target, var/mob/living/user, var/no_logs = 0)
var/quality = src.holder.quality
if (no_logs != 1)
logTheThing("combat", user, target, "mauls %target% with wendigo limbs at [log_loc(user)].")
var/obj/item/affecting = target.get_affecting(user)
var/datum/attackResults/msgs = user.calculate_melee_attack(target, affecting, 6, 9, rand(5,9) * quality)
user.attack_effects(target, affecting)
var/action = pick("maim", "maul", "mangle", "rip", "claw", "lacerate", "mutilate")
msgs.base_attack_message = "<b><span style='color:red'>[user] [action]s [target] with their [src.holder]!</span></b>"
msgs.played_sound = "sound/effects/bloody_stab.ogg"
msgs.damage_type = DAMAGE_CUT
msgs.flush(SUPPRESS_LOGS)
if (prob(35 * quality))
target.weakened += 4 * quality
// A replacement for the awful custom_attack() overrides in mutantraces.dm, which consisted of two
// entire copies of pre-stamina melee attack code (Convair880).
/datum/limb/abomination
var/weak = 0
werewolf
weak = 1 // Werewolf melee attacks are similar enough. Less repeated code.
attack_hand(atom/target, var/mob/living/user, var/reach)
if (!holder)
return
if (!istype(user))
target.attack_hand(user)
return
if (istype(target, /obj/critter))
var/obj/critter/victim = target
if (src.weak == 1)
spawn (0)
step_away(victim, user, 15)
playsound(user.loc, pick('sound/misc/werewolf_attack1.ogg', 'sound/misc/werewolf_attack2.ogg', 'sound/misc/werewolf_attack3.ogg'), 50, 1)
spawn (1)
if (user) playsound(user.loc, "sound/weapons/DSCLAW.ogg", 40, 1, -1)
user.visible_message("<span style=\"color:red\"><B>[user] slashes viciously at [victim]!</B></span>")
victim.health -= rand(4,8) * victim.brutevuln
else
var/turf/T = get_edge_target_turf(user, user.dir)
if (prob(66) && T && isturf(T))
user.visible_message("<span style=\"color:red\"><B>[user] savagely punches [victim], sending them flying!</B></span>")
victim.health -= 6 * victim.brutevuln
spawn (0)
victim.throw_at(T, 10, 2)
else
user.visible_message("<span style=\"color:red\"><B>[user] punches [victim]!</span>")
victim.health -= 4 * victim.brutevuln
playsound(user.loc, "punch", 25, 1, -1)
if (victim && victim.alive && victim.health <= 0)
victim.CritterDeath()
return
if (isobj(target))
switch (user.smash_through(target, list("window", "grille", "door")))
if (0)
target.attack_hand(user)
return
if (1)
return
if (ismob(target))
if (issilicon(target))
special_attack_silicon(target, user)
return
else
..()
return
..()
return
grab(mob/target, var/mob/living/user)
if (!holder)
return
if (!istype(user) || !ismob(target))
target.attack_hand(user)
return
if (issilicon(target))
special_attack_silicon(target, user)
return
user.grab_other(target, 1) // Use standard grab proc.
// Werewolves and shamblers grab aggressively by default.
var/obj/item/grab/GD = user.equipped()
if (GD && istype(GD) && (GD.affecting && GD.affecting == target))
target.stunned = max(2, target.stunned)
GD.state = 1
GD.update_icon()
user.visible_message("<span style=\"color:red\">[user] grabs hold of [target] aggressively!</span>")
return
disarm(mob/target, var/mob/living/user)
if (!holder)
return
if (!istype(user) || !ismob(target))
target.attack_hand(user)
return
if (target.melee_attack_test(user, null, null, 1) != 1) // Target.lying check is in there.
return
if (issilicon(target))
special_attack_silicon(target, user)
return
var/send_flying = 0 // 1: a little bit | 2: across the room
var/obj/item/affecting = target.get_affecting(user)
var/datum/attackResults/disarm/msgs = user.calculate_disarm_attack(target, affecting)
if (!msgs || !istype(msgs))
return
if (src.weak == 1) // Werewolves get a guaranteed knockdown.
if (!target.anchored && prob(50))
send_flying = 1
msgs.played_sound = 'sound/weapons/thudswoosh.ogg'
user.werewolf_audio_effects(target, "disarm")
msgs.base_attack_message = "<span style=\"color:red\"><B>[user] [pick("clocks", "strikes", "smashes")] [target] with a [pick("fierce", "fearsome", "supernatural", "wild", "beastly")] punch, forcing them to the ground!</B></span>"
if (prob(35))
msgs.damage_type = DAMAGE_CUT // Nasty claws!
msgs.damage = rand(1,9)
target.weakened += 2
target.stuttering += 1
else
if (prob(25) && ishuman(target))
var/mob/living/carbon/human/HH = target
var/limb_name = "unknown limb"
if (!HH || !ishuman(HH))
..() // Something went very wrong, fall back to default disarm proc.
return
if (HH.l_hand)
HH.sever_limb("l_arm")
limb_name = "left arm"
else if (HH.r_hand)
HH.sever_limb("r_arm")
limb_name = "right arm"
else
var/list/limbs = list("l_arm","r_arm","l_leg","r_leg")
var/the_limb = pick(limbs)
if (!HH.has_limb(the_limb))
return 0
HH.sever_limb(the_limb)
switch (the_limb)
if ("l_arm")
limb_name = "left arm"
if ("r_arm")
limb_name = "right arm"
if ("l_leg")
limb_name = "left leg"
if ("r_leg")
limb_name = "right leg"
if (prob(50) && HH.stat != 2)
HH.emote("scream")
msgs.played_sound = 'sound/effects/bloody_stab.ogg'
msgs.base_attack_message = "<span style=\"color:red\"><B>[user] whips [HH] with the sharp edge of a chitinous tendril, shearing off their [limb_name]!</span>"
msgs.damage_type = DAMAGE_CUT // We just lost a limb.
msgs.damage = rand(1,5)
HH.stunned += 2
else
if (!target.anchored && prob(30))
send_flying = 1
else
target.drop_item() // Shamblers get a guaranteed disarm.
msgs.played_sound = 'sound/weapons/thudswoosh.ogg'
msgs.base_attack_message = "<span style=\"color:red\"><B>[user] shoves [target] with a [pick("powerful", "fearsome", "intimidating", "strong")] tendril[send_flying == 0 ? "" : ", forcing them to the ground"]!</B></span>"
msgs.damage = rand(1,2)
logTheThing("combat", user, target, "diarms %target% with [src.weak == 1 ? "werewolf" : "abomination"] arms at [log_loc(user)].")
if (send_flying == 2)
msgs.after_effects += /proc/wrestler_backfist
else if (send_flying == 1)
msgs.after_effects += /proc/wrestler_knockdown
msgs.flush(SUPPRESS_LOGS)
return
harm(mob/target, var/mob/living/user)
if (!holder)
return
if (!istype(user) || !ismob(target))
target.attack_hand(user)
return
if (target.melee_attack_test(user) != 1)
return
if (issilicon(target))
special_attack_silicon(target, user)
return
var/send_flying = 0 // 1: a little bit | 2: across the room
var/obj/item/affecting = target.get_affecting(user)
var/datum/attackResults/msgs = user.calculate_melee_attack(target, affecting)
if (!msgs || !istype(msgs))
return
if (target.canmove && !target.anchored && !target.lying)
if (prob(50))
if (prob(60))
target.stuttering += 2
send_flying = 1
else
target.stuttering += 3
send_flying = 2
else
target.stuttering += 1
target.stunned += 1
else
target.stunned += 1
target.stuttering += 1
if (src.weak == 1)
if (send_flying == 2)
msgs.base_attack_message = "<span style=\"color:red\"><B>[user] delivers a supernatural punch, sending [target] flying!</b></span>"
else
if (prob(25))
msgs.base_attack_message = "<span style=\"color:red\"><B>[user] mauls [target] viciously[send_flying == 0 ? "" : ", forcing them to the ground"]!</B></span>"
else
msgs.base_attack_message = "<span style=\"color:red\"><B>[user] slashes viciously at [target][send_flying == 0 ? "" : ", forcing them to the ground"]!</B></span>"
target.add_fingerprint(user)
if (prob(33) && target.stat != 2 && !issilicon(target))
target.emote("scream")
msgs.played_sound = 'sound/weapons/thudswoosh.ogg'
user.werewolf_audio_effects(target, "swipe")
msgs.damage = rand(8, 17)
msgs.damage_type = DAMAGE_CUT // Nasty claws!
else
if (send_flying == 2)
msgs.base_attack_message = "<span style=\"color:red\"><B>[user] delivers a savage blow, sending [target] flying!</b></span>"
else
msgs.base_attack_message = "<span style=\"color:red\"><B>[user] punches [target] with a [pick("powerful", "fearsome", "intimidating", "strong")] tendril[send_flying == 0 ? "" : ", forcing them to the ground"]!</B></span>"
msgs.played_sound = 'sound/weapons/punch1.ogg'
msgs.damage = rand(6, 13)
msgs.damage_type = DAMAGE_BLUNT
if (send_flying == 2)
msgs.after_effects += /proc/wrestler_backfist
else if (send_flying == 1)
msgs.after_effects += /proc/wrestler_knockdown
logTheThing("combat", user, target, "punches %target% with [src.weak == 1 ? "werewolf" : "abomination"] arms at [log_loc(user)].")
user.attack_effects(target, affecting)
msgs.flush(SUPPRESS_LOGS)
return
// And why not (Convair880).
/datum/limb/predator
attack_hand(atom/target, var/mob/living/user, var/reach)
if (!holder)
return
if (!istype(user))
target.attack_hand(user)
return
if (isobj(target))
switch (user.smash_through(target, list("door")))
if (0)
target.attack_hand(user)
return
if (1)
return
..()
return
harm(mob/target, var/mob/living/user)
if (!holder)
return
if (!istype(user) || !ismob(target))
target.attack_hand(user)
return
if (ismob(target))
user.melee_attack_normal(target, 5) // Slightly more powerful punches. This is bonus damage, not a multiplier.
return
..()
return | 412 | 0.983612 | 1 | 0.983612 | game-dev | MEDIA | 0.998894 | game-dev | 0.959319 | 1 | 0.959319 |
mastercomfig/tf2-patches-old | 10,741 | src/game/server/basebludgeonweapon.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#include "cbase.h"
#include "basehlcombatweapon.h"
#include "player.h"
#include "gamerules.h"
#include "ammodef.h"
#include "mathlib/mathlib.h"
#include "in_buttons.h"
#include "soundent.h"
#include "animation.h"
#include "ai_condition.h"
#include "basebludgeonweapon.h"
#include "ndebugoverlay.h"
#include "te_effect_dispatch.h"
#include "rumble_shared.h"
#include "gamestats.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
IMPLEMENT_SERVERCLASS_ST( CBaseHLBludgeonWeapon, DT_BaseHLBludgeonWeapon )
END_SEND_TABLE()
#define BLUDGEON_HULL_DIM 16
static const Vector g_bludgeonMins(-BLUDGEON_HULL_DIM,-BLUDGEON_HULL_DIM,-BLUDGEON_HULL_DIM);
static const Vector g_bludgeonMaxs(BLUDGEON_HULL_DIM,BLUDGEON_HULL_DIM,BLUDGEON_HULL_DIM);
//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
CBaseHLBludgeonWeapon::CBaseHLBludgeonWeapon()
{
m_bFiresUnderwater = true;
}
//-----------------------------------------------------------------------------
// Purpose: Spawn the weapon
//-----------------------------------------------------------------------------
void CBaseHLBludgeonWeapon::Spawn( void )
{
m_fMinRange1 = 0;
m_fMinRange2 = 0;
m_fMaxRange1 = 64;
m_fMaxRange2 = 64;
//Call base class first
BaseClass::Spawn();
}
//-----------------------------------------------------------------------------
// Purpose: Precache the weapon
//-----------------------------------------------------------------------------
void CBaseHLBludgeonWeapon::Precache( void )
{
//Call base class first
BaseClass::Precache();
}
int CBaseHLBludgeonWeapon::CapabilitiesGet()
{
return bits_CAP_WEAPON_MELEE_ATTACK1;
}
int CBaseHLBludgeonWeapon::WeaponMeleeAttack1Condition( float flDot, float flDist )
{
if (flDist > 64)
{
return COND_TOO_FAR_TO_ATTACK;
}
else if (flDot < 0.7)
{
return COND_NOT_FACING_ATTACK;
}
return COND_CAN_MELEE_ATTACK1;
}
//------------------------------------------------------------------------------
// Purpose : Update weapon
//------------------------------------------------------------------------------
void CBaseHLBludgeonWeapon::ItemPostFrame( void )
{
CBasePlayer *pOwner = ToBasePlayer( GetOwner() );
if ( pOwner == NULL )
return;
if ( (pOwner->m_nButtons & IN_ATTACK) && (m_flNextPrimaryAttack <= gpGlobals->curtime) )
{
PrimaryAttack();
}
else if ( (pOwner->m_nButtons & IN_ATTACK2) && (m_flNextSecondaryAttack <= gpGlobals->curtime) )
{
SecondaryAttack();
}
else
{
WeaponIdle();
return;
}
}
//------------------------------------------------------------------------------
// Purpose :
// Input :
// Output :
//------------------------------------------------------------------------------
void CBaseHLBludgeonWeapon::PrimaryAttack()
{
Swing( false );
}
//------------------------------------------------------------------------------
// Purpose :
// Input :
// Output :
//------------------------------------------------------------------------------
void CBaseHLBludgeonWeapon::SecondaryAttack()
{
Swing( true );
}
//------------------------------------------------------------------------------
// Purpose: Implement impact function
//------------------------------------------------------------------------------
void CBaseHLBludgeonWeapon::Hit( trace_t &traceHit, Activity nHitActivity, bool bIsSecondary )
{
CBasePlayer *pPlayer = ToBasePlayer( GetOwner() );
//Do view kick
AddViewKick();
//Make sound for the AI
CSoundEnt::InsertSound( SOUND_BULLET_IMPACT, traceHit.endpos, 400, 0.2f, pPlayer );
// This isn't great, but it's something for when the crowbar hits.
pPlayer->RumbleEffect( RUMBLE_AR2, 0, RUMBLE_FLAG_RESTART );
CBaseEntity *pHitEntity = traceHit.m_pEnt;
//Apply damage to a hit target
if ( pHitEntity != NULL )
{
Vector hitDirection;
pPlayer->EyeVectors( &hitDirection, NULL, NULL );
VectorNormalize( hitDirection );
CTakeDamageInfo info( GetOwner(), GetOwner(), GetDamageForActivity( nHitActivity ), DMG_CLUB );
if( pPlayer && pHitEntity->IsNPC() )
{
// If bonking an NPC, adjust damage.
info.AdjustPlayerDamageInflictedForSkillLevel();
}
CalculateMeleeDamageForce( &info, hitDirection, traceHit.endpos );
pHitEntity->DispatchTraceAttack( info, hitDirection, &traceHit );
ApplyMultiDamage();
// Now hit all triggers along the ray that...
TraceAttackToTriggers( info, traceHit.startpos, traceHit.endpos, hitDirection );
if ( ToBaseCombatCharacter( pHitEntity ) )
{
gamestats->Event_WeaponHit( pPlayer, !bIsSecondary, GetClassname(), info );
}
}
// Apply an impact effect
ImpactEffect( traceHit );
}
Activity CBaseHLBludgeonWeapon::ChooseIntersectionPointAndActivity( trace_t &hitTrace, const Vector &mins, const Vector &maxs, CBasePlayer *pOwner )
{
int i, j, k;
float distance;
const float *minmaxs[2] = {mins.Base(), maxs.Base()};
trace_t tmpTrace;
Vector vecHullEnd = hitTrace.endpos;
Vector vecEnd;
distance = 1e6f;
Vector vecSrc = hitTrace.startpos;
vecHullEnd = vecSrc + ((vecHullEnd - vecSrc)*2);
UTIL_TraceLine( vecSrc, vecHullEnd, MASK_SHOT_HULL, pOwner, COLLISION_GROUP_NONE, &tmpTrace );
if ( tmpTrace.fraction == 1.0 )
{
for ( i = 0; i < 2; i++ )
{
for ( j = 0; j < 2; j++ )
{
for ( k = 0; k < 2; k++ )
{
vecEnd.x = vecHullEnd.x + minmaxs[i][0];
vecEnd.y = vecHullEnd.y + minmaxs[j][1];
vecEnd.z = vecHullEnd.z + minmaxs[k][2];
UTIL_TraceLine( vecSrc, vecEnd, MASK_SHOT_HULL, pOwner, COLLISION_GROUP_NONE, &tmpTrace );
if ( tmpTrace.fraction < 1.0 )
{
float thisDistance = (tmpTrace.endpos - vecSrc).Length();
if ( thisDistance < distance )
{
hitTrace = tmpTrace;
distance = thisDistance;
}
}
}
}
}
}
else
{
hitTrace = tmpTrace;
}
return ACT_VM_HITCENTER;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &traceHit -
//-----------------------------------------------------------------------------
bool CBaseHLBludgeonWeapon::ImpactWater( const Vector &start, const Vector &end )
{
//FIXME: This doesn't handle the case of trying to splash while being underwater, but that's not going to look good
// right now anyway...
// We must start outside the water
if ( UTIL_PointContents( start ) & (CONTENTS_WATER|CONTENTS_SLIME))
return false;
// We must end inside of water
if ( !(UTIL_PointContents( end ) & (CONTENTS_WATER|CONTENTS_SLIME)))
return false;
trace_t waterTrace;
UTIL_TraceLine( start, end, (CONTENTS_WATER|CONTENTS_SLIME), GetOwner(), COLLISION_GROUP_NONE, &waterTrace );
if ( waterTrace.fraction < 1.0f )
{
CEffectData data;
data.m_fFlags = 0;
data.m_vOrigin = waterTrace.endpos;
data.m_vNormal = waterTrace.plane.normal;
data.m_flScale = 8.0f;
// See if we hit slime
if ( waterTrace.contents & CONTENTS_SLIME )
{
data.m_fFlags |= FX_WATER_IN_SLIME;
}
DispatchEffect( "watersplash", data );
}
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBaseHLBludgeonWeapon::ImpactEffect( trace_t &traceHit )
{
// See if we hit water (we don't do the other impact effects in this case)
if ( ImpactWater( traceHit.startpos, traceHit.endpos ) )
return;
//FIXME: need new decals
UTIL_ImpactTrace( &traceHit, DMG_CLUB );
}
//------------------------------------------------------------------------------
// Purpose : Starts the swing of the weapon and determines the animation
// Input : bIsSecondary - is this a secondary attack?
//------------------------------------------------------------------------------
void CBaseHLBludgeonWeapon::Swing( int bIsSecondary )
{
trace_t traceHit;
// Try a ray
CBasePlayer *pOwner = ToBasePlayer( GetOwner() );
if ( !pOwner )
return;
pOwner->RumbleEffect( RUMBLE_CROWBAR_SWING, 0, RUMBLE_FLAG_RESTART );
Vector swingStart = pOwner->Weapon_ShootPosition( );
Vector forward;
forward = pOwner->GetAutoaimVector( AUTOAIM_SCALE_DEFAULT, GetRange() );
Vector swingEnd = swingStart + forward * GetRange();
UTIL_TraceLine( swingStart, swingEnd, MASK_SHOT_HULL, pOwner, COLLISION_GROUP_NONE, &traceHit );
Activity nHitActivity = ACT_VM_HITCENTER;
// Like bullets, bludgeon traces have to trace against triggers.
CTakeDamageInfo triggerInfo( GetOwner(), GetOwner(), GetDamageForActivity( nHitActivity ), DMG_CLUB );
triggerInfo.SetDamagePosition( traceHit.startpos );
triggerInfo.SetDamageForce( forward );
TraceAttackToTriggers( triggerInfo, traceHit.startpos, traceHit.endpos, forward );
if ( traceHit.fraction == 1.0 )
{
float bludgeonHullRadius = 1.732f * BLUDGEON_HULL_DIM; // hull is +/- 16, so use cuberoot of 2 to determine how big the hull is from center to the corner point
// Back off by hull "radius"
swingEnd -= forward * bludgeonHullRadius;
UTIL_TraceHull( swingStart, swingEnd, g_bludgeonMins, g_bludgeonMaxs, MASK_SHOT_HULL, pOwner, COLLISION_GROUP_NONE, &traceHit );
if ( traceHit.fraction < 1.0 && traceHit.m_pEnt )
{
Vector vecToTarget = traceHit.m_pEnt->GetAbsOrigin() - swingStart;
VectorNormalize( vecToTarget );
float dot = vecToTarget.Dot( forward );
// YWB: Make sure they are sort of facing the guy at least...
if ( dot < 0.70721f )
{
// Force amiss
traceHit.fraction = 1.0f;
}
else
{
nHitActivity = ChooseIntersectionPointAndActivity( traceHit, g_bludgeonMins, g_bludgeonMaxs, pOwner );
}
}
}
if ( !bIsSecondary )
{
m_iPrimaryAttacks++;
}
else
{
m_iSecondaryAttacks++;
}
gamestats->Event_WeaponFired( pOwner, !bIsSecondary, GetClassname() );
// -------------------------
// Miss
// -------------------------
if ( traceHit.fraction == 1.0f )
{
nHitActivity = bIsSecondary ? ACT_VM_MISSCENTER2 : ACT_VM_MISSCENTER;
// We want to test the first swing again
Vector testEnd = swingStart + forward * GetRange();
// See if we happened to hit water
ImpactWater( swingStart, testEnd );
}
else
{
Hit( traceHit, nHitActivity, bIsSecondary ? true : false );
}
// Send the anim
SendWeaponAnim( nHitActivity );
//Setup our next attack times
m_flNextPrimaryAttack = gpGlobals->curtime + GetFireRate();
m_flNextSecondaryAttack = gpGlobals->curtime + SequenceDuration();
//Play swing sound
WeaponSound( SINGLE );
}
| 412 | 0.96628 | 1 | 0.96628 | game-dev | MEDIA | 0.995036 | game-dev | 0.984565 | 1 | 0.984565 |
shawwn/noh | 3,756 | src/sav_shared/c_propbasebuilding.cpp | // (C)2006 S2 Games
// c_propbasebuilding.cpp
//
//=============================================================================
//=============================================================================
// Headers
//=============================================================================
#include "game_shared_common.h"
#include "c_propbasebuilding.h"
#include "c_teaminfo.h"
#include "c_teamdefinition.h"
#include "../k2/c_worldentity.h"
//=============================================================================
//=============================================================================
// Definitions
//=============================================================================
DEFINE_ENT_ALLOCATOR2(Prop, BaseBuilding);
//=============================================================================
/*====================
CPropBaseBuilding::CPropBaseBuilding
====================*/
CPropBaseBuilding::CPropBaseBuilding() :
IPropEntity(GetEntityConfig()),
m_uiBaseUID(INVALID_INDEX)
{
}
/*====================
CPropBaseBuilding::GameStart
====================*/
void CPropBaseBuilding::GameStart()
{
// Client will receive the proper entity from the server
if (Game.IsClient())
return;
// Get the info for the team that this belongs to
CEntityTeamInfo *pTeam(Game.GetTeam(m_iTeam));
if (pTeam == NULL)
{
Console.Warn << _T("CPropBaseBuilding::Spawn() - Team does not exist: ") << int(m_iTeam) << newl;
return;
}
// Create a new building of the appropriate type
tstring sBuildingName(pTeam->GetDefinition()->GetBaseBuildingName());
IGameEntity *pNewEnt(Game.AllocateEntity(sBuildingName));
if (pNewEnt == NULL)
{
Console.Warn << _T("CPropBaseBuilding::Spawn() - Failed to allocate entity: ") << sBuildingName << newl;
return;
}
if (pNewEnt->IsVisual())
{
IVisualEntity *pVisEnt(pNewEnt->GetAsVisualEnt());
pVisEnt->SetPosition(GetPosition());
pVisEnt->SetAngles(GetAngles());
pVisEnt->SetTeam(GetTeam());
}
pNewEnt->Spawn();
Console << _T("Adding BaseBuilding #") << m_uiWorldIndex << _T(" as entity #") << m_uiIndex << _T(" to team ") << int(m_iTeam) << newl;
pTeam->SetBaseBuildingIndex(pNewEnt->GetIndex());
m_uiBaseUID = pNewEnt->GetUniqueID();
}
/*====================
CPropBaseBuilding::WarmupStart
====================*/
void CPropBaseBuilding::WarmupStart()
{
// Client will receive the proper entity from the server
if (Game.IsClient())
return;
// Get the info for the team that this belongs to
CEntityTeamInfo *pTeam(Game.GetTeam(m_iTeam));
if (pTeam == NULL)
{
Console.Warn << _T("CPropBaseBuilding::Spawn() - Team does not exist: ") << int(m_iTeam) << newl;
return;
}
// Create a new building of the appropriate type
tstring sBuildingName(pTeam->GetDefinition()->GetBaseBuildingName());
IGameEntity *pNewEnt(Game.AllocateEntity(sBuildingName));
if (pNewEnt == NULL)
{
Console.Warn << _T("CPropBaseBuilding::Spawn() - Failed to allocate entity: ") << sBuildingName << newl;
return;
}
if (pNewEnt->IsVisual())
{
IVisualEntity *pVisEnt(pNewEnt->GetAsVisualEnt());
pVisEnt->SetPosition(GetPosition());
pVisEnt->SetAngles(GetAngles());
pVisEnt->SetTeam(GetTeam());
pVisEnt->SetInvulnerable(true);
}
pNewEnt->Spawn();
Console << _T("Adding BaseBuilding #") << m_uiWorldIndex << _T(" as entity #") << m_uiIndex << _T(" to team ") << int(m_iTeam) << newl;
pTeam->SetBaseBuildingIndex(pNewEnt->GetIndex());
m_uiBaseUID = pNewEnt->GetUniqueID();
}
| 412 | 0.948322 | 1 | 0.948322 | game-dev | MEDIA | 0.939347 | game-dev | 0.579803 | 1 | 0.579803 |
bobbens/clothes_parsing | 3,580 | lib/+bsr/src/gpb_src/include/functors/keyable_functors.hh | /*
* Keyable functors.
*/
#ifndef FUNCTORS__KEYABLE_FUNCTORS_HH
#define FUNCTORS__KEYABLE_FUNCTORS_HH
#include "collections/abstract/collection.hh"
#include "interfaces/keyable.hh"
namespace functors {
/*
* Imports.
*/
using collections::abstract::collection;
using interfaces::keyable;
/*
* Abstract functor for compare operations.
* Note that the functor is the same regardless of the type const qualifier.
*/
template <typename T, typename K>
class keyable_compare_functor {
public:
virtual ~keyable_compare_functor() { }
virtual int operator()(const T&, const K&) const = 0;
};
template <typename T, typename K>
class keyable_compare_functor<const T,K>
: public keyable_compare_functor<T,K> { };
template <typename T, typename K>
class keyable_compare_functor<T,const K>
: public keyable_compare_functor<T,K> { };
template <typename T, typename K>
class keyable_compare_functor<const T,const K>
: public keyable_compare_functor<T,K> { };
/*
* Abstract functor for split operations.
*/
template <typename T, typename K>
class keyable_split_functor {
public:
virtual ~keyable_split_functor() { }
virtual K operator()(const collection<T>&) const = 0;
};
/*
* Functor for comparison of a keyable object to a key.
* Call the underlying compare function.
*/
template <typename T, typename K>
class key_compare_functor : public keyable_compare_functor<const T,K> {
public:
int operator()(const T& t, const K& k) const {
return keyable<T,K>::compare(t, k);
}
};
template <typename T, typename K>
class key_compare_functor<const T,K> : public key_compare_functor<T,K> { };
/*
* Functor that reverses normal key comparison order
*/
template <typename T, typename K>
class key_compare_functor_reverse : public keyable_compare_functor<const T,K> {
public:
key_compare_functor_reverse() : _f() { }
int operator()(const T& t, const K& k) const {
return (-(_f(t, k)));
}
private:
const key_compare_functor<T,K> _f;
};
template <typename T, typename K>
class key_compare_functor_reverse<const T,K>
: public key_compare_functor_reverse<T,K> { };
/*
* Functor for splitting of collections of keyable objects.
* Call the underlying split function.
*/
template <typename T, typename K>
class key_split_functor : public keyable_split_functor<T,K> {
public:
K operator()(const collection<T>& c) const {
return keyable<T,K>::key_split(c);
}
};
/*
* Globally accessible set of default key comparison functors.
*/
template <typename T, typename K>
class key_compare_functors {
public:
static const key_compare_functor<T,K>& f_key_compare();
static const key_compare_functor_reverse<T,K>& f_key_compare_reverse();
};
template <typename T, typename K>
const key_compare_functor<T,K>& key_compare_functors<T,K>::f_key_compare() {
static const key_compare_functor<T,K>* f
= new key_compare_functor<T,K>();
return *f;
}
template <typename T, typename K>
const key_compare_functor_reverse<T,K>& key_compare_functors<T,K>::f_key_compare_reverse() {
static const key_compare_functor_reverse<T,K>* f
= new key_compare_functor_reverse<T,K>();
return *f;
}
/*
* Globally accessible set of default key split functors.
*/
template <typename T, typename K>
class key_split_functors {
public:
static const key_split_functor<T,K>& f_key_split();
};
template <typename T, typename K>
const key_split_functor<T,K>& key_split_functors<T,K>::f_key_split() {
static const key_split_functor<T,K>* f = new key_split_functor<T,K>();
return *f;
}
} /* namespace functors */
#endif
| 412 | 0.695459 | 1 | 0.695459 | game-dev | MEDIA | 0.419014 | game-dev | 0.71659 | 1 | 0.71659 |
magicskysword/Next | 8,903 | Next/Scr/Xlua/Gen/FairyGUI_PixelHitTestWrap.cs | #if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
using XLua;
using System.Collections.Generic;
namespace XLua.CSObjectWrap
{
using Utils = XLua.Utils;
public class FairyGUIPixelHitTestWrap
{
public static void __Register(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
System.Type type = typeof(FairyGUI.PixelHitTest);
Utils.BeginObjectRegister(type, L, translator, 0, 1, 4, 4);
Utils.RegisterFunc(L, Utils.METHOD_IDX, "HitTest", _m_HitTest);
Utils.RegisterFunc(L, Utils.GETTER_IDX, "offsetX", _g_get_offsetX);
Utils.RegisterFunc(L, Utils.GETTER_IDX, "offsetY", _g_get_offsetY);
Utils.RegisterFunc(L, Utils.GETTER_IDX, "sourceWidth", _g_get_sourceWidth);
Utils.RegisterFunc(L, Utils.GETTER_IDX, "sourceHeight", _g_get_sourceHeight);
Utils.RegisterFunc(L, Utils.SETTER_IDX, "offsetX", _s_set_offsetX);
Utils.RegisterFunc(L, Utils.SETTER_IDX, "offsetY", _s_set_offsetY);
Utils.RegisterFunc(L, Utils.SETTER_IDX, "sourceWidth", _s_set_sourceWidth);
Utils.RegisterFunc(L, Utils.SETTER_IDX, "sourceHeight", _s_set_sourceHeight);
Utils.EndObjectRegister(type, L, translator, null, null,
null, null, null);
Utils.BeginClassRegister(type, L, __CreateInstance, 1, 0, 0);
Utils.EndClassRegister(type, L, translator);
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int __CreateInstance(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
if(LuaAPI.lua_gettop(L) == 6 && translator.Assignable<FairyGUI.PixelHitTestData>(L, 2) && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 3) && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 4) && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 5) && LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 6))
{
FairyGUI.PixelHitTestData _data = (FairyGUI.PixelHitTestData)translator.GetObject(L, 2, typeof(FairyGUI.PixelHitTestData));
int _offsetX = LuaAPI.xlua_tointeger(L, 3);
int _offsetY = LuaAPI.xlua_tointeger(L, 4);
float _sourceWidth = (float)LuaAPI.lua_tonumber(L, 5);
float _sourceHeight = (float)LuaAPI.lua_tonumber(L, 6);
var gen_ret = new FairyGUI.PixelHitTest(_data, _offsetX, _offsetY, _sourceWidth, _sourceHeight);
translator.Push(L, gen_ret);
return 1;
}
}
catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return LuaAPI.luaL_error(L, "invalid arguments to FairyGUI.PixelHitTest constructor!");
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _m_HitTest(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
FairyGUI.PixelHitTest gen_to_be_invoked = (FairyGUI.PixelHitTest)translator.FastGetCSObj(L, 1);
{
UnityEngine.Rect _contentRect;translator.Get(L, 2, out _contentRect);
UnityEngine.Vector2 _localPoint;translator.Get(L, 3, out _localPoint);
var gen_ret = gen_to_be_invoked.HitTest( _contentRect, _localPoint );
LuaAPI.lua_pushboolean(L, gen_ret);
return 1;
}
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _g_get_offsetX(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
FairyGUI.PixelHitTest gen_to_be_invoked = (FairyGUI.PixelHitTest)translator.FastGetCSObj(L, 1);
LuaAPI.xlua_pushinteger(L, gen_to_be_invoked.offsetX);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _g_get_offsetY(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
FairyGUI.PixelHitTest gen_to_be_invoked = (FairyGUI.PixelHitTest)translator.FastGetCSObj(L, 1);
LuaAPI.xlua_pushinteger(L, gen_to_be_invoked.offsetY);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _g_get_sourceWidth(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
FairyGUI.PixelHitTest gen_to_be_invoked = (FairyGUI.PixelHitTest)translator.FastGetCSObj(L, 1);
LuaAPI.lua_pushnumber(L, gen_to_be_invoked.sourceWidth);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _g_get_sourceHeight(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
FairyGUI.PixelHitTest gen_to_be_invoked = (FairyGUI.PixelHitTest)translator.FastGetCSObj(L, 1);
LuaAPI.lua_pushnumber(L, gen_to_be_invoked.sourceHeight);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _s_set_offsetX(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
FairyGUI.PixelHitTest gen_to_be_invoked = (FairyGUI.PixelHitTest)translator.FastGetCSObj(L, 1);
gen_to_be_invoked.offsetX = LuaAPI.xlua_tointeger(L, 2);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _s_set_offsetY(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
FairyGUI.PixelHitTest gen_to_be_invoked = (FairyGUI.PixelHitTest)translator.FastGetCSObj(L, 1);
gen_to_be_invoked.offsetY = LuaAPI.xlua_tointeger(L, 2);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _s_set_sourceWidth(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
FairyGUI.PixelHitTest gen_to_be_invoked = (FairyGUI.PixelHitTest)translator.FastGetCSObj(L, 1);
gen_to_be_invoked.sourceWidth = (float)LuaAPI.lua_tonumber(L, 2);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _s_set_sourceHeight(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
FairyGUI.PixelHitTest gen_to_be_invoked = (FairyGUI.PixelHitTest)translator.FastGetCSObj(L, 1);
gen_to_be_invoked.sourceHeight = (float)LuaAPI.lua_tonumber(L, 2);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 0;
}
}
}
| 412 | 0.788735 | 1 | 0.788735 | game-dev | MEDIA | 0.782551 | game-dev | 0.589139 | 1 | 0.589139 |
utilForever/RosettaStone | 1,885 | Sources/Rosetta/PlayMode/Tasks/SimpleTasks/NumberConditionTask.cpp | // This code is based on Sabberstone project.
// Copyright (c) 2017-2021 SabberStone Team, darkfriend77 & rnilva
// RosettaStone is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2017-2024 Chris Ohk
#include <Rosetta/PlayMode/Games/Game.hpp>
#include <Rosetta/PlayMode/Tasks/SimpleTasks/NumberConditionTask.hpp>
#include <limits>
namespace RosettaStone::PlayMode::SimpleTasks
{
NumberConditionTask::NumberConditionTask(int referenceValue, RelaSign relaSign)
: m_referenceValue(referenceValue), m_relaSign(relaSign)
{
// Do nothing
}
NumberConditionTask::NumberConditionTask(RelaSign relaSign)
: m_referenceValue(std::numeric_limits<int>::min()), m_relaSign(relaSign)
{
// Do nothing
}
TaskStatus NumberConditionTask::Impl(Player* player)
{
auto& taskStack = player->game->taskStack;
if (m_referenceValue == std::numeric_limits<int>::min())
{
if (m_relaSign == RelaSign::GEQ)
{
taskStack.flag = taskStack.num[0] >= taskStack.num[1];
}
else if (m_relaSign == RelaSign::LEQ)
{
taskStack.flag = taskStack.num[0] <= taskStack.num[1];
}
else
{
taskStack.flag = taskStack.num[0] == taskStack.num[1];
}
}
else
{
if (m_relaSign == RelaSign::GEQ)
{
taskStack.flag = taskStack.num[0] >= m_referenceValue;
}
else if (m_relaSign == RelaSign::LEQ)
{
taskStack.flag = taskStack.num[0] <= m_referenceValue;
}
else
{
taskStack.flag = taskStack.num[0] == m_referenceValue;
}
}
return TaskStatus::COMPLETE;
}
std::unique_ptr<ITask> NumberConditionTask::CloneImpl()
{
return std::make_unique<NumberConditionTask>(m_referenceValue, m_relaSign);
}
} // namespace RosettaStone::PlayMode::SimpleTasks
| 412 | 0.772674 | 1 | 0.772674 | game-dev | MEDIA | 0.919666 | game-dev | 0.881809 | 1 | 0.881809 |
josh-m/RW-Decompile | 4,179 | Verse/GenRecipe.cs | using RimWorld;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using UnityEngine;
namespace Verse
{
public static class GenRecipe
{
[DebuggerHidden]
public static IEnumerable<Thing> MakeRecipeProducts(RecipeDef recipeDef, Pawn worker, List<Thing> ingredients, Thing dominantIngredient, IBillGiver billGiver)
{
float efficiency;
if (recipeDef.efficiencyStat == null)
{
efficiency = 1f;
}
else
{
efficiency = worker.GetStatValue(recipeDef.efficiencyStat, true);
}
if (recipeDef.workTableEfficiencyStat != null)
{
Building_WorkTable building_WorkTable = billGiver as Building_WorkTable;
if (building_WorkTable != null)
{
efficiency *= building_WorkTable.GetStatValue(recipeDef.workTableEfficiencyStat, true);
}
}
if (recipeDef.products != null)
{
for (int i = 0; i < recipeDef.products.Count; i++)
{
ThingDefCountClass prod = recipeDef.products[i];
ThingDef stuffDef;
if (prod.thingDef.MadeFromStuff)
{
stuffDef = dominantIngredient.def;
}
else
{
stuffDef = null;
}
Thing product = ThingMaker.MakeThing(prod.thingDef, stuffDef);
product.stackCount = Mathf.CeilToInt((float)prod.count * efficiency);
if (dominantIngredient != null)
{
product.SetColor(dominantIngredient.DrawColor, false);
}
CompIngredients ingredientsComp = product.TryGetComp<CompIngredients>();
if (ingredientsComp != null)
{
for (int l = 0; l < ingredients.Count; l++)
{
ingredientsComp.RegisterIngredient(ingredients[l].def);
}
}
CompFoodPoisonable foodPoisonable = product.TryGetComp<CompFoodPoisonable>();
if (foodPoisonable != null)
{
Room room = worker.GetRoom(RegionType.Set_Passable);
float chance = (room == null) ? RoomStatDefOf.FoodPoisonChance.roomlessScore : room.GetStat(RoomStatDefOf.FoodPoisonChance);
if (Rand.Chance(chance))
{
foodPoisonable.SetPoisoned(FoodPoisonCause.FilthyKitchen);
}
else
{
float statValue = worker.GetStatValue(StatDefOf.FoodPoisonChance, true);
if (Rand.Chance(statValue))
{
foodPoisonable.SetPoisoned(FoodPoisonCause.IncompetentCook);
}
}
}
yield return GenRecipe.PostProcessProduct(product, recipeDef, worker);
}
}
if (recipeDef.specialProducts != null)
{
for (int j = 0; j < recipeDef.specialProducts.Count; j++)
{
for (int k = 0; k < ingredients.Count; k++)
{
Thing ing = ingredients[k];
SpecialProductType specialProductType = recipeDef.specialProducts[j];
if (specialProductType != SpecialProductType.Butchery)
{
if (specialProductType == SpecialProductType.Smelted)
{
foreach (Thing product2 in ing.SmeltProducts(efficiency))
{
yield return GenRecipe.PostProcessProduct(product2, recipeDef, worker);
}
}
}
else
{
foreach (Thing product3 in ing.ButcherProducts(worker, efficiency))
{
yield return GenRecipe.PostProcessProduct(product3, recipeDef, worker);
}
}
}
}
}
}
private static Thing PostProcessProduct(Thing product, RecipeDef recipeDef, Pawn worker)
{
CompQuality compQuality = product.TryGetComp<CompQuality>();
if (compQuality != null)
{
if (recipeDef.workSkill == null)
{
Log.Error(recipeDef + " needs workSkill because it creates a product with a quality.", false);
}
QualityCategory q = QualityUtility.GenerateQualityCreatedByPawn(worker, recipeDef.workSkill);
compQuality.SetQuality(q, ArtGenerationContext.Colony);
QualityUtility.SendCraftNotification(product, worker);
}
CompArt compArt = product.TryGetComp<CompArt>();
if (compArt != null)
{
compArt.JustCreatedBy(worker);
if (compQuality.Quality >= QualityCategory.Excellent)
{
TaleRecorder.RecordTale(TaleDefOf.CraftedArt, new object[]
{
worker,
product
});
}
}
if (product.def.Minifiable)
{
product = product.MakeMinified();
}
return product;
}
}
}
| 412 | 0.737125 | 1 | 0.737125 | game-dev | MEDIA | 0.739712 | game-dev | 0.761035 | 1 | 0.761035 |
magarena/magarena | 1,107 | release/Magarena/scripts/Paradigm_Shift.groovy | [
new MagicSpellCardEvent() {
@Override
public MagicEvent getEvent(final MagicCardOnStack cardOnStack,final MagicPayedCost payedCost) {
return new MagicEvent(
cardOnStack,
this,
"PN exiles all cards from his or her library, then shuffles his or her graveyard into his or her library."
);
}
@Override
public void executeEvent(final MagicGame game, final MagicEvent event) {
final MagicPlayer player = event.getPlayer();
final MagicCardList graveyard = new MagicCardList(player.getGraveyard());
final MagicCardList library = new MagicCardList(player.getLibrary());
for (final MagicCard cardLibrary : library) {
game.doAction(new ShiftCardAction(
cardLibrary,
MagicLocationType.OwnersLibrary,
MagicLocationType.Exile
));
}
game.doAction(new ShuffleCardsIntoLibraryAction(graveyard, MagicLocationType.Graveyard))
}
}
]
| 412 | 0.647655 | 1 | 0.647655 | game-dev | MEDIA | 0.871221 | game-dev | 0.619984 | 1 | 0.619984 |
Roblox/avatar | 1,905 | InGameAvatarEditor/src/ServerScriptService/AvatarEditorInGameSetup/AvatarEditorInGame/Modules/Common/Action.lua | --[[
A helper function to define a Rodux action creator with an associated name.
Normally when creating a Rodux action, you can just create a function:
return function(value)
return {
type = "MyAction",
value = value,
}
end
And then when you check for it in your reducer, you either use a constant,
or type out the string name:
if action.type == "MyAction" then
-- change some state
end
Typos here are a remarkably common bug. We also have the issue that there's
no link between reducers and the actions that they respond to!
`Action` (this helper) provides a utility that makes this a bit cleaner.
Instead, define your Rodux action like this:
return Action("MyAction", function(value)
return {
value = value,
}
end)
We no longer need to add the `type` field manually.
Additionally, the returned action creator now has a 'name' property that can
be checked by your reducer:
local MyAction = require(Reducers.MyAction)
...
if action.type == MyAction.name then
-- change some state!
end
Now we have a clear link between our reducers and the actions they use, and
if we ever typo a name, we'll get a warning in LuaCheck as well as an error
at runtime!
]]
return function(name, fn)
assert(type(name) == "string", "A name must be provided to create an Action")
assert(type(fn) == "function", "A function must be provided to create an Action")
return setmetatable({
name = name,
}, {
__call = function(self, ...)
local result = fn(...)
assert(type(result) == "table", "An action must return a table")
result.type = name
return result
end
})
end | 412 | 0.740725 | 1 | 0.740725 | game-dev | MEDIA | 0.440305 | game-dev | 0.9218 | 1 | 0.9218 |
SelfishKrus/K_URP_ToonShading | 54,614 | Assets/Adobe/Substance3DForUnity/Editor/Scripts/SubstanceGraphSOEditor.cs | using Adobe.Substance;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEditor.Graphs;
using UnityEditor.SceneManagement;
using UnityEngine;
namespace Adobe.SubstanceEditor
{
[CustomEditor(typeof(SubstanceGraphSO))]
public class SubstanceGraphSOEditor : UnityEditor.Editor
{
private GraphInputsGroupingHelper _inputGroupingHelper;
private GraphOutputAlphaChannelsHelper _outputChannelsHelper;
private bool _propertiesChanged = false;
private bool _showOutput = true;
private bool _showExportPresentationHandler = false;
private bool _showPhysicalSize = false;
private SubstanceGraphSO _target = null;
private SubstanceNativeGraph _nativeGraph = null;
private Rect lastRect;
private Texture2D _backgroundImage;
private MaterialEditor _materialPreviewEditor;
private Vector2 _textureOutputScrollView;
private SerializedProperty _generateAllOutputsProperty;
private SerializedProperty _generateAllMipmapsProperty;
private SerializedProperty _runtimeOnlyProperty;
private SerializedProperty _outputRemapedProperty;
private SerializedProperty _graphOutputs;
private SerializedProperty _presetProperty;
private SerializedProperty _physicalSizelProperty;
private SerializedProperty _hasPhysicalSizeProperty;
private SerializedProperty _enablePhysicalSizeProperty;
private IReadOnlyList<SerializedProperty> _outputProperties;
private SerializedProperty _presetsListProperty;
public void OnEnable()
{
if (!IsSerializedObjectReady())
return;
_target = serializedObject.targetObject as SubstanceGraphSO;
_textureOutputScrollView = Vector2.zero;
_propertiesChanged = false;
if (_inputGroupingHelper == null)
_inputGroupingHelper = new GraphInputsGroupingHelper(_target, serializedObject);
if (_outputChannelsHelper == null)
_outputChannelsHelper = new GraphOutputAlphaChannelsHelper(_target);
float c = (EditorGUIUtility.isProSkin) ? 0.35f : 0.65f;
if (_backgroundImage == null)
_backgroundImage = Globals.CreateColoredTexture(16, 16, new Color(c, c, c, 1));
EditorApplication.projectWindowItemOnGUI += OnHierarchyWindowItemOnGUI;
_generateAllOutputsProperty = serializedObject.FindProperty("GenerateAllOutputs");
_generateAllMipmapsProperty = serializedObject.FindProperty("GenerateAllMipmaps");
_runtimeOnlyProperty = serializedObject.FindProperty("IsRuntimeOnly");
_outputRemapedProperty = serializedObject.FindProperty("OutputRemaped");
_graphOutputs = serializedObject.FindProperty("Output");
_presetProperty = serializedObject.FindProperty("CurrentStatePreset");
_physicalSizelProperty = serializedObject.FindProperty("PhysicalSize");
_hasPhysicalSizeProperty = serializedObject.FindProperty("HasPhysicalSize");
_enablePhysicalSizeProperty = serializedObject.FindProperty("EnablePhysicalSize");
_presetsListProperty = serializedObject.FindProperty("Presets");
if (!SubstanceEditorEngine.instance.TryGetHandlerFromInstance(_target, out _nativeGraph))
{
if (!SubstanceEditorEngine.instance.IsInitialized)
return;
SubstanceEditorEngine.instance.InitializeInstance(_target, null, out SubstanceGraphSO _);
if (SubstanceEditorEngine.instance.TryGetHandlerFromInstance(_target, out _nativeGraph))
_target.RuntimeInitialize(_nativeGraph, _target.IsRuntimeOnly);
}
PopulateOutputProperties();
}
private void PopulateOutputProperties()
{
var list = new List<SerializedProperty>();
for (int i = 0; i < _graphOutputs.arraySize; i++)
{
var output = _graphOutputs.GetArrayElementAtIndex(i);
var textureTarget = output.FindPropertyRelative("MaterialTextureTarget");
list.Add(textureTarget);
}
_outputProperties = list;
}
private void GetShaderInputTextures(Shader shader)
{
_shaderInputTextures.Add("none");
EditorTools.GetShaderProperties(shader, _shaderInputTextures);
}
public void OnDisable()
{
if (_materialPreviewEditor != null)
{
_materialPreviewEditor.OnDisable();
_materialPreviewEditor = null;
}
SaveEditorChanges();
EditorApplication.projectWindowItemOnGUI -= OnHierarchyWindowItemOnGUI;
}
public void SaveEditorChanges()
{
if (_propertiesChanged)
{
SaveTGAFiles();
UpdateGraphMaterialLabel();
AssetDatabase.Refresh();
}
_propertiesChanged = false;
}
public override void OnInspectorGUI()
{
if (serializedObject.targetObject == null)
{
return;
}
if (_nativeGraph == null)
{
if (!SubstanceEditorEngine.instance.TryGetHandlerFromInstance(_target, out _nativeGraph))
{
return;
}
if (_nativeGraph.IsDisposed())
{
_nativeGraph = null;
return;
}
}
if (_materialPreviewEditor == null)
{
var material = _target.OutputMaterial;
if (material != null)
_materialPreviewEditor = MaterialEditor.CreateEditor(material) as MaterialEditor;
}
serializedObject.Update();
try
{
if (FirstConfigurePresets() || DrawGraph())
{
serializedObject.ApplyModifiedProperties();
_propertiesChanged = true;
}
}
catch (ObjectDisposedException)
{
}
}
/// <summary>
/// Callback for GUI events to block substance files from been duplicated
/// </summary>
/// <param name="guid">Asset guid.</param>
/// <param name="rt">GUI rect.</param>
protected static void OnHierarchyWindowItemOnGUI(string guid, Rect rt)
{
var currentEvent = Event.current;
if ("Duplicate" == currentEvent.commandName && currentEvent.type == EventType.ExecuteCommand)
{
var assetPath = AssetDatabase.GUIDToAssetPath(guid);
var instanceObject = AssetDatabase.LoadAssetAtPath<SubstanceGraphSO>(assetPath);
if (instanceObject != null)
{
Debug.LogWarning("Substance graph can not be manually duplicated.");
currentEvent.Use();
}
}
}
#region Material Preview
public override bool HasPreviewGUI()
{
return _materialPreviewEditor != null;
}
public override GUIContent GetPreviewTitle()
{
return new GUIContent("Material", null, "");
}
public override void OnPreviewSettings()
{
if (_materialPreviewEditor)
_materialPreviewEditor.OnPreviewSettings();
}
public override void OnPreviewGUI(Rect r, GUIStyle background)
{
if (_materialPreviewEditor)
_materialPreviewEditor.OnPreviewGUI(r, background);
}
#endregion Material Preview
#region Draw
private bool DrawGraph()
{
bool valuesChanged = false;
if (DrawTextureGenerationSettings(_generateAllOutputsProperty, _generateAllMipmapsProperty, _runtimeOnlyProperty))
{
_outputRemapedProperty.boolValue = true;
valuesChanged = true;
}
GUILayout.Space(16);
if (DrawPresentExport(_target))
valuesChanged = true;
DrawInputs(out bool serializedObject, out bool renderGraph);
if (renderGraph)
{
var newPreset = _nativeGraph.CreatePresetFromCurrentState();
_presetProperty.stringValue = newPreset;
SubstanceEditorEngine.instance.SubmitAsyncRenderWork(_nativeGraph, _target);
valuesChanged = true;
}
if (serializedObject)
valuesChanged = true;
EditorGUILayout.Space();
_showOutput = EditorGUILayout.Foldout(_showOutput, "Generated textures");
if (_showOutput)
{
if (DrawAdvanceSettings())
{
MaterialUtils.EnableEmissionIfAssigned(_target.OutputMaterial);
_outputRemapedProperty.boolValue = true;
valuesChanged = true;
}
if (DrawGeneratedTextures(_graphOutputs, _generateAllOutputsProperty.boolValue))
{
_outputRemapedProperty.boolValue = true;
valuesChanged = true;
}
}
return valuesChanged;
}
#region Texture Generation Settings
private bool DrawTextureGenerationSettings(SerializedProperty generateAllOutputsProperty, SerializedProperty generateAllMipmapsProperty, SerializedProperty runtimeOnlyProperty)
{
bool changed = false;
GUILayout.Space(4);
var boxWidth = EditorGUIUtility.currentViewWidth;
var boxHeight = (3 * EditorGUIUtility.singleLineHeight) + 16;
var padding = 16;
DrawHighlightBox(boxWidth, boxHeight, padding);
if (DrawGenerateAllOutputs(generateAllOutputsProperty) ||
DrawGenerateAllMipmaps(generateAllMipmapsProperty) ||
DrawRuntimeOnlyToggle(runtimeOnlyProperty))
{
changed = true;
}
return changed;
}
private static readonly GUIContent _GenerateAllOutputsGUI = new GUIContent("Generate All Outputs", "Force the generation of all Substance outputs");
private bool DrawGenerateAllOutputs(SerializedProperty generateAllOutputsProperty)
{
var oldValue = generateAllOutputsProperty.boolValue;
generateAllOutputsProperty.boolValue = EditorGUILayout.Toggle(_GenerateAllOutputsGUI, generateAllOutputsProperty.boolValue);
return oldValue != generateAllOutputsProperty.boolValue;
}
private static readonly GUIContent _GenerateAllMipMapsGUI = new GUIContent("Generate Mip Maps", "Enable MipMaps when generating textures");
private bool DrawGenerateAllMipmaps(SerializedProperty generateAllMipmapsProperty)
{
var oldValue = generateAllMipmapsProperty.boolValue;
generateAllMipmapsProperty.boolValue = EditorGUILayout.Toggle(_GenerateAllMipMapsGUI, generateAllMipmapsProperty.boolValue);
return oldValue != generateAllMipmapsProperty.boolValue;
}
private static readonly GUIContent _RuntimeOnlyGUI = new GUIContent("Runtime only", "If checked this instance will not generate TGA texture files");
private bool DrawRuntimeOnlyToggle(SerializedProperty runtimeOnlyProperty)
{
var oldValue = runtimeOnlyProperty.boolValue;
runtimeOnlyProperty.boolValue = EditorGUILayout.Toggle(_RuntimeOnlyGUI, runtimeOnlyProperty.boolValue);
return oldValue != runtimeOnlyProperty.boolValue;
}
#endregion Texture Generation Settings
#region Physical size
private bool DrawPhysicalSize()
{
if (!_hasPhysicalSizeProperty.boolValue)
return false;
_showPhysicalSize = EditorGUILayout.Foldout(_showPhysicalSize, "Physical Size");
bool valueChanged = false;
if (_showPhysicalSize)
{
var currentValue = _physicalSizelProperty.vector3Value;
var enablePhysicaSize = _enablePhysicalSizeProperty.boolValue;
if (EditorGUILayout.Toggle("Use Physical Size", enablePhysicaSize) != enablePhysicaSize)
{
_enablePhysicalSizeProperty.boolValue = !enablePhysicaSize;
valueChanged = true;
}
var newValue = new Vector3();
newValue.x = EditorGUILayout.FloatField("X:", currentValue.x);
newValue.y = EditorGUILayout.FloatField("Y:", currentValue.y);
newValue.z = EditorGUILayout.FloatField("Z:", currentValue.z);
if ((newValue - currentValue).sqrMagnitude >= 0.01f)
{
_physicalSizelProperty.vector3Value = newValue;
valueChanged = true;
}
if (_target.OutputMaterial != null)
{
DrawPhysicalSizeOffsets(_target.OutputMaterial);
}
}
return valueChanged;
}
private static bool _showPhysicalSizePositionOffset = false;
private void DrawPhysicalSizeOffsets(Material material)
{
EditorGUI.indentLevel++;
_showPhysicalSizePositionOffset = EditorGUILayout.Foldout(_showPhysicalSizePositionOffset, "Position Offset (In %)");
if (_showPhysicalSizePositionOffset)
{
Vector2 offset = MaterialUtils.GetPhysicalSizePositionOffset(material);
Vector2 newOffset = offset;
newOffset.x = EditorGUILayout.FloatField("X:", offset.x * 100.0f) / 100.0f;
newOffset.y = EditorGUILayout.FloatField("Y:", offset.y * 100.0f) / 100.0f;
if ((newOffset - offset).sqrMagnitude >= 0.0000001f)
{
MaterialUtils.SetPhysicalSizePositionOffset(material, newOffset);
}
}
EditorGUI.indentLevel--;
}
#endregion Physical size
#region Input draw
/// <summary>
/// Draws substance file inputs.
/// </summary>
/// <param name="serializeObject">True if object properties have changed.</param>
/// <param name="renderGraph">True if substance graph must be re rendered.</param>
private void DrawInputs(out bool serializeObject, out bool renderGraph)
{
renderGraph = false;
serializeObject = false;
EditorGUILayout.Space();
if (DrawGrouplessInputs(_inputGroupingHelper.GrouplessInputs))
{
renderGraph = true;
serializeObject = true;
}
EditorGUILayout.Space();
if (PhysicalSizeExtension.IsSupported())
{
if (DrawPhysicalSize())
{
renderGraph = true;
serializeObject = true;
MaterialUtils.ApplyPhysicalSize(_target.OutputMaterial, _physicalSizelProperty.vector3Value, _enablePhysicalSizeProperty.boolValue);
UpdateGraphMaterialLabel();
}
EditorGUILayout.Space();
}
foreach (var groupInfo in _inputGroupingHelper.InputGroups)
{
if (DrawInputGroup(groupInfo))
{
renderGraph = true;
serializeObject = true;
}
}
}
/// <summary>
/// Draws the inputs that are not part of any input group.
/// </summary>
/// <param name="inputsInfo">Inputs info</param>
/// <returns>True if any input has changed.</returns>
private bool DrawGrouplessInputs(SubstanceInputGroupCachedInfo inputsInfo)
{
var indexArray = inputsInfo.Inputs;
bool changed = false;
for (int i = 0; i < indexArray.Count; i++)
{
var property = indexArray[i].InputProperty;
var guiContent = indexArray[i].GUIContent;
var index = indexArray[i].Index;
if (_nativeGraph.IsInputVisible(index))
{
if (SubstanceInputDrawer.DrawInput(property, guiContent, _nativeGraph, index))
changed = true;
}
}
return changed;
}
/// <summary>
/// Draws inputs from a input group.
/// </summary>
/// <param name="groupInfo"></param>
/// <returns></returns>
private bool DrawInputGroup(SubstanceInputGroupCachedInfo groupInfo)
{
var groupName = groupInfo.Name;
var indexArray = groupInfo.Inputs;
var visibilityArray = indexArray.Select(a => _nativeGraph.IsInputVisible(a.Index)).ToArray();
if (visibilityArray.Where(a => a).Count() == 0)
{
return false;
}
groupInfo.ShowGroup = EditorGUILayout.Foldout(groupInfo.ShowGroup, groupName);
if (!groupInfo.ShowGroup)
{
EditorGUILayout.Space();
return false;
}
bool changed = false;
for (int i = 0; i < indexArray.Count; i++)
{
EditorGUI.indentLevel++;
var index = indexArray[i].Index;
if (visibilityArray[i])
{
var property = indexArray[i].InputProperty;
var guiContent = indexArray[i].GUIContent;
if (SubstanceInputDrawer.DrawInput(property, guiContent, _nativeGraph, index))
changed = true;
}
EditorGUI.indentLevel--;
}
EditorGUILayout.Space();
return changed;
}
#endregion Input draw
#region Output draw
private static readonly GUIContent _GeneratedTextureGUI = new GUIContent();
private bool DrawGeneratedTextures(SerializedProperty outputList, bool generateAllTextures)
{
bool valueChanged = false;
EditorGUILayout.Space(4);
using (var scrollViewScope = new EditorGUILayout.ScrollViewScope(_textureOutputScrollView, false, false))
{
scrollViewScope.handleScrollWheel = false;
_textureOutputScrollView = scrollViewScope.scrollPosition;
EditorGUILayout.BeginHorizontal();
{
var outputsCount = outputList.arraySize;
var shaderProperties = EditorTools.GetShaderProperties(_target.GetShader());
for (int i = 0; i < outputsCount; i++)
{
var outputProperty = outputList.GetArrayElementAtIndex(i);
var outputTexture = _target.Output[i];
if (generateAllTextures || outputTexture.IsStandardOutput(shaderProperties))
valueChanged |= DrawOutputTexture(outputProperty, _GeneratedTextureGUI, outputTexture);
}
}
EditorGUILayout.EndHorizontal();
}
return valueChanged;
}
private bool DrawOutputTexture(SerializedProperty output, GUIContent content, SubstanceOutputTexture substanceOutput)
{
var valueChanged = false;
EditorGUILayout.BeginVertical(GUILayout.Width(120));
{
var texture = output.FindPropertyRelative("OutputTexture").objectReferenceValue as Texture2D;
var label = output.FindPropertyRelative("Description.Channel").stringValue;
var sRGB = output.FindPropertyRelative("sRGB");
var alpha = output.FindPropertyRelative("AlphaChannel");
var inverAlpha = output.FindPropertyRelative("InvertAssignedAlpha");
var isAlphaAssignable = output.FindPropertyRelative("IsAlphaAssignable").boolValue;
//Draw texture preview.
if (texture != null)
{
if (texture != null)
{
content.text = null;
var thumbnail = EditorUtility.IsDirty(texture) ? AssetPreview.GetMiniThumbnail(texture) : AssetPreview.GetAssetPreview(texture);
if (thumbnail == null)
thumbnail = AssetPreview.GetAssetPreview(texture);
content.image = thumbnail;
content.tooltip = texture.name;
if (GUILayout.Button(content, //style,
GUILayout.Width(70),
GUILayout.Height(70)))
{
// Highlight object in project browser:
EditorGUIUtility.PingObject(texture);
}
}
}
GUILayout.Label(label);
if (substanceOutput.IsBaseColor() || substanceOutput.IsDiffuse() || substanceOutput.IsEmissive())
{
var oldsRGB = sRGB.boolValue;
var newsRGB = GUILayout.Toggle(oldsRGB, "sRGB");
if (newsRGB != oldsRGB)
{
sRGB.boolValue = newsRGB;
valueChanged = true;
}
}
//Draw alpha remapping.
EditorGUILayout.BeginHorizontal(GUILayout.Width(80), GUILayout.Height(EditorGUIUtility.singleLineHeight));
{
if (isAlphaAssignable)
{
var option = _outputChannelsHelper.GetAlphaChannels(label);
var index = 0;
if (!string.IsNullOrEmpty(alpha.stringValue))
index = Array.IndexOf(option, alpha.stringValue);
EditorGUILayout.LabelField("A", GUILayout.Width(10));
var newIndex = EditorGUILayout.Popup(index, option, GUILayout.Width(70));
if (newIndex != index)
{
alpha.stringValue = newIndex != 0 ? option[newIndex] : string.Empty;
valueChanged = true;
}
}
}
EditorGUILayout.EndHorizontal();
//Draw inver alpha.
EditorGUILayout.BeginHorizontal(GUILayout.Width(80), GUILayout.Height(EditorGUIUtility.singleLineHeight));
{
if (!string.IsNullOrEmpty(alpha.stringValue))
{
var oldValue = inverAlpha.boolValue;
var newValue = GUILayout.Toggle(oldValue, "Invert alpha");
if (newValue != oldValue)
{
inverAlpha.boolValue = newValue;
valueChanged = true;
}
}
}
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.EndVertical();
return valueChanged;
}
private static bool _showAdvanceSettings = false;
private readonly List<string> _shaderInputTextures = new List<string>();
private string _shaderName = string.Empty;
private bool DrawAdvanceSettings()
{
EditorGUILayout.Space();
EditorGUI.indentLevel++;
_showAdvanceSettings = EditorGUILayout.Foldout(_showAdvanceSettings, "Output Textures Mapping");
EditorGUILayout.Space();
bool result = false;
if (_showAdvanceSettings)
{
EditorGUI.indentLevel++;
if (_target.OutputMaterial != null)
{
if (!_shaderName.Equals(_target.OutputMaterial.shader.name, StringComparison.OrdinalIgnoreCase))
{
_shaderInputTextures.Clear();
GetShaderInputTextures(_target.OutputMaterial.shader);
}
if (_outputProperties == null)
{
PopulateOutputProperties();
}
if (_outputProperties != null)
{
for (int i = 0; i < _outputProperties.Count; i++)
{
EditorGUILayout.BeginHorizontal();
{
GUILayout.TextField(_target.Output[i].Description.Channel, GUILayout.Width(200));
var oldstring = _outputProperties[i].stringValue;
var oldSelected = _shaderInputTextures.FindIndex(0, _shaderInputTextures.Count, (value) => { return oldstring.Equals(value, StringComparison.OrdinalIgnoreCase); });
if (oldSelected == -1)
oldSelected = 0;
var newSelectedIndex = EditorGUILayout.Popup("", oldSelected, _shaderInputTextures.ToArray());
if (newSelectedIndex != oldSelected)
{
result = true;
var updateString = newSelectedIndex == 0 ? string.Empty : _shaderInputTextures[newSelectedIndex];
_outputProperties[i].stringValue = updateString;
MaterialUtils.UpdateTextureTarget(_target.OutputMaterial, _target.Output[i].OutputTexture, oldstring, updateString);
//Clean other outputs that have the same assignment.
for (int j = 0; j < _outputProperties.Count; j++)
{
if (string.Equals(_outputProperties[j].stringValue, updateString) && i != j)
{
_outputProperties[j].stringValue = string.Empty;
}
}
}
}
EditorGUILayout.EndHorizontal();
}
}
}
EditorGUI.indentLevel--;
}
EditorGUI.indentLevel--;
return result;
}
#endregion Output draw
#region Presets draw
private static readonly GUIContent _ApplyPresetGUIContent = new GUIContent("Apply", "Apply preset.");
private static readonly GUIContent _UpdatePresetGUIContent = new GUIContent("Update", "Update preset.");
private static readonly GUIContent _DeletePresetGUIContent = new GUIContent("Delete", "Delete preset.");
private static readonly GUIContent _PresetExportGUIContent = new GUIContent("Export", "Export preset");
private static readonly GUIContent _CreateNewPresetGUIContent = new GUIContent("Create", "Create preset.");
private static readonly GUIContent _PresetImportGUIContent = new GUIContent("Import", "Import preset");
private static readonly GUIContent _CreateNewPresetApplyGUIContent = new GUIContent("Create", "Create");
private static readonly GUIContent _UpdateApplyGUIContent = new GUIContent("Update", "Update");
private static readonly GUIContent _DeleteConfirmText = new GUIContent("Confirm", "Confirm");
private bool _showPresetsUpdate = false;
private bool _showPresetsCreateField = false;
private bool _showDeleteLabelText = false;
private string _createPresetName = string.Empty;
private string _renamePresetName = string.Empty;
private static int _presetSelectedIndex = 0;
private bool DrawPresentExport(SubstanceGraphSO graph)
{
var result = false;
int labelWidth = (int)EditorGUIUtility.labelWidth - 15;
_showExportPresentationHandler = EditorGUILayout.Foldout(_showExportPresentationHandler, "Preset Handling", true);
if (_showExportPresentationHandler)
{
if (_presetsListProperty != null)
{
EditorGUILayout.BeginHorizontal();
{
GUILayout.Space(6);
var presetsToShow = GetPresetsGUIList();
var oldIndex = _presetSelectedIndex;
_presetSelectedIndex = EditorGUILayout.Popup(oldIndex, presetsToShow, GUILayout.Width(labelWidth));
if (oldIndex != _presetSelectedIndex)
{
ResetPresetsUIState();
}
EditorGUILayout.BeginVertical();
{
var isNative = IsPresetNative();
//Apply Preset
if (GUILayout.Button(_ApplyPresetGUIContent))
{
HandleApplyPreset(graph);
result = true;
}
//Disable Update and Delete for native presets.
if (isNative)
{
GUI.enabled = false;
}
{
//Update Preset
EditorGUILayout.BeginHorizontal();
{
if (_showPresetsUpdate)
{
if (GUILayout.Button("Cancel"))
{
_showPresetsUpdate = false;
}
}
if (GUILayout.Button(_showPresetsUpdate ? _UpdateApplyGUIContent : _UpdatePresetGUIContent) && !isNative)
{
if (HandleUpdatePreset(graph))
{
result = true;
}
}
if (_showPresetsUpdate)
{
ShowPresetsRenameField(graph);
}
}
EditorGUILayout.EndHorizontal();
//Delete Preset.
EditorGUILayout.BeginHorizontal();
{
if (isNative)
{
GUI.enabled = false;
}
if (_showDeleteLabelText)
{
if (GUILayout.Button("Cancel"))
{
_showDeleteLabelText = false;
}
}
if (GUILayout.Button(_showDeleteLabelText ? _DeleteConfirmText : _DeletePresetGUIContent) && !isNative)
{
if (HandleDeletePreset(graph))
{
result = true;
}
}
if (_showDeleteLabelText)
{
ShowDeleteConfirmationField();
}
if (isNative)
{
GUI.enabled = true;
}
}
EditorGUILayout.EndHorizontal();
}
if (isNative)
{
GUI.enabled = true;
}
//Export Preset.
if (GUILayout.Button(_PresetExportGUIContent))
{
HandleExportPresets(graph);
}
//Creare new Preset.
EditorGUILayout.BeginHorizontal();
{
if (_showPresetsCreateField)
{
if (GUILayout.Button("Cancel"))
{
_showPresetsCreateField = false;
}
}
if (GUILayout.Button(_showPresetsCreateField ? _CreateNewPresetApplyGUIContent : _CreateNewPresetGUIContent))
{
if (HandleCreatePreset(graph))
{
result = true;
}
}
if (_showPresetsCreateField)
{
ShowPresetCreateField(graph);
}
}
EditorGUILayout.EndHorizontal();
//Import preset.
if (GUILayout.Button(_PresetImportGUIContent))
{
HandleImportPresets(graph);
result = true;
}
}
EditorGUILayout.EndVertical();
}
EditorGUILayout.EndHorizontal();
}
}
return result;
}
private void HandleExportPresets(SubstanceGraphSO graph)
{
var presetLabel = "Default";
if (_presetSelectedIndex != 0)
{
var presetElement = _presetsListProperty.GetArrayElementAtIndex(_presetSelectedIndex - 1);
var presetInfoProp = presetElement.FindPropertyRelative("Info");
presetLabel = presetInfoProp.FindPropertyRelative("Label").stringValue;
}
string savePath = EditorUtility.SaveFilePanel("Save Preset as...", graph.AssetPath, presetLabel, "sbsprs");
if (savePath != "")
{
string savePreset = "<sbspresets count=\"1\" formatversion=\"1.1\">\n "; //formatting line needed by other integrations
savePreset += SubstanceEditorEngine.instance.ExportGraphPresetXML(graph);
savePreset += "</sbspresets>";
savePreset = ReplaceLabelField(savePreset, presetLabel);
File.WriteAllText(savePath, savePreset);
}
GUIUtility.ExitGUI();
}
private void HandleImportPresets(SubstanceGraphSO graph)
{
string loadPath = EditorUtility.OpenFilePanel("Select Preset", graph.AssetPath, "sbsprs");
if (loadPath != "")
{
string presetFile = System.IO.File.ReadAllText(loadPath);
int startIndex = presetFile.IndexOf("<sbspreset ");
int endIndex = presetFile.IndexOf("sbspreset>") + 10;
var presetXML = presetFile.Substring(startIndex, endIndex - startIndex);
var label = Path.GetFileName(loadPath);
CreateNewPreset(label, string.Empty, string.Empty, presetXML);
SubstanceEditorEngine.instance.LoadPresetsToGraph(graph, presetXML);
}
GUIUtility.ExitGUI();
}
private void HandleApplyPreset(SubstanceGraphSO graph)
{
if (_presetsListProperty == null)
{
return;
}
if (_presetsListProperty.arraySize <= _presetSelectedIndex - 1)
{
return;
}
if (_presetSelectedIndex == 0)
{
SubstanceEditorEngine.instance.LoadPresetsToGraph(graph, graph.DefaultPreset);
return;
}
var presetElement = _presetsListProperty.GetArrayElementAtIndex(_presetSelectedIndex - 1);
var isNative = presetElement.FindPropertyRelative("NativePreset").boolValue;
if (isNative)
{
SubstanceEditorEngine.instance.LoadBakedPresetsToGraph(graph, _presetSelectedIndex - 1);
}
else
{
var presetValue = presetElement.FindPropertyRelative("PresetValue").stringValue;
SubstanceEditorEngine.instance.LoadPresetsToGraph(graph, presetValue);
}
}
private bool HandleCreatePreset(SubstanceGraphSO graph)
{
if (_presetsListProperty == null)
return false;
if (!_showPresetsCreateField)
{
_showPresetsCreateField = true;
_createPresetName = string.Empty;
return false;
}
_showPresetsCreateField = false;
if (string.IsNullOrEmpty(_createPresetName))
{
Debug.LogWarning("Presets label can not be null;");
return false;
}
CreateNewPreset(_createPresetName, string.Empty, string.Empty, _nativeGraph.CreatePresetFromCurrentState());
return true;
}
private bool HandleDeletePreset(SubstanceGraphSO graph)
{
if (_presetsListProperty == null)
{
return false;
}
if (_presetsListProperty.arraySize <= _presetSelectedIndex - 1)
{
return false;
}
if (!_showDeleteLabelText)
{
_showDeleteLabelText = true;
return false;
}
_presetsListProperty.DeleteArrayElementAtIndex(_presetSelectedIndex - 1);
_presetSelectedIndex = 0;
_showDeleteLabelText = false;
return true;
}
private bool HandleUpdatePreset(SubstanceGraphSO graph)
{
if (_presetSelectedIndex == 0)
{
Debug.LogWarning("This preset is baked into the sbsar file and can not be updated.");
return false;
}
if (_presetsListProperty == null)
{
_showPresetsUpdate = false;
Debug.LogWarning("Invalid preset to rename");
return false;
}
if (_presetsListProperty.arraySize <= _presetSelectedIndex - 1)
{
_showPresetsUpdate = false;
Debug.LogWarning("Invalid preset to rename");
return false;
}
var presetElement = _presetsListProperty.GetArrayElementAtIndex(_presetSelectedIndex - 1);
var presetInfoProp = presetElement.FindPropertyRelative("Info");
var labelProperty = presetInfoProp.FindPropertyRelative("Label");
var presetValueProp = presetElement.FindPropertyRelative("PresetValue");
bool result = false;
if (_showPresetsUpdate)
{
if (string.IsNullOrEmpty(_renamePresetName))
{
Debug.LogWarning("Presets label can not be null;");
}
else
{
labelProperty.stringValue = _renamePresetName;
presetValueProp.stringValue = _nativeGraph.CreatePresetFromCurrentState();
result = true;
}
_renamePresetName = string.Empty;
}
else
{
_renamePresetName = labelProperty.stringValue;
}
_showPresetsUpdate = !_showPresetsUpdate;
return result;
}
private void ShowPresetsRenameField(SubstanceGraphSO graph)
{
int labelWidth = ((int)EditorGUIUtility.labelWidth) / 2;
_renamePresetName = GUILayout.TextField(_renamePresetName, GUILayout.Width(labelWidth));
}
private void ShowPresetCreateField(SubstanceGraphSO graph)
{
int labelWidth = ((int)EditorGUIUtility.labelWidth) / 2;
_createPresetName = GUILayout.TextField(_createPresetName, GUILayout.Width(labelWidth));
}
private void ShowDeleteConfirmationField()
{
int labelWidth = ((int)EditorGUIUtility.labelWidth) / 2;
GUILayout.Label("Delete?", GUILayout.Width(labelWidth));
}
private void CreateNewPreset(string label, string description, string URL, string value)
{
var index = _presetsListProperty.arraySize;
_presetsListProperty.InsertArrayElementAtIndex(index);
var presetElement = _presetsListProperty.GetArrayElementAtIndex(index);
presetElement.FindPropertyRelative("NativePreset").boolValue = false;
presetElement.FindPropertyRelative("PresetValue").stringValue = value;
presetElement.FindPropertyRelative("PresetIndex").intValue = 0;
var presetInfoProp = presetElement.FindPropertyRelative("Info");
presetInfoProp.FindPropertyRelative("Label").stringValue = label;
presetInfoProp.FindPropertyRelative("Description").stringValue = description;
presetInfoProp.FindPropertyRelative("URL").stringValue = URL;
}
private bool IsPresetNative()
{
if (_presetSelectedIndex == 0)
return true;
var presetElement = _presetsListProperty.GetArrayElementAtIndex(_presetSelectedIndex - 1);
var isNative = presetElement.FindPropertyRelative("NativePreset").boolValue;
return isNative;
}
private string[] GetPresetsGUIList()
{
var arraySize = _presetsListProperty.arraySize;
string[] result = new string[arraySize + 1];
result[0] = "Default";
for (int i = 0; i < arraySize; i++)
{
var presetElement = _presetsListProperty.GetArrayElementAtIndex(i);
var presetInfoProp = presetElement.FindPropertyRelative("Info");
result[i + 1] = presetInfoProp.FindPropertyRelative("Label").stringValue;
if (string.IsNullOrEmpty(result[i + 1]))
{
result[i + 1] = "empty";
}
}
return result;
}
private void ResetPresetsUIState()
{
_showPresetsUpdate = false;
_showPresetsCreateField = false;
_showDeleteLabelText = false;
_createPresetName = string.Empty;
_renamePresetName = string.Empty;
}
private string ReplaceLabelField(string presetXML, string label)
{
return presetXML.Replace("label=\"\"", $"label=\"{label}\"");
}
#endregion Presets draw
#region Thumbnail preview
public override Texture2D RenderStaticPreview(string assetPath, UnityEngine.Object[] subAssets, int width, int height)
{
if (_target.HasThumbnail)
return _target.GetThumbnailTexture();
var icon = UnityPackageInfo.GetSubstanceIcon(width, height);
if (icon != null)
{
Texture2D tex = new Texture2D(width, height);
EditorUtility.CopySerialized(icon, tex);
return tex;
}
return base.RenderStaticPreview(assetPath, subAssets, width, height);
}
#endregion Thumbnail preview
#endregion Draw
#region Scene Drag
static Renderer s_previousDraggedUponRenderer;
static Material[] s_previousMaterialValue;
static bool s_previousAlreadyHadPrefabModification;
private const string undoAssignMaterial = "Assign Material";
public void OnSceneDrag(SceneView sceneView, int index)
{
Event evt = Event.current;
if (evt.type == EventType.Repaint)
return;
var go = HandleUtility.PickGameObject(evt.mousePosition, out int materialIndex);
if (EditorMaterialUtility.IsBackgroundMaterial((_target.OutputMaterial as Material)))
{
ClearDragMaterialRendering();
}
else if (go && go.GetComponent<Renderer>())
{
if (_target.OutputMaterial != null)
{
if (go && go.GetComponent<Renderer>())
{
HandleRenderer(go.GetComponent<Renderer>(), materialIndex, _target.OutputMaterial, evt.type, evt.alt);
EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());
if (_target.IsRuntimeOnly)
{
var runtimeComponent = go.GetComponent<Adobe.Substance.Runtime.SubstanceRuntimeGraph>();
if (runtimeComponent == null)
runtimeComponent = go.AddComponent<Adobe.Substance.Runtime.SubstanceRuntimeGraph>();
runtimeComponent.AttachGraph(_target);
}
}
}
}
else
{
ClearDragMaterialRendering();
}
}
internal static void HandleRenderer(Renderer r, int materialIndex, Material dragMaterial, EventType eventType, bool alt)
{
var applyMaterial = false;
switch (eventType)
{
case EventType.DragUpdated:
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
applyMaterial = true;
break;
case EventType.DragPerform:
DragAndDrop.AcceptDrag();
applyMaterial = true;
ClearDragMaterialRendering();
break;
}
if (applyMaterial)
{
if (eventType != EventType.DragPerform)
{
ClearDragMaterialRendering();
s_previousDraggedUponRenderer = r;
s_previousMaterialValue = r.sharedMaterials;
// Update prefab modification status cache
s_previousAlreadyHadPrefabModification = false;
if (PrefabUtility.GetPrefabInstanceStatus(s_previousDraggedUponRenderer) == PrefabInstanceStatus.Connected)
{
var materialRendererSerializedObject = new SerializedObject(s_previousDraggedUponRenderer).FindProperty("m_Materials");
s_previousAlreadyHadPrefabModification = materialRendererSerializedObject.prefabOverride;
}
}
Undo.RecordObject(r, undoAssignMaterial);
var materials = r.sharedMaterials;
bool isValidMaterialIndex = (materialIndex >= 0 && materialIndex < r.sharedMaterials.Length);
if (!alt && isValidMaterialIndex)
{
materials[materialIndex] = dragMaterial;
}
else
{
for (int q = 0; q < materials.Length; ++q)
materials[q] = dragMaterial;
}
r.sharedMaterials = materials;
}
}
private static void ClearDragMaterialRendering()
{
TryRevertDragChanges();
s_previousDraggedUponRenderer = null;
s_previousMaterialValue = null;
}
private static void TryRevertDragChanges()
{
if (s_previousDraggedUponRenderer != null)
{
bool hasRevert = false;
if (!s_previousAlreadyHadPrefabModification &&
PrefabUtility.GetPrefabInstanceStatus(s_previousDraggedUponRenderer) == PrefabInstanceStatus.Connected)
{
var materialRendererSerializedObject = new SerializedObject(s_previousDraggedUponRenderer).FindProperty("m_Materials");
PrefabUtility.RevertPropertyOverride(materialRendererSerializedObject, InteractionMode.AutomatedAction);
hasRevert = true;
if (!hasRevert)
s_previousDraggedUponRenderer.sharedMaterials = s_previousMaterialValue;
}
}
}
#endregion Scene Drag
#region Utilities
private void SaveTGAFiles()
{
if (_target == null)
return;
if (_target.IsRuntimeOnly)
return;
_target.OutputRemaped = true;
_target.RenderTextures = true;
EditorUtility.SetDirty(_target);
}
private Rect DrawHighlightBox(float width, float height, float xPadding)
{
float bx, by, bw, bh;
bx = xPadding;
by = GetPosition();
bw = width - xPadding;
bh = height;
var boxRect = new Rect(bx, by, bw, bh);
var backgroundStyle = new GUIStyle();
backgroundStyle.normal.background = _backgroundImage;
GUI.Box(boxRect, GUIContent.none, backgroundStyle);
return boxRect;
}
private int GetPosition()
{
Rect rect = GUILayoutUtility.GetLastRect();
if ((rect.x != 0) || (rect.y != 0))
lastRect = rect;
return (int)lastRect.y;
}
/// This is a workaround a bug in the Unity asset database for generating materials previews.
/// It basically generated a previews image whenever a property changes in the material, but it is now considering changes in the
/// textures assign to the material itself. By adding a random label we ensure that the asset preview image will be updated.
private void UpdateGraphMaterialLabel()
{
if (_target == null)
return;
const string tagPrefix = "sb_";
var material = _target.OutputMaterial;
if (material != null)
{
var labels = AssetDatabase.GetLabels(material);
var newLabels = labels.Where(a => !a.Contains(tagPrefix)).ToList();
newLabels.Add($"{tagPrefix}{Guid.NewGuid().ToString("N")}");
AssetDatabase.SetLabels(material, newLabels.ToArray());
}
}
#endregion Utilities
#region Presets Config
private bool _presetsFirstConfig = false;
private bool FirstConfigurePresets()
{
if (_presetsFirstConfig)
return false;
_presetsFirstConfig = true;
if (_presetsListProperty == null)
return false;
if (_presetsListProperty.arraySize != 0)
return false;
var bakedPresets = _nativeGraph.GetPresetsList();
if (bakedPresets.Count == 0)
return false;
for (int i = 0; i < bakedPresets.Count; i++)
{
_presetsListProperty.InsertArrayElementAtIndex(i);
var presetElement = _presetsListProperty.GetArrayElementAtIndex(i);
presetElement.FindPropertyRelative("NativePreset").boolValue = true;
presetElement.FindPropertyRelative("PresetValue").stringValue = string.Empty;
presetElement.FindPropertyRelative("PresetIndex").intValue = i;
var presetInfoProp = presetElement.FindPropertyRelative("Info");
presetInfoProp.FindPropertyRelative("Label").stringValue = bakedPresets[i].Label;
presetInfoProp.FindPropertyRelative("Description").stringValue = bakedPresets[i].Description;
presetInfoProp.FindPropertyRelative("URL").stringValue = bakedPresets[i].URL;
}
return true;
}
#endregion Presets Config
/// Work around Unity SerializedObjectNotCreatableException during script compilation.
private bool IsSerializedObjectReady()
{
try
{
if (serializedObject.targetObject == null)
return false;
}
catch (Exception)
{
return false;
}
return true;
}
}
} | 412 | 0.954022 | 1 | 0.954022 | game-dev | MEDIA | 0.875194 | game-dev | 0.966704 | 1 | 0.966704 |
Jyouhou/UnrealText | 1,182 | code/UnrealText/Plugins/UnrealCV/Source/UnrealCV/Public/Actor/StereoCameraActor.h | // Weichao Qiu @ 2017
#pragma once
#include "Runtime/Engine/Classes/GameFramework/Actor.h"
#include "CamSensorActor.h"
#include "FusionCameraActor.h"
#include "StereoCameraActor.generated.h"
UCLASS()
class UNREALCV_API AStereoCameraActor : public ACamSensorActor
{
GENERATED_BODY()
public:
// AStereoCameraActor(const FObjectInitializer& ObjectInitializer);
AStereoCameraActor();
virtual void BeginPlay() override;
UPROPERTY(EditInstanceOnly)
float BaselineDistance;
virtual TArray<FString> GetSensorNames() override;
virtual TArray<UFusionCamSensor*> GetSensors() override;
private:
UPROPERTY(Instanced, Category = StereoCameraActor, VisibleAnywhere, BlueprintReadOnly, meta = (AllowPrivateAccess = "true"))
UFusionCamSensor* LeftSensor;
UPROPERTY(Instanced, Category = StereoCameraActor, VisibleAnywhere, BlueprintReadOnly, meta = (AllowPrivateAccess = "true"))
UFusionCamSensor* RightSensor;
UPROPERTY(Category = StereoCameraActor, VisibleAnywhere, BlueprintReadOnly, meta = (AllowPrivateAccess = "true"))
class USceneComponent* SceneComponent;
void SetBaselineDistance();
void PostEditChangeProperty(FPropertyChangedEvent &PropertyChangedEvent);
};
| 412 | 0.856056 | 1 | 0.856056 | game-dev | MEDIA | 0.645423 | game-dev | 0.683989 | 1 | 0.683989 |
mozilla/pdfjs-dist | 2,615 | lib/web/overlay_manager.js | /**
* @licstart The following is the entire license notice for the
* JavaScript code in this page
*
* Copyright 2022 Mozilla Foundation
*
* 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.
*
* @licend The above is the entire license notice for the
* JavaScript code in this page
*/
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.OverlayManager = void 0;
class OverlayManager {
#overlays = new WeakMap();
#active = null;
get active() {
return this.#active;
}
async register(dialog, canForceClose = false) {
if (typeof dialog !== "object") {
throw new Error("Not enough parameters.");
} else if (this.#overlays.has(dialog)) {
throw new Error("The overlay is already registered.");
}
this.#overlays.set(dialog, {
canForceClose
});
dialog.addEventListener("cancel", evt => {
this.#active = null;
});
}
async unregister(dialog) {
if (!this.#overlays.has(dialog)) {
throw new Error("The overlay does not exist.");
} else if (this.#active === dialog) {
throw new Error("The overlay cannot be removed while it is active.");
}
this.#overlays.delete(dialog);
}
async open(dialog) {
if (!this.#overlays.has(dialog)) {
throw new Error("The overlay does not exist.");
} else if (this.#active) {
if (this.#active === dialog) {
throw new Error("The overlay is already active.");
} else if (this.#overlays.get(dialog).canForceClose) {
await this.close();
} else {
throw new Error("Another overlay is currently active.");
}
}
this.#active = dialog;
dialog.showModal();
}
async close(dialog = this.#active) {
if (!this.#overlays.has(dialog)) {
throw new Error("The overlay does not exist.");
} else if (!this.#active) {
throw new Error("The overlay is currently not active.");
} else if (this.#active !== dialog) {
throw new Error("Another overlay is currently active.");
}
dialog.close();
this.#active = null;
}
}
exports.OverlayManager = OverlayManager; | 412 | 0.891807 | 1 | 0.891807 | game-dev | MEDIA | 0.438662 | game-dev | 0.973077 | 1 | 0.973077 |
Suprcode/Crystal | 3,674 | Server/MirObjects/Monsters/EvilCentipede.cs | using Server.MirDatabase;
using Server.MirEnvir;
using S = ServerPackets;
namespace Server.MirObjects.Monsters
{
public class EvilCentipede : MonsterObject
{
public bool Visible;
public long VisibleTime;
protected override bool CanAttack
{
get
{
return Visible && base.CanAttack;
}
}
protected override bool CanMove { get { return false; } }
public override bool Blocking
{
get
{
return Visible && base.Blocking;
}
}
protected internal EvilCentipede(MonsterInfo info)
: base(info)
{
Visible = false;
}
protected override void ProcessAI()
{
if (!Visible)
SetHP(Stats[Stat.HP]);
if (!Dead && Envir.Time > VisibleTime)
{
VisibleTime = Envir.Time + 2000;
bool visible = FindNearby(Visible ? 7 : 3);
if (!Visible && visible)
{
Visible = true;
CellTime = Envir.Time + 500;
Broadcast(GetInfo());
Broadcast(new S.ObjectShow { ObjectID = ObjectID });
ActionTime = Envir.Time + 2000;
}
if (Visible && !visible)
{
Visible = false;
VisibleTime = Envir.Time + 3000;
Broadcast(new S.ObjectHide { ObjectID = ObjectID });
SetHP(Stats[Stat.HP]);
}
}
base.ProcessAI();
}
public override void Turn(MirDirection dir)
{
}
public override bool Walk(MirDirection dir) { return false; }
public override bool IsAttackTarget(MonsterObject attacker)
{
return Visible && base.IsAttackTarget(attacker);
}
public override bool IsAttackTarget(HumanObject attacker)
{
return Visible && base.IsAttackTarget(attacker);
}
protected override void ProcessRoam() { }
protected override void ProcessSearch()
{
if (Visible)
base.ProcessSearch();
}
protected override void CompleteAttack(IList<object> data)
{
List<MapObject> targets = FindAllTargets(7, CurrentLocation, false);
if (targets.Count == 0) return;
for (int i = 0; i < targets.Count; i++)
{
Target = targets[i];
Attack();
}
}
protected override void ProcessTarget()
{
if (!CanAttack) return;
if (!FindNearby(7)) return;
ShockTime = 0;
Broadcast(new S.ObjectAttack { ObjectID = ObjectID, Direction = Direction, Location = CurrentLocation });
ActionList.Add(new DelayedAction(DelayedType.Damage, Envir.Time + 500));
ActionTime = Envir.Time + 300;
AttackTime = Envir.Time + AttackSpeed;
}
protected override void Attack()
{
int damage = GetAttackPower(Stats[Stat.MinDC], Stats[Stat.MaxDC]);
if (damage == 0) return;
if (Target.Attacked(this, damage, DefenceType.MAC) <= 0) return;
PoisonTarget(Target, 5, 15, PoisonType.Green, 2000);
PoisonTarget(Target, 15, 5, PoisonType.Paralysis, 2000);
}
public override Packet GetInfo()
{
return !Visible ? null : base.GetInfo();
}
}
}
| 412 | 0.95754 | 1 | 0.95754 | game-dev | MEDIA | 0.87082 | game-dev | 0.962213 | 1 | 0.962213 |
3UR/Simpsons-Hit-Run | 6,469 | src/libs/radcore/src/radobject/object.cpp | //=============================================================================
// Copyright (c) 2002 Radical Games Ltd. All rights reserved.
//=============================================================================
//=============================================================================
//
// File: radobject.cpp
//
// Subsystem: Fountation Technologies Base Class Implementations
//
// Description: This file contains the implementation of the radical object
// base class. Provides object tracking in a debug build.
//
// Revisions: V1.00 Mar 9, 2001 Creation
//
//=============================================================================
//=============================================================================
// Include Files
//=============================================================================
#include "pch.hpp"
#include <radobject.hpp>
#include <radmemory.hpp>
#include <radmemorymonitor.hpp>
#include <typeinfo>
#include <string.h>
#include <radthread.hpp>
//=============================================================================
// Implementation
//=============================================================================
const char * const g_nameFTech = "FTech";
radMemoryAllocator radObject::s_Allocator = -1;
#ifdef RAD_DEBUG
radBaseObject * radBaseObject::s_pRadBaseObjectHead = NULL;
void radBaseObject::DumpObjects( void )
{
rDebugString( "\nradObject Dump:\n" );
rDebugString( "---------------\n" );
char className[ 256 ];
strcpy( className, " " );
unsigned int totalMemoryCountDebug = 0;
unsigned int totalMemoryCountRelease = 0;
unsigned int totalObjectCount = 0;
bool leaksFound = s_pRadBaseObjectHead != NULL;
while( 1 )
{
// Find the class which is next alphabetically.
radBaseObject * pSearch = s_pRadBaseObjectHead;
radBaseObject * pLower = NULL;
while ( pSearch != NULL )
{
// if this class is greater that the previous one we printed
if ( strcmp( typeid( *pSearch ).name( ), className ) > 0 )
{
// AND lower than the last search item, it is our new candiate for
// summarizing.
if ( pLower == NULL || strcmp( typeid( *pLower ).name( ), typeid( *pSearch ).name( ) ) > 0 )
{
pLower = pSearch;
}
}
// Keeping going until we've found the next lexigraphical class name
pSearch = pSearch->m_pRadBaseObjectNext;
}
// Now search for all classes of this type, and tally up the info.
if ( pLower != NULL )
{
strcpy( className, typeid( *pLower ).name( ) );
unsigned int classObjectCount = 0;
unsigned int classObjectSizeDebug = 0;
unsigned int classObjectSizeRelease = 0;
unsigned int classSizeDebug = pLower->GetObjectSize( );
unsigned int classSizeRelease = classSizeDebug - 12;
radBaseObject * pTallySearch = s_pRadBaseObjectHead;
while ( pTallySearch != NULL )
{
const char * pClassName = typeid( *pTallySearch ).name( );
if ( strcmp( pClassName, className ) == 0 )
{
classObjectCount ++;
classObjectSizeDebug += classSizeDebug;
classObjectSizeRelease += classSizeRelease;
totalObjectCount ++;
totalMemoryCountDebug += classSizeDebug;
totalMemoryCountRelease += classSizeRelease;
}
pTallySearch = pTallySearch->m_pRadBaseObjectNext;
}
//
// Print Results for this class type
//
if ( classSizeDebug == 0xFFFFFFFF )
{
rDebugPrintf( " Class: [%48s] Count: [%5d] No Size Information!\n",
className,
classObjectCount );
}
else
{
rDebugPrintf( " Class: [%48s] Count: [%5d] Bytes: [%5d(Debug),%5d(Release)] TotalBytes: [%5d(Debug),%5d(Release)]\n",
className,
classObjectCount,
classSizeDebug,
classSizeRelease,
classObjectSizeDebug,
classObjectSizeRelease );
}
}
else
{
if ( leaksFound == false )
{
rDebugPrintf( " No leaks detected.\n" );
}
// print total results and end.
rDebugString( "\n" );
rDebugString( "radObject Dump Summary:\n" );
rDebugString( "---------------------\n" );
rDebugPrintf( " Total number of objects: [%d].\n", totalObjectCount );
rDebugPrintf( " Total number of byte allocated for debug: [%d].\n", totalMemoryCountDebug );
rDebugPrintf( " Total number of byte allocated for release: [%d].\n\n", totalMemoryCountRelease );
break;
}
}
}
void radBaseObject::AddToList( void )
{
m_pRadBaseObjectNext = s_pRadBaseObjectHead;
if ( m_pRadBaseObjectNext != NULL )
{
m_pRadBaseObjectNext->m_pRadBaseObjectPrev = this;
}
m_pRadBaseObjectPrev = NULL;
s_pRadBaseObjectHead = this;
}
void radBaseObject::RemoveFromList( void )
{
if ( m_pRadBaseObjectPrev != NULL )
{
m_pRadBaseObjectPrev->m_pRadBaseObjectNext = m_pRadBaseObjectNext;
}
else
{
s_pRadBaseObjectHead = m_pRadBaseObjectNext;
}
if ( m_pRadBaseObjectNext != NULL )
{
m_pRadBaseObjectNext->m_pRadBaseObjectPrev = m_pRadBaseObjectPrev;
}
}
size_t radBaseObject::GetObjectSize( void )
{
return 0xFFFFFFFF;
}
void radBaseObject::Dump( char* pStringBuffer, unsigned int bufferSize )
{
strcpy( pStringBuffer, "Unknown!" );
}
#endif
#if defined RADMEMORYMONITOR
void radMemoryMonitorIdentifyAllocationAdaptor( void * address, const char * group, const char * name, unsigned int* pReferenceCount )
{
radMemoryMonitorIdentifyAllocation( address, group, name, pReferenceCount );
}
void radMemoryMonitorReportAddRefAdaptor( void* pReference, void* pObject )
{
radMemoryMonitorReportAddRef( pReference, pObject );
}
void radMemoryMonitorReportReleaseAdaptor( void* pReference, void* pObject )
{
radMemoryMonitorReportRelease( pReference, pObject );
}
#endif | 412 | 0.97024 | 1 | 0.97024 | game-dev | MEDIA | 0.222225 | game-dev | 0.960168 | 1 | 0.960168 |
cafel176/RPGFrameWork | 1,373 | 2DSample/Assets/Engine/script/Components/UI/UI Struct/others/CanDoHint.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UI;
public class CanDoHint : basePanel
{
public Text txt;
private Vector3 pos;
public Vector3 Pos
{
set
{
pos = value;
}
}
private bool show = false;
public bool canShow
{
get
{
return show;
}
}
private Animator anima;
override protected void onAwake()
{
anima = gameObject.GetComponent<Animator>();
}
private void Update()
{
doEveryFrame();
}
override public void doEveryFrame()
{
if (show)
{
Vector2 cPos = Camera.main.WorldToScreenPoint(pos);
Vector2 uipos = new Vector2(cPos.x - Screen.width * 0.5f, cPos.y - 0.5f * Screen.height);
gameObject.GetComponent<RectTransform>().localPosition = uipos;
transform.SetAsFirstSibling();
}
}
public void Show(string t)
{
txt.text = findText(t, getSetting().nowlang);
show = true;
anima.SetTrigger(getHat().start);
}
public void Hide()
{
anima.SetTrigger(getHat().end);
}
public void showAnimaEnd()
{
}
public void hideAnimaEnd()
{
show = false;
gameObject.SetActive(false);
}
}
| 412 | 0.7635 | 1 | 0.7635 | game-dev | MEDIA | 0.965839 | game-dev | 0.622428 | 1 | 0.622428 |
swgemu/Core3 | 10,298 | MMOCoreORB/src/server/zone/managers/gcw/sessions/WildContrabandScanSessionImplementation.cpp | /*
* WildContrabandScanSessionImplementation.cpp
*
* Created on: Aug 30, 2020
* Author: loshult
*/
#include "server/zone/managers/creature/CreatureManager.h"
#include "server/zone/managers/gcw/GCWManager.h"
#include "server/zone/managers/gcw/observers/ProbotObserver.h"
#include "server/zone/managers/gcw/sessions/WildContrabandScanSession.h"
#include "server/zone/managers/gcw/tasks/LambdaShuttleWithReinforcementsTask.h"
#include "server/zone/managers/gcw/tasks/WildContrabandScanTask.h"
#include "server/zone/managers/mission/MissionManager.h"
#include "server/zone/managers/planet/PlanetManager.h"
#include "server/zone/objects/creature/ai/AiAgent.h"
#include "server/zone/objects/creature/CreatureObject.h"
#include "server/zone/packets/scene/PlayClientEffectLocMessage.h"
#include "server/zone/Zone.h"
int WildContrabandScanSessionImplementation::initializeSession() {
ManagedReference<CreatureObject*> player = weakPlayer.get();
if (player == nullptr) {
return false;
}
ManagedReference<Zone*> zone = player->getZone();
if (zone == nullptr) {
return false;
}
Locker lock(player);
if (wildContrabandScanTask == nullptr) {
wildContrabandScanTask = new WildContrabandScanTask(player);
}
if (!wildContrabandScanTask->isScheduled()) {
wildContrabandScanTask->schedule(TASKDELAY);
}
GCWManager* gcwMan = zone->getGCWManager();
if (gcwMan != nullptr)
player->updateCooldownTimer("crackdown_scan", gcwMan->getCrackdownPlayerScanCooldown() * 1000);
if (player->getActiveSession(SessionFacadeType::WILDCONTRABANDSCAN) != nullptr) {
player->dropActiveSession(SessionFacadeType::WILDCONTRABANDSCAN);
}
player->addActiveSession(SessionFacadeType::WILDCONTRABANDSCAN, _this.getReferenceUnsafeStaticCast());
Vector3 playerPos = player->getPosition();
landingCoordinates = getLandingCoordinates(zone, player, playerPos);
return true;
}
int WildContrabandScanSessionImplementation::cancelSession() {
ManagedReference<CreatureObject*> player = weakPlayer.get();
AiAgent* droid = getDroid();
if (droid != nullptr) {
Locker dlocker(droid);
droid->destroyObjectFromWorld(true);
}
if (player != nullptr) {
player->dropActiveSession(SessionFacadeType::WILDCONTRABANDSCAN);
}
if (wildContrabandScanTask != nullptr) {
wildContrabandScanTask->cancel();
}
return clearSession();
}
int WildContrabandScanSessionImplementation::clearSession() {
return 0;
}
void WildContrabandScanSessionImplementation::runWildContrabandScan() {
ManagedReference<CreatureObject*> player = weakPlayer.get();
if (!scanPrerequisitesMet(player)) {
cancelSession();
}
Locker plocker(player);
ManagedReference<Zone*> zone = player->getZone();
if (zone == nullptr) {
cancelSession();
return;
}
AiAgent* droid = getDroid();
if (droid != nullptr && droid->isInCombat()) {
scanState = INCOMBAT;
}
timeLeft--;
switch (scanState) {
case LANDING:
landProbeDroid(zone, player);
scanState = HEADTOPLAYER;
break;
case HEADTOPLAYER:
if (timeLeft <= 0) {
weakDroid = cast<AiAgent*>(zone->getCreatureManager()->spawnCreature(STRING_HASHCODE("crackdown_probot"), 0, landingCoordinates.getX(), landingCoordinates.getZ(), landingCoordinates.getY(), 0));
AiAgent* droid = getDroid();
if (droid != nullptr) {
Locker clocker(droid, player);
ManagedReference<ProbotObserver*> probotObserver = new ProbotObserver();
probotObserver->setProbot(droid);
droid->registerObserver(ObserverEventType::DEFENDERADDED, probotObserver);
droid->setAITemplate();
droid->addObjectFlag(ObjectFlag::FOLLOW);
droid->setFollowObject(player);
scanState = CLOSINGIN;
timeLeft = 30;
} else {
error("Probot is missing.");
scanState = FINISHED;
}
}
break;
case CLOSINGIN:
if (timeLeft > 0) {
AiAgent* droid = getDroid();
if (droid != nullptr) {
if (player->getWorldPosition().distanceTo(droid->getWorldPosition()) < 32) {
scanState = INITIATESCAN;
}
} else {
error("Probot is missing.");
scanState = FINISHED;
}
} else {
scanState = TAKEOFF; // Probot has not reached the player in 30 s, take off again.
}
break;
case INITIATESCAN: {
sendSystemMessage(player, "dismount_imperial");
if (player->isRidingMount()) {
player->dismount();
sendSystemMessage(player, "dismount");
}
sendSystemMessage(player, "probe_scan");
AiAgent* droid = getDroid();
if (droid != nullptr) {
Locker clocker(droid, player);
droid->showFlyText("imperial_presence/contraband_search", "probe_scan_fly", 255, 0, 0);
droid->setFollowObject(player);
timeLeft = SCANTIME;
scanState = SCANDELAY;
} else {
error("Probot is missing.");
scanState = FINISHED;
}
} break;
case SCANDELAY: {
PlayerObject* ghost = player->getPlayerObject();
if ((ghost != nullptr && ghost->hasCrackdownTefTowards(Factions::FACTIONIMPERIAL)) || (player->getFaction() == Factions::FACTIONREBEL && (player->getFactionStatus() == FactionStatus::OVERT || player->getFactionStatus() == FactionStatus::COVERT))) {
AiAgent* droid = getDroid();
if (droid != nullptr) {
Locker droidlock(droid);
droid->addDefender(player);
}
}
if (timeLeft <= 0) {
int numberOfContrabandItems = 0;
GCWManager* gcwManager = zone->getGCWManager();
if (gcwManager != nullptr) {
numberOfContrabandItems = gcwManager->countContrabandItems(player);
}
if (numberOfContrabandItems > 0) {
sendSystemMessage(player, "probe_scan_positive");
scanState = TAKEOFF;
timeLeft = 12;
MissionManager* missionManager = player->getZoneServer()->getMissionManager();
auto spawnPoint = missionManager->getFreeNpcSpawnPoint(player->getPlanetCRC(), player->getWorldPositionX(), player->getWorldPositionY(), NpcSpawnPoint::LAMBDASHUTTLESPAWN, 128.f);
if (spawnPoint != nullptr) {
Reference<Task*> lambdaTask = new LambdaShuttleWithReinforcementsTask(player, Factions::FACTIONIMPERIAL, 1, "@imperial_presence/contraband_search:containment_team_imperial", *spawnPoint->getPosition(), *spawnPoint->getDirection(), LambdaShuttleWithReinforcementsTask::LAMBDASHUTTLESCAN);
lambdaTask->schedule(1000);
} else {
float spawnDirection = player->getDirection()->getRadians() + Math::PI;
if (spawnDirection >= 2 * Math::PI) {
spawnDirection -= 2 * Math::PI;
}
Reference<Task*> lambdaTask = new LambdaShuttleWithReinforcementsTask(player, Factions::FACTIONIMPERIAL, 1, "@imperial_presence/contraband_search:containment_team_imperial", landingCoordinates, Quaternion(Vector3(0, 1, 0), spawnDirection), LambdaShuttleWithReinforcementsTask::LAMBDASHUTTLESCAN);
lambdaTask->schedule(1000);
}
AiAgent* droid = getDroid();
if (droid != nullptr && !droid->isDead()) {
Locker dlocker(droid);
PatrolPoint* homeLocation = droid->getHomeLocation();
droid->removeObjectFlag(ObjectFlag::FOLLOW);
droid->clearPatrolPoints();
droid->setMovementState(AiAgent::PATROLLING);
droid->setAITemplate();
droid->setNextPosition(homeLocation->getPositionX(), homeLocation->getPositionZ(), homeLocation->getPositionY());
droid->showFlyText("imperial_presence/contraband_search", "probot_support_fly", 255, 0, 0);
}
} else {
sendSystemMessage(player, "probe_scan_negative");
scanState = TAKEOFF;
timeLeft = 5;
}
}
break;
}
case INCOMBAT: {
AiAgent* droid = getDroid();
if (droid != nullptr) {
if (!droid->isInCombat() && !droid->isDead()) {
scanState = TAKEOFF;
timeLeft = 5;
} else if (droid->isDead()) {
scanState = TAKINGOFF;
timeLeft = 60;
}
} else {
scanState = FINISHED; // Probot is destroyed.
}
} break;
case TAKEOFF:
if (timeLeft <= 0) {
scanState = TAKINGOFF;
timeLeft = 12;
AiAgent* droid = getDroid();
if (droid != nullptr) {
Locker dlocker(droid, player);
Vector3 playerPos = player->getWorldPosition();
float diffX = playerPos.getX();
float diffY = playerPos.getY();
float angle = atan2(diffY, diffX);
float newX = droid->getWorldPositionX() + (cos(angle) * 60.f);
float newY = droid->getWorldPositionY() + (sin(angle) * 60.f);
droid->setMovementState(AiAgent::PATROLLING);
droid->setAITemplate();
droid->setNextPosition(newX, droid->getPositionZ(), newY, nullptr);
} else {
scanState = FINISHED; // Probot is destroyed.
}
}
break;
case TAKINGOFF:
if (timeLeft <= 0) {
scanState = FINISHED;
} else if (timeLeft < 7 && droid->getPosture() == CreaturePosture::UPRIGHT) {
AiAgent* droid = getDroid();
if (droid != nullptr) {
Locker dlocker(droid);
droid->setPosture(CreaturePosture::SITTING, true); // Takeoff
}
}
break;
default:
error("Incorrect state");
break;
}
if (scanState != FINISHED) {
wildContrabandScanTask->reschedule(TASKDELAY);
} else {
cancelSession();
}
}
bool WildContrabandScanSessionImplementation::scanPrerequisitesMet(CreatureObject* player) {
return player != nullptr && player->isPlayerCreature();
}
void WildContrabandScanSessionImplementation::landProbeDroid(Zone* zone, CreatureObject* player) {
PlayClientEffectLoc* effect = new PlayClientEffectLoc("clienteffect/probot_delivery.cef", zone->getZoneName(), landingCoordinates.getX(), landingCoordinates.getZ(), landingCoordinates.getY(), 0, 0);
player->sendMessage(effect);
timeLeft = 3;
}
Vector3 WildContrabandScanSessionImplementation::getLandingCoordinates(Zone* zone, CreatureObject* player, Vector3& playerPos) {
if (zone == nullptr || player == nullptr) {
return playerPos;
}
PlanetManager* planetManager = zone->getPlanetManager();
if (planetManager == nullptr) {
return playerPos;
}
Vector3 coords = planetManager->getInSightSpawnPoint(player, 30, 120, 25);
float z = CollisionManager::getWorldFloorCollision(coords.getX(), coords.getY(), coords.getZ(), zone, true);
coords.setZ(z);
return coords;
}
void WildContrabandScanSessionImplementation::sendSystemMessage(CreatureObject* player, const String& messageName) {
StringIdChatParameter systemMessage;
systemMessage.setStringId("@imperial_presence/contraband_search:" + messageName);
player->sendSystemMessage(systemMessage);
}
AiAgent* WildContrabandScanSessionImplementation::getDroid() {
return weakDroid.get();
}
| 412 | 0.99131 | 1 | 0.99131 | game-dev | MEDIA | 0.877028 | game-dev | 0.999395 | 1 | 0.999395 |
Houzich/CUDA-GPU-Brute-Force-Mnemonic-Old-Electrum-V1 | 5,993 | bitcoin/chain.cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <chain.h>
#include <util/time.h>
std::string CBlockFileInfo::ToString() const
{
return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u...%u, time=%s...%s)", nBlocks, nSize, nHeightFirst, nHeightLast, FormatISO8601Date(nTimeFirst), FormatISO8601Date(nTimeLast));
}
void CChain::SetTip(CBlockIndex *pindex) {
if (pindex == nullptr) {
vChain.clear();
return;
}
vChain.resize(pindex->nHeight + 1);
while (pindex && vChain[pindex->nHeight] != pindex) {
vChain[pindex->nHeight] = pindex;
pindex = pindex->pprev;
}
}
CBlockLocator CChain::GetLocator(const CBlockIndex *pindex) const {
int nStep = 1;
std::vector<uint256> vHave;
vHave.reserve(32);
if (!pindex)
pindex = Tip();
while (pindex) {
vHave.push_back(pindex->GetBlockHash());
// Stop when we have added the genesis block.
if (pindex->nHeight == 0)
break;
// Exponentially larger steps back, plus the genesis block.
int nHeight = std::max(pindex->nHeight - nStep, 0);
if (Contains(pindex)) {
// Use O(1) CChain index if possible.
pindex = (*this)[nHeight];
} else {
// Otherwise, use O(log n) skiplist.
pindex = pindex->GetAncestor(nHeight);
}
if (vHave.size() > 10)
nStep *= 2;
}
return CBlockLocator(vHave);
}
const CBlockIndex *CChain::FindFork(const CBlockIndex *pindex) const {
if (pindex == nullptr) {
return nullptr;
}
if (pindex->nHeight > Height())
pindex = pindex->GetAncestor(Height());
while (pindex && !Contains(pindex))
pindex = pindex->pprev;
return pindex;
}
CBlockIndex* CChain::FindEarliestAtLeast(int64_t nTime, int height) const
{
std::pair<int64_t, int> blockparams = std::make_pair(nTime, height);
std::vector<CBlockIndex*>::const_iterator lower = std::lower_bound(vChain.begin(), vChain.end(), blockparams,
[](CBlockIndex* pBlock, const std::pair<int64_t, int>& blockparams) -> bool { return pBlock->GetBlockTimeMax() < blockparams.first || pBlock->nHeight < blockparams.second; });
return (lower == vChain.end() ? nullptr : *lower);
}
/** Turn the lowest '1' bit in the binary representation of a number into a '0'. */
int static inline InvertLowestOne(int n) { return n & (n - 1); }
/** Compute what height to jump back to with the CBlockIndex::pskip pointer. */
int static inline GetSkipHeight(int height) {
if (height < 2)
return 0;
// Determine which height to jump back to. Any number strictly lower than height is acceptable,
// but the following expression seems to perform well in simulations (max 110 steps to go back
// up to 2**18 blocks).
return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height);
}
const CBlockIndex* CBlockIndex::GetAncestor(int height) const
{
if (height > nHeight || height < 0) {
return nullptr;
}
const CBlockIndex* pindexWalk = this;
int heightWalk = nHeight;
while (heightWalk > height) {
int heightSkip = GetSkipHeight(heightWalk);
int heightSkipPrev = GetSkipHeight(heightWalk - 1);
if (pindexWalk->pskip != nullptr &&
(heightSkip == height ||
(heightSkip > height && !(heightSkipPrev < heightSkip - 2 &&
heightSkipPrev >= height)))) {
// Only follow pskip if pprev->pskip isn't better than pskip->pprev.
pindexWalk = pindexWalk->pskip;
heightWalk = heightSkip;
} else {
assert(pindexWalk->pprev);
pindexWalk = pindexWalk->pprev;
heightWalk--;
}
}
return pindexWalk;
}
CBlockIndex* CBlockIndex::GetAncestor(int height)
{
return const_cast<CBlockIndex*>(static_cast<const CBlockIndex*>(this)->GetAncestor(height));
}
void CBlockIndex::BuildSkip()
{
if (pprev)
pskip = pprev->GetAncestor(GetSkipHeight(nHeight));
}
arith_uint256 GetBlockProof(const CBlockIndex& block)
{
arith_uint256 bnTarget;
bool fNegative;
bool fOverflow;
bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow);
if (fNegative || fOverflow || bnTarget == 0)
return 0;
// We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256
// as it's too large for an arith_uint256. However, as 2**256 is at least as large
// as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1,
// or ~bnTarget / (bnTarget+1) + 1.
return (~bnTarget / (bnTarget + 1)) + 1;
}
int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params& params)
{
arith_uint256 r;
int sign = 1;
if (to.nChainWork > from.nChainWork) {
r = to.nChainWork - from.nChainWork;
} else {
r = from.nChainWork - to.nChainWork;
sign = -1;
}
r = r * arith_uint256(params.nPowTargetSpacing) / GetBlockProof(tip);
if (r.bits() > 63) {
return sign * std::numeric_limits<int64_t>::max();
}
return sign * int64_t(r.GetLow64());
}
/** Find the last common ancestor two blocks have.
* Both pa and pb must be non-nullptr. */
const CBlockIndex* LastCommonAncestor(const CBlockIndex* pa, const CBlockIndex* pb) {
if (pa->nHeight > pb->nHeight) {
pa = pa->GetAncestor(pb->nHeight);
} else if (pb->nHeight > pa->nHeight) {
pb = pb->GetAncestor(pa->nHeight);
}
while (pa != pb && pa && pb) {
pa = pa->pprev;
pb = pb->pprev;
}
// Eventually all chain branches meet at the genesis block.
assert(pa == pb);
return pa;
}
| 412 | 0.979363 | 1 | 0.979363 | game-dev | MEDIA | 0.508186 | game-dev | 0.998341 | 1 | 0.998341 |
luttje/Key2Joy | 2,005 | Core/Key2Joy.Core/LowLevelInput/SimulatedGamePad/ISimulatedGamePad.cs | using SimWinInput;
namespace Key2Joy.LowLevelInput.SimulatedGamePad;
/// <summary>
/// Represents a simulated gamepad device.
/// </summary>
public interface ISimulatedGamePad
{
/// <summary>
/// Gets the index of the simulated gamepad.
/// </summary>
int Index { get; }
/// <summary>
/// Plugs in the simulated gamepad.
/// </summary>
void PlugIn();
/// <summary>
/// Checks if the simulated gamepad is currently plugged in.
/// </summary>
/// <returns>True if the gamepad is plugged in; otherwise, false.</returns>
bool GetIsPluggedIn();
/// <summary>
/// Unplugs the simulated gamepad.
/// </summary>
void Unplug();
/// <summary>
/// Simulates pressing and holding a control on the gamepad.
/// </summary>
/// <param name="control">The control to simulate.</param>
/// <param name="holdTimeMS">The duration (in milliseconds) to hold the control (default is 50ms).</param>
void Use(GamePadControl control, int holdTimeMS = 50);
/// <summary>
/// Sets a specific control on the gamepad.
/// </summary>
/// <param name="control">The control to set.</param>
void SetControl(GamePadControl control);
/// <summary>
/// Releases a specific control on the gamepad.
/// </summary>
/// <param name="control">The control to release.</param>
void ReleaseControl(GamePadControl control);
/// <summary>
/// Get the raw input state from the GamePad
/// </summary>
/// <returns>The raw input state of the gamepad.</returns>
SimulatedGamePadState GetState();
/// <summary>
/// Resets the GamePad state to the natural at-rest stat
/// </summary>
void ResetState();
/// <summary>
/// Update any changes made to the state to be reflected in the gamepad
/// </summary>
void Update();
/// <summary>
/// Returns the gamepad info on this device
/// </summary>
/// <returns></returns>
IGamePadInfo GetInfo();
}
| 412 | 0.53706 | 1 | 0.53706 | game-dev | MEDIA | 0.71696 | game-dev | 0.556857 | 1 | 0.556857 |
SkyblockerMod/Skyblocker | 3,919 | src/main/java/de/hysky/skyblocker/skyblock/dungeon/puzzle/waterboard/Waterboard.java | package de.hysky.skyblocker.skyblock.dungeon.puzzle.waterboard;
import java.util.Locale;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.serialization.Codec;
import net.minecraft.block.Block;
import net.minecraft.block.Blocks;
import net.minecraft.command.argument.EnumArgumentType;
import net.minecraft.util.DyeColor;
import net.minecraft.util.StringIdentifiable;
import net.minecraft.util.math.BlockPos;
public class Waterboard {
public static final int BOARD_MIN_X = 6;
public static final int BOARD_MAX_X = 24;
public static final int BOARD_MIN_Y = 58;
public static final int BOARD_MAX_Y = 81;
public static final int BOARD_Z = 26;
// The top center of the grid, between the first two toggleable blocks
public static final BlockPos WATER_ENTRANCE_POSITION = new BlockPos(15, 78, 26);
public enum LeverType implements StringIdentifiable {
COAL(Blocks.COAL_BLOCK, new BlockPos(20, 61, 10), DyeColor.RED, new BlockPos[]{
new BlockPos(0, -2, 0), new BlockPos(2, -1, 1),
null, new BlockPos(5, -1, 0)
}),
GOLD(Blocks.GOLD_BLOCK, new BlockPos(20, 61, 15), DyeColor.YELLOW, new BlockPos[]{
new BlockPos(1, -1, 0), new BlockPos(3, -2, 0),
new BlockPos(-4, -1, 1), new BlockPos(1, 0, 0)
}),
QUARTZ(Blocks.QUARTZ_BLOCK, new BlockPos(20, 61, 20), DyeColor.LIGHT_GRAY, new BlockPos[]{
new BlockPos(1, -4, 1), new BlockPos(-1, 0, 0),
new BlockPos(1, 0, 0), new BlockPos(-1, 0, 1)
}),
DIAMOND(Blocks.DIAMOND_BLOCK, new BlockPos(10, 61, 20), DyeColor.CYAN, new BlockPos[]{
new BlockPos(0, -5, 1), new BlockPos(-2, -1, 0),
new BlockPos(-1, 0, 1), new BlockPos(-3, -4, 1)
}),
EMERALD(Blocks.EMERALD_BLOCK, new BlockPos(10, 61, 15), DyeColor.LIME, new BlockPos[]{
new BlockPos(-1, -10, 1), new BlockPos(1, 0, 1),
new BlockPos(-6, 0, 0), new BlockPos(1, -4, 0)
}),
TERRACOTTA(Blocks.TERRACOTTA, new BlockPos(10, 61, 10), DyeColor.ORANGE, new BlockPos[]{
new BlockPos(-1, -1, 1), new BlockPos(0, -3, 1),
null, new BlockPos(-4, -5, 1)
}),
WATER(Blocks.LAVA, new BlockPos(15, 60, 5), DyeColor.LIGHT_BLUE, null);
private static final Codec<LeverType> CODEC = StringIdentifiable.createCodec(LeverType::values);
public final Block block;
public final BlockPos leverPos;
public final DyeColor color;
// Holds positions where the corresponding block is present in the initial state of each variant, offset from the water entrance position
// This is more reliable at detecting if the lever is active than looking at the lever's block state
public final BlockPos[] initialPositions;
LeverType(Block block, BlockPos leverPos, DyeColor color, BlockPos[] initialPositions) {
this.block = block;
this.leverPos = leverPos;
this.color = color;
this.initialPositions = initialPositions;
}
public static LeverType fromName(String name) {
for (LeverType leverType : LeverType.values()) {
if (leverType.name().equalsIgnoreCase(name)) {
return leverType;
}
}
return null;
}
public static LeverType fromBlock(Block block) {
for (LeverType leverType : LeverType.values()) {
if (leverType.block == block) {
return leverType;
}
}
return null;
}
public static LeverType fromPos(BlockPos leverPos) {
for (LeverType leverType : LeverType.values()) {
if (leverPos.equals(leverType.leverPos)) {
return leverType;
}
}
return null;
}
@Override
public String asString() {
return name().toLowerCase(Locale.ENGLISH);
}
public static class LeverTypeArgumentType extends EnumArgumentType<LeverType> {
private LeverTypeArgumentType() {
super(CODEC, LeverType::values);
}
public static LeverTypeArgumentType leverType() {
return new LeverTypeArgumentType();
}
public static <S> LeverType getLeverType(CommandContext<S> context, String name) {
return context.getArgument(name, LeverType.class);
}
}
}
}
| 412 | 0.851528 | 1 | 0.851528 | game-dev | MEDIA | 0.87028 | game-dev | 0.90511 | 1 | 0.90511 |
Monkestation/Monkestation2.0 | 2,312 | code/modules/mining/equipment/kinetic_crusher/crusher_variants/hammer.dm | /obj/item/kinetic_crusher/hammer
icon = 'icons/obj/mining.dmi'
icon_state = "PKHammer"
inhand_icon_state = "PKHammer0"
lefthand_file = 'icons/mob/inhands/weapons/hammers_lefthand.dmi'
righthand_file = 'icons/mob/inhands/weapons/hammers_righthand.dmi'
worn_icon = 'icons/mob/clothing/back.dmi'
worn_icon_state = "PKHammer0"
name = "proto-kinetic hammer"
desc = "Somehow research and development managed to make the proto-kinetic crusher even bigger, allowing more parts to be fit inside and increase the power output. \
This increased power output allows it to surpass the power generated by the standard crusher, while also pushing back the target. Unfortunetly the flat head \
results in backstabs being impossible."
force = 0
w_class = WEIGHT_CLASS_HUGE
slot_flags = ITEM_SLOT_BACK
throwforce = 5
throw_speed = 4
armour_penetration = 0
custom_materials = list(/datum/material/iron=1150, /datum/material/glass=2075)
hitsound = 'sound/weapons/sonic_jackhammer.ogg'
attack_verb_continuous = list("slams", "crushes", "smashes", "flattens", "pounds")
attack_verb_simple = list("slam", "crush", "smash", "flatten", "pound")
sharpness = NONE
actions_types = list(/datum/action/item_action/toggle_light)
obj_flags = UNIQUE_RENAME
light_system = OVERLAY_LIGHT
light_outer_range = 5
light_on = FALSE
charged = TRUE
detonation_damage = 70
backstab_bonus = 0
overrides_main = TRUE
overrides_twohandrequired = FALSE
override_twohandedsprite = TRUE
force_wielded = 20
override_light_overlay_sprite = TRUE
/obj/item/kinetic_crusher/hammer/Initialize(mapload)
. = ..()
AddComponent(/datum/component/two_handed, force_unwielded=0, force_wielded=force_wielded)
/obj/item/kinetic_crusher/hammer/attack(mob/living/target, mob/living/user)
var/relative_direction = get_cardinal_dir(src, target)
var/atom/throw_target = get_edge_target_turf(target, relative_direction)
. = ..()
if(HAS_TRAIT(user, TRAIT_PACIFISM) || !HAS_TRAIT(src, TRAIT_WIELDED))
return
else if(!QDELETED(target) && !target.anchored)
var/whack_speed = (2)
target.throw_at(throw_target, 2, whack_speed, user, gentle = TRUE)
/obj/item/kinetic_crusher/hammer/update_icon_state()
inhand_icon_state = "PKHammer[HAS_TRAIT(src, TRAIT_WIELDED)]" // this is not icon_state and not supported by 2hcomponent
return ..()
| 412 | 0.936042 | 1 | 0.936042 | game-dev | MEDIA | 0.980342 | game-dev | 0.956032 | 1 | 0.956032 |
ReversecLabs/C3 | 3,106 | Src/Core/BaseQuery.cpp | #include "StdAfx.h"
#include "BaseQuery.h"
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
FSecure::C3::Core::BaseQuery::BaseQuery(std::weak_ptr<DeviceBridge> sender)
: m_ReceivedOrWillBeSent(true)
, m_SequenceNumber(0) /// THIS IS WRONG
, m_SenderChannel(sender)
{
// TODO, parse query.
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
FSecure::C3::Core::BaseQuery::BaseQuery(ResponseType responseType)
: m_ReceivedOrWillBeSent(false)
, m_SequenceNumber(GenerateSequenceNumber())
, m_ResponseType(responseType)
{
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void FSecure::C3::Core::BaseQuery::SetResponseType(ResponseType responseType)
{
m_ResponseType = responseType;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
FSecure::ByteVector FSecure::C3::Core::BaseQuery::CompileQueryHeader() const
{
if (m_ResponseType == ResponseType::None)
return ByteVector{}.Write(GetProcedureNumber());
return ByteVector{}.Write(~GetProcedureNumber(), BuildSequenceNumberField(static_cast<std::uint8_t>(m_ResponseType)));
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::uint8_t FSecure::C3::Core::BaseQuery::BuildSequenceNumberField(std::uint8_t statusBits) const
{
return (m_SequenceNumber & (3 << s_SequenceNumberBitLength)) & (statusBits << s_SequenceNumberBitLength);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
FSecure::C3::Core::BaseQuery::SequenceNumberFieldUnderlyingType FSecure::C3::Core::BaseQuery::GenerateSequenceNumber()
{
static std::mutex accessMutex;
std::scoped_lock lock(accessMutex);
static SequenceNumberFieldUnderlyingType nextGlobalSequenceNumber = 0;
if (nextGlobalSequenceNumber & (3 << s_SequenceNumberBitLength))
return nextGlobalSequenceNumber = 0;
return nextGlobalSequenceNumber++;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::weak_ptr<FSecure::C3::Core::DeviceBridge> FSecure::C3::Core::BaseQuery::GetSenderChannel()
{
return m_SenderChannel;
}
| 412 | 0.624968 | 1 | 0.624968 | game-dev | MEDIA | 0.331677 | game-dev | 0.578453 | 1 | 0.578453 |
harfang3d/harfang3d | 2,358 | extern/bullet3/BulletDynamics/ConstraintSolver/btSolverConstraint.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_SOLVER_CONSTRAINT_H
#define BT_SOLVER_CONSTRAINT_H
class btRigidBody;
#include "LinearMath/btVector3.h"
#include "LinearMath/btMatrix3x3.h"
#include "btJacobianEntry.h"
#include "LinearMath/btAlignedObjectArray.h"
//#define NO_FRICTION_TANGENTIALS 1
#include "btSolverBody.h"
///1D constraint along a normal axis between bodyA and bodyB. It can be combined to solve contact and friction constraints.
ATTRIBUTE_ALIGNED16(struct)
btSolverConstraint
{
BT_DECLARE_ALIGNED_ALLOCATOR();
btVector3 m_relpos1CrossNormal;
btVector3 m_contactNormal1;
btVector3 m_relpos2CrossNormal;
btVector3 m_contactNormal2; //usually m_contactNormal2 == -m_contactNormal1, but not always
btVector3 m_angularComponentA;
btVector3 m_angularComponentB;
mutable btSimdScalar m_appliedPushImpulse;
mutable btSimdScalar m_appliedImpulse;
btScalar m_friction;
btScalar m_jacDiagABInv;
btScalar m_rhs;
btScalar m_cfm;
btScalar m_lowerLimit;
btScalar m_upperLimit;
btScalar m_rhsPenetration;
union {
void* m_originalContactPoint;
btScalar m_unusedPadding4;
int m_numRowsForNonContactConstraint;
};
int m_overrideNumSolverIterations;
int m_frictionIndex;
int m_solverBodyIdA;
int m_solverBodyIdB;
enum btSolverConstraintType
{
BT_SOLVER_CONTACT_1D = 0,
BT_SOLVER_FRICTION_1D
};
};
typedef btAlignedObjectArray<btSolverConstraint> btConstraintArray;
#endif //BT_SOLVER_CONSTRAINT_H
| 412 | 0.857266 | 1 | 0.857266 | game-dev | MEDIA | 0.997063 | game-dev | 0.912622 | 1 | 0.912622 |
TheAnswer/Core3 | 1,998 | MMOCoreORB/src/server/zone/objects/creature/commands/SetPerformanceBuffTargetCommand.h | /*
Copyright <SWGEmu>
See file COPYING for copying conditions.*/
#ifndef SETPERFORMANCEBUFFTARGETCOMMAND_H_
#define SETPERFORMANCEBUFFTARGETCOMMAND_H_
class SetPerformanceBuffTargetCommand : public QueueCommand {
public:
SetPerformanceBuffTargetCommand(const String& name, ZoneProcessServer* server) : QueueCommand(name, server) {
}
int doQueueCommand(CreatureObject* creature, const uint64& target, const UnicodeString& arguments) const {
if (!checkStateMask(creature))
return INVALIDSTATE;
if (!checkInvalidLocomotions(creature))
return INVALIDLOCOMOTION;
if(!creature->isPlayerCreature())
return GENERALERROR;
ManagedReference<PlayerObject*> ghost = creature->getPlayerObject();
if (ghost == nullptr)
return GENERALERROR;
ZoneServer* zoneServer = server->getZoneServer();
if (zoneServer == nullptr)
return GENERALERROR;
ManagedReference<SceneObject*> targetObject = zoneServer->getObject(target);
if (targetObject == nullptr || targetObject == creature || !targetObject->isPlayerCreature()) {
creature->sendSystemMessage("@performance:buff_invalid_target_self");
return GENERALERROR;
}
if (!CollisionManager::checkLineOfSight(targetObject, creature)) {
creature->sendSystemMessage("@healing:no_line_of_sight"); // You cannot see your target.
return GENERALERROR;
}
CreatureObject* targetCreature = targetObject->asCreatureObject();
if (targetCreature == nullptr)
return GENERALERROR;
StringIdChatParameter selfMessage;
StringIdChatParameter otherMessage;
selfMessage.setStringId("performance", "buff_set_target_self");
selfMessage.setTT(targetCreature->getDisplayedName());
otherMessage.setStringId("performance", "buff_set_target_other");
otherMessage.setTU(creature->getDisplayedName());
creature->sendSystemMessage(selfMessage);
targetCreature->sendSystemMessage(otherMessage);
ghost->setPerformanceBuffTarget(target);
return SUCCESS;
}
};
#endif //SETPERFORMANCEBUFFTARGETCOMMAND_H_
| 412 | 0.821717 | 1 | 0.821717 | game-dev | MEDIA | 0.854111 | game-dev | 0.889656 | 1 | 0.889656 |
open-goal/jak-project | 22,638 | goalc/emitter/ObjectGenerator.cpp | /*!
* @file ObjectGenerator.cpp
* Tool to build GOAL object files. Will eventually support v3 and v4.
*
* There are 5 steps:
* 1. The user adds static data / instructions and specifies links.
* 2. The functions and static data are laid out in memory
* 3. The user specified links are updated according to the memory layout, and jumps are patched
* 4. The link table is generated for each segment
* 5. All segments and link tables are put into a final object file, along with a header.
*
* Step 1 can be done with the add_.... and link_... functions
* Steps 2 - 5 are done in generate_data_vX()
*/
#include "ObjectGenerator.h"
#include "common/goal_constants.h"
#include "common/type_system/TypeSystem.h"
#include "common/versions/versions.h"
#include "goalc/debugger/DebugInfo.h"
#include "fmt/format.h"
namespace emitter {
ObjectGenerator::ObjectGenerator(GameVersion version) : m_version(version) {}
/*!
* Build an object file with the v3 format.
*/
ObjectFileData ObjectGenerator::generate_data_v3(const TypeSystem* ts) {
ObjectFileData out;
// do functions (step 2, part 1)
for (int seg = N_SEG; seg-- > 0;) {
auto& data = m_data_by_seg.at(seg);
// loop over functions in this segment
for (auto& function : m_function_data_by_seg.at(seg)) {
// align
while (data.size() % function.min_align) {
insert_data<u8>(seg, 0);
}
// add a type tag link
m_type_ptr_links_by_seg.at(seg)["function"].push_back(data.size());
// add room for a type tag
for (int i = 0; i < POINTER_SIZE; i++) {
insert_data<u8>(seg, 0xae);
}
// add debug info for the function start
function.debug->offset_in_seg = m_data_by_seg.at(seg).size();
function.debug->seg = seg;
// insert instructions!
for (size_t instr_idx = 0; instr_idx < function.instructions.size(); instr_idx++) {
const auto& instr = function.instructions[instr_idx];
u8 temp[128];
auto count = instr.emit(temp);
ASSERT(count < 128);
function.instruction_to_byte_in_data.push_back(data.size());
function.debug->instructions.at(instr_idx).offset =
data.size() - function.debug->offset_in_seg;
for (int i = 0; i < count; i++) {
insert_data<u8>(seg, temp[i]);
}
}
function.debug->length = m_data_by_seg.at(seg).size() - function.debug->offset_in_seg;
}
}
// do static data layout (step 2, part 2)
for (int seg = N_SEG; seg-- > 0;) {
auto& data = m_data_by_seg.at(seg);
for (auto& s : m_static_data_by_seg.at(seg)) {
// align
while (data.size() % s.min_align) {
insert_data<u8>(seg, 0);
}
s.location = data.size();
data.insert(data.end(), s.data.begin(), s.data.end());
}
}
// step 3, cleaning up things now that we know the memory layout
for (int seg = N_SEG; seg-- > 0;) {
handle_temp_static_type_links(seg);
handle_temp_static_sym_links(seg);
handle_temp_jump_links(seg);
handle_temp_instr_sym_links(seg);
handle_temp_rip_func_links(seg);
handle_temp_rip_data_links(seg);
handle_temp_static_ptr_links(seg);
}
// step 4, generate the link table
for (int seg = N_SEG; seg-- > 0;) {
emit_link_table(seg, ts);
}
// step 4.5, collect final result of code/object generation for compiler debugging disassembly
for (int seg = 0; seg < N_SEG; seg++) {
for (auto& function : m_function_data_by_seg.at(seg)) {
auto start = m_data_by_seg.at(seg).begin() + function.instruction_to_byte_in_data.at(0);
auto end = start + function.debug->length;
function.debug->generated_code = {start, end};
}
}
// step 5, build header and combine sections
out.header = generate_header_v3();
out.segment_data = std::move(m_data_by_seg);
out.link_tables = std::move(m_link_by_seg);
return out;
}
/*!
* Add a new function to seg, and return a FunctionRecord which can be used to specify this
* new function.
*/
FunctionRecord ObjectGenerator::add_function_to_seg(int seg,
FunctionDebugInfo* debug,
int min_align) {
FunctionRecord rec;
rec.seg = seg;
rec.func_id = int(m_function_data_by_seg.at(seg).size());
rec.debug = debug;
m_function_data_by_seg.at(seg).emplace_back();
m_function_data_by_seg.at(seg).back().min_align = min_align;
m_function_data_by_seg.at(seg).back().debug = debug;
m_all_function_records.push_back(rec);
return rec;
}
FunctionRecord ObjectGenerator::get_existing_function_record(int f_idx) {
return m_all_function_records.at(f_idx);
}
/*!
* Add a new IR instruction to the function. An IR instruction may contain 0, 1, or multiple
* actual Instructions. These Instructions can be added with add_instruction. The IR_Record
* can be used as a label for jump targets.
*/
IR_Record ObjectGenerator::add_ir(const FunctionRecord& func) {
IR_Record rec;
rec.seg = func.seg;
rec.func_id = func.func_id;
auto& func_data = m_function_data_by_seg.at(rec.seg).at(rec.func_id);
rec.ir_id = int(func_data.ir_to_instruction.size());
func_data.ir_to_instruction.push_back(int(func_data.instructions.size()));
return rec;
}
/*!
* Get an IR Record that points to an IR that hasn't been added yet. This can be used to create
* jumps forward to things we haven't seen yet.
*/
IR_Record ObjectGenerator::get_future_ir_record(const FunctionRecord& func, int ir_id) {
ASSERT(func.func_id == int(m_function_data_by_seg.at(func.seg).size()) - 1);
IR_Record rec;
rec.seg = func.seg;
rec.func_id = func.func_id;
rec.ir_id = ir_id;
return rec;
}
IR_Record ObjectGenerator::get_future_ir_record_in_same_func(const IR_Record& irec, int ir_id) {
IR_Record rec;
rec.seg = irec.seg;
rec.func_id = irec.func_id;
rec.ir_id = ir_id;
return rec;
}
/*!
* Add a new Instruction for the given IR instruction.
*/
InstructionRecord ObjectGenerator::add_instr(Instruction inst, IR_Record ir) {
// only this second condition is an actual error.
ASSERT(ir.ir_id ==
int(m_function_data_by_seg.at(ir.seg).at(ir.func_id).ir_to_instruction.size()) - 1);
InstructionRecord rec;
rec.seg = ir.seg;
rec.func_id = ir.func_id;
rec.ir_id = ir.ir_id;
auto& func_data = m_function_data_by_seg.at(rec.seg).at(rec.func_id);
rec.instr_id = int(func_data.instructions.size());
func_data.instructions.emplace_back(inst);
auto debug = m_function_data_by_seg.at(ir.seg).at(ir.func_id).debug;
debug->instructions.emplace_back(inst, InstructionInfo::Kind::IR, ir.ir_id);
return rec;
}
void ObjectGenerator::add_instr_no_ir(FunctionRecord func,
Instruction inst,
InstructionInfo::Kind kind) {
auto info = InstructionInfo(inst, kind);
m_function_data_by_seg.at(func.seg).at(func.func_id).instructions.emplace_back(inst);
func.debug->instructions.push_back(info);
}
/*!
* Create a new static object in the given segment.
*/
StaticRecord ObjectGenerator::add_static_to_seg(int seg, int min_align) {
StaticRecord rec;
rec.seg = seg;
rec.static_id = m_static_data_by_seg.at(seg).size();
m_static_data_by_seg.at(seg).emplace_back();
m_static_data_by_seg.at(seg).back().min_align = min_align;
return rec;
}
std::vector<u8>& ObjectGenerator::get_static_data(const StaticRecord& rec) {
return m_static_data_by_seg.at(rec.seg).at(rec.static_id).data;
}
/*!
* Add linking data to add a type pointer in rec at offset.
* This will add an entry to the linking data, which will get patched at runtime, during linking.
*/
void ObjectGenerator::link_static_type_ptr(StaticRecord rec,
int offset,
const std::string& type_name) {
StaticTypeLink link;
link.offset = offset;
link.rec = rec;
m_static_type_temp_links_by_seg.at(rec.seg)[type_name].push_back(link);
}
/*!
* This will patch the jump_instr to jump to destination. This happens during compile time and
* doesn't add anything to the link table. The jump_instr must already be emitted, however the
* destination can be a future IR. To get a reference to a future IR, you must know the index and
* use get_future_ir.
*/
void ObjectGenerator::link_instruction_jump(InstructionRecord jump_instr, IR_Record destination) {
// must jump within our own function.
ASSERT(jump_instr.seg == destination.seg);
ASSERT(jump_instr.func_id == destination.func_id);
m_jump_temp_links_by_seg.at(jump_instr.seg).push_back({jump_instr, destination});
}
/*!
* Patch a load/store instruction to refer to a symbol. This patching will happen at runtime
* linking. The instruction must use 32-bit immediate displacement addressing, relative to the
* symbol table.
*/
void ObjectGenerator::link_instruction_symbol_mem(const InstructionRecord& rec,
const std::string& name) {
m_symbol_instr_temp_links_by_seg.at(rec.seg)[name].push_back({rec, true});
}
/*!
* Patch an add instruction to generate a pointer to a symbol. This patching will happen during
* runtime linking. The instruction should be an "add st, imm32".
*/
void ObjectGenerator::link_instruction_symbol_ptr(const InstructionRecord& rec,
const std::string& name) {
m_symbol_instr_temp_links_by_seg.at(rec.seg)[name].push_back({rec, false});
}
/*!
* Insert a GOAL pointer to a symbol inside of static data. This patching will happen during runtime
* linking.
*/
void ObjectGenerator::link_static_symbol_ptr(StaticRecord rec,
int offset,
const std::string& name) {
m_static_sym_temp_links_by_seg.at(rec.seg)[name].push_back({rec, offset});
}
/*!
* Insert a pointer to other static data. This patching will happen during runtime linking.
* The source and destination must be in the same segment.
*/
void ObjectGenerator::link_static_pointer_to_data(const StaticRecord& source,
int source_offset,
const StaticRecord& dest,
int dest_offset) {
StaticDataPointerLink link;
link.source = source;
link.dest = dest;
link.offset_in_source = source_offset;
link.offset_in_dest = dest_offset;
ASSERT(link.source.seg == link.dest.seg);
m_static_data_temp_ptr_links_by_seg.at(source.seg).push_back(link);
}
/*!
* Insert a pointer to a function in static data.
* The patching will happen during runtime linking.
*/
void ObjectGenerator::link_static_pointer_to_function(const StaticRecord& source,
int source_offset,
const FunctionRecord& target_func) {
StaticFunctionPointerLink link;
link.source = source;
link.offset_in_source = source_offset;
link.dest = target_func;
ASSERT(target_func.seg == source.seg);
m_static_function_temp_ptr_links_by_seg.at(source.seg).push_back(link);
}
void ObjectGenerator::link_instruction_static(const InstructionRecord& instr,
const StaticRecord& target_static,
int offset) {
m_rip_data_temp_links_by_seg.at(instr.seg).push_back({instr, target_static, offset});
}
void ObjectGenerator::link_instruction_to_function(const InstructionRecord& instr,
const FunctionRecord& target_func) {
m_rip_func_temp_links_by_seg.at(instr.seg).push_back({instr, target_func});
}
/*!
* Convert:
* m_static_type_temp_links_by_seg -> m_type_ptr_links_by_seg
* after memory layout is done and before link tables are generated
*/
void ObjectGenerator::handle_temp_static_type_links(int seg) {
for (const auto& type_links : m_static_type_temp_links_by_seg.at(seg)) {
const auto& type_name = type_links.first;
for (const auto& link : type_links.second) {
ASSERT(seg == link.rec.seg);
const auto& static_object = m_static_data_by_seg.at(seg).at(link.rec.static_id);
int total_offset = static_object.location + link.offset;
m_type_ptr_links_by_seg.at(seg)[type_name].push_back(total_offset);
}
}
}
/*!
* Convert:
* m_static_sym_temp_links_by_seg -> m_sym_links_by_seg
* after memory layout is done and before link tables are generated
*/
void ObjectGenerator::handle_temp_static_sym_links(int seg) {
for (const auto& sym_links : m_static_sym_temp_links_by_seg.at(seg)) {
const auto& sym_name = sym_links.first;
for (const auto& link : sym_links.second) {
ASSERT(seg == link.rec.seg);
const auto& static_object = m_static_data_by_seg.at(seg).at(link.rec.static_id);
int total_offset = static_object.location + link.offset;
m_sym_links_by_seg.at(seg)[sym_name].push_back(total_offset);
}
}
}
/*!
* m_static_temp_ptr_links_by_seg -> m_pointer_links_by_seg
*/
void ObjectGenerator::handle_temp_static_ptr_links(int seg) {
for (const auto& link : m_static_data_temp_ptr_links_by_seg.at(seg)) {
const auto& source_object = m_static_data_by_seg.at(seg).at(link.source.static_id);
const auto& dest_object = m_static_data_by_seg.at(seg).at(link.dest.static_id);
PointerLink result_link;
result_link.segment = seg;
result_link.source = source_object.location + link.offset_in_source;
result_link.dest = dest_object.location + link.offset_in_dest;
m_pointer_links_by_seg.at(seg).push_back(result_link);
}
for (const auto& link : m_static_function_temp_ptr_links_by_seg.at(seg)) {
const auto& source_object = m_static_data_by_seg.at(seg).at(link.source.static_id);
const auto& dest_function = m_function_data_by_seg.at(seg).at(link.dest.func_id);
ASSERT(link.dest.seg == seg);
int loc = dest_function.instruction_to_byte_in_data.at(0);
PointerLink result_link;
result_link.segment = seg;
result_link.source = source_object.location + link.offset_in_source;
result_link.dest = loc;
m_pointer_links_by_seg.at(seg).push_back(result_link);
}
}
/*!
* m_jump_temp_links_by_seg patching after memory layout is done
*/
void ObjectGenerator::handle_temp_jump_links(int seg) {
for (const auto& link : m_jump_temp_links_by_seg.at(seg)) {
// we need to compute three offsets, all relative to the start of data.
// 1). the location of the patch (the immediate of the opcode)
// 2). the value of RIP at the jump (the instruction after the jump, on x86)
// 3). the value of RIP we want
const auto& function = m_function_data_by_seg.at(seg).at(link.jump_instr.func_id);
ASSERT(link.jump_instr.func_id == link.dest.func_id);
ASSERT(link.jump_instr.seg == seg);
ASSERT(link.dest.seg == seg);
const auto& jump_instr = function.instructions.at(link.jump_instr.instr_id);
ASSERT(jump_instr.get_imm_size() == 4);
// 1). patch = instruction location + location of imm in instruction.
int patch_location = function.instruction_to_byte_in_data.at(link.jump_instr.instr_id) +
jump_instr.offset_of_imm();
// 2). source rip = jump instr + 1 location
int source_rip = function.instruction_to_byte_in_data.at(link.jump_instr.instr_id + 1);
// 3). dest rip = first instruction of dest IR
int dest_rip =
function.instruction_to_byte_in_data.at(function.ir_to_instruction.at(link.dest.ir_id));
patch_data<s32>(seg, patch_location, dest_rip - source_rip);
}
}
/*!
* Convert:
* m_symbol_instr_temp_links_by_seg -> m_sym_links_by_seg
* after memory layout is done and before link tables are generated
*/
void ObjectGenerator::handle_temp_instr_sym_links(int seg) {
for (const auto& links : m_symbol_instr_temp_links_by_seg.at(seg)) {
const auto& sym_name = links.first;
for (const auto& link : links.second) {
ASSERT(seg == link.rec.seg);
const auto& function = m_function_data_by_seg.at(seg).at(link.rec.func_id);
const auto& instruction = function.instructions.at(link.rec.instr_id);
int offset_of_instruction = function.instruction_to_byte_in_data.at(link.rec.instr_id);
int offset_in_instruction =
link.is_mem_access ? instruction.offset_of_disp() : instruction.offset_of_imm();
if (link.is_mem_access) {
ASSERT(instruction.get_disp_size() == 4);
} else {
ASSERT(instruction.get_imm_size() == 4);
}
m_sym_links_by_seg.at(seg)[sym_name].push_back(offset_of_instruction + offset_in_instruction);
}
}
}
void ObjectGenerator::handle_temp_rip_func_links(int seg) {
for (const auto& link : m_rip_func_temp_links_by_seg.at(seg)) {
RipLink result;
result.instr = link.instr;
result.target_segment = link.target.seg;
const auto& target_func = m_function_data_by_seg.at(link.target.seg).at(link.target.func_id);
result.offset_in_segment = target_func.instruction_to_byte_in_data.at(0);
m_rip_links_by_seg.at(seg).push_back(result);
}
}
void ObjectGenerator::handle_temp_rip_data_links(int seg) {
for (const auto& link : m_rip_data_temp_links_by_seg.at(seg)) {
RipLink result;
result.instr = link.instr;
result.target_segment = link.data.seg;
const auto& target = m_static_data_by_seg.at(link.data.seg).at(link.data.static_id);
result.offset_in_segment = target.location + link.offset;
m_rip_links_by_seg.at(seg).push_back(result);
}
}
namespace {
template <typename T>
uint32_t push_data(const T& data, std::vector<u8>& v) {
auto insert = v.size();
v.resize(insert + sizeof(T));
memcpy(v.data() + insert, &data, sizeof(T));
return sizeof(T);
}
} // namespace
void ObjectGenerator::emit_link_type_pointer(int seg, const TypeSystem* ts) {
auto& out = m_link_by_seg.at(seg);
for (auto& rec : m_type_ptr_links_by_seg.at(seg)) {
u32 size = rec.second.size();
if (!size) {
continue;
}
// start
out.push_back(LINK_TYPE_PTR);
// name
for (char c : rec.first) {
out.push_back(c);
}
out.push_back(0);
// method count
switch (m_version) {
case GameVersion::Jak1:
out.push_back(ts->get_type_method_count(rec.first));
break;
case GameVersion::Jak2:
case GameVersion::Jak3: // jak3 opengoal uses same format as jak2 for code.
// the linker/intern_type functions do the +3.
out.push_back(ts->get_type_method_count(rec.first) / 4);
break;
default:
ASSERT(false);
}
// number of links
push_data<u32>(size, out);
for (auto& r : rec.second) {
push_data<s32>(r, out);
}
}
}
void ObjectGenerator::emit_link_symbol(int seg) {
auto& out = m_link_by_seg.at(seg);
for (auto& rec : m_sym_links_by_seg.at(seg)) {
out.push_back(LINK_SYMBOL_OFFSET);
for (char c : rec.first) {
out.push_back(c);
}
out.push_back(0);
// number of links
push_data<u32>(rec.second.size(), out);
for (auto& r : rec.second) {
push_data<s32>(r, out);
}
}
}
void ObjectGenerator::emit_link_ptr(int seg) {
auto& out = m_link_by_seg.at(seg);
for (auto& rec : m_pointer_links_by_seg.at(seg)) {
out.push_back(LINK_PTR);
ASSERT(rec.dest >= 0);
ASSERT(rec.source >= 0);
push_data<u32>(rec.source, out);
push_data<u32>(rec.dest, out);
}
}
void ObjectGenerator::emit_link_rip(int seg) {
auto& out = m_link_by_seg.at(seg);
for (auto& rec : m_rip_links_by_seg.at(seg)) {
// kind (u8)
// target segment (u8)
// offset in current (u32)
// offset into target (u32)
// patch loc (u32) (todo, make this a s8 offset from offset into current?)
// kind
out.push_back(LINK_DISTANCE_TO_OTHER_SEG_32);
// target segment
out.push_back(rec.target_segment);
// offset into current
const auto& src_func = m_function_data_by_seg.at(rec.instr.seg).at(rec.instr.func_id);
push_data<u32>(src_func.instruction_to_byte_in_data.at(rec.instr.instr_id + 1), out);
// offset into target
ASSERT(rec.offset_in_segment >= 0);
push_data<u32>(rec.offset_in_segment, out);
// patch location
const auto& src_instr = src_func.instructions.at(rec.instr.instr_id);
ASSERT(src_instr.get_disp_size() == 4);
push_data<u32>(
src_func.instruction_to_byte_in_data.at(rec.instr.instr_id) + src_instr.offset_of_disp(),
out);
}
}
void ObjectGenerator::emit_link_table(int seg, const TypeSystem* ts) {
emit_link_symbol(seg);
emit_link_type_pointer(seg, ts);
emit_link_rip(seg);
emit_link_ptr(seg);
m_link_by_seg.at(seg).push_back(LINK_TABLE_END);
}
/*!
* Generate linker header.
*/
std::vector<u8> ObjectGenerator::generate_header_v3() {
std::vector<u8> result;
// header starts with a "GOAL" magic word
result.push_back('G');
result.push_back('O');
result.push_back('A');
result.push_back('L');
u32 offset = 0; // the GOAL doesn't count toward the offset, first 4 bytes are killed.
// then, the version. todo, bump the version once we use this!
offset += push_data<u16>(versions::GOAL_VERSION_MAJOR, result);
offset += push_data<u16>(versions::GOAL_VERSION_MINOR, result);
// the object file version
offset += push_data<u32>(3, result);
// the segment count
offset += push_data<u32>(N_SEG, result);
offset += sizeof(u32) * N_SEG * 4; // 4 u32's per segment
offset += 4;
struct SizeOffset {
uint32_t offset, size;
};
struct SizeOffsetTable {
SizeOffset link_seg[N_SEG];
SizeOffset code_seg[N_SEG];
};
SizeOffsetTable table;
int total_link_size = 0;
for (int i = N_SEG; i-- > 0;) {
table.link_seg[i].offset = offset; // start of the link
table.link_seg[i].size = m_link_by_seg[i].size(); // size of the link data
offset += m_link_by_seg[i].size(); // to next link data
total_link_size += m_link_by_seg[i].size(); // need to track this.
}
offset = 0;
for (int i = N_SEG; i-- > 0;) {
table.code_seg[i].offset = offset;
table.code_seg[i].size = m_data_by_seg[i].size();
offset += m_data_by_seg[i].size();
}
push_data<SizeOffsetTable>(table, result);
push_data<uint32_t>(64 + 4 + total_link_size, result); // todo, make these numbers less magic.
return result;
}
ObjectGeneratorStats ObjectGenerator::get_stats() const {
return m_stats;
}
void ObjectGenerator::count_eliminated_move() {
m_stats.moves_eliminated++;
}
} // namespace emitter
| 412 | 0.720533 | 1 | 0.720533 | game-dev | MEDIA | 0.692856 | game-dev | 0.565898 | 1 | 0.565898 |
SkelletonX/DDTank4.1 | 5,086 | Source Server/Game.Logic/PetEffects/PetEffectList.cs | // Decompiled with JetBrains decompiler
// Type: Game.Logic.PetEffects.PetEffectList
// Assembly: Game.Logic, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: E8B04D54-7E5B-47C4-9280-AF82495F6281
// Assembly location: C:\Users\Pham Van Hungg\Desktop\Decompiler\Road\Game.Logic.dll
using Game.Logic.Phy.Object;
using log4net;
using System;
using System.Collections;
using System.Reflection;
namespace Game.Logic.PetEffects
{
public class PetEffectList
{
private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected volatile sbyte m_changesCount;
protected ArrayList m_effects;
protected int m_immunity;
protected readonly Living m_owner;
public PetEffectList(Living owner, int immunity)
{
this.m_owner = owner;
this.m_effects = new ArrayList(5);
this.m_immunity = immunity;
}
public virtual bool Add(AbstractPetEffect effect)
{
if (!this.CanAddEffect(effect.TypeValue))
return false;
lock (this.m_effects)
this.m_effects.Add((object)effect);
effect.OnAttached(this.m_owner);
this.OnEffectsChanged(effect);
return true;
}
public void BeginChanges()
{
++this.m_changesCount;
}
public bool CanAddEffect(int id)
{
if (id <= 350 && id >= 0)
return (1 << id - 1 & this.m_immunity) == 0;
return true;
}
public virtual void CommitChanges()
{
if (--this.m_changesCount < (sbyte)0)
{
if (PetEffectList.log.IsWarnEnabled)
PetEffectList.log.Warn((object)("changes count is less than zero, forgot BeginChanges()?\n" + Environment.StackTrace));
this.m_changesCount = (sbyte)0;
}
if ((uint)this.m_changesCount > 0U)
return;
this.UpdateChangedEffects();
}
public virtual IList GetAllOfType(Type effectType)
{
ArrayList arrayList = new ArrayList();
lock (this.m_effects)
{
foreach (AbstractPetEffect effect in this.m_effects)
{
if (effect.GetType().Equals(effectType))
arrayList.Add((object)effect);
}
}
return (IList)arrayList;
}
public virtual AbstractPetEffect GetOfType(ePetEffectType effectType)
{
lock (this.m_effects)
{
foreach (AbstractPetEffect effect in this.m_effects)
{
if (effect.Type == effectType)
return effect;
}
}
return (AbstractPetEffect)null;
}
public virtual void OnEffectsChanged(AbstractPetEffect changedEffect)
{
if (this.m_changesCount > (sbyte)0)
return;
this.UpdateChangedEffects();
}
public virtual bool Remove(AbstractPetEffect effect)
{
int index = -1;
lock (this.m_effects)
{
index = this.m_effects.IndexOf((object)effect);
if (index < 0)
return false;
this.m_effects.RemoveAt(index);
}
if (index == -1)
return false;
effect.OnRemoved(this.m_owner);
this.OnEffectsChanged(effect);
return true;
}
public void StopAllEffect()
{
if (this.m_effects.Count <= 0)
return;
AbstractPetEffect[] abstractPetEffectArray = new AbstractPetEffect[this.m_effects.Count];
this.m_effects.CopyTo((Array)abstractPetEffectArray);
foreach (AbstractPetEffect abstractPetEffect in abstractPetEffectArray)
abstractPetEffect.Stop();
this.m_effects.Clear();
}
public virtual bool Pause(AbstractPetEffect effect)
{
ArrayList effects = this.m_effects;
lock (effects)
{
if (this.m_effects.IndexOf(effect) < 0)
{
return false;
}
}
effect.OnPaused(this.m_owner);
this.OnEffectsChanged(effect);
return true;
}
public void StopEffect(Type effectType)
{
IList allOfType = this.GetAllOfType(effectType);
this.BeginChanges();
foreach (AbstractPetEffect abstractPetEffect in (IEnumerable)allOfType)
abstractPetEffect.Stop();
this.CommitChanges();
}
protected virtual void UpdateChangedEffects()
{
}
public ArrayList List
{
get
{
return this.m_effects;
}
}
}
}
| 412 | 0.91422 | 1 | 0.91422 | game-dev | MEDIA | 0.632461 | game-dev | 0.875094 | 1 | 0.875094 |
Vladislav-EG/Flexible2DCharacterControllerForUnity | 1,698 | Assets/PlatformerController2D/Runtime/Scripts/StateMachine/PlayerStateMachine/PlayerStates/RunJumpState.cs | using UnityEngine;
public class RunJumpState : BaseState
{
private readonly JumpModule _jumpModule;
private readonly FallModule _fallModule;
private readonly MovementModule _movementModule;
private Vector2 _moveVelocity;
public RunJumpState(PlayerStateContext context, JumpModule jumpModule, FallModule fallModule, MovementModule movementModule) :
base(context)
{
_jumpModule = jumpModule;
_fallModule = fallModule;
_movementModule = movementModule;
}
public override void OnEnter()
{
Debug.Log("RunJumpState");
animationController.PlayAnimation("Jump");
_jumpModule.OnMultiJump += () => animationController.PlayAnimation("MultiJump");
}
public override void Update()
{
_jumpModule.HandleInput(inputReader.GetJumpState());
turnChecker.TurnCheck(inputReader.GetMoveDirection());
_fallModule.SetHoldState(inputReader.GetJumpState().IsHeld);
}
public override void FixedUpdate()
{
_moveVelocity.y = _jumpModule.JumpPhysicsProcessing(physicsHandler2D.GetVelocity()).y;
_moveVelocity.x = _movementModule.HandleMovement(physicsHandler2D.GetVelocity(), inputReader.GetNormalizedHorizontalDirection(), playerControllerStats.RunSpeed, playerControllerStats.AirAcceleration, playerControllerStats.AirDeceleration).x; // player.GetMoveDirection заменить на InputHandler.GetMoveDirection
_moveVelocity.y = _fallModule.HandleFalling(_moveVelocity).y;
physicsHandler2D.AddVelocity(_moveVelocity);
}
public override void OnExit()
{
_jumpModule.OnExitJump();
}
} | 412 | 0.675116 | 1 | 0.675116 | game-dev | MEDIA | 0.924927 | game-dev | 0.919212 | 1 | 0.919212 |
ppy/osu | 1,966 | osu.Game.Rulesets.Catch.Tests/TestSceneAutoJuiceStream.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using osu.Game.Audio;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Catch.UI;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Types;
using osu.Game.Tests.Visual;
using osuTK;
namespace osu.Game.Rulesets.Catch.Tests
{
public partial class TestSceneAutoJuiceStream : TestSceneCatchPlayer
{
protected override IBeatmap CreateBeatmap(RulesetInfo ruleset)
{
var beatmap = new Beatmap
{
BeatmapInfo = new BeatmapInfo
{
Difficulty = new BeatmapDifficulty { CircleSize = 6, SliderMultiplier = 3 },
Ruleset = ruleset
}
};
for (int i = 0; i < 100; i++)
{
float width = (i % 10 + 1) / 20f * CatchPlayfield.WIDTH;
beatmap.HitObjects.Add(new JuiceStream
{
X = CatchPlayfield.CENTER_X - width / 2,
Path = new SliderPath(PathType.LINEAR, new[]
{
Vector2.Zero,
new Vector2(width, 0)
}),
StartTime = i * 2000,
NewCombo = i % 8 == 0,
Samples = new List<HitSampleInfo>(new[]
{
new HitSampleInfo(HitSampleInfo.HIT_NORMAL)
})
});
}
return beatmap;
}
protected override TestPlayer CreatePlayer(Ruleset ruleset)
{
SelectedMods.Value = SelectedMods.Value.Concat(new[] { ruleset.GetAutoplayMod() }).ToArray();
return base.CreatePlayer(ruleset);
}
}
}
| 412 | 0.74172 | 1 | 0.74172 | game-dev | MEDIA | 0.774647 | game-dev,testing-qa | 0.84682 | 1 | 0.84682 |
ChillBDD/Chill | 6,008 | Src/Chill/ObjectMotherContainerDecorator.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Chill
{
/// <summary>
/// Wraps an <see cref="IChillContainer" /> to allow implementations of <see cref="IObjectMother"/> to
/// generate objects not registered in the container.
/// </summary>
public class ObjectMotherContainerDecorator : IChillContainer, IChillObjectResolver
{
private readonly List<IObjectMother> objectMothers = new List<IObjectMother>();
private readonly Dictionary<Tuple<Type, string>, object>
initializedValues = new Dictionary<Tuple<Type, string>, object>();
private readonly IChillContainer internalChillContainer;
private readonly object syncRoot = new object();
/// <summary>
/// Initializes a new instance of the <see cref="ObjectMotherContainerDecorator" /> class.
/// </summary>
/// <param name="internalChillContainer">The internal chill container.</param>
public ObjectMotherContainerDecorator(IChillContainer internalChillContainer)
{
this.internalChillContainer = internalChillContainer;
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
public void Dispose()
{
internalChillContainer.Dispose();
}
/// <summary>
/// Registers the type.
/// </summary>
/// <typeparam name="T"></typeparam>
public void RegisterType<T>() where T : class
{
internalChillContainer.RegisterType<T>();
}
/// <summary>
/// Gets an instance from the container, optionally by key.
/// </summary>
/// <typeparam name="T">The type of object registered in the container. </typeparam>
/// <param name="key">The key.</param>
/// <returns>The requested value from the container</returns>
/// <exception cref="System.InvalidOperationException">Thrown if more than one builder of the specified type is registered</exception>
public T Get<T>(string key = null) where T : class
{
if (internalChillContainer.IsRegistered(typeof(T)))
{
return internalChillContainer.Get<T>();
}
// Combine the type and key into a string
var initializedValuesKey = new Tuple<Type, string>(typeof(T), key);
if (initializedValues.ContainsKey(initializedValuesKey))
{
return initializedValues[initializedValuesKey] as T;
}
lock (syncRoot)
{
if (initializedValues.ContainsKey(initializedValuesKey))
{
return initializedValues[initializedValuesKey] as T;
}
var applicableMothers = objectMothers
.Where(m => m.Applies(typeof(T)))
.OrderBy(m => m.IsFallback)
.ToList();
if (!applicableMothers.Any())
{
return internalChillContainer.Get<T>(key);
}
if (applicableMothers.Count(m => !m.IsFallback) > 1)
{
throw new InvalidOperationException(
$"There are more than one builders that apply to build: {typeof(T).Name}. Namely: {string.Join(",", applicableMothers.Select(x => x.GetType().Name))}.");
}
object item = applicableMothers
.First()
.Create(typeof(T), new ContainerResolverAdapter(internalChillContainer));
initializedValues.Add(initializedValuesKey, item);
return (T) item;
}
}
/// <summary>
/// Sets the specified value to set.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="valueToSet">The value to set.</param>
/// <param name="key">The key.</param>
/// <returns></returns>
public T Set<T>(T valueToSet, string key = null) where T : class
{
return internalChillContainer.Set(valueToSet, key);
}
/// <summary>
/// Determines whether an instance of this type is registered.
/// </summary>
/// <returns></returns>
public bool IsRegistered<T>() where T : class
{
return internalChillContainer.IsRegistered(typeof(T));
}
/// <summary>
/// Determines whether an instance of this type is registered.
/// </summary>
/// <param name="type">The type.</param>
/// <returns></returns>
public bool IsRegistered(Type type)
{
return internalChillContainer.IsRegistered(type);
}
/// <summary>
/// Loads the automatic mothers.
/// </summary>
/// <param name="assemblies">The assemblies.</param>
public void LoadAutoMothers(IEnumerable<Assembly> assemblies)
{
var types = AssemblyTypeResolver
.GetAllTypesFromAssemblies(assemblies)
.Where(IsAutoMother);
foreach (var type in types)
{
objectMothers.Add((IObjectMother) Activator.CreateInstance(type));
}
}
private static bool IsAutoMother(Type x)
{
return typeof(IObjectMother).GetTypeInfo().IsAssignableFrom(x.GetTypeInfo());
}
}
internal class ContainerResolverAdapter : IChillObjectResolver
{
private readonly IChillContainer container;
public ContainerResolverAdapter(IChillContainer container)
{
this.container = container;
}
public T Get<T>(string key = null) where T : class
{
return container.Get<T>(key);
}
}
} | 412 | 0.96648 | 1 | 0.96648 | game-dev | MEDIA | 0.371657 | game-dev | 0.965929 | 1 | 0.965929 |
SamuelTulach/SecureFakePkg | 5,689 | edk2/CryptoPkg/Library/OpensslLib/openssl/crypto/engine/eng_cnf.c | /*
* Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "eng_int.h"
#include <openssl/conf.h>
/* #define ENGINE_CONF_DEBUG */
/* ENGINE config module */
static const char *skip_dot(const char *name)
{
const char *p = strchr(name, '.');
if (p != NULL)
return p + 1;
return name;
}
static STACK_OF(ENGINE) *initialized_engines = NULL;
static int int_engine_init(ENGINE *e)
{
if (!ENGINE_init(e))
return 0;
if (!initialized_engines)
initialized_engines = sk_ENGINE_new_null();
if (!initialized_engines || !sk_ENGINE_push(initialized_engines, e)) {
ENGINE_finish(e);
return 0;
}
return 1;
}
static int int_engine_configure(const char *name, const char *value, const CONF *cnf)
{
int i;
int ret = 0;
long do_init = -1;
STACK_OF(CONF_VALUE) *ecmds;
CONF_VALUE *ecmd = NULL;
const char *ctrlname, *ctrlvalue;
ENGINE *e = NULL;
int soft = 0;
name = skip_dot(name);
#ifdef ENGINE_CONF_DEBUG
fprintf(stderr, "Configuring engine %s\n", name);
#endif
/* Value is a section containing ENGINE commands */
ecmds = NCONF_get_section(cnf, value);
if (!ecmds) {
ENGINEerr(ENGINE_F_INT_ENGINE_CONFIGURE,
ENGINE_R_ENGINE_SECTION_ERROR);
return 0;
}
for (i = 0; i < sk_CONF_VALUE_num(ecmds); i++) {
ecmd = sk_CONF_VALUE_value(ecmds, i);
ctrlname = skip_dot(ecmd->name);
ctrlvalue = ecmd->value;
#ifdef ENGINE_CONF_DEBUG
fprintf(stderr, "ENGINE conf: doing ctrl(%s,%s)\n", ctrlname,
ctrlvalue);
#endif
/* First handle some special pseudo ctrls */
/* Override engine name to use */
if (strcmp(ctrlname, "engine_id") == 0)
name = ctrlvalue;
else if (strcmp(ctrlname, "soft_load") == 0)
soft = 1;
/* Load a dynamic ENGINE */
else if (strcmp(ctrlname, "dynamic_path") == 0) {
e = ENGINE_by_id("dynamic");
if (!e)
goto err;
if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", ctrlvalue, 0))
goto err;
if (!ENGINE_ctrl_cmd_string(e, "LIST_ADD", "2", 0))
goto err;
if (!ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0))
goto err;
}
/* ... add other pseudos here ... */
else {
/*
* At this point we need an ENGINE structural reference if we
* don't already have one.
*/
if (!e) {
e = ENGINE_by_id(name);
if (!e && soft) {
ERR_clear_error();
return 1;
}
if (!e)
goto err;
}
/*
* Allow "EMPTY" to mean no value: this allows a valid "value" to
* be passed to ctrls of type NO_INPUT
*/
if (strcmp(ctrlvalue, "EMPTY") == 0)
ctrlvalue = NULL;
if (strcmp(ctrlname, "init") == 0) {
if (!NCONF_get_number_e(cnf, value, "init", &do_init))
goto err;
if (do_init == 1) {
if (!int_engine_init(e))
goto err;
} else if (do_init != 0) {
ENGINEerr(ENGINE_F_INT_ENGINE_CONFIGURE,
ENGINE_R_INVALID_INIT_VALUE);
goto err;
}
} else if (strcmp(ctrlname, "default_algorithms") == 0) {
if (!ENGINE_set_default_string(e, ctrlvalue))
goto err;
} else if (!ENGINE_ctrl_cmd_string(e, ctrlname, ctrlvalue, 0))
goto err;
}
}
if (e && (do_init == -1) && !int_engine_init(e)) {
ecmd = NULL;
goto err;
}
ret = 1;
err:
if (ret != 1) {
ENGINEerr(ENGINE_F_INT_ENGINE_CONFIGURE,
ENGINE_R_ENGINE_CONFIGURATION_ERROR);
if (ecmd)
ERR_add_error_data(6, "section=", ecmd->section,
", name=", ecmd->name,
", value=", ecmd->value);
}
ENGINE_free(e);
return ret;
}
static int int_engine_module_init(CONF_IMODULE *md, const CONF *cnf)
{
STACK_OF(CONF_VALUE) *elist;
CONF_VALUE *cval;
int i;
#ifdef ENGINE_CONF_DEBUG
fprintf(stderr, "Called engine module: name %s, value %s\n",
CONF_imodule_get_name(md), CONF_imodule_get_value(md));
#endif
/* Value is a section containing ENGINEs to configure */
elist = NCONF_get_section(cnf, CONF_imodule_get_value(md));
if (!elist) {
ENGINEerr(ENGINE_F_INT_ENGINE_MODULE_INIT,
ENGINE_R_ENGINES_SECTION_ERROR);
return 0;
}
for (i = 0; i < sk_CONF_VALUE_num(elist); i++) {
cval = sk_CONF_VALUE_value(elist, i);
if (!int_engine_configure(cval->name, cval->value, cnf))
return 0;
}
return 1;
}
static void int_engine_module_finish(CONF_IMODULE *md)
{
ENGINE *e;
while ((e = sk_ENGINE_pop(initialized_engines)))
ENGINE_finish(e);
sk_ENGINE_free(initialized_engines);
initialized_engines = NULL;
}
void ENGINE_add_conf_module(void)
{
CONF_module_add("engines",
int_engine_module_init, int_engine_module_finish);
}
| 412 | 0.916548 | 1 | 0.916548 | game-dev | MEDIA | 0.291564 | game-dev | 0.807561 | 1 | 0.807561 |
sdboyer/gliph | 2,689 | src/Gliph/Visitor/DepthFirstBasicVisitor.php | <?php
namespace Gliph\Visitor;
use Gliph\Exception\WrongVisitorStateException;
/**
* Basic depth-first visitor.
*
* This visitor records reachability data for each vertex and creates a
* topologically sorted list.
*/
class DepthFirstBasicVisitor extends DepthFirstToposortVisitor {
/**
* @var \SplObjectStorage
*/
public $active;
/**
* @var \SplObjectStorage
*/
protected $paths;
public function __construct() {
$this->active = new \SplObjectStorage();
$this->paths = new \SplObjectStorage();
}
public function onInitializeVertex($vertex, $source, \SplQueue $queue) {
parent::onInitializeVertex($vertex, $source, $queue);
$this->paths[$vertex] = array();
}
public function onStartVertex($vertex, \Closure $visit) {
parent::onStartVertex($vertex, $visit);
$this->active->attach($vertex);
if (!isset($this->paths[$vertex])) {
$this->paths[$vertex] = array();
}
}
public function onExamineEdge($from, $to, \Closure $visit) {
parent::onExamineEdge($from, $to, $visit);
foreach ($this->active as $vertex) {
// TODO this check makes this less efficient - find a better algo
if (!in_array($to, $this->paths[$vertex], TRUE)) {
$path = $this->paths[$vertex];
$path[] = $to;
$this->paths[$vertex] = $path;
}
}
}
public function onFinishVertex($vertex, \Closure $visit) {
parent::onFinishVertex($vertex, $visit);
$this->active->detach($vertex);
}
/**
* Returns an array of all vertices reachable from the given vertex.
*
* @param object $vertex
* The vertex for which reachability data is desired.
*
* @return array|bool
* An array of reachable vertices, or FALSE if the vertex could not be
* found in the reachability data. Note that an empty array will be
* returned for vertices that zero reachable vertices. This is a different
* from FALSE, so the identity operator (===) should be used to verify
* returns.
*
* @throws WrongVisitorStateException
* Thrown if reachability data is requested before the traversal algorithm
* completes.
*/
public function getReachable($vertex) {
if ($this->getState() !== self::COMPLETE) {
throw new WrongVisitorStateException('Correct reachability data cannot be retrieved until traversal is complete.');
}
if (!isset($this->paths[$vertex])) {
return FALSE;
}
return $this->paths[$vertex];
}
} | 412 | 0.901269 | 1 | 0.901269 | game-dev | MEDIA | 0.631008 | game-dev | 0.925976 | 1 | 0.925976 |
BLACKujira/SekaiTools | 5,453 | SekaiTools/Assets/XCharts/Editor/ChildComponents/ThemeDrawer.cs | using System.IO;
using UnityEditor;
using UnityEngine;
#if dUI_TextMeshPro
using TMPro;
#endif
using XCharts.Runtime;
namespace XCharts.Editor
{
[CustomPropertyDrawer(typeof(ThemeStyle), true)]
public class ThemeStyleDrawer : BasePropertyDrawer
{
public override string ClassName { get { return "Theme"; } }
public override void OnGUI(Rect pos, SerializedProperty prop, GUIContent label)
{
base.OnGUI(pos, prop, label);
var defaultWidth = pos.width;
var defaultX = pos.x;
var chart = prop.serializedObject.targetObject as BaseChart;
if (MakeComponentFoldout(prop, "m_Show", false, new HeaderMenuInfo("Reset|Reset to theme default color", () =>
{
chart.theme.sharedTheme.ResetTheme();
chart.RefreshAllComponent();
}), new HeaderMenuInfo("Export|Export theme to asset for a new theme", () =>
{
ExportThemeWindow.target = chart;
EditorWindow.GetWindow(typeof(ExportThemeWindow));
}), new HeaderMenuInfo("Sync color to custom|Sync shared theme color to custom color", () =>
{
chart.theme.SyncSharedThemeColorToCustom();
})))
{
++EditorGUI.indentLevel;
var chartNameList = XCThemeMgr.GetAllThemeNames();
var lastIndex = chartNameList.IndexOf(chart.theme.themeName);
var y = pos.y + EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing;
var selectedIndex = EditorGUI.Popup(new Rect(pos.x, y, pos.width, EditorGUIUtility.singleLineHeight),
"Shared Theme", lastIndex, chartNameList.ToArray());
AddSingleLineHeight();
if (lastIndex != selectedIndex)
{
XCThemeMgr.SwitchTheme(chart, chartNameList[selectedIndex]);
}
PropertyField(prop, "m_SharedTheme");
PropertyField(prop, "m_TransparentBackground");
PropertyField(prop, "m_EnableCustomTheme");
using(new EditorGUI.DisabledScope(!prop.FindPropertyRelative("m_EnableCustomTheme").boolValue))
{
PropertyField(prop, "m_CustomBackgroundColor");
PropertyField(prop, "m_CustomColorPalette");
}
--EditorGUI.indentLevel;
}
}
private void AddPropertyField(Rect pos, SerializedProperty prop, ref float y)
{
float height = EditorGUI.GetPropertyHeight(prop, new GUIContent(prop.displayName), true);
EditorGUI.PropertyField(new Rect(pos.x, y, pos.width, height), prop, true);
y += height + EditorGUIUtility.standardVerticalSpacing;
m_Heights[m_KeyName] += height + EditorGUIUtility.standardVerticalSpacing;
}
}
public class ExportThemeWindow : UnityEditor.EditorWindow
{
public static BaseChart target;
private static ExportThemeWindow window;
private string m_ChartName;
static void Init()
{
window = (ExportThemeWindow) EditorWindow.GetWindow(typeof(ExportThemeWindow), false, "Export Theme", true);
window.minSize = new Vector2(600, 50);
window.maxSize = new Vector2(600, 50);
window.Show();
}
void OnInspectorUpdate()
{
Repaint();
}
private void OnGUI()
{
if (target == null)
{
Close();
return;
}
GUILayout.Space(10);
GUILayout.Label("Input a new name for theme:");
m_ChartName = GUILayout.TextField(m_ChartName);
GUILayout.Space(10);
GUILayout.Label("Export path:");
if (string.IsNullOrEmpty(m_ChartName))
{
GUILayout.Label("Need input a new name.");
}
else
{
GUILayout.Label(XCThemeMgr.GetThemeAssetPath(m_ChartName));
}
GUILayout.Space(20);
if (GUILayout.Button("Export"))
{
if (string.IsNullOrEmpty(m_ChartName))
{
ShowNotification(new GUIContent("ERROR:Need input a new name!"));
}
else if (XCThemeMgr.ContainsTheme(m_ChartName))
{
ShowNotification(new GUIContent("ERROR:The name you entered is already in use!"));
}
else if (IsAssetsExist(XCThemeMgr.GetThemeAssetPath(m_ChartName)))
{
ShowNotification(new GUIContent("ERROR:The asset is exist! \npath=" +
XCThemeMgr.GetThemeAssetPath(m_ChartName)));
}
else
{
XCThemeMgr.ExportTheme(target.theme.sharedTheme, m_ChartName);
ShowNotification(new GUIContent("SUCCESS:The theme is exported. \npath=" +
XCThemeMgr.GetThemeAssetPath(m_ChartName)));
}
}
}
private bool IsAssetsExist(string path)
{
return File.Exists(Application.dataPath + "/../" + path);
}
}
} | 412 | 0.923366 | 1 | 0.923366 | game-dev | MEDIA | 0.628326 | game-dev,desktop-app | 0.970388 | 1 | 0.970388 |
atsb/NakedAVP | 8,851 | src/avp/win95/avpchunk.hpp | #ifndef _avpchunk_hpp_
#define _avpchunk_hpp_
#include "chunk.hpp"
#include "chnktype.hpp"
#include "envchunk.hpp"
#include "sndchunk.hpp"
#define AVPGENFLAG_MODEFLAGSSET 0x00000001
// same as obchunk 4 compatibility
#define AVPGENFLAG_AVPGAMEMODEMARINE 0x00000800
#define AVPGENFLAG_AVPGAMEMODEALIEN 0x00001000
#define AVPGENFLAG_AVPGAMEMODEPREDATOR 0x00002000
#define AVPGENFLAG_NOTDIFFICULTY1 0x00100000
#define AVPGENFLAG_NOTDIFFICULTY2 0x00200000
#define AVPGENFLAG_NOTDIFFICULTY3 0x00400000
#define AVPGENFLAG_USEOWNLIMIT 0x02000000
#define AVPGENFLAG_USEOWNRATE 0x04000000
#define AVPGENFLAG_ADVANCEDGENERATOR 0x08000000
#define AVPGENFLAG_MULTIPLAYERSTART 0x40000000
#define AVPGENFLAG_GENERATORINACTIVE 0x80000000
enum GenerTypes
{
GenerType_Intermittent = 0,
GenerType_BadGuy1,
GenerType_BadGuy2,
GenerType_BadGuy3,
};
class AVP_Generator_Extra_Data_Chunk;
class AVP_Generator_Extended_Settings_Chunk;
class Object_Alternate_Locations_Chunk;
class AVP_Generator_Chunk : public Chunk
{
public:
AVP_Generator_Chunk (Chunk_With_Children * parent)
: Chunk (parent, "AVPGENER"),
textureID (0),
sub_type (0),
extra1 (0),
extra2 (0),
name (0)
{}
~AVP_Generator_Chunk ();
ChunkVectorInt location;
int orientation; //euler y
int type;
int flags;
unsigned char textureID;
unsigned char sub_type;
unsigned char extra1;
unsigned char extra2;
char * name;
ObjectID CalculateID();
virtual void fill_data_block (char * data_start);
virtual size_t size_chunk ();
AVP_Generator_Extra_Data_Chunk* get_extra_data_chunk();
AVP_Generator_Extra_Data_Chunk* create_extra_data_chunk();
AVP_Generator_Extended_Settings_Chunk* get_extended_settings();
AVP_Generator_Extended_Settings_Chunk* create_extended_settings();
Object_Alternate_Locations_Chunk* get_alternate_locations_chunk();
AVP_Generator_Chunk (Chunk_With_Children * parent, const char * data, size_t size);
private:
friend class Special_Objects_Chunk;
};
//For attaching extra data to the generators and badguys
class AVP_Generator_Extra_Data_Chunk:public Chunk_With_Children
{
public:
AVP_Generator_Extra_Data_Chunk(Chunk_With_Children * parent)
: Chunk_With_Children (parent, "AVPGENEX")
{}
AVP_Generator_Extra_Data_Chunk (Chunk_With_Children * const parent,const char *, size_t const);
AVP_Generator_Extra_Data_Chunk (Chunk_With_Children * parent,AVP_Generator_Chunk*);
AVP_Generator_Chunk* get_generator_chunk();
};
//Needed so I can match the extra data chunk with the appropriate generator_chunk
class AVP_Generator_Extra_Name_Chunk : public Chunk
{
public :
AVP_Generator_Extra_Name_Chunk(Chunk_With_Children* parent,const char*,size_t);
AVP_Generator_Extra_Name_Chunk(Chunk_With_Children* parent,const char* _name);
~AVP_Generator_Extra_Name_Chunk();
char* name;
virtual size_t size_chunk();
virtual void fill_data_block(char* data_start);
};
struct AVP_Generator_Weighting
{
int data_size;
int PulseMarine_Wt;
int FlameMarine_Wt;
int SmartMarine_Wt;
int SadarMarine_Wt;
int GrenadeMarine_Wt;
int MinigunMarine_Wt;
int ShotgunCiv_Wt;
int PistolCiv_Wt;
int FlameCiv_Wt;
int UnarmedCiv_Wt;
int MolotovCiv_Wt;
int Alien_Wt;
int PredAlien_Wt;
int Praetorian_Wt;
int PistolMarine_Wt;
};
class AVP_Generator_Extended_Settings_Chunk : public Chunk
{
public :
AVP_Generator_Extended_Settings_Chunk(Chunk_With_Children* parent,const char* data, size_t);
AVP_Generator_Extended_Settings_Chunk(Chunk_With_Children* parent);
~AVP_Generator_Extended_Settings_Chunk();
void fill_data_block(char* data);
size_t size_chunk();
int GenerationRate;
int GenRateIncrease;
unsigned char GenLimit;
unsigned char pad1,pad2,pad3;
int spare1;
int spare2;
AVP_Generator_Weighting * weights;
};
#define R6GENFLAG_OBJECTIVE_MASK 0x00000007
#define R6GENFLAG_BADDY_INDEX_MASK 0xff000000
#define R6GENFLAG_BADDY_INDEX_SHIFT 24
class Rainbow6_Generator_Extra_Data_Chunk : public Chunk
{
public :
Rainbow6_Generator_Extra_Data_Chunk(Chunk_With_Children* parent,const char*,size_t);
Rainbow6_Generator_Extra_Data_Chunk(Chunk_With_Children*);
~Rainbow6_Generator_Extra_Data_Chunk();
int Get_Baddy_Index(){ return (flags & R6GENFLAG_BADDY_INDEX_MASK)>>R6GENFLAG_BADDY_INDEX_SHIFT;}
void Set_Baddy_Index(int index) { flags&=~R6GENFLAG_BADDY_INDEX_MASK; flags |=(index<<R6GENFLAG_BADDY_INDEX_SHIFT);}
int distance;
int flags;
int num_extra_data;
int* extra_data;
size_t size_chunk();
void fill_data_block(char* data_start);
};
enum Generated_Enemies
{
Generate_Aliens,
Generate_Marines,
};
class Global_Generator_Data_Chunk : public Chunk
{
public :
Global_Generator_Data_Chunk(Chunk_With_Children* parent,const char*,size_t);
Global_Generator_Data_Chunk(Chunk_With_Children* parent);
int EnemyGenerated;
int MaxNPCSOnLevel;
int NPCSPerMinute;
int NPCAcceleration; //in npcs per minute per minute
int HiveStateChangeTime; //in seconds
int spare1;
int spare2;
virtual size_t size_chunk();
virtual void fill_data_block(char* data_start);
};
class AVP_Player_Start_Chunk : public Chunk
{
public :
AVP_Player_Start_Chunk (Chunk_With_Children * parent, const char * data, size_t size);
AVP_Player_Start_Chunk (Chunk_With_Children * parent);
virtual void fill_data_block (char * data);
virtual size_t size_chunk ();
ChunkVectorInt location;
ChunkMatrix orientation;
ObjectID moduleID; //r6 only
};
#define PowerCableFlag_UseDefaultSettings 0x00000001
class AVP_Power_Cable_Chunk : public Chunk
{
public :
AVP_Power_Cable_Chunk(Chunk_With_Children* parent,const char* data, size_t);
AVP_Power_Cable_Chunk(Chunk_With_Children* parent,const char* _name,ObjectID _id);
~AVP_Power_Cable_Chunk();
void fill_data_block(char* data);
size_t size_chunk();
ChunkVectorInt location;
char* name;
ObjectID id;
int max_charge;
int initial_charge;
int recharge_rate;
int flags;
int spare[3];
};
class AVP_Environment_Settings_Chunk;
struct AVP_Environment_Settings
{
private :
friend class AVP_Environment_Settings_Chunk;
int data_size;
public :
int sky_colour_red;
int sky_colour_green;
int sky_colour_blue;
//available predator weapons
unsigned int predator_pistol :1;
unsigned int predator_plasmacaster :1;
unsigned int predator_disc :1;
unsigned int predator_grappling_hook :1;
unsigned int predator_medicomp :1;
unsigned int marine_jetpack :1;
unsigned int stars_in_sky :1;
unsigned int spare_bits :25;
int predator_num_spears;
};
class AVP_Environment_Settings_Chunk : public Chunk
{
public :
AVP_Environment_Settings_Chunk(Chunk_With_Children* parent,const char* data, size_t);
AVP_Environment_Settings_Chunk(Chunk_With_Children* parent);
~AVP_Environment_Settings_Chunk();
void fill_data_block(char* data);
size_t size_chunk();
AVP_Environment_Settings * settings;
};
AVP_Environment_Settings_Chunk* GetAVPEnvironmentSettings(Environment_Data_Chunk* env_chunk);
struct AVP_Decal
{
int DecalID;
ChunkVectorInt Vertices[4];
int UOffset;
int object_index;
};
class AVP_Decal_Chunk : public Chunk
{
public :
AVP_Decal_Chunk(Chunk_With_Children* parent,const char* data, size_t);
AVP_Decal_Chunk(Chunk_With_Children* parent,int num_dec);
~AVP_Decal_Chunk();
void fill_data_block(char* data);
size_t size_chunk();
int num_decals;
/*the pointer to the array of decals is only set if the loaded decal structure size
is less than or equal to the current decal structure size*/
AVP_Decal* decals;
private :
int decal_size;
char* decal_buffer;
};
/////////////////////Particle Generators////////////////////////////////////////
class AVP_Particle_Generator_Data_Chunk;
class AVP_Particle_Generator_Chunk : public Chunk_With_Children
{
public :
AVP_Particle_Generator_Chunk(Chunk_With_Children* parent,const char* name,ObjectID& id);
AVP_Particle_Generator_Chunk(Chunk_With_Children * const parent,const char *, size_t const);
AVP_Particle_Generator_Data_Chunk* get_data_chunk();
Object_Alternate_Locations_Chunk* get_alternate_locations_chunk();
Indexed_Sound_Chunk* get_sound_chunk();
};
#define ParticleGeneratorFlag_Inactive 0x00000001
class AVP_Particle_Generator_Data_Chunk : public Chunk
{
public :
AVP_Particle_Generator_Data_Chunk(Chunk_With_Children* parent,const char* data, size_t);
AVP_Particle_Generator_Data_Chunk(Chunk_With_Children* parent,const char* _name,ObjectID& _id);
~AVP_Particle_Generator_Data_Chunk();
void fill_data_block(char* data);
size_t size_chunk();
int type;
unsigned short time; //int tenths of a second
unsigned short probability;//0-100
unsigned short speed;//in cm/second
unsigned short quantity;
int spare1,spare2;
int flags;
ObjectID id;
ObjectID parent_id; //gnerator can be positioned relative to another object
ChunkVectorInt location;
ChunkQuat orientation;
char* name;
};
#endif
| 412 | 0.932128 | 1 | 0.932128 | game-dev | MEDIA | 0.613887 | game-dev | 0.64672 | 1 | 0.64672 |
Fluorohydride/ygopro-scripts | 3,417 | c71817640.lua | --ドラゴニックP
function c71817640.initial_effect(c)
--activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--atk&def
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_UPDATE_ATTACK)
e2:SetRange(LOCATION_FZONE)
e2:SetTargetRange(LOCATION_MZONE,LOCATION_MZONE)
e2:SetTarget(aux.TargetBoolFunction(Card.IsSetCard,0xc7))
e2:SetValue(300)
c:RegisterEffect(e2)
local e3=e2:Clone()
e3:SetCode(EFFECT_UPDATE_DEFENSE)
c:RegisterEffect(e3)
--destroy
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(71817640,0))
e4:SetCategory(CATEGORY_DESTROY)
e4:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e4:SetCode(EVENT_CHAINING)
e4:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DELAY)
e4:SetRange(LOCATION_FZONE)
e4:SetCountLimit(1,71817640)
e4:SetCondition(c71817640.descon)
e4:SetTarget(c71817640.destg)
e4:SetOperation(c71817640.desop)
c:RegisterEffect(e4)
--to hand or spsummon
local e5=Effect.CreateEffect(c)
e5:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_SEARCH+CATEGORY_TOHAND)
e5:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e5:SetCode(EVENT_DESTROYED)
e5:SetProperty(EFFECT_FLAG_DELAY)
e5:SetCountLimit(1,71817641)
e5:SetCondition(c71817640.tscon)
e5:SetTarget(c71817640.tstg)
e5:SetOperation(c71817640.tsop)
c:RegisterEffect(e5)
end
function c71817640.descon(e,tp,eg,ep,ev,re,r,rp)
local rc=re:GetHandler()
return re:IsActiveType(TYPE_MONSTER) and rp==tp and rc:IsSetCard(0xc7) and rc:IsRace(RACE_DRAGON)
and rc:IsLocation(LOCATION_MZONE) and re:GetActivateLocation()==LOCATION_MZONE
end
function c71817640.destg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsOnField() end
if chk==0 then return Duel.IsExistingTarget(aux.TRUE,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectTarget(tp,aux.TRUE,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0)
end
function c71817640.desop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.Destroy(tc,REASON_EFFECT)
end
end
function c71817640.tscon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return c:IsPreviousLocation(LOCATION_ONFIELD)
end
function c71817640.tsfilter(c,e,tp)
if not (c:IsSetCard(0xc7,0xda) and c:IsType(TYPE_MONSTER)) then return false end
local ft=Duel.GetLocationCount(tp,LOCATION_MZONE)
return c:IsAbleToHand() or (ft>0 and c:IsCanBeSpecialSummoned(e,0,tp,false,false))
end
function c71817640.tstg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c71817640.tsfilter,tp,LOCATION_DECK,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK)
end
function c71817640.tsop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_OPERATECARD)
local g=Duel.SelectMatchingCard(tp,c71817640.tsfilter,tp,LOCATION_DECK,0,1,1,nil,e,tp)
local ft=Duel.GetLocationCount(tp,LOCATION_MZONE)
local tc=g:GetFirst()
if tc then
if tc:IsAbleToHand() and (not tc:IsCanBeSpecialSummoned(e,0,tp,false,false) or ft<=0 or Duel.SelectOption(tp,1190,1152)==0) then
Duel.SendtoHand(tc,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,tc)
else
Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)
end
end
end
| 412 | 0.95156 | 1 | 0.95156 | game-dev | MEDIA | 0.98784 | game-dev | 0.956329 | 1 | 0.956329 |
google/google-ctf | 2,146 | 2024/hackceler8/rounds/round_4/server/game/components/npc/weapon_grader_npc.py | # Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from game.engine import hitbox
from game.components.items import check_item_loaded
from .npc import Npc
grades = "ZYXWVUTSRQPONMLKJIHGFEDCBA"
class WeaponGraderNpc(Npc):
def __init__(self, coords, **kwargs):
super().__init__(coords=coords, scale=1, tileset_path="resources/NPCs/Snake_NPC_Green.h8t", **kwargs)
rect = hitbox.Rectangle(coords.x - 15, coords.x + 15, coords.y - 25, coords.y + 25)
self.update_hitbox(rect)
self.graded = False
def dialogue(self):
if self.graded:
self.display_textbox("I already graded your weaponssss, no takesies backsiessssss")
return
if len(self.game.player.weapons) <= 0:
self.display_textbox("You have no itemsssss to grade!")
return
text = "Psssst! Do you want me to grade your weaponsssss?"
def resp_process(resp: str):
if resp == "Yes":
self.graded = True
grade_weapon()
else:
self.display_textbox("Oh, then why are you here?")
def grade_weapon():
txt = []
for weapon in self.game.player.weapons:
grade_i = min(weapon.kill_counter, len(grades) - 1)
old_name = weapon.display_name
weapon.display_name = grades[grade_i] + weapon.display_name
txt.append("Weapon %s got grade %s" % (old_name, grades[grade_i]))
self.display_textbox("\n".join(txt))
self.display_textbox(text, choices=["Yes", "No"], process_fun=resp_process)
| 412 | 0.602688 | 1 | 0.602688 | game-dev | MEDIA | 0.930392 | game-dev | 0.687442 | 1 | 0.687442 |
KiwanoEngine/Kiwano | 5,311 | src/3rd-party/Box2D/Common/b2Settings.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_SETTINGS_H
#define B2_SETTINGS_H
#include <stddef.h>
#include <assert.h>
#include <float.h>
#if !defined(NDEBUG)
#define b2DEBUG
#endif
#define B2_NOT_USED(x) ((void)(x))
#define b2Assert(A) assert(A)
typedef signed char int8;
typedef signed short int16;
typedef signed int int32;
typedef unsigned char uint8;
typedef unsigned short uint16;
typedef unsigned int uint32;
typedef float float32;
typedef double float64;
#define b2_maxFloat FLT_MAX
#define b2_epsilon FLT_EPSILON
#define b2_pi 3.14159265359f
/// @file
/// Global tuning constants based on meters-kilograms-seconds (MKS) units.
///
// Collision
/// The maximum number of contact points between two convex shapes. Do
/// not change this value.
#define b2_maxManifoldPoints 2
/// The maximum number of vertices on a convex polygon. You cannot increase
/// this too much because b2BlockAllocator has a maximum object size.
#define b2_maxPolygonVertices 8
/// This is used to fatten AABBs in the dynamic tree. This allows proxies
/// to move by a small amount without triggering a tree adjustment.
/// This is in meters.
#define b2_aabbExtension 0.1f
/// This is used to fatten AABBs in the dynamic tree. This is used to predict
/// the future position based on the current displacement.
/// This is a dimensionless multiplier.
#define b2_aabbMultiplier 2.0f
/// A small length used as a collision and constraint tolerance. Usually it is
/// chosen to be numerically significant, but visually insignificant.
#define b2_linearSlop 0.005f
/// A small angle used as a collision and constraint tolerance. Usually it is
/// chosen to be numerically significant, but visually insignificant.
#define b2_angularSlop (2.0f / 180.0f * b2_pi)
/// The radius of the polygon/edge shape skin. This should not be modified. Making
/// this smaller means polygons will have an insufficient buffer for continuous collision.
/// Making it larger may create artifacts for vertex collision.
#define b2_polygonRadius (2.0f * b2_linearSlop)
/// Maximum number of sub-steps per contact in continuous physics simulation.
#define b2_maxSubSteps 8
// Dynamics
/// Maximum number of contacts to be handled to solve a TOI impact.
#define b2_maxTOIContacts 32
/// A velocity threshold for elastic collisions. Any collision with a relative linear
/// velocity below this threshold will be treated as inelastic.
#define b2_velocityThreshold 1.0f
/// The maximum linear position correction used when solving constraints. This helps to
/// prevent overshoot.
#define b2_maxLinearCorrection 0.2f
/// The maximum angular position correction used when solving constraints. This helps to
/// prevent overshoot.
#define b2_maxAngularCorrection (8.0f / 180.0f * b2_pi)
/// The maximum linear velocity of a body. This limit is very large and is used
/// to prevent numerical problems. You shouldn't need to adjust this.
#define b2_maxTranslation 2.0f
#define b2_maxTranslationSquared (b2_maxTranslation * b2_maxTranslation)
/// The maximum angular velocity of a body. This limit is very large and is used
/// to prevent numerical problems. You shouldn't need to adjust this.
#define b2_maxRotation (0.5f * b2_pi)
#define b2_maxRotationSquared (b2_maxRotation * b2_maxRotation)
/// This scale factor controls how fast overlap is resolved. Ideally this would be 1 so
/// that overlap is removed in one time step. However using values close to 1 often lead
/// to overshoot.
#define b2_baumgarte 0.2f
#define b2_toiBaugarte 0.75f
// Sleep
/// The time that a body must be still before it will go to sleep.
#define b2_timeToSleep 0.5f
/// A body cannot sleep if its linear velocity is above this tolerance.
#define b2_linearSleepTolerance 0.01f
/// A body cannot sleep if its angular velocity is above this tolerance.
#define b2_angularSleepTolerance (2.0f / 180.0f * b2_pi)
// Memory Allocation
/// Implement this function to use your own memory allocator.
void* b2Alloc(int32 size);
/// If you implement b2Alloc, you should also implement this function.
void b2Free(void* mem);
/// Logging function.
void b2Log(const char* string, ...);
/// Version numbering scheme.
/// See http://en.wikipedia.org/wiki/Software_versioning
struct b2Version
{
int32 major; ///< significant changes
int32 minor; ///< incremental changes
int32 revision; ///< bug fixes
};
/// Current version.
extern b2Version b2_version;
#endif
| 412 | 0.87551 | 1 | 0.87551 | game-dev | MEDIA | 0.833183 | game-dev | 0.762538 | 1 | 0.762538 |
TeamMetallurgy/Atum2 | 8,016 | src/main/java/com/teammetallurgy/atum/blocks/stone/limestone/chest/SarcophagusBlock.java | package com.teammetallurgy.atum.blocks.stone.limestone.chest;
import com.teammetallurgy.atum.Atum;
import com.teammetallurgy.atum.blocks.QuandaryBlock;
import com.teammetallurgy.atum.blocks.base.ChestBaseBlock;
import com.teammetallurgy.atum.blocks.stone.limestone.chest.tileentity.SarcophagusTileEntity;
import com.teammetallurgy.atum.init.AtumBlocks;
import com.teammetallurgy.atum.init.AtumTileEntities;
import com.teammetallurgy.atum.network.NetworkHandler;
import com.teammetallurgy.atum.network.packet.SyncHandStackSizePacket;
import net.minecraft.ChatFormatting;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.Difficulty;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.MenuProvider;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.*;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.properties.ChestType;
import net.minecraft.world.level.block.state.properties.NoteBlockInstrument;
import net.minecraft.world.level.material.MapColor;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.HitResult;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.common.Mod;
import net.neoforged.neoforge.event.level.BlockEvent;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
@Mod.EventBusSubscriber(modid = Atum.MOD_ID)
public class SarcophagusBlock extends ChestBaseBlock {
public SarcophagusBlock() {
super(AtumTileEntities.SARCOPHAGUS::get, BlockBehaviour.Properties.of().mapColor(MapColor.SAND).instrument(NoteBlockInstrument.BASEDRUM).strength(4.0F));
}
@Override
public BlockEntity newBlockEntity(@Nonnull BlockPos pos, @Nonnull BlockState state) {
return AtumTileEntities.SARCOPHAGUS.get().create(pos, state);
}
@SubscribeEvent
public static void onBlockBreak(BlockEvent.BreakEvent event) {
BlockState state = event.getState();
if (state.getBlock() instanceof SarcophagusBlock) {
BlockEntity tileEntity = event.getLevel().getBlockEntity(event.getPos());
if (tileEntity instanceof SarcophagusTileEntity && !((SarcophagusTileEntity) tileEntity).isOpenable) {
event.setCanceled(true);
}
}
}
@Override
public float getExplosionResistance(BlockState state, BlockGetter level, BlockPos pos, Explosion explosion) {
BlockEntity tileEntity = level.getBlockEntity(pos);
if (tileEntity instanceof SarcophagusTileEntity && !((SarcophagusTileEntity) tileEntity).isOpenable) {
return 6000000.0F;
} else {
return super.getExplosionResistance(state, level, pos, explosion);
}
}
@Override
@Nonnull
public InteractionResult use(BlockState state, Level level, @Nonnull BlockPos pos, @Nonnull Player player, @Nonnull InteractionHand hand, @Nonnull BlockHitResult hit) {
BlockEntity tileEntity = level.getBlockEntity(pos);
Direction facing = state.getValue(FACING);
//Right-Click left block, when right-clicking right block
BlockPos posLeft = pos.relative(facing.getClockWise());
BlockEntity tileLeft = level.getBlockEntity(posLeft);
if (level.getBlockState(posLeft).getBlock() == this && tileLeft instanceof SarcophagusTileEntity sarcophagus) {
if (level.getDifficulty() != Difficulty.PEACEFUL && !sarcophagus.hasSpawned) {
this.use(state, level, pos.relative(facing.getClockWise()), player, hand, hit);
return InteractionResult.PASS;
}
}
if (tileEntity instanceof SarcophagusTileEntity sarcophagus) {
if (level.getDifficulty() != Difficulty.PEACEFUL && !sarcophagus.hasSpawned) {
if (QuandaryBlock.Helper.canSpawnPharaoh(level, pos, facing, player, level.random, sarcophagus)) {
return InteractionResult.PASS;
} else if (!sarcophagus.isOpenable) {
player.displayClientMessage(Component.translatable("chat.atum.cannot_spawn_pharaoh").withStyle(ChatFormatting.RED), true);
level.playLocalSound(pos.getX(), pos.getY(), pos.getZ(), SoundEvents.ZOMBIE_INFECT, SoundSource.HOSTILE, 0.7F, 0.4F, false);
return InteractionResult.PASS;
}
}
}
return super.use(state, level, pos, player, hand, hit);
}
@Nullable
@Override
public MenuProvider getMenuProvider(@Nonnull BlockState state, @Nonnull Level level, @Nonnull BlockPos pos) { //Workaround so you can't see loot before pharaoh is beaten
BlockEntity tileEntity = level.getBlockEntity(pos);
return tileEntity instanceof SarcophagusTileEntity && ((SarcophagusTileEntity) tileEntity).isOpenable ? super.getMenuProvider(state, level, pos) : null;
}
@Override
public void setPlacedBy(@Nonnull Level level, @Nonnull BlockPos pos, @Nonnull BlockState state, @Nonnull LivingEntity placer, @Nonnull ItemStack stack) {
super.setPlacedBy(level, pos, state, placer, stack);
BlockEntity tileEntity = level.getBlockEntity(pos);
if (tileEntity instanceof SarcophagusTileEntity sarcophagus) {
sarcophagus.hasSpawned = true;
sarcophagus.setOpenable();
sarcophagus.setChanged();
for (Direction horizontal : Direction.Plane.HORIZONTAL) {
BlockEntity tileEntityOffset = level.getBlockEntity(pos.relative(horizontal));
if (tileEntityOffset instanceof SarcophagusTileEntity) {
((SarcophagusTileEntity) tileEntityOffset).hasSpawned = true;
((SarcophagusTileEntity) tileEntityOffset).setOpenable();
tileEntityOffset.setChanged();
}
}
}
}
@SubscribeEvent
public static void onPlaced(BlockEvent.EntityPlaceEvent event) { //Prevent placement, 1 block left of another block
BlockState placedState = event.getPlacedBlock();
if (placedState.getBlock() instanceof SarcophagusBlock) {
if (!canPlaceRightSac(event.getLevel(), event.getPos(), placedState.getValue(FACING))) {
event.setCanceled(true);
if (event.getEntity() instanceof ServerPlayer player) {
ItemStack placedStack = new ItemStack(placedState.getBlock().asItem());
InteractionHand hand = player.getMainHandItem().getItem() == placedStack.getItem() ? InteractionHand.MAIN_HAND : InteractionHand.OFF_HAND;
NetworkHandler.sendTo(player, new SyncHandStackSizePacket(placedStack, hand == InteractionHand.MAIN_HAND ? 1 : 0));
}
}
}
}
private static boolean canPlaceRightSac(LevelAccessor level, BlockPos pos, Direction facing) {
BlockPos posOffset = pos.relative(facing.getCounterClockWise());
BlockState offsetState = level.getBlockState(posOffset);
if (offsetState.getBlock() instanceof SarcophagusBlock) {
return offsetState.getValue(SarcophagusBlock.TYPE) == ChestType.LEFT && offsetState.getValue(SarcophagusBlock.FACING) == facing;
}
return false;
}
@Override
@Nonnull
public ItemStack getCloneItemStack(@Nonnull BlockState state, @Nonnull HitResult target, @Nonnull LevelReader level, @Nonnull BlockPos pos, @Nonnull Player player) {
return new ItemStack(AtumBlocks.SARCOPHAGUS.get());
}
} | 412 | 0.957362 | 1 | 0.957362 | game-dev | MEDIA | 0.995279 | game-dev | 0.955269 | 1 | 0.955269 |
DarkPacks/SevTech-Ages | 1,328 | src/scripts/crafttweaker/staging/itemsAndRecipes/mods/progressiontweaks.zs | import crafttweaker.item.IIngredient;
import mods.zenstages.ZenStager;
import scripts.crafttweaker.stages.stageTutorial;
import scripts.crafttweaker.stages.stageZero;
import scripts.crafttweaker.stages.stageOne;
static stagedItems as IIngredient[][string] = {
stageTutorial.stage: [
<progressiontweaks:fire_pit_unlit:0>,
<progressiontweaks:spear:0>,
<progressiontweaks:stone_hammer:0>,
<progressiontweaks:tomahawk:0>
],
stageZero.stage: [
<progressiontweaks:broken_spear_shaft:0>,
<progressiontweaks:broken_spear_tip:0>,
<progressiontweaks:flat_bread:0>,
<progressiontweaks:unfired_clay_bowl:0>
],
stageOne.stage: [
<progressiontweaks:blank_teleporter:0>
]
};
static hiddenItems as IIngredient[] = [
<progressiontweaks:lime>,
<progressiontweaks:machine_frame>,
<progressiontweaks:nanomachine_frame>
];
function init() {
var modId as string = stagedItems.entrySet[0].value[0].items[0].definition.owner;
var modStage as string = scripts.crafttweaker.staging.itemsAndRecipes.modId.containsMod(modId);
var doOverride as bool = modStage != "";
for stageName, items in stagedItems {
if (doOverride && stageName != modStage) {
ZenStager.addModItemOverrides(modId, items);
}
ZenStager.getStage(stageName).addIngredients(items);
}
recipeUtil.hideItems(hiddenItems as IIngredient[]);
}
| 412 | 0.863522 | 1 | 0.863522 | game-dev | MEDIA | 0.968033 | game-dev | 0.786956 | 1 | 0.786956 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.