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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ForgeEssentials/ForgeEssentials | 2,032 | src/main/java/com/forgeessentials/perftools/MemoryWatchdog.java | package com.forgeessentials.perftools;
import java.util.TimerTask;
import com.forgeessentials.api.APIRegistry;
import com.forgeessentials.util.ServerUtil;
import com.forgeessentials.util.output.ChatOutputHandler;
import com.forgeessentials.util.output.logger.LoggingHandler;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.server.MinecraftServer;
import net.minecraftforge.fml.loading.FMLEnvironment;
import net.minecraftforge.fml.server.ServerLifecycleHooks;
/**
* Warns those with permission when the memory usage passes a certain percentage threshold
*/
public class MemoryWatchdog extends TimerTask
{
public MemoryWatchdog()
{
}
@Override
public void run()
{
long max = Runtime.getRuntime().maxMemory();
long total = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
long percentage = total * 100L / max;
if (percentage >= PerfToolsModule.percentageWarn)
{
MinecraftServer server = ServerLifecycleHooks.getCurrentServer();
try
{
if (FMLEnvironment.dist.isClient())
{
LoggingHandler.felog.info("High memory use detected. " + percentage + "% of memory in use.");
}
else
{
ChatOutputHandler.sendMessage(server.createCommandSourceStack(),
"[ForgeEssentials] High memory use detected. " + percentage + "% of memory in use.");
}
for (ServerPlayerEntity player : ServerUtil.getPlayerList())
if (APIRegistry.perms.checkPermission(player, PerfToolsModule.PERM_WARN))
ChatOutputHandler.chatNotification(player.createCommandSourceStack(),
"[ForgeEssentials] High memory use detected. " + percentage + "% of memory in use.");
}
catch (Exception ignored)
{
}
}
}
}
| 0 | 0.938912 | 1 | 0.938912 | game-dev | MEDIA | 0.866204 | game-dev | 0.928414 | 1 | 0.928414 |
DCS-Skunkworks/DCSFlightpanels | 5,904 | src/NonVisuals/GenericPanelBinding.cs | namespace NonVisuals
{
using System;
using System.Collections.Generic;
using System.Text;
using ClassLibraryCommon;
using HID;
public class GenericPanelBinding
{
private readonly GamingPanelEnum _panelType = GamingPanelEnum.Unknown;
private string _hidInstance;
private string _bindingHash;
private List<string> _settings = new(50);
private readonly StringBuilder _jsonString = new();
public GenericPanelBinding()
{ }
public GenericPanelBinding(string hidInstance, string bindingHash, GamingPanelEnum panelType)
{
_hidInstance = hidInstance;
_bindingHash = bindingHash;
_panelType = panelType;
}
public string HIDInstance
{
get => _hidInstance;
set => _hidInstance = value;
}
public string BindingHash
{
get => _bindingHash;
set => _bindingHash = value;
}
public List<string> Settings
{
get => _settings;
set => _settings = value;
}
public bool Match(HIDSkeleton hidSkeleton)
{
return HIDInstance.Equals(hidSkeleton.HIDInstance) && PanelType == hidSkeleton.GamingPanelType;
}
public bool Match(GenericPanelBinding genericPanelBinding)
{
return HIDInstance.Equals(genericPanelBinding.HIDInstance) && PanelType == genericPanelBinding.PanelType;
}
public void JSONAddLine(string jsonLine)
{
if (_jsonString.Length == 0)
{
_jsonString.Append(jsonLine);
}
else
{
_jsonString.AppendLine(RefactorClassNamesAndNameSpaces(jsonLine));
}
}
/// <summary>
/// Since the implementation of Streamdeck the projects have been organized and namespaces
/// have changed. Only in the JSON (Streamdeck) are namespaces saved within this project.
/// If a class changes name it will be handled here too.
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
private static string RefactorClassNamesAndNameSpaces(string s)
{
string result = s;
result = result.Replace("NonVisuals.StreamDeck", "NonVisuals.Panels.StreamDeck");
result = result.Replace("InputObject", "InputInterface");
result = result.Replace("SelectedDCSBIOSInput", "SelectedDCSBIOSInterface");
return result;
}
public GamingPanelEnum PanelType
{
get => _panelType;
init => _panelType = value;
}
public bool HasBeenDeleted { get; set; }
public string JSONString
{
get => _jsonString.ToString();
set
{
_jsonString.Clear();
_jsonString.Append(value);
}
}
/// <summary>
/// If a panel has been found with matching HID and type this will be true
/// </summary>
public bool InUse { get; set; }
public string SettingsString
{
get
{
if (IsJSON())
{
return _jsonString.ToString();
}
var stringBuilder = new StringBuilder(500);
foreach (var setting in _settings)
{
stringBuilder.AppendLine(setting);
}
return stringBuilder.ToString();
}
}
public bool IsJSON()
{
return PanelType == GamingPanelEnum.StreamDeckMini ||
PanelType == GamingPanelEnum.StreamDeckMiniV2 ||
PanelType == GamingPanelEnum.StreamDeck ||
PanelType == GamingPanelEnum.StreamDeckV2 ||
PanelType == GamingPanelEnum.StreamDeckMK2 ||
PanelType == GamingPanelEnum.StreamDeckXL ||
PanelType == GamingPanelEnum.StreamDeckXLRev2 ||
PanelType == GamingPanelEnum.StreamDeckPlus;
}
public void ClearSettings()
{
_settings.Clear();
}
public string ExportBinding()
{
var stringBuilder = new StringBuilder();
stringBuilder.AppendLine("PanelType=" + _panelType);
stringBuilder.AppendLine("PanelInstanceID=" + _hidInstance);
stringBuilder.AppendLine("BindingHash=" + _bindingHash);
stringBuilder.AppendLine(IsJSON() ? "BeginPanelJSON" : "BeginPanel");
if (IsJSON())
{
stringBuilder.Append(_jsonString);
}
else
{
foreach (var str in _settings)
{
if (!string.IsNullOrEmpty(str))
{
stringBuilder.AppendLine("\t" + str);
}
}
}
if (IsJSON())
{
stringBuilder.AppendLine(Environment.NewLine + "EndPanelJSON");
}
else
{
stringBuilder.AppendLine("EndPanel");
}
return stringBuilder.ToString();
}
}
public enum GenericBindingStateEnum
{
Unknown,
New,
Modified,
Deleted
}
public class ModifiedGenericBinding
{
public ModifiedGenericBinding(GenericBindingStateEnum state, GenericPanelBinding genericPanelBinding)
{
State = state;
GenericPanelBinding = genericPanelBinding;
}
public GenericBindingStateEnum State { get; }
public GenericPanelBinding GenericPanelBinding { get; }
}
}
| 0 | 0.873022 | 1 | 0.873022 | game-dev | MEDIA | 0.926686 | game-dev | 0.886371 | 1 | 0.886371 |
Gaby-Station/Gaby-Station | 3,166 | Content.Server/EntityEffects/Effects/MovespeedModifier.cs | // SPDX-FileCopyrightText: 2024 SlamBamActionman <83650252+SlamBamActionman@users.noreply.github.com>
// SPDX-FileCopyrightText: 2025 Aiden <28298836+Aidenkrz@users.noreply.github.com>
//
// SPDX-License-Identifier: AGPL-3.0-or-later
using Content.Shared.Chemistry.Components;
using Content.Shared.EntityEffects;
using Content.Shared.Movement.Systems;
using Robust.Shared.Prototypes;
using Robust.Shared.Timing;
namespace Content.Server.EntityEffects.Effects;
/// <summary>
/// Default metabolism for stimulants and tranqs. Attempts to find a MovementSpeedModifier on the target,
/// adding one if not there and to change the movespeed
/// </summary>
public sealed partial class MovespeedModifier : EntityEffect
{
/// <summary>
/// How much the entities' walk speed is multiplied by.
/// </summary>
[DataField]
public float WalkSpeedModifier { get; set; } = 1;
/// <summary>
/// How much the entities' run speed is multiplied by.
/// </summary>
[DataField]
public float SprintSpeedModifier { get; set; } = 1;
/// <summary>
/// How long the modifier applies (in seconds).
/// Is scaled by reagent amount if used with an EntityEffectReagentArgs.
/// </summary>
[DataField]
public float StatusLifetime = 2f;
protected override string? ReagentEffectGuidebookText(IPrototypeManager prototype, IEntitySystemManager entSys)
{
return Loc.GetString("reagent-effect-guidebook-movespeed-modifier",
("chance", Probability),
("walkspeed", WalkSpeedModifier),
("time", StatusLifetime));
}
/// <summary>
/// Remove reagent at set rate, changes the movespeed modifiers and adds a MovespeedModifierMetabolismComponent if not already there.
/// </summary>
public override void Effect(EntityEffectBaseArgs args)
{
var status = args.EntityManager.EnsureComponent<MovespeedModifierMetabolismComponent>(args.TargetEntity);
// Only refresh movement if we need to.
var modified = !status.WalkSpeedModifier.Equals(WalkSpeedModifier) ||
!status.SprintSpeedModifier.Equals(SprintSpeedModifier);
status.WalkSpeedModifier = WalkSpeedModifier;
status.SprintSpeedModifier = SprintSpeedModifier;
// only going to scale application time
var statusLifetime = StatusLifetime;
if (args is EntityEffectReagentArgs reagentArgs)
{
statusLifetime *= reagentArgs.Scale.Float();
}
IncreaseTimer(status, statusLifetime, args.EntityManager, args.TargetEntity);
if (modified)
args.EntityManager.System<MovementSpeedModifierSystem>().RefreshMovementSpeedModifiers(args.TargetEntity);
}
private void IncreaseTimer(MovespeedModifierMetabolismComponent status, float time, IEntityManager entityManager, EntityUid uid)
{
var gameTiming = IoCManager.Resolve<IGameTiming>();
var offsetTime = Math.Max(status.ModifierTimer.TotalSeconds, gameTiming.CurTime.TotalSeconds);
status.ModifierTimer = TimeSpan.FromSeconds(offsetTime + time);
entityManager.Dirty(uid, status);
}
} | 0 | 0.815254 | 1 | 0.815254 | game-dev | MEDIA | 0.933902 | game-dev | 0.894207 | 1 | 0.894207 |
Crypto137/MHServerEmu | 5,253 | src/MHServerEmu.Games/Regions/ObjectiveGraphs/ObjectiveGraph.cs | using System.Text;
using MHServerEmu.Core.Logging;
using MHServerEmu.Core.Serialization;
using MHServerEmu.Core.VectorMath;
using MHServerEmu.Games.Common;
namespace MHServerEmu.Games.Regions.ObjectiveGraphs
{
public class ObjectiveGraph : ISerialize
{
private static readonly Logger Logger = LogManager.CreateLogger();
private readonly Game _game;
private readonly Region _region;
private readonly List<ObjectiveGraphNode> _nodeList = new();
public ObjectiveGraph(Game game, Region region)
{
_game = game;
_region = region;
}
public bool Serialize(Archive archive)
{
bool success = true;
if (archive.IsPacking)
{
uint numNodes = (uint)_nodeList.Count;
success &= Serializer.Transfer(archive, ref numNodes);
// Node connection information is stored in temporary structs
List<ObjectiveGraphConnection> connectionList = new();
for (int i = 0; i < _nodeList.Count; i++)
{
ObjectiveGraphNode node = _nodeList[i];
node.Serialize(archive);
uint index = (uint)i;
Serializer.Transfer(archive, ref index);
foreach (var connection in node.IterateConnections())
connectionList.Add(new(node, connection.Key, connection.Value));
}
uint numConnections = (uint)connectionList.Count;
Serializer.Transfer(archive, ref numConnections);
foreach (ObjectiveGraphConnection connection in connectionList)
{
uint nodeIndex0 = (uint)_nodeList.IndexOf(connection.Node0);
uint nodeIndex1 = (uint)_nodeList.IndexOf(connection.Node1);
float distance = connection.Distance;
Serializer.Transfer(archive, ref nodeIndex0);
Serializer.Transfer(archive, ref nodeIndex1);
Serializer.Transfer(archive, ref distance);
}
}
else
{
DestroyGraph();
uint numNodes = 0;
success &= Serializer.Transfer(archive, ref numNodes);
for (uint i = 0; i < numNodes; i++)
{
ObjectiveGraphNode node = PushNode(archive);
if (node == null) Logger.Warn($"Serialize(): node == null");
}
uint numConnections = 0;
success &= Serializer.Transfer(archive, ref numConnections);
for (uint i = 0; i < numConnections; i++)
{
uint nodeIndex0 = 0;
uint nodeIndex1 = 0;
float distance = 0f;
success &= Serializer.Transfer(archive, ref nodeIndex0);
success &= Serializer.Transfer(archive, ref nodeIndex1);
success &= Serializer.Transfer(archive, ref distance);
if (nodeIndex0 >= _nodeList.Count || _nodeList[(int)nodeIndex0] == null)
{
Logger.Warn($"Serialize(): Unpacked invalid index {nodeIndex0} for node0");
continue;
}
if (nodeIndex1 >= _nodeList.Count || _nodeList[(int)nodeIndex1] == null)
{
Logger.Warn($"Serialize(): Unpacked invalid index {nodeIndex1} for node1");
continue;
}
_nodeList[(int)nodeIndex0].Connect(_nodeList[(int)nodeIndex1], distance);
_nodeList[(int)nodeIndex1].Connect(_nodeList[(int)nodeIndex0], distance);
}
_nodeList.Sort();
}
return success;
}
public override string ToString()
{
StringBuilder sb = new();
for (int i = 0; i < _nodeList.Count; i++)
sb.AppendLine($"{nameof(_nodeList)}[{i}]: {_nodeList[i]}");
return sb.ToString();
}
private ObjectiveGraphNode PushNode(Archive archive)
{
ObjectiveGraphNode node = new(_game, _region, 0, Vector3.Zero, ObjectiveGraphType.Invalid);
node.Serialize(archive);
// This method is called only during deserialization, and existing nodes are cleared before deserialization.
// So rather than resizing an array, we are going to use a list and use the encoded index just for verification.
_nodeList.Add(node);
uint index = 0;
Serializer.Transfer(archive, ref index);
if (_nodeList.Count - 1 != (int)index)
Logger.Warn($"PushNode(): Node index mismatch (expected {index}, actual {_nodeList.Count - 1})");
// TODO: find and insert into the correct cell node
return node;
}
private void DestroyGraph()
{
// if (_game == null) return;
_nodeList.Clear();
}
}
}
| 0 | 0.712413 | 1 | 0.712413 | game-dev | MEDIA | 0.63886 | game-dev | 0.947067 | 1 | 0.947067 |
ravendb/docs | 12,247 | versioned_docs/version-5.3/document-extensions/timeseries/client-api/operations/patch.mdx | ---
title: "Operations: Patch Time Series"
hide_table_of_contents: true
sidebar_label: Patch
sidebar_position: 2
---
import Admonition from '@theme/Admonition';
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
import CodeBlock from '@theme/CodeBlock';
import LanguageSwitcher from "@site/src/components/LanguageSwitcher";
import LanguageContent from "@site/src/components/LanguageContent";
# Operations: Patch Time Series
<Admonition type="note" title="">
* Time series data can be patched -
* to a single document located by its ID, using [PatchOperation](../../../../client-api/operations/patching/single-document.mdx#patching-how-to-perform-single-document-patch-operations).
* to multiple documents located by a query, using [PatchByQueryOperation](../../../../client-api/operations/patching/set-based.mdx).
* Both patching operations can be used to Append, Get and Delete time series entries.
* In this page:
* [Patching Operations](../../../../document-extensions/timeseries/client-api/operations/patch.mdx#patching-operations)
* [`PatchOperation`](../../../../document-extensions/timeseries/client-api/operations/patch.mdx#patchoperation)
* [Syntax](../../../../document-extensions/timeseries/client-api/operations/patch.mdx#syntax)
* [Usage Flow](../../../../document-extensions/timeseries/client-api/operations/patch.mdx#usage-flow)
* [Usage Samples](../../../../document-extensions/timeseries/client-api/operations/patch.mdx#usage-samples)
* [`PatchByQueryOperation`](../../../../document-extensions/timeseries/client-api/operations/patch.mdx#patchbyqueryoperation)
* [Syntax](../../../../document-extensions/timeseries/client-api/operations/patch.mdx#syntax-1)
* [Usage Flow](../../../../document-extensions/timeseries/client-api/operations/patch.mdx#usage-flow-1)
* [Usage Samples](../../../../document-extensions/timeseries/client-api/operations/patch.mdx#usage-samples-1)
</Admonition>
## Patching Operations
<Admonition type="info" title="">
* To patch time series data, use `PatchOperation` or `PatchByQueryOperation`.
* `PatchOperation` is RavenDB's operation for single-document patching, and
`PatchByQueryOperation` is used for set-based document operations.
You can use both to patch time series data, by
[customizing the JavaScript](../../../../document-extensions/timeseries/client-api/javascript-support.mdx)
they are using.
</Admonition>
* Use `PatchOperation` to **load a document by its ID and patch it time series entries**.
Here, for example, we use `PatchOperation` to patch a document a single time series entry.
<TabItem value="TS_region-Operation_Patch-Append-Single-TS-Entry" label="TS_region-Operation_Patch-Append-Single-TS-Entry">
<CodeBlock language="csharp">
{`var baseTime = DateTime.UtcNow;
var patchRequest = new PatchRequest
\{
// Define the patch request using JavaScript:
Script = "timeseries(this, $timeseries).append($timestamp, $values, $tag);",
// Provide values for the parameters in the script:
Values =
\{
\{ "timeseries", "HeartRates" \},
\{ "timestamp", baseTime.AddMinutes(1) \},
\{ "values", 59d \},
\{ "tag", "watches/fitbit" \}
\}
\};
// Define the patch operation;
var patchOp = new PatchOperation("users/john", null, patchRequest);
// Execute the operation:
store.Operations.Send(patchOp);
`}
</CodeBlock>
</TabItem>
* Use `PatchByQueryOperation` to **run a document query and patch time series entries to matching documents**.
Here, we use `PatchByQueryOperation` to append a time series entry to all
documents of the User collection.
<TabItem value="TS_region-PatchByQueryOperation-Append-To-Multiple-Docs" label="TS_region-PatchByQueryOperation-Append-To-Multiple-Docs">
<CodeBlock language="csharp">
{`var indexQuery = new IndexQuery
\{
// Define the query and the patching action that follows the 'update' keyword:
Query = @"from Users as u
update
\{
timeseries(u, $name).append($time, $values, $tag)
\}",
// Provide values for the parameters in the script:
QueryParameters = new Parameters
\{
\{ "name", "HeartRates" \},
\{ "time", baseline.AddMinutes(1) \},
\{ "values", new[] \{59d\} \},
\{ "tag", "watches/fitbit" \}
\}
\};
// Define the patch operation:
var patchByQueryOp = new PatchByQueryOperation(indexQuery);
// Execute the operation:
store.Operations.Send(patchByQueryOp);
`}
</CodeBlock>
</TabItem>
## `PatchOperation`
#### Syntax
* **`PatchOperation`**
* **Definition**
<TabItem value="PatchOperation-definition" label="PatchOperation-definition">
<CodeBlock language="csharp">
{`public PatchOperation(
string id,
string changeVector,
PatchRequest patch,
PatchRequest patchIfMissing = null,
bool skipPatchIfChangeVectorMismatch = false)
`}
</CodeBlock>
</TabItem>
* **Parameters**
| Parameters | Type | Description |
|:-------------|:-------------|:-------------|
| `id` | `string` | Patched document ID |
| `changeVector` | `string` | Change vector, to verify that the document hasn't been modified. <br/> Can be `null`. |
| `patch` | `PatchRequest` | The patching JavaScript |
| `patchIfMissing` | `PatchRequest` | Patching JavaScript to be used if the document isn't found |
| `skipPatchIfChangeVectorMismatch` | `bool` | If true, do not patch if the document has been modified <br/> default: **false** |
* **`PatchRequest`**
* **Definition**
<TabItem value="PatchRequest-definition" label="PatchRequest-definition">
<CodeBlock language="csharp">
{`public class PatchRequest
\{
// The patching script
public string Script \{ get; set; \}
// Values for the parameters used by the patching script
public Dictionary<string, object> Values \{ get; set; \}
\}
`}
</CodeBlock>
</TabItem>
* **Parameters**
| Parameters | Type | Description |
|:-------------|:-------------|:-------------|
| `Script` | `string` | Patching script |
| `Values` | `Dictionary<string, object>` | Values that the patching script can use |
#### Usage Flow
* Create an instance of `PatchOperation` and pass its constructor -
* the document ID
* the change vector (or `null`)
* a new `PatchRequest` instance
* Use the `PatchRequest` instance to pass `PatchOperation`
a JavaScript that appends or deletes time series entries.
* Call `store.Operations.Send` to execute the operation.
#### Usage Samples
* In this sample, we provide `PatchOperation`with a script that appends
100 time series entries to a document.
Timestamps and values are drawn from an array, and other
arguments are provided in the "Values" section.
<TabItem value="TS_region-Operation_Patch-Append-100-TS-Entries" label="TS_region-Operation_Patch-Append-100-TS-Entries">
<CodeBlock language="csharp">
{`var baseTime = DateTime.UtcNow;
// Create arrays of timestamps and random values to patch
var values = new List<double>();
var timeStamps = new List<DateTime>();
for (var i = 0; i < 100; i++)
\{
values.Add(68 + Math.Round(19 * new Random().NextDouble()));
timeStamps.Add(baseTime.AddMinutes(i));
\}
var patchRequest = new PatchRequest
\{
Script = @"var i = 0;
for (i = 0; i < $values.length; i++) \{
timeseries(id(this), $timeseries).append (
$timeStamps[i],
$values[i],
$tag);
\}",
Values =
\{
\{ "timeseries", "HeartRates" \},
\{ "timeStamps", timeStamps \},
\{ "values", values \},
\{ "tag", "watches/fitbit" \}
\}
\};
var patchOp = new PatchOperation("users/john", null, patchRequest);
store.Operations.Send(patchOp);
`}
</CodeBlock>
</TabItem>
* In this sample, we use `PatchOperation` to delete a range of 50 time series
entries from a document.
<TabItem value="TS_region-Operation_Patch-Delete-50-TS-Entries" label="TS_region-Operation_Patch-Delete-50-TS-Entries">
<CodeBlock language="csharp">
{`store.Operations.Send(new PatchOperation("users/john", null,
new PatchRequest
\{
Script = "timeseries(this, $timeseries).delete($from, $to);",
Values =
\{
\{ "timeseries", "HeartRates" \},
\{ "from", baseTime \},
\{ "to", baseTime.AddMinutes(49) \}
\}
\}));
`}
</CodeBlock>
</TabItem>
## `PatchByQueryOperation`
#### Syntax
* **`store.Operations.Send` Definition**
<TabItem value="json" label="json">
<CodeBlock language="json">
{`public Operation Send(IOperation<OperationIdResult> operation,
SessionInfo sessionInfo = null)
`}
</CodeBlock>
</TabItem>
* **`PatchByQueryOperation` Definition**
<TabItem value="PatchByQueryOperation-definition" label="PatchByQueryOperation-definition">
<CodeBlock language="csharp">
{`-1
public PatchByQueryOperation(string queryToUpdate)
`}
</CodeBlock>
</TabItem>
* **Parameters**
| Parameters | Type | Description |
|:-------------|:-------------|:-------------|
| `queryToUpdate` | `IndexQuery` | The query, including the JavaScript |
| `QueryOperationOptions` | `options` | Additional options <br/> Default: `null` |
* **Return Value**: `Operation`
#### Usage Flow
* Create a `PatchByQueryOperation` operation.
* Pass `PatchByQueryOperation` a new `IndexQuery` instance.
* Add the `IndexQuery` instance a JavaScript that specifies
the query you want to run.
* Call `store.Operations.Send` to execute the operation.
#### Usage Samples
* In this sample, we run a document query and delete the HeartRate time series
from documents we find.
<TabItem value="TS_region-PatchByQueryOperation-Delete-From-Multiple-Docs" label="TS_region-PatchByQueryOperation-Delete-From-Multiple-Docs">
<CodeBlock language="csharp">
{`PatchByQueryOperation deleteByQueryOp = new PatchByQueryOperation(new IndexQuery
\{
Query = @"from Users as u
where u.Age < 30
update
\{
timeseries(u, $name).delete($from, $to)
\}",
QueryParameters = new Parameters
\{
\{ "name", "HeartRates" \},
\{ "from", DateTime.MinValue \},
\{ "to", DateTime.MaxValue \}
\}
\});
// Execute the operation:
// Time series "HeartRates" will be deleted for all users with age < 30
store.Operations.Send(deleteByQueryOp);
`}
</CodeBlock>
</TabItem>
* In this sample, we patch each User document a "NumberOfUniqueTagsInTS" field with
the number of different tags in the user's "ExerciseHeartRate" time series.
To do this, we use the JavaScript `get` method to get each time series' entries (the
range we choose includes them all), and check each entry's tag.
<TabItem value="TS_region-PatchByQueryOperation-Get" label="TS_region-PatchByQueryOperation-Get">
<CodeBlock language="csharp">
{`PatchByQueryOperation patchNumOfUniqueTags = new PatchByQueryOperation(new IndexQuery
\{
Query = @"
declare function patchDocumentField(doc) \{
var differentTags = [];
var entries = timeseries(doc, $name).get($from, $to);
for (var i = 0; i < entries.length; i++) \{
var e = entries[i];
if (e.Tag !== null) \{
if (!differentTags.includes(e.Tag)) \{
differentTags.push(e.Tag);
\}
\}
\}
doc.NumberOfUniqueTagsInTS = differentTags.length;
return doc;
\}
from Users as u
update \{
put(id(u), patchDocumentField(u))
\}",
QueryParameters = new Parameters
\{
\{ "name", "HeartRates" \},
\{ "from", DateTime.MinValue \},
\{ "to", DateTime.MaxValue \}
\}
\});
// Execute the operation and Wait for completion:
var result = store.Operations.Send(patchNumOfUniqueTags).WaitForCompletion();
`}
</CodeBlock>
</TabItem>
| 0 | 0.795764 | 1 | 0.795764 | game-dev | MEDIA | 0.168505 | game-dev | 0.874094 | 1 | 0.874094 |
PacktPublishing/Expert-CSharp-Programming | 4,010 | ch01/Codebreaker.Bot.Console/CodeBreakerAlgorithms.cs | using System.Runtime.CompilerServices;
namespace CodeBreaker.Bot;
public record struct KeyPegWithFlag(string Value, bool Used);
public static class CodeBreakerAlgorithms
{
/// <summary>
/// Reduces the possible values based on the black matches with the selection
/// </summary>
/// <param name="values">The list of possible moves</param>
/// <param name="blackHits">The number of black hits with the selection</param>
/// <param name="selection">The key pegs of the selected move</param>
/// <returns>The remaining possible moves</returns>
/// <exception cref="ArgumentException"></exception>
public static List<string[]> ProcessBlackMatches(this IList<string[]> values, int blackHits, string[] guesses)
{
if (blackHits is < 1 or > 3)
{
throw new ArgumentException("invalid argument - hits need to be between 1 and 3");
}
List<string[]> matchingValues1 = [.. values
.Where(fields => fields.Where((color, ix) => color == guesses[ix]).Count() == blackHits) ];
List<string[]> matchingValues = [];
foreach (var fields in values)
{
int count = 0;
for (int i = 0; i < fields.Length; i++)
{
if (fields[i] == guesses[i])
{
count++;
}
}
if (count == blackHits)
{
matchingValues.Add(fields);
}
}
return matchingValues;
}
/// <summary>
/// Reduces the possible values based on the white matches with the selection
/// </summary>
/// <param name="values">The possible values</param>
/// <param name="whiteBlackHits">The number of white hits with the selection</param>
/// <param name="selection">The selected pegs</param>
/// <returns>The remaining possible values</returns>
public static List<string[]> ProcessWhiteMatches(this IList<string[]> values, int whiteBlackHits, string[] guesses)
{
if (whiteBlackHits is < 1 or > 4)
{
throw new ArgumentException("invalid argument - hits need to be between 1 and 4");
}
List<string[]> matchingValues = new(values.Count); // max size needed of the previous collection
foreach (var value in values)
{
KeyPegArray guesses1 = new();
for (int i = 0; i < 4; i++)
{
guesses1[i] = new KeyPegWithFlag(guesses[i], false);
}
KeyPegArray row = new();
for (int i = 0; i < 4; i++)
{
row[i] = new KeyPegWithFlag(value[i], false);
}
int matchCount = 0;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (!row[i].Used && !guesses1[j].Used && row[i].Value == guesses1[j].Value)
{
matchCount++;
row[i] = row[i] with { Used = true };
guesses1[j] = guesses1[j] with { Used = true };
}
}
if (matchCount == whiteBlackHits)
{
matchingValues.Add(value);
}
}
}
return matchingValues;
}
/// <summary>
/// Reduces the possible values if no selection was correct
/// </summary>
/// <param name="values">The possible values</param>
/// <param name="guesses">The selected pegs</param>
/// <returns>The remaining possible values</returns>
public static List<string[]> ProcessNoMatches(this IList<string[]> values, string[] guesses)
{
List<string[]> matchingValues;
matchingValues = [.. values.Where(fields => !fields.Intersect(guesses).Any()).ToList()];
return matchingValues;
}
}
[InlineArray(4)]
internal struct KeyPegArray
{
private KeyPegWithFlag _keyPegWithFlag;
} | 0 | 0.916884 | 1 | 0.916884 | game-dev | MEDIA | 0.475199 | game-dev | 0.961369 | 1 | 0.961369 |
loukylor/VRC-Mods | 5,111 | InstanceHistory/MenuManager.cs | using System;
using MelonLoader;
using UnityEngine;
using UnityEngine.UI;
using VRChatUtilityKit.Ui;
using VRChatUtilityKit.Utilities;
namespace InstanceHistory
{
class MenuManager
{
private static int _instanceIndex = 0;
public static int InstanceIndex
{
get { return _instanceIndex; }
set
{
if (value > InstanceManager.instances.Count - 1 || value < 0)
return;
_instanceIndex = value;
pageNumLabel.TextComponent.text = $"Page: {PageNum} of {LastPageNum}";
if (PageNum == LastPageNum || LastPageNum == 1)
pageDown.gameObject.SetActive(false);
else
pageDown.gameObject.SetActive(true);
if (PageNum == 1)
{
pageUp.gameObject.SetActive(false);
backButton.gameObject.SetActive(true);
}
else
{
pageUp.gameObject.SetActive(true);
backButton.gameObject.SetActive(false);
}
for (int i = 0; i < 9; i++)
{
if (_instanceIndex + i >= InstanceManager.instances.Count)
{
buttons[i].gameObject.SetActive(false);
}
else
{
InstanceManager.WorldInstance instance = InstanceManager.instances[InstanceIndex + i];
buttons[i].TextComponent.text = instance.worldName + ": " + instance.instanceId.Split('~')[0];
buttons[i].ButtonComponent.onClick = new Button.ButtonClickedEvent();
buttons[i].ButtonComponent.onClick.AddListener(new Action(() => WorldManager.EnterWorld(instance.worldId + ":" + instance.instanceId)));
buttons[i].gameObject.SetActive(true);
}
}
}
}
public static int PageNum
{
get { return Mathf.CeilToInt((_instanceIndex + 1) / 9f); }
}
public static int LastPageNum
{
get { return Mathf.CeilToInt(InstanceManager.instances.Count / 9f); }
}
public static SingleButton openButton;
public static SubMenu menu;
private static readonly SingleButton[] buttons = new SingleButton[9];
private static SingleButton pageUp;
private static SingleButton pageDown;
private static SingleButton backButton;
private static Label pageNumLabel;
public static void UiInit()
{
MelonLogger.Msg("Loading UI...");
menu = new SubMenu(QuickMenu.prop_QuickMenu_0.gameObject, "InstanceHistoryModMenu");
openButton = new SingleButton(QuickMenu.prop_QuickMenu_0.transform.FindChild("ShortcutMenu").gameObject, new Vector3(Config.openButtonX.Value, Config.openButtonY.Value), "Instance History", new Action(OpenInstanceHistoryMenu), "Open instance history", "InstancenHistoryButton");
openButton.gameObject.SetActive(!(InstanceHistoryMod.HasUIX && Config.useUIX.Value));
Config.openButtonX.OnValueChanged += OnPositionChange;
Config.openButtonY.OnValueChanged += OnPositionChange;
if (InstanceHistoryMod.HasUIX)
typeof(UIXManager).GetMethod("AddOpenButtonToUIX").Invoke(null, null);
pageUp = new SingleButton(menu.gameObject, GameObject.Find("UserInterface/QuickMenu/EmojiMenu/PageUp"), new Vector3(4, 0), "", new Action(() => InstanceIndex -= 9), $"Go up a page", "UpPageButton");
pageDown = new SingleButton(menu.gameObject, GameObject.Find("UserInterface/QuickMenu/EmojiMenu/PageDown"), new Vector3(4, 2), "", new Action(() => InstanceIndex += 9), $"Go down a page", "DownPageButton");
backButton = new SingleButton(menu.gameObject, new Vector3(4, 0), "Back", new Action(() => UiManager.OpenSubMenu("UserInterface/QuickMenu/ShortcutMenu")), "Press to go back to the Shortcut Menu", "BackButton", textColor: Color.yellow);
backButton.gameObject.SetActive(false);
pageNumLabel = new Label(menu.gameObject, new Vector3(4, 1), $"Page: 1 of {LastPageNum}", "PageNumberLabel");
for (int i = 0; i < 9; i++)
buttons[i] = new SingleButton(menu.gameObject, new Vector3((i % 3) + 1, Mathf.Floor(i / 3)), "Placeholder text", null, "Placeholder text", $"World Button {i + 1}", resize: true);
MelonLogger.Msg("UI Loaded!");
}
public static void OpenInstanceHistoryMenu()
{
menu.OpenSubMenu();
InstanceIndex = 0;
}
private static void OnPositionChange(float oldValue, float newValue)
{
if (oldValue == newValue) return;
openButton.gameObject.transform.localPosition = Converters.ConvertToUnityUnits(new Vector3(Config.openButtonX.Value, Config.openButtonY.Value));
}
}
}
| 0 | 0.921955 | 1 | 0.921955 | game-dev | MEDIA | 0.982208 | game-dev | 0.917799 | 1 | 0.917799 |
savatkinv/VoxelGame | 3,494 | VoxelGame_UnityProject/Assets/Plugins/Zenject/OptionalExtras/SampleGame2 (Advanced)/Scripts/Installers/GameInstaller.cs | using System;
using UnityEngine;
namespace Zenject.SpaceFighter
{
// Main installer for our game
public class GameInstaller : MonoInstaller
{
[Inject]
Settings _settings = null;
public override void InstallBindings()
{
Container.BindInterfacesAndSelfTo<EnemySpawner>().AsSingle();
Container.BindFactory<float, float, EnemyFacade, EnemyFacade.Factory>()
// We could just use FromMonoPoolableMemoryPool here instead, but
// for IL2CPP to work we need our pool class to be used explicitly here
.FromPoolableMemoryPool<float, float, EnemyFacade, EnemyFacadePool>(poolBinder => poolBinder
// Spawn 5 enemies right off the bat so that we don't incur spikes at runtime
.WithInitialSize(5)
.FromSubContainerResolve()
.ByNewPrefabInstaller<EnemyInstaller>(_settings.EnemyFacadePrefab)
// Place each enemy under an Enemies game object at the root of scene hierarchy
.UnderTransformGroup("Enemies"));
Container.BindFactory<float, float, BulletTypes, Bullet, Bullet.Factory>()
// We could just use FromMonoPoolableMemoryPool here instead, but
// for IL2CPP to work we need our pool class to be used explicitly here
.FromPoolableMemoryPool<float, float, BulletTypes, Bullet, BulletPool>(poolBinder => poolBinder
// Spawn 20 right off the bat so that we don't incur spikes at runtime
.WithInitialSize(20)
// Bullets are simple enough that we don't need to make a subcontainer for them
// The logic can all just be in one class
.FromComponentInNewPrefab(_settings.BulletPrefab)
.UnderTransformGroup("Bullets"));
Container.Bind<LevelBoundary>().AsSingle();
Container.BindFactory<Explosion, Explosion.Factory>()
// We could just use FromMonoPoolableMemoryPool here instead, but
// for IL2CPP to work we need our pool class to be used explicitly here
.FromPoolableMemoryPool<Explosion, ExplosionPool>(poolBinder => poolBinder
// Spawn 4 right off the bat so that we don't incur spikes at runtime
.WithInitialSize(4)
.FromComponentInNewPrefab(_settings.ExplosionPrefab)
.UnderTransformGroup("Explosions"));
Container.Bind<AudioPlayer>().AsSingle();
Container.BindInterfacesTo<GameRestartHandler>().AsSingle();
Container.Bind<EnemyRegistry>().AsSingle();
GameSignalsInstaller.Install(Container);
}
[Serializable]
public class Settings
{
public GameObject EnemyFacadePrefab;
public GameObject BulletPrefab;
public GameObject ExplosionPrefab;
}
// We could just use FromMonoPoolableMemoryPool above, but we have to use these instead
// for IL2CPP to work
class EnemyFacadePool : MonoPoolableMemoryPool<float, float, IMemoryPool, EnemyFacade>
{
}
class BulletPool : MonoPoolableMemoryPool<float, float, BulletTypes, IMemoryPool, Bullet>
{
}
class ExplosionPool : MonoPoolableMemoryPool<IMemoryPool, Explosion>
{
}
}
}
| 0 | 0.785817 | 1 | 0.785817 | game-dev | MEDIA | 0.974401 | game-dev | 0.679344 | 1 | 0.679344 |
PMC-Unga-Marines/Unga-Marines | 5,732 | code/modules/mapping/map_template.dm | /datum/map_template
var/name = "Default Template Name"
var/width = 0
var/height = 0
var/mappath = null
/// Times loaded this round
var/loaded = 0
var/datum/parsed_map/cached_map
var/keep_cached_map = FALSE
///Default area associated with the map template
var/default_area
///if true, turfs loaded from this template are placed on top of the turfs already there, defaults to TRUE
var/should_place_on_top = TRUE
///if true, creates a list of all atoms created by this template loading, defaults to FALSE
var/returns_created_atoms = FALSE
///the list of atoms created by this template being loaded, only populated if returns_created_atoms is TRUE
var/list/created_atoms = list()
//make sure this list is accounted for/cleared if you request it from ssatoms!
/datum/map_template/New(path = null, rename = null, cache = FALSE)
if(path)
mappath = path
if(mappath)
preload_size(mappath, cache)
if(rename)
name = rename
/datum/map_template/proc/preload_size(path, cache = FALSE)
var/datum/parsed_map/parsed = new(file(path))
var/bounds = parsed?.bounds
if(bounds)
width = bounds[MAP_MAXX] // Assumes all templates are rectangular, have a single Z level, and begin at 1,1,1
height = bounds[MAP_MAXY]
if(cache)
cached_map = parsed
return bounds
/datum/map_template/proc/initTemplateBounds(list/bounds)
if(!bounds) //something went wrong
stack_trace("[name] template failed to initialize correctly!")
return
var/list/turfs = block(
locate(
bounds[MAP_MINX],
bounds[MAP_MINY],
bounds[MAP_MINZ]
),
locate(
bounds[MAP_MAXX],
bounds[MAP_MAXY],
bounds[MAP_MAXZ]
)
)
var/list/atom/movable/movables = list()
var/list/obj/structure/cable/cables = list()
var/list/obj/docking_port/stationary/ports = list()
var/list/area/areas = list()
for(var/turf/current_turf as anything in turfs)
var/area/current_turfs_area = current_turf.loc
areas |= current_turfs_area
if(!SSatoms.initialized)
continue
for(var/movable_in_turf in current_turf)
if(istype(movable_in_turf, /obj/docking_port/mobile))
continue // mobile docking ports need to be initialized after their template has finished loading, to ensure that their bounds are setup
movables += movable_in_turf
if(istype(movable_in_turf, /obj/structure/cable))
cables += movable_in_turf
continue
if(istype(movable_in_turf, /obj/docking_port/stationary))
ports += movable_in_turf
// Not sure if there is some importance here to make sure the area is in z
// first or not. Its defined In Initialize yet its run first in templates
// BEFORE so... hummm
SSmapping.reg_in_areas_in_z(areas)
if(!SSatoms.initialized)
return
SSatoms.InitializeAtoms(areas + turfs + movables, returns_created_atoms ? created_atoms : null)
// Sadly we still need this, so the shuttles like Canterbury properly make powernets
SSmachines.setup_template_powernets(cables)
/datum/map_template/proc/load_new_z(minimap = TRUE, list/traits = list(ZTRAIT_AWAY = TRUE))
var/x = round((world.maxx - width) * 0.5) + 1
var/y = round((world.maxy - height) * 0.5) + 1
var/datum/space_level/level = SSmapping.add_new_zlevel(name, list(), contain_turfs = FALSE)
var/datum/parsed_map/parsed = load_map(
file(mappath),
x,
y,
level.z_value,
no_changeturf = (SSatoms.initialized == INITIALIZATION_INSSATOMS),
place_on_top = should_place_on_top,
new_z = TRUE,
)
var/list/bounds = parsed.bounds
if(!bounds)
return FALSE
require_area_resort()
//initialize things that are normally initialized after map load
initTemplateBounds(bounds)
SSmodularmapping.load_modular_maps() //must be run after initTemplateBounds so markers have an actual loc
SSweather.load_late_z(level.z_value)
SSair.setup_atmos_machinery()
SSair.setup_pipenets()
smooth_zlevel(level.z_value)
if(minimap)
SSminimaps.load_new_z(null, level)
log_game("Z-level [name] loaded at [x], [y], [world.maxz]")
return level
/datum/map_template/proc/load(turf/T, centered = FALSE, delete = FALSE)
if(centered)
T = locate(T.x - round(width * 0.5), T.y - round(height * 0.5), T.z)
if(!T)
return
if((T.x + width) - 1 > world.maxx)
return
if((T.y + height) - 1> world.maxy)
return
// Accept cached maps, but don't save them automatically - we don't want
// ruins clogging up memory for the whole round.
var/datum/parsed_map/parsed = cached_map || new(file(mappath))
cached_map = keep_cached_map ? parsed : null
var/list/turf_blacklist = list()
update_blacklist(T, turf_blacklist)
UNSETEMPTY(turf_blacklist)
parsed.turf_blacklist = turf_blacklist
if(!parsed.load(
T.x,
T.y,
T.z,
crop_map = TRUE,
no_changeturf = (SSatoms.initialized == INITIALIZATION_INSSATOMS),
place_on_top = should_place_on_top,
))
return
var/list/bounds = parsed.bounds
if(!bounds)
return
require_area_resort()
//initialize things that are normally initialized after map load
initTemplateBounds(bounds)
log_game("[name] loaded at [T.x], [T.y], [T.z]")
return bounds
///Whatever special stuff you want
/datum/map_template/proc/post_load()
return
/datum/map_template/proc/update_blacklist(turf/T, list/input_blacklist)
return
/datum/map_template/proc/get_affected_turfs(turf/T, centered = FALSE)
var/turf/placement = T
if(centered)
var/turf/corner = locate(placement.x - round(width * 0.5), placement.y - round(height * 0.5), placement.z)
if(corner)
placement = corner
return block(placement, locate(placement.x+width-1, placement.y+height-1, placement.z))
//for your ever biggening badminnery kevinz000
//❤ - Cyberboss
/proc/load_new_z_level(file, name, minimap = TRUE, list/traits = list())
var/datum/map_template/template = new(file, name)
return template.load_new_z(minimap, traits)
| 0 | 0.981921 | 1 | 0.981921 | game-dev | MEDIA | 0.837788 | game-dev | 0.967322 | 1 | 0.967322 |
davidly/cpm_compilers | 8,083 | borland turbo pascal v3/TTT.PAS | { App to prove you can't win at Tic-Tac-Toe }
{ This flag turns off checking if the recursion stack and heap collide }
{$K-}
program ttt;
{$I timeutil.pas}
{$I cpm_gt.pas }
const
scoreWin = 6;
scoreTie = 5;
scoreLose = 4;
scoreMax = 9;
scoreMin = 2;
scoreInvalid = 0;
pieceBlank = 0;
pieceX = 1;
pieceO = 2;
iterations = 1;
type
boardType = array[ 0..8 ] of integer;
CommandString = string[127];
var
evaluated: integer;
board: boardType;
timeStart, timeEnd: timetype;
procedure dumpBoard;
var
i : integer;
begin
Write( '{' );
for i := 0 to 8 do
Write( board[i] );
Write( '}' );
end;
function lookForWinner : integer;
var
t, p : integer;
begin
{dumpBoard;}
p := pieceBlank;
t := board[ 0 ];
if pieceBlank <> t then
begin
if ( ( ( t = board[1] ) and ( t = board[2] ) ) or
( ( t = board[3] ) and ( t = board[6] ) ) ) then
p := t;
end;
if pieceBlank = p then
begin
t := board[1];
if ( t = board[4] ) and ( t = board[7] ) then
p := t
else
begin
t := board[2];
if ( t = board[5] ) and ( t = board[8] ) then
p := t
else
begin
t := board[3];
if ( t = board[4] ) and ( t = board[5] ) then
p := t
else
begin
t := board[6];
if ( t = board[7] ) and ( t = board[8] ) then
p := t
else
begin
t := board[4];
if ( ( ( t = board[0] ) and ( t = board[8] ) ) or
( ( t = board[2] ) and ( t = board[6] ) ) ) then
p := t
end;
end;
end;
end;
end;
lookForWinner := p;
end;
function winner2( move: integer ) : integer;
var
x : integer;
begin
case move of
0: begin
x := board[ 0 ];
if not ( ( ( x = board[1] ) and ( x = board[2] ) ) or
( ( x = board[3] ) and ( x = board[6] ) ) or
( ( x = board[4] ) and ( x = board[8] ) ) )
then x := PieceBlank;
end;
1: begin
x := board[ 1 ];
if not ( ( ( x = board[0] ) and ( x = board[2] ) ) or
( ( x = board[4] ) and ( x = board[7] ) ) )
then x := PieceBlank;
end;
2: begin
x := board[ 2 ];
if not ( ( ( x = board[0] ) and ( x = board[1] ) ) or
( ( x = board[5] ) and ( x = board[8] ) ) or
( ( x = board[4] ) and ( x = board[6] ) ) )
then x := PieceBlank;
end;
3: begin
x := board[ 3 ];
if not ( ( ( x = board[4] ) and ( x = board[5] ) ) or
( ( x = board[0] ) and ( x = board[6] ) ) )
then x := PieceBlank;
end;
4: begin
x := board[ 4 ];
if not ( ( ( x = board[0] ) and ( x = board[8] ) ) or
( ( x = board[2] ) and ( x = board[6] ) ) or
( ( x = board[1] ) and ( x = board[7] ) ) or
( ( x = board[3] ) and ( x = board[5] ) ) )
then x := PieceBlank;
end;
5: begin
x := board[ 5 ];
if not ( ( ( x = board[3] ) and ( x = board[4] ) ) or
( ( x = board[2] ) and ( x = board[8] ) ) )
then x := PieceBlank;
end;
6: begin
x := board[ 6 ];
if not ( ( ( x = board[7] ) and ( x = board[8] ) ) or
( ( x = board[0] ) and ( x = board[3] ) ) or
( ( x = board[4] ) and ( x = board[2] ) ) )
then x := PieceBlank;
end;
7: begin
x := board[ 7 ];
if not ( ( ( x = board[6] ) and ( x = board[8] ) ) or
( ( x = board[1] ) and ( x = board[4] ) ) )
then x := PieceBlank;
end;
8: begin
x := board[ 8 ];
if not ( ( ( x = board[6] ) and ( x = board[7] ) ) or
( ( x = board[2] ) and ( x = board[5] ) ) or
( ( x = board[0] ) and ( x = board[4] ) ) )
then x := PieceBlank;
end;
end;
winner2 := x;
end;
{ If this flag isn't set, recursion doesn't work on CP/M }
{$A-}
function minmax( alpha: integer; beta: integer; depth: integer; move: integer ): integer;
var
p, value, pieceMove, score : integer;
begin
evaluated := evaluated + 1;
value := scoreInvalid;
if depth >= 4 then
begin
{ p := lookForWinner; } { this is much slower }
p := winner2( move );
if p <> pieceBlank then
begin
if p = pieceX then
value := scoreWin
else
value := scoreLose
end
else if depth = 8 then
value := scoreTie;
end;
if value = scoreInvalid then
begin
if Odd( depth ) then
begin
value := scoreMin;
pieceMove := pieceX;
end
else
begin
value := scoreMax;
pieceMove := pieceO;
end;
p := 0;
repeat
if board[ p ] = pieceBlank then
begin
board[ p ] := pieceMove;
score := minmax( alpha, beta, depth + 1, p );
board[ p ] := pieceBlank;
if Odd( depth ) then
begin
if ( score > value ) then
begin
value := score;
if ( value = scoreWin ) or ( value >= beta ) then p := 10
else if ( value > alpha ) then alpha := value;
end;
end
else
begin
if ( score < value ) then
begin
value := score;
if ( value = scoreLose ) or ( value <= alpha ) then p := 10
else if ( value < beta ) then beta := value;
end;
end;
end;
p := p + 1;
until p > 8;
end;
minmax := value;
end;
{$A+}
procedure runit( move : integer );
var
score: integer;
begin
board[move] := pieceX;
score := minmax( scoreMin, scoreMax, 0, move );
board[move] := pieceBlank;
end;
function Trim( intext : CommandString ): CommandString;
var FirstPos, LastPos: integer;
begin
FirstPos := 1;
while ( FirstPos <= Length( intext ) ) and ( intext[FirstPos] = #32 ) do
FirstPos := FirstPos + 1;
LastPos := Length( intext );
while ( LastPos >= 1 ) and ( intext[LastPos] = #32 ) do
LastPos := LastPos - 1;
Trim := Copy( intext, FirstPos, LastPos - FirstPos + 1 );
end;
var
i, loops, code: integer;
strArg : CommandString;
cmdTail : CommandString absolute $80;
begin
loops := Iterations;
{ on cp/m 2.2 the length is 1 for no arguments -- it's just a space }
if ( mem[ 128 ] > 1 ) then
begin
{ trim the space at the start that's always there }
strArg := Trim( cmdTail );
Val( strArg, loops, code );
end;
if ( loops > 0 ) then
begin
for i := 0 to 8 do
board[i] := pieceBlank;
get_time( timeStart );
for i := 1 to loops do
begin
evaluated := 0; { once per loop to prevent overflow }
runit( 0 );
runit( 1 );
runit( 4 );
end;
get_time( timeEnd );
print_elapsed_time( timeStart, timeEnd );
WriteLn( 'moves evaluated: ', evaluated );
end;
WriteLn( 'iterations: ', loops );
end.
| 0 | 0.754533 | 1 | 0.754533 | game-dev | MEDIA | 0.7007 | game-dev | 0.87405 | 1 | 0.87405 |
Me-Maped/Gameframework-at-FairyGUI | 3,987 | Client/Assets/UnityGameFramework/Scripts/Editor/Misc/Type.cs | using GameFramework;
using System.Collections.Generic;
using System.Reflection;
namespace UnityGameFramework.Editor
{
/// <summary>
/// 类型相关的实用函数。
/// </summary>
public static class Type
{
private static readonly string[] RuntimeAssemblyNames =
{
#if UNITY_2017_3_OR_NEWER
"UnityGameFramework.Runtime",
#endif
"Assembly-CSharp",
"GameMain.Runtime",
"GameLogic",
"GameProto",
};
private static readonly string[] RuntimeOrEditorAssemblyNames =
{
#if UNITY_2017_3_OR_NEWER
"UnityGameFramework.Runtime",
#endif
"Assembly-CSharp",
#if UNITY_2017_3_OR_NEWER
"UnityGameFramework.Editor",
#endif
"Assembly-CSharp-Editor",
"GameMain.Runtime",
"GameMain.Editor",
"GameLogic",
"GameProto",
};
/// <summary>
/// 获取配置路径。
/// </summary>
/// <typeparam name="T">配置类型。</typeparam>
/// <returns>配置路径。</returns>
public static string GetConfigurationPath<T>() where T : ConfigPathAttribute
{
foreach (System.Type type in Utility.Assembly.GetTypes())
{
if (!type.IsAbstract || !type.IsSealed)
{
continue;
}
foreach (FieldInfo fieldInfo in type.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly))
{
if (fieldInfo.FieldType == typeof(string) && fieldInfo.IsDefined(typeof(T), false))
{
return (string)fieldInfo.GetValue(null);
}
}
foreach (PropertyInfo propertyInfo in type.GetProperties(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly))
{
if (propertyInfo.PropertyType == typeof(string) && propertyInfo.IsDefined(typeof(T), false))
{
return (string)propertyInfo.GetValue(null, null);
}
}
}
return null;
}
/// <summary>
/// 在运行时程序集中获取指定基类的所有子类的名称。
/// </summary>
/// <param name="typeBase">基类类型。</param>
/// <returns>指定基类的所有子类的名称。</returns>
public static string[] GetRuntimeTypeNames(System.Type typeBase)
{
return GetTypeNames(typeBase, RuntimeAssemblyNames);
}
/// <summary>
/// 在运行时或编辑器程序集中获取指定基类的所有子类的名称。
/// </summary>
/// <param name="typeBase">基类类型。</param>
/// <returns>指定基类的所有子类的名称。</returns>
public static string[] GetRuntimeOrEditorTypeNames(System.Type typeBase)
{
return GetTypeNames(typeBase, RuntimeOrEditorAssemblyNames);
}
private static string[] GetTypeNames(System.Type typeBase, string[] assemblyNames)
{
List<string> typeNames = new List<string>();
foreach (string assemblyName in assemblyNames)
{
Assembly assembly = null;
try
{
assembly = Assembly.Load(assemblyName);
}
catch
{
continue;
}
if (assembly == null)
{
continue;
}
System.Type[] types = assembly.GetTypes();
foreach (System.Type type in types)
{
if (type.IsClass && !type.IsAbstract && typeBase.IsAssignableFrom(type))
{
typeNames.Add(type.FullName);
}
}
}
typeNames.Sort();
return typeNames.ToArray();
}
}
}
| 0 | 0.837237 | 1 | 0.837237 | game-dev | MEDIA | 0.665427 | game-dev | 0.981362 | 1 | 0.981362 |
MergHQ/CRYENGINE | 34,432 | Code/GameSDK/GameDll/LocalPlayerComponent.cpp | // Copyright 2001-2016 Crytek GmbH / Crytek Group. All rights reserved.
#include "StdAfx.h"
#include "LocalPlayerComponent.h"
#include "ScreenEffects.h"
#include "Player.h"
#include "Utility/CryWatch.h"
#include "RecordingSystem.h"
#include "AutoAimManager.h"
#include <CryGame/GameUtils.h>
#include "GameRulesModules/IGameRulesStateModule.h"
#include "GameRulesModules/IGameRulesDamageHandlingModule.h"
#include "GameCVars.h"
#include "Item.h"
#include "Weapon.h"
#include "PlayerStateSwim.h"
#include "PersistantStats.h"
#include "GamePhysicsSettings.h"
#include "GameActions.h"
#include "NetPlayerInput.h"
#include "ActorManager.h"
#ifndef _RELEASE
static int g_spectate_follow_debug_enable;
static int g_spectate_follow_debug_setDebugSettingsToCurrentViewSettings;
static float g_spectate_follow_debug_targetOffset_x;
static float g_spectate_follow_debug_targetOffset_y;
static float g_spectate_follow_debug_targetOffset_z;
static float g_spectate_follow_debug_viewOffset_x;
static float g_spectate_follow_debug_viewOffset_y;
static float g_spectate_follow_debug_viewOffset_z;
static float g_spectate_follow_debug_offsetspeed_x;
static float g_spectate_follow_debug_offsetspeed_y;
static float g_spectate_follow_debug_offsetspeed_z;
static float g_spectate_follow_debug_desiredDistance;
static float g_spectate_follow_debug_cameraHeightOffset;
static float g_spectate_follow_debug_cameraYaw;
static float g_spectate_follow_debug_cameraSpeed;
static float g_spectate_follow_debug_cameraFov;
static int g_spectate_follow_debug_allowOrbitYaw;
static int g_spectate_follow_debug_allowOrbitPitch;
static int g_spectate_follow_debug_useEyeDir;
static int g_spectate_follow_debug_userSelectable;
#endif //_RELEASE
CLocalPlayerComponent::CLocalPlayerComponent(CPlayer& rParentPlayer)
: m_playedMidHealthSound(false)
, m_fpCompleteBodyVisible(false)
, m_freeFallDeathFadeTimer(0.0f)
, m_screenFadeEffectId(InvalidEffectId)
, m_bIsInFreeFallDeath(false)
, m_rPlayer(rParentPlayer)
, m_currentFollowCameraSettingsIndex(0)
, m_autoArmourFlags(0)
{
m_freeFallLookTarget.Set(0.f, 0.f, 0.f);
m_lastMeleeParams.m_boostedMelee = false;
m_lastMeleeParams.m_hitNormal.Set(0.f, 0.f, 0.f);
m_lastMeleeParams.m_hitOffset.Set(0.f, 0.f, 0.f);
m_lastMeleeParams.m_surfaceIdx = 0;
m_lastMeleeParams.m_targetId = 0;
m_timeForBreath = 0;
m_stapElevLimit = gf_PI * 0.5f;
m_lastSTAPCameraDelta.SetIdentity();
if( gEnv->bMultiplayer )
{
m_rPlayer.GetInventory()->AddListener( this );
}
#ifndef _RELEASE
REGISTER_CVAR(g_spectate_follow_debug_enable, 0, 0, "Enables A cvar controlled camera mode");
REGISTER_CVAR(g_spectate_follow_debug_setDebugSettingsToCurrentViewSettings, 0, 0, "Sets the debug camera mode settings to match the currently selected camera settings");
REGISTER_CVAR(g_spectate_follow_debug_targetOffset_x, 0.f, 0, "where the camera should point at relative to the target entity. The value is in the target's local space");
REGISTER_CVAR(g_spectate_follow_debug_targetOffset_y, 0.f, 0, "where the camera should point at relative to the target entity. The value is in the target's local space");
REGISTER_CVAR(g_spectate_follow_debug_targetOffset_z, 1.5f, 0, "where the camera should point at relative to the target entity. The value is in the target's local space");
REGISTER_CVAR(g_spectate_follow_debug_viewOffset_x, 0.f, 0, "the amount the camera should be shifted by. Does not affect rotation. The value is in the view space.");
REGISTER_CVAR(g_spectate_follow_debug_viewOffset_y, 0.f, 0, "the amount the camera should be shifted by. Does not affect rotation. The value is in the view space.");
REGISTER_CVAR(g_spectate_follow_debug_viewOffset_z, 0.f, 0, "the amount the camera should be shifted by. Does not affect rotation. The value is in the view space.");
REGISTER_CVAR(g_spectate_follow_debug_offsetspeed_x, 1.f, 0, "the speed for the left-right camera offset from the target (in cam space).");
REGISTER_CVAR(g_spectate_follow_debug_offsetspeed_y, 1.f, 0, "the speed for the in-out camera offset from the target (in cam space).");
REGISTER_CVAR(g_spectate_follow_debug_offsetspeed_z, 1.f, 0, "the speed for the up-down camera offset from the target (in cam space).");
REGISTER_CVAR(g_spectate_follow_debug_desiredDistance, 3.0f, 0, "how far the camera should be placed from the target. This is an ideal value which will change to avoid obstructions");
REGISTER_CVAR(g_spectate_follow_debug_cameraHeightOffset, 0.75f, 0, "how high/low the camera should be placed in relation to the target entity");
REGISTER_CVAR(g_spectate_follow_debug_cameraYaw, 0.0f, 0, "camera's rotation about the target entity. The value is in degrees and moves clockwise about the target. 0.0 faces the same direction as the target");
REGISTER_CVAR(g_spectate_follow_debug_cameraSpeed, 5.f, 0, "how much the camera 'lags' when following a moving target. A value of 0 is an instant snap");
REGISTER_CVAR(g_spectate_follow_debug_cameraFov, 0.0f, 0, "camera's Field of view. The value is in degrees. 0.0 uses the default existing");
REGISTER_CVAR(g_spectate_follow_debug_allowOrbitYaw, 1, 0, "allows the player to adjust the camera yaw value themselves");
REGISTER_CVAR(g_spectate_follow_debug_allowOrbitPitch, 1, 0, "allows the player to adjust the camera pitch value themselves");
REGISTER_CVAR(g_spectate_follow_debug_useEyeDir, 0, 0, "uses the target's eye direction to control the camera rather than the entity matrix");
REGISTER_CVAR(g_spectate_follow_debug_userSelectable, 1, 0, "allows the view to be used changed to during the follow mode.");
m_followCameraDebugSettings.m_settingsName = "Debug";
#endif //_RELEASE
}
CLocalPlayerComponent::~CLocalPlayerComponent()
{
if( gEnv->bMultiplayer )
{
m_rPlayer.GetInventory()->RemoveListener( this );
}
#ifndef _RELEASE
gEnv->pConsole->UnregisterVariable("g_spectate_follow_debug_enable");
gEnv->pConsole->UnregisterVariable("g_spectate_follow_debug_setDebugSettingsToCurrentViewSettings");
gEnv->pConsole->UnregisterVariable("g_spectate_follow_debug_targetOffset_x");
gEnv->pConsole->UnregisterVariable("g_spectate_follow_debug_targetOffset_y");
gEnv->pConsole->UnregisterVariable("g_spectate_follow_debug_targetOffset_z");
gEnv->pConsole->UnregisterVariable("g_spectate_follow_debug_viewOffset_x");
gEnv->pConsole->UnregisterVariable("g_spectate_follow_debug_viewOffset_y");
gEnv->pConsole->UnregisterVariable("g_spectate_follow_debug_viewOffset_z");
gEnv->pConsole->UnregisterVariable("g_spectate_follow_debug_offsetspeed_x");
gEnv->pConsole->UnregisterVariable("g_spectate_follow_debug_offsetspeed_y");
gEnv->pConsole->UnregisterVariable("g_spectate_follow_debug_offsetspeed_z");
gEnv->pConsole->UnregisterVariable("g_spectate_follow_debug_desiredDistance");
gEnv->pConsole->UnregisterVariable("g_spectate_follow_debug_cameraHeightOffset");
gEnv->pConsole->UnregisterVariable("g_spectate_follow_debug_cameraYaw");
gEnv->pConsole->UnregisterVariable("g_spectate_follow_debug_cameraSpeed");
gEnv->pConsole->UnregisterVariable("g_spectate_follow_debug_cameraFov");
gEnv->pConsole->UnregisterVariable("g_spectate_follow_debug_allowOrbitYaw");
gEnv->pConsole->UnregisterVariable("g_spectate_follow_debug_allowOrbitPitch");
gEnv->pConsole->UnregisterVariable("g_spectate_follow_debug_useEyeDir");
gEnv->pConsole->UnregisterVariable("g_spectate_follow_debug_userSelectable");
#endif //_RELEASE
}
void CLocalPlayerComponent::Revive()
{
if(gEnv->bMultiplayer)
{
// Reset NotYetSpawned filter.
IActionFilter* pNYSFilter = g_pGameActions->FilterNotYetSpawned();
if(pNYSFilter && pNYSFilter->Enabled())
{
pNYSFilter->Enable(false);
}
// For Modes where we can swap teams per round, refresh everyone else's cloak colour on revive.
CGameRules *pGameRules = g_pGame->GetGameRules();
if( pGameRules->GetGameMode()==eGM_Gladiator )
{
IActorSystem* pActorSys = g_pGame->GetIGameFramework()->GetIActorSystem();
CActorManager* pActorManager = CActorManager::GetActorManager();
pActorManager->PrepareForIteration();
const int kNumActors = pActorManager->GetNumActors();
for(int i=0; i<kNumActors; i++)
{
SActorData actorData;
pActorManager->GetNthActorData(i, actorData);
if(CActor* pActor = static_cast<CActor*>(pActorSys->GetActor(actorData.entityId)))
{
if(pActor->IsCloaked())
{
pActor->SetCloakLayer(false);
pActor->SetCloakLayer(true);
}
}
}
}
}
m_bIsInFreeFallDeath = false;
m_playedMidHealthSound = false;
}
void CLocalPlayerComponent::OnKill()
{
// Stop Movement Input
g_pGameActions->FilterNoMove()->Enable(true);
if(gEnv->bMultiplayer)
{
// Set NotYetSpawned filter.
IActionFilter* pNYSFilter = g_pGameActions->FilterNotYetSpawned();
if(pNYSFilter && !pNYSFilter->Enabled())
{
pNYSFilter->Enable(true);
}
// Re-cache FP weapon geometry from load-out just before respawn.
if(CEquipmentLoadout* pEquipmentLoadout = g_pGame->GetEquipmentLoadout())
{
pEquipmentLoadout->StreamFPGeometry(CEquipmentLoadout::ePGE_OnDeath, pEquipmentLoadout->GetCurrentSelectedPackageIndex());
}
}
}
void CLocalPlayerComponent::InitFollowCameraSettings( const IItemParamsNode* pFollowCameraNode )
{
int numSettings = pFollowCameraNode->GetChildCount();
m_followCameraSettings.resize(numSettings);
for(int i = 0; i < numSettings; ++i)
{
const IItemParamsNode* pCameraModeNode = pFollowCameraNode->GetChild(i);
SFollowCameraSettings& mode = m_followCameraSettings[i];
float cameraYawDeg = 0.f;
float cameraFovDeg = 0.f;
int allowOrbitYaw = 0;
int allowOrbitPitch = 0;
int useEyeDir = 0;
int userSelectable = 0;
int disableHeightAdj = 0;
bool success = true;
success &= pCameraModeNode->GetAttribute("targetOffset", mode.m_targetOffset);
success &= pCameraModeNode->GetAttribute("viewOffset", mode.m_viewOffset);
success &= pCameraModeNode->GetAttribute("offsetSpeeds", mode.m_offsetSpeeds);
success &= pCameraModeNode->GetAttribute("desiredDistance", mode.m_desiredDistance);
success &= pCameraModeNode->GetAttribute("cameraHeightOffset", mode.m_cameraHeightOffset);
success &= pCameraModeNode->GetAttribute("cameraYaw", cameraYawDeg);
success &= pCameraModeNode->GetAttribute("cameraFov", cameraFovDeg);
success &= pCameraModeNode->GetAttribute("cameraSpeed", mode.m_cameraSpeed);
success &= pCameraModeNode->GetAttribute("cameraSpeed", mode.m_cameraSpeed);
success &= pCameraModeNode->GetAttribute("allowOrbitYaw", allowOrbitYaw);
success &= pCameraModeNode->GetAttribute("allowOrbitPitch", allowOrbitPitch);
success &= pCameraModeNode->GetAttribute("useEyeDir", useEyeDir);
success &= pCameraModeNode->GetAttribute("userSelectable", userSelectable);
success &= pCameraModeNode->GetAttribute("disableHeightAdj", disableHeightAdj);
CRY_ASSERT_MESSAGE(success, string().Format("CLocalPlayerComponent::InitFollowCameraSettings - Invalid follow camera settings - mode %i. Check XML data.", i+1));
mode.m_cameraYaw = DEG2RAD(cameraYawDeg);
mode.m_cameraFov = DEG2RAD(cameraFovDeg);
mode.m_flags |= allowOrbitYaw > 0 ? SFollowCameraSettings::eFCF_AllowOrbitYaw : SFollowCameraSettings::eFCF_None;
mode.m_flags |= allowOrbitPitch > 0 ? SFollowCameraSettings::eFCF_AllowOrbitPitch : SFollowCameraSettings::eFCF_None;
mode.m_flags |= useEyeDir > 0 ? SFollowCameraSettings::eFCF_UseEyeDir : SFollowCameraSettings::eFCF_None;
mode.m_flags |= userSelectable > 0 ? SFollowCameraSettings::eFCF_UserSelectable : SFollowCameraSettings::eFCF_None;
mode.m_flags |= disableHeightAdj > 0 ? SFollowCameraSettings::eFCF_DisableHeightAdj : SFollowCameraSettings::eFCF_None;
const string nameString = pCameraModeNode->GetAttribute("name");
mode.m_crcSettingsName = CCrc32::ComputeLowercase(nameString.c_str());
#ifndef _RELEASE
mode.m_settingsName = nameString;
#endif //_RELEASE
}
}
void CLocalPlayerComponent::StartFreeFallDeath()
{
m_bIsInFreeFallDeath = true;
Vec3 currentLook = m_rPlayer.GetEntity()->GetWorldTM().GetColumn1();
currentLook.z = tan_tpl(DEG2RAD(g_pGameCVars->pl_freeFallDeath_cameraAngle));
currentLook.Normalize();
m_freeFallLookTarget = currentLook;
}
void CLocalPlayerComponent::UpdateFreeFallDeath( const float frameTime )
{
if(m_bIsInFreeFallDeath)
{
m_rPlayer.m_pPlayerRotation->SetForceLookAt(m_freeFallLookTarget);
m_freeFallDeathFadeTimer += frameTime;
if(m_rPlayer.m_stats.isRagDoll || (m_freeFallDeathFadeTimer > g_pGameCVars->pl_freeFallDeath_fadeTimer))
{
CRecordingSystem* pRecordingSystem = g_pGame->GetRecordingSystem();
if (!pRecordingSystem || !pRecordingSystem->IsPlayingBack()) // Don't do the fade screen effect if in killcam
{
TriggerFadeToBlack();
}
m_rPlayer.m_pPlayerRotation->SetForceLookAt(ZERO);
m_bIsInFreeFallDeath = false;
}
}
else
{
m_freeFallDeathFadeTimer = 0.0f;
}
}
void CLocalPlayerComponent::TriggerFadeToBlack()
{
if(m_screenFadeEffectId == InvalidEffectId)
{
UpdateScreenFadeEffect();
}
SMFXRunTimeEffectParams effectParams;
effectParams.pos = m_rPlayer.GetEntity()->GetWorldPos();
//effectParams.soundSemantic = eSoundSemantic_HUD;
gEnv->pGame->GetIGameFramework()->GetIMaterialEffects()->ExecuteEffect(m_screenFadeEffectId, effectParams);
}
void CLocalPlayerComponent::UpdateFPBodyPartsVisibility()
{
if (m_rPlayer.m_stats.isThirdPerson == false)
{
ICharacterInstance *pMainCharacter = m_rPlayer.GetEntity()->GetCharacter(0);
IAttachmentManager *pAttachmentManager = pMainCharacter ? pMainCharacter->GetIAttachmentManager() : NULL;
if (pAttachmentManager)
{
CRY_ASSERT(m_rPlayer.HasBoneID(BONE_CALF_L));
CRY_ASSERT(m_rPlayer.HasBoneID(BONE_CALF_R));
const CCamera& camera = gEnv->p3DEngine->GetRenderingCamera();
const Matrix34& playerWorldTM = m_rPlayer.GetEntity()->GetWorldTM();
bool visible = true;
if (m_rPlayer.m_linkStats.linkID == 0)
{
//volatile static float radius = 0.475f;
const float radius = 0.16f;
const Sphere calfSphereL(playerWorldTM.TransformPoint(m_rPlayer.GetBoneTransform(BONE_CALF_L).t), radius);
const Sphere calfSpehreR(playerWorldTM.TransformPoint(m_rPlayer.GetBoneTransform(BONE_CALF_R).t), radius);
visible = camera.IsSphereVisible_F(calfSphereL) || camera.IsSphereVisible_F(calfSpehreR);
}
//const float white[4] = {1.0f, 1.0f, 1.0f, 1.0f};
//gEnv->pRenderer->Draw2dLabel(50.0f, 50.0f, 2.0f, white, false, visible ? "Rendering complete FP body" : "Rendering only arms");
//Early out if no change
if (m_fpCompleteBodyVisible == visible)
return;
//Hide/Unhide certain parts depending on visibility
const int kNumParstToToggle = 2;
const char *tooglePartsTable[kNumParstToToggle] = {"lower_body", "upper_body"};
for (int i=0; i<kNumParstToToggle; i++)
{
IAttachment* pAttachment = pAttachmentManager->GetInterfaceByName(tooglePartsTable[i]);
if (pAttachment)
{
pAttachment->HideAttachment(!visible);
pAttachment->HideInShadow(1);
}
}
m_fpCompleteBodyVisible = visible;
}
}
}
void CLocalPlayerComponent::UpdateScreenFadeEffect()
{
IMaterialEffects* pMaterialEffects = gEnv->pGame->GetIGameFramework()->GetIMaterialEffects();
if(pMaterialEffects)
{
m_screenFadeEffectId = pMaterialEffects->GetEffectIdByName("cw2_player_fx", "c2mp_fallDeath_fadeOut");
}
}
void CLocalPlayerComponent::ResetScreenFX()
{
gEnv->p3DEngine->ResetPostEffects();
if(g_pGame->GetScreenEffects())
g_pGame->GetScreenEffects()->ResetAllBlendGroups(true);
m_rPlayer.GetActorParams().viewFoVScale = 1.0f;
if(m_screenFadeEffectId != InvalidEffectId)
{
gEnv->pGame->GetIGameFramework()->GetIMaterialEffects()->StopEffect(m_screenFadeEffectId);
}
}
//
// Client Soundmood-related code
//
void CLocalPlayerComponent::SetClientSoundmood(CPlayer::EClientSoundmoods soundmood)
{
if(soundmood != m_soundmood)
{
RemoveClientSoundmood(m_soundmood);
AddClientSoundmood(soundmood);
m_soundmood = soundmood;
}
}
void CLocalPlayerComponent::AddClientSoundmood(CPlayer::EClientSoundmoods soundmood)
{
/*if(soundmood > CPlayer::ESoundmood_Invalid && soundmood < CPlayer::ESoundmood_Last)
{
m_soundmoods[soundmood].m_enter.Play();
}*/
}
void CLocalPlayerComponent::RemoveClientSoundmood(CPlayer::EClientSoundmoods soundmood)
{
REINST("needs verification!");
//if(soundmood > CPlayer::ESoundmood_Invalid && soundmood < CPlayer::ESoundmood_Last)
//{
// //Stop any looping sound that might have been playing
// m_soundmoods[soundmood].m_enter.Stop();
// //intentionally play ( so it runs execute commands that include RemoveSoundMood )
// m_soundmoods[soundmood].m_exit.Play();
//}
}
void CLocalPlayerComponent::InitSoundmoods()
{
// Do not re-use moods for other systems here.. ie. menu muted moods, as triggering the moods from elsewhere will remove them even though your player state's unchanged
m_soundmoods[CPlayer::ESoundmood_Alive].Empty(); //Clears other soundmoods when set
const char* lowHealthEnter = gEnv->bMultiplayer ? "Player_LowHealth_Enter_MP" : "Player_LowHealth_Enter";
const char* lowHealthExit = gEnv->bMultiplayer ? "Player_LowHealth_Exit_MP" : "Player_LowHealth_Exit";
m_soundmoods[CPlayer::ESoundmood_LowHealth].Set(lowHealthEnter, lowHealthExit);
m_soundmoods[CPlayer::ESoundmood_Dead].Set(gEnv->bMultiplayer ? "Player_Death_Enter_MP" : "Player_Death_Enter", "Player_Death_Exit");
m_soundmoods[CPlayer::ESoundmood_Killcam].Set("Killcam_Enter", "Killcam_Exit");
m_soundmoods[CPlayer::ESoundmood_KillcamSlow].Set("Killcam_SlowMo_Enter", "Killcam_SlowMo_Exit");
m_soundmoods[CPlayer::ESoundmood_Spectating].Set("Spectator_Enter", "Spectator_Leave");
m_soundmoods[CPlayer::ESoundmood_PreGame].Set("Menu_Pregame_Enter", "Menu_Pregame_Leave");
m_soundmoods[CPlayer::ESoundmood_PostGame].Set("Menu_Postgame_Enter", "Menu_Postgame_Leave");
m_soundmoods[CPlayer::ESoundmood_EMPBlasted].Set("Player_EMPBlasted_Enter", "Player_EMPBlasted_Leave");
m_soundmood = CPlayer::ESoundmood_Invalid;
}
//STAP and FP IK
//------------------------------------------------------------------------------------
// Adjust the aim dir before we pass it to the torsoAim pose modifier, this allows us
// to have the weapon deviate from the camera in certain circumstances
// Should only be called once per frame as it time-steps internal vars
//------------------------------------------------------------------------------------
void CLocalPlayerComponent::AdjustTorsoAimDir(float fFrameTime, Vec3 &aimDir)
{
const f32 HALF_PI = gf_PI * 0.5f;
float newElevLimit = HALF_PI;
const f32 MIN_FLATTEN_LEVEL = -0.3f;
const f32 MAX_FLATTEN_LEVEL = -0.1f;
const f32 TARGET_FLATTEN_ELEV = -0.2f;
const f32 LIMIT_CHANGE_RATE = HALF_PI;
if (g_pGameCVars->pl_swimAlignArmsToSurface && m_rPlayer.IsSwimming() && (m_rPlayer.m_playerStateSwim_WaterTestProxy.GetRelativeWaterLevel() > MIN_FLATTEN_LEVEL))
{
newElevLimit = (m_rPlayer.m_playerStateSwim_WaterTestProxy.GetRelativeWaterLevel() - MIN_FLATTEN_LEVEL) / (MAX_FLATTEN_LEVEL - MIN_FLATTEN_LEVEL);
newElevLimit = LERP(gf_PI * 0.5f, TARGET_FLATTEN_ELEV, clamp_tpl(newElevLimit, 0.0f, 1.0f));
}
float limitDelta = LIMIT_CHANGE_RATE * fFrameTime;
float limitDiff = newElevLimit - m_stapElevLimit;
float smoothedLimit = (float) __fsel(fabs_tpl(limitDiff) - limitDelta, m_stapElevLimit + (fsgnf(limitDiff) * limitDelta), newElevLimit);
m_stapElevLimit = smoothedLimit;
if (smoothedLimit < HALF_PI)
{
//--- Need to limit, convert to yaw & elev, limit & then convert back
float yaw, elev;
float xy = aimDir.GetLengthSquared2D();
if (xy > 0.001f)
{
yaw = atan2_tpl(aimDir.y,aimDir.x);
elev = asin_tpl(clamp_tpl(aimDir.z, -1.f, +1.f));
}
else
{
yaw = 0.f;
elev = (float)__fsel(aimDir.z, +1.f, -1.f) * (gf_PI*0.5f);
}
elev = min(elev, smoothedLimit);
float sinYaw, cosYaw;
float sinElev, cosElev;
sincos_tpl(yaw, &sinYaw, &cosYaw);
sincos_tpl(elev, &sinElev, &cosElev);
aimDir.x = cosYaw * cosElev;
aimDir.y = sinYaw * cosElev;
aimDir.z = sinElev;
}
}
void CLocalPlayerComponent::Update( const float frameTime )
{
const float health = m_rPlayer.m_health.GetHealth();
UpdatePlayerLowHealthStatus( health );
CPlayerProgression::GetInstance()->Update( &m_rPlayer, frameTime, health );
UpdateFreeFallDeath( frameTime );
if(gEnv->bMultiplayer)
{
if(g_pGameCVars->pl_autoPickupItemsWhenUseHeld)
{
UpdateItemUsage(frameTime);
}
}
UpdateFPBodyPartsVisibility();
}
void CLocalPlayerComponent::UpdateFPIKTorso(float fFrameTime, IItem * pCurrentItem, const Vec3& cameraPosition)
{
//Get const ref instead of doing a full copy
SMovementState info;
m_rPlayer.m_pMovementController->GetMovementState(info);
const QuatT &cameraTran = m_rPlayer.GetCameraTran();
if (m_rPlayer.m_torsoAimIK.GetBlendFactor() > 0.9f)
{
m_lastSTAPCameraDelta = m_rPlayer.m_torsoAimIK.GetLastEffectorTransform().GetInverted() * cameraTran;
}
else
{
m_lastSTAPCameraDelta.SetIdentity();
}
ICharacterInstance* pCharacter = m_rPlayer.GetEntity()->GetCharacter(0);
ICharacterInstance* pCharacterShadow = m_rPlayer.GetShadowCharacter();
QuatT torsoOffset;
GetFPTotalTorsoOffset(torsoOffset, pCurrentItem);
if (pCharacter != 0)
{
Vec3 aimDir;
if (m_rPlayer.m_params.mountedWeaponCameraTarget.IsZero() && (m_rPlayer.GetLinkedVehicle() == NULL))
{
aimDir = !m_rPlayer.m_pPlayerRotation->GetBaseQuat() * info.aimDirection;
}
else
{
aimDir = !m_rPlayer.GetEntity()->GetWorldRotation() * info.aimDirection;
}
AdjustTorsoAimDir(fFrameTime, aimDir);
const bool needsPositionAdjust = !m_rPlayer.IsSliding();
CIKTorsoAim_Helper::SIKTorsoParams IKParams(pCharacter, pCharacterShadow, aimDir, torsoOffset, cameraPosition, m_rPlayer.GetBoneID(BONE_CAMERA), m_rPlayer.GetBoneID(BONE_SPINE2), m_rPlayer.GetBoneID(BONE_SPINE), ShouldUpdateTranslationPinning(), needsPositionAdjust);
m_rPlayer.m_torsoAimIK.Update(IKParams);
}
#ifndef _RELEASE
if (g_pGameCVars->pl_debug_view != 0)
{
CryWatch("CPlayer:UpdateFPIKTorso: RawCamera Pos(%f, %f, %f) Rot(%f, %f, %f, %f)", cameraTran.t.x, cameraTran.t.x, cameraTran.t.x, cameraTran.q.v.x, cameraTran.q.v.y, cameraTran.q.v.z, cameraTran.q.w );
CryWatch("CPlayer:UpdateFPIKTorso: MountedTarget (%f, %f, %f)", m_rPlayer.m_params.mountedWeaponCameraTarget.x, m_rPlayer.m_params.mountedWeaponCameraTarget.y, m_rPlayer.m_params.mountedWeaponCameraTarget.z );
CryWatch("CPlayer:UpdateFPIKTorso: CamPos(%f, %f, %f) Dir(%f, %f, %f)", cameraPosition.x, cameraPosition.y, cameraPosition.z, info.aimDirection.x, info.aimDirection.y, info.aimDirection.z);
CryWatch("CPlayer:UpdateFPIKTorso: Anim Pos(%f, %f, %f) Rot(%f, %f, %f, %f)", m_lastSTAPCameraDelta.t.x, m_lastSTAPCameraDelta.t.y, m_lastSTAPCameraDelta.t.z, m_lastSTAPCameraDelta.q.v.x, m_lastSTAPCameraDelta.q.v.y, m_lastSTAPCameraDelta.q.v.z, m_lastSTAPCameraDelta.q.w);
if (g_pGameCVars->pl_debug_view >= 2)
{
CryLog("CPlayer:UpdateFPIKTorso: CamPos(%f, %f, %f) Dir(%f, %f, %f)", cameraPosition.x, cameraPosition.y, cameraPosition.z, info.aimDirection.x, info.aimDirection.y, info.aimDirection.z);
CryLog("CPlayer:UpdateFPIKTorso: EyeOffset(%f, %f, %f)", m_rPlayer.m_eyeOffset.x, m_rPlayer.m_eyeOffset.y, m_rPlayer.m_eyeOffset.z);
}
const QuatT cameraWorld = QuatT(m_rPlayer.GetEntity()->GetWorldTM()) * cameraTran;
gEnv->pRenderer->GetIRenderAuxGeom()->DrawSphere(cameraWorld.t, 0.1f, ColorB(0, 0, 255));
gEnv->pRenderer->GetIRenderAuxGeom()->DrawLine(cameraWorld.t, ColorB(255, 0, 0), cameraWorld.t + cameraWorld.q.GetColumn1(), ColorB(255, 0, 0), 3.0f);
}
if(g_pGameCVars->p_collclassdebug == 1)
{
const QuatT cameraQuatT = QuatT(m_rPlayer.GetEntity()->GetWorldTM()) * cameraTran;
ray_hit hit;
if(gEnv->pPhysicalWorld->RayWorldIntersection(cameraQuatT.t+(cameraQuatT.q.GetColumn1()*1.5f), cameraQuatT.q.GetColumn1()*200.f, ent_all, rwi_colltype_any(geom_collides)|rwi_force_pierceable_noncoll|rwi_stop_at_pierceable, &hit, 1 ))
{
if(hit.pCollider)
{
gEnv->pRenderer->GetIRenderAuxGeom()->DrawSphere(hit.pt, 0.1f, ColorB(0, 0, 255));
g_pGame->GetGamePhysicsSettings()->Debug(*hit.pCollider, true);
}
}
}
#endif
}
void CLocalPlayerComponent::GetFPTotalTorsoOffset(QuatT &offset, IItem * pCurrentItem) const
{
CItem *pItem = (CItem *)pCurrentItem;
if (pItem)
{
pItem->GetFPOffset(offset);
}
else
{
offset.SetIdentity();
}
}
bool CLocalPlayerComponent::ShouldUpdateTranslationPinning() const
{
return !m_rPlayer.IsSliding() && !m_rPlayer.IsExitingSlide()
&& (GetGameConstCVar(g_translationPinningEnable) != 0)
&& !m_rPlayer.GetActorStats()->bDisableTranslationPinning;
}
void CLocalPlayerComponent::UpdateSwimming(float fFrameTime, float breathingInterval )
{
if (gEnv->IsEditor() && gEnv->IsEditing())
return;
const CWeapon* pWeapon = m_rPlayer.GetWeapon( m_rPlayer.GetCurrentItemId() );
if( !pWeapon || pWeapon->GetEntity()->GetClass() != CItem::sNoWeaponClass )
{
//Select underwater weapon here
m_rPlayer.SelectItemByName( "NoWeapon", true, true );
}
m_timeForBreath -= fFrameTime;
const bool isHeadUnderWater = m_rPlayer.IsHeadUnderWater();
if( m_timeForBreath<=0 && isHeadUnderWater )
{
PlayBreathingUnderwater(breathingInterval);
}
CPlayerStateSwim::UpdateAudio(m_rPlayer);
}
void CLocalPlayerComponent::PlayBreathingUnderwater(float breathingInterval)
{
m_rPlayer.PlaySound( CPlayer::ESound_Breathing_UnderWater, true, "speed", m_rPlayer.m_stats.speedFlat );
m_timeForBreath = breathingInterval;
}
void CLocalPlayerComponent::UpdateStumble( const float frameTime )
{
IEntity * pEntity = m_rPlayer.GetEntity();
IPhysicalEntity * pPhysEntity = pEntity->GetPhysics();
if ( pPhysEntity )
{
pe_status_dynamics dynamics;
pPhysEntity->GetStatus( &dynamics );
if ( m_playerStumble.Update( frameTime, dynamics ) )
{
pe_action_impulse ai;
ai.impulse = m_playerStumble.GetCurrentActionImpulse();
pPhysEntity->Action( &ai );
}
}
}
void CLocalPlayerComponent::UpdateItemUsage( const float frameTime )
{
m_playerEntityInteraction.Update( &m_rPlayer, frameTime );
}
void CLocalPlayerComponent::UpdatePlayerLowHealthStatus( const float oldHealth )
{
const float healthThrLow = g_pGameCVars->g_playerLowHealthThreshold;
const float healthThrMid = g_pGameCVars->g_playerMidHealthThreshold;
const float maxHealth = (float)m_rPlayer.GetMaxHealth();
const float minHealth = 0;
const float currentHealth = m_rPlayer.m_health.GetHealth();
const bool isDead = m_rPlayer.m_health.IsDead();
CRY_ASSERT( maxHealth > minHealth );
//Extra 'mid-low' health sound hint
if ((currentHealth <= healthThrMid) && (oldHealth > healthThrMid))
{
m_rPlayer.PlaySound(CPlayer::ESound_EnterMidHealth);
m_playedMidHealthSound = true;
}
else if ((oldHealth <= healthThrMid) && (currentHealth > healthThrMid) && m_playedMidHealthSound)
{
m_rPlayer.PlaySound(CPlayer::ESound_EnterMidHealth, false);
m_rPlayer.PlaySound(CPlayer::ESound_ExitMidHealth);
m_playedMidHealthSound = false;
}
if((currentHealth <= healthThrLow) && (oldHealth > healthThrLow))
{
if(!isDead)
{
m_rPlayer.SetClientSoundmood(CPlayer::ESoundmood_LowHealth);
}
IAIObject* pAI = m_rPlayer.GetEntity()->GetAI();
if (pAI)
{
float mercyTimeScale = 1.0f;
SAIEVENT aiEvent;
aiEvent.fThreat = mercyTimeScale;
pAI->Event(AIEVENT_LOWHEALTH, &aiEvent);
CGameRules* pGameRules = g_pGame->GetGameRules();
if(pGameRules != NULL)
{
IGameRulesDamageHandlingModule* pDamageHandling = pGameRules->GetDamageHandlingModule();
if(pDamageHandling != NULL)
{
pDamageHandling->OnGameEvent(IGameRulesDamageHandlingModule::eGameEvent_LocalPlayerEnteredMercyTime);
}
}
}
}
else if((currentHealth > healthThrLow) && (oldHealth <= healthThrLow))
{
m_rPlayer.SetClientSoundmood(CPlayer::ESoundmood_Alive);
}
const float k_minDamageForHit = 10.0f; //this is partly to deal with small differences in health over the network
if(!isDead && (currentHealth < oldHealth - k_minDamageForHit))
{
// Update ATL-Switch maybe?
}
const float defiantSkillKillLowHealth = maxHealth * g_pGameCVars->g_defiant_lowHealthFraction;
if(currentHealth > defiantSkillKillLowHealth)
{
m_timeEnteredLowHealth = 0.f;
}
else if(m_timeEnteredLowHealth <= 0.f)
{
m_timeEnteredLowHealth = gEnv->pTimer->GetFrameStartTime();
}
}
const SFollowCameraSettings& CLocalPlayerComponent::GetCurrentFollowCameraSettings() const
{
#ifndef _RELEASE
if(g_spectate_follow_debug_enable > 0)
{
m_followCameraDebugSettings.m_targetOffset = Vec3(g_spectate_follow_debug_targetOffset_x, g_spectate_follow_debug_targetOffset_y, g_spectate_follow_debug_targetOffset_z);
m_followCameraDebugSettings.m_viewOffset = Vec3(g_spectate_follow_debug_viewOffset_x, g_spectate_follow_debug_viewOffset_y, g_spectate_follow_debug_viewOffset_z);
m_followCameraDebugSettings.m_offsetSpeeds = Vec3(g_spectate_follow_debug_offsetspeed_x, g_spectate_follow_debug_offsetspeed_y, g_spectate_follow_debug_offsetspeed_z);
m_followCameraDebugSettings.m_desiredDistance = g_spectate_follow_debug_desiredDistance;
m_followCameraDebugSettings.m_cameraHeightOffset = g_spectate_follow_debug_cameraHeightOffset;
m_followCameraDebugSettings.m_cameraYaw = DEG2RAD(g_spectate_follow_debug_cameraYaw);
m_followCameraDebugSettings.m_cameraSpeed = g_spectate_follow_debug_cameraSpeed;
m_followCameraDebugSettings.m_cameraFov = DEG2RAD(g_spectate_follow_debug_cameraFov);
m_followCameraDebugSettings.m_flags = SFollowCameraSettings::eFCF_None;
m_followCameraDebugSettings.m_flags |= g_spectate_follow_debug_allowOrbitYaw > 0 ? SFollowCameraSettings::eFCF_AllowOrbitYaw : SFollowCameraSettings::eFCF_None;
m_followCameraDebugSettings.m_flags |= g_spectate_follow_debug_allowOrbitPitch > 0 ? SFollowCameraSettings::eFCF_AllowOrbitPitch : SFollowCameraSettings::eFCF_None;
m_followCameraDebugSettings.m_flags |= g_spectate_follow_debug_useEyeDir > 0 ? SFollowCameraSettings::eFCF_UseEyeDir : SFollowCameraSettings::eFCF_None;
m_followCameraDebugSettings.m_flags |= g_spectate_follow_debug_userSelectable > 0 ? SFollowCameraSettings::eFCF_UserSelectable : SFollowCameraSettings::eFCF_None;
return m_followCameraDebugSettings;
}
else
{
if(g_spectate_follow_debug_setDebugSettingsToCurrentViewSettings)
{
g_spectate_follow_debug_setDebugSettingsToCurrentViewSettings = 0;
const SFollowCameraSettings& settings = m_followCameraSettings[m_currentFollowCameraSettingsIndex];
g_spectate_follow_debug_targetOffset_x = settings.m_targetOffset.x;
g_spectate_follow_debug_targetOffset_y = settings.m_targetOffset.y;
g_spectate_follow_debug_targetOffset_z = settings.m_targetOffset.z;
g_spectate_follow_debug_viewOffset_x = settings.m_viewOffset.x;
g_spectate_follow_debug_viewOffset_y = settings.m_viewOffset.y;
g_spectate_follow_debug_viewOffset_z = settings.m_viewOffset.z;
g_spectate_follow_debug_offsetspeed_x = settings.m_offsetSpeeds.x;
g_spectate_follow_debug_offsetspeed_y = settings.m_offsetSpeeds.y;
g_spectate_follow_debug_offsetspeed_z = settings.m_offsetSpeeds.z;
g_spectate_follow_debug_desiredDistance = settings.m_desiredDistance;
g_spectate_follow_debug_cameraHeightOffset = settings.m_cameraHeightOffset;
g_spectate_follow_debug_cameraYaw = settings.m_cameraYaw;
g_spectate_follow_debug_cameraSpeed = settings.m_cameraSpeed;
g_spectate_follow_debug_cameraFov = settings.m_cameraFov;
g_spectate_follow_debug_allowOrbitYaw = (settings.m_flags & SFollowCameraSettings::eFCF_AllowOrbitYaw) > 0 ? 1 : 0;
g_spectate_follow_debug_allowOrbitPitch = (settings.m_flags & SFollowCameraSettings::eFCF_AllowOrbitPitch) > 0 ? 1 : 0;
g_spectate_follow_debug_useEyeDir = (settings.m_flags & SFollowCameraSettings::eFCF_UseEyeDir) > 0 ? 1 : 0;
}
}
#endif //_RELEASE
CRY_ASSERT(m_currentFollowCameraSettingsIndex >= 0 && m_currentFollowCameraSettingsIndex < (int8)m_followCameraSettings.size());
return m_followCameraSettings[m_currentFollowCameraSettingsIndex];
}
void CLocalPlayerComponent::ChangeCurrentFollowCameraSettings( bool increment )
{
const int initial = m_currentFollowCameraSettingsIndex;
bool valid = false;
do
{
if(increment && ++m_currentFollowCameraSettingsIndex == m_followCameraSettings.size())
{
m_currentFollowCameraSettingsIndex = 0;
}
else if(!increment && --m_currentFollowCameraSettingsIndex < 0)
{
m_currentFollowCameraSettingsIndex = m_followCameraSettings.size() - 1;
}
const SFollowCameraSettings& settings = m_followCameraSettings[m_currentFollowCameraSettingsIndex];
valid = (m_currentFollowCameraSettingsIndex==initial) || (settings.m_flags & SFollowCameraSettings::eFCF_UserSelectable)!=0;
} while( !valid );
}
bool CLocalPlayerComponent::SetCurrentFollowCameraSettings( uint32 crcName )
{
const int total = m_followCameraSettings.size();
for( int i=0; i<total; i++ )
{
const SFollowCameraSettings& settings = m_followCameraSettings[i];
if( settings.m_crcSettingsName == crcName )
{
m_currentFollowCameraSettingsIndex = i;
return true;
}
}
return false;
}
CPlayer::EClientSoundmoods CLocalPlayerComponent::FindClientSoundmoodBestFit() const
{
const CRecordingSystem* pRecordingSystem = g_pGame->GetRecordingSystem();
if(pRecordingSystem && pRecordingSystem->IsPlayingBack())
{
return pRecordingSystem->IsInBulletTime() ? CPlayer::ESoundmood_KillcamSlow : CPlayer::ESoundmood_Killcam;
}
CGameRules* pGameRules = g_pGame->GetGameRules();
const IGameRulesStateModule *pStateModule = pGameRules ? pGameRules->GetStateModule() : NULL;
const IGameRulesStateModule::EGR_GameState gameState = pStateModule ? pStateModule->GetGameState() : IGameRulesStateModule::EGRS_InGame;
if(gameState == IGameRulesStateModule::EGRS_PreGame)
{
return CPlayer::ESoundmood_PreGame;
}
else if(gameState == IGameRulesStateModule::EGRS_PostGame)
{
return CPlayer::ESoundmood_PostGame;
}
else if(m_rPlayer.GetSpectatorMode() != CActor::eASM_None)
{
return CPlayer::ESoundmood_Spectating;
}
else if(m_rPlayer.IsDead())
{
return CPlayer::ESoundmood_Dead;
}
else if(m_rPlayer.GetHealth() < g_pGameCVars->g_playerLowHealthThreshold)
{
return CPlayer::ESoundmood_LowHealth;
}
return CPlayer::ESoundmood_Alive;
}
void CLocalPlayerComponent::OnClearInventory()
{
if( CEquipmentLoadout* pLoadout = g_pGame->GetEquipmentLoadout() )
{
pLoadout->SetCurrentAttachmentsToUnlocked();
}
}
| 0 | 0.980668 | 1 | 0.980668 | game-dev | MEDIA | 0.584454 | game-dev,graphics-rendering | 0.917518 | 1 | 0.917518 |
pixelcmtd/CXClient | 19,168 | src/minecraft/net/minecraft/block/BlockFire.java | package net.minecraft.block;
import com.google.common.collect.Maps;
import java.util.Map;
import java.util.Random;
import net.minecraft.block.material.MapColor;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyBool;
import net.minecraft.block.properties.PropertyInteger;
import net.minecraft.block.state.BlockState;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.EnumWorldBlockLayer;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraft.world.WorldProviderEnd;
public class BlockFire extends Block
{
public static final PropertyInteger AGE = PropertyInteger.create("age", 0, 15);
public static final PropertyBool FLIP = PropertyBool.create("flip");
public static final PropertyBool ALT = PropertyBool.create("alt");
public static final PropertyBool NORTH = PropertyBool.create("north");
public static final PropertyBool EAST = PropertyBool.create("east");
public static final PropertyBool SOUTH = PropertyBool.create("south");
public static final PropertyBool WEST = PropertyBool.create("west");
public static final PropertyInteger UPPER = PropertyInteger.create("upper", 0, 2);
private final Map<Block, Integer> encouragements = Maps.<Block, Integer>newIdentityHashMap();
private final Map<Block, Integer> flammabilities = Maps.<Block, Integer>newIdentityHashMap();
/**
* Get the actual Block state of this Block at the given position. This applies properties not visible in the
* metadata, such as fence connections.
*/
public IBlockState getActualState(IBlockState state, IBlockAccess worldIn, BlockPos pos)
{
int i = pos.getX();
int j = pos.getY();
int k = pos.getZ();
if (!World.doesBlockHaveSolidTopSurface(worldIn, pos.down()) && !Blocks.fire.canCatchFire(worldIn, pos.down()))
{
boolean flag = (i + j + k & 1) == 1;
boolean flag1 = (i / 2 + j / 2 + k / 2 & 1) == 1;
int l = 0;
if (this.canCatchFire(worldIn, pos.up()))
{
l = flag ? 1 : 2;
}
return state.withProperty(NORTH, Boolean.valueOf(this.canCatchFire(worldIn, pos.north()))).withProperty(EAST, Boolean.valueOf(this.canCatchFire(worldIn, pos.east()))).withProperty(SOUTH, Boolean.valueOf(this.canCatchFire(worldIn, pos.south()))).withProperty(WEST, Boolean.valueOf(this.canCatchFire(worldIn, pos.west()))).withProperty(UPPER, Integer.valueOf(l)).withProperty(FLIP, Boolean.valueOf(flag1)).withProperty(ALT, Boolean.valueOf(flag));
}
else
{
return this.getDefaultState();
}
}
protected BlockFire()
{
super(Material.fire);
this.setDefaultState(this.blockState.getBaseState().withProperty(AGE, Integer.valueOf(0)).withProperty(FLIP, Boolean.valueOf(false)).withProperty(ALT, Boolean.valueOf(false)).withProperty(NORTH, Boolean.valueOf(false)).withProperty(EAST, Boolean.valueOf(false)).withProperty(SOUTH, Boolean.valueOf(false)).withProperty(WEST, Boolean.valueOf(false)).withProperty(UPPER, Integer.valueOf(0)));
this.setTickRandomly(true);
}
public static void init()
{
Blocks.fire.setFireInfo(Blocks.planks, 5, 20);
Blocks.fire.setFireInfo(Blocks.double_wooden_slab, 5, 20);
Blocks.fire.setFireInfo(Blocks.wooden_slab, 5, 20);
Blocks.fire.setFireInfo(Blocks.oak_fence_gate, 5, 20);
Blocks.fire.setFireInfo(Blocks.spruce_fence_gate, 5, 20);
Blocks.fire.setFireInfo(Blocks.birch_fence_gate, 5, 20);
Blocks.fire.setFireInfo(Blocks.jungle_fence_gate, 5, 20);
Blocks.fire.setFireInfo(Blocks.dark_oak_fence_gate, 5, 20);
Blocks.fire.setFireInfo(Blocks.acacia_fence_gate, 5, 20);
Blocks.fire.setFireInfo(Blocks.oak_fence, 5, 20);
Blocks.fire.setFireInfo(Blocks.spruce_fence, 5, 20);
Blocks.fire.setFireInfo(Blocks.birch_fence, 5, 20);
Blocks.fire.setFireInfo(Blocks.jungle_fence, 5, 20);
Blocks.fire.setFireInfo(Blocks.dark_oak_fence, 5, 20);
Blocks.fire.setFireInfo(Blocks.acacia_fence, 5, 20);
Blocks.fire.setFireInfo(Blocks.oak_stairs, 5, 20);
Blocks.fire.setFireInfo(Blocks.birch_stairs, 5, 20);
Blocks.fire.setFireInfo(Blocks.spruce_stairs, 5, 20);
Blocks.fire.setFireInfo(Blocks.jungle_stairs, 5, 20);
Blocks.fire.setFireInfo(Blocks.log, 5, 5);
Blocks.fire.setFireInfo(Blocks.log2, 5, 5);
Blocks.fire.setFireInfo(Blocks.leaves, 30, 60);
Blocks.fire.setFireInfo(Blocks.leaves2, 30, 60);
Blocks.fire.setFireInfo(Blocks.bookshelf, 30, 20);
Blocks.fire.setFireInfo(Blocks.tnt, 15, 100);
Blocks.fire.setFireInfo(Blocks.tallgrass, 60, 100);
Blocks.fire.setFireInfo(Blocks.double_plant, 60, 100);
Blocks.fire.setFireInfo(Blocks.yellow_flower, 60, 100);
Blocks.fire.setFireInfo(Blocks.red_flower, 60, 100);
Blocks.fire.setFireInfo(Blocks.deadbush, 60, 100);
Blocks.fire.setFireInfo(Blocks.wool, 30, 60);
Blocks.fire.setFireInfo(Blocks.vine, 15, 100);
Blocks.fire.setFireInfo(Blocks.coal_block, 5, 5);
Blocks.fire.setFireInfo(Blocks.hay_block, 60, 20);
Blocks.fire.setFireInfo(Blocks.carpet, 60, 20);
}
public void setFireInfo(Block blockIn, int encouragement, int flammability)
{
this.encouragements.put(blockIn, Integer.valueOf(encouragement));
this.flammabilities.put(blockIn, Integer.valueOf(flammability));
}
public AxisAlignedBB getCollisionBoundingBox(World worldIn, BlockPos pos, IBlockState state)
{
return null;
}
/**
* Used to determine ambient occlusion and culling when rebuilding chunks for render
*/
public boolean isOpaqueCube()
{
return false;
}
public boolean isFullCube()
{
return false;
}
/**
* Returns the quantity of items to drop on block destruction.
*/
public int quantityDropped(Random random)
{
return 0;
}
/**
* How many world ticks before ticking
*/
public int tickRate(World worldIn)
{
return 30;
}
public void updateTick(World worldIn, BlockPos pos, IBlockState state, Random rand)
{
if (worldIn.getGameRules().getBoolean("doFireTick"))
{
if (!this.canPlaceBlockAt(worldIn, pos))
{
worldIn.setBlockToAir(pos);
}
Block block = worldIn.getBlockState(pos.down()).getBlock();
boolean flag = block == Blocks.netherrack;
if (worldIn.provider instanceof WorldProviderEnd && block == Blocks.bedrock)
{
flag = true;
}
if (!flag && worldIn.isRaining() && this.canDie(worldIn, pos))
{
worldIn.setBlockToAir(pos);
}
else
{
int i = ((Integer)state.getValue(AGE)).intValue();
if (i < 15)
{
state = state.withProperty(AGE, Integer.valueOf(i + rand.nextInt(3) / 2));
worldIn.setBlockState(pos, state, 4);
}
worldIn.scheduleUpdate(pos, this, this.tickRate(worldIn) + rand.nextInt(10));
if (!flag)
{
if (!this.canNeighborCatchFire(worldIn, pos))
{
if (!World.doesBlockHaveSolidTopSurface(worldIn, pos.down()) || i > 3)
{
worldIn.setBlockToAir(pos);
}
return;
}
if (!this.canCatchFire(worldIn, pos.down()) && i == 15 && rand.nextInt(4) == 0)
{
worldIn.setBlockToAir(pos);
return;
}
}
boolean flag1 = worldIn.isBlockinHighHumidity(pos);
int j = 0;
if (flag1)
{
j = -50;
}
this.catchOnFire(worldIn, pos.east(), 300 + j, rand, i);
this.catchOnFire(worldIn, pos.west(), 300 + j, rand, i);
this.catchOnFire(worldIn, pos.down(), 250 + j, rand, i);
this.catchOnFire(worldIn, pos.up(), 250 + j, rand, i);
this.catchOnFire(worldIn, pos.north(), 300 + j, rand, i);
this.catchOnFire(worldIn, pos.south(), 300 + j, rand, i);
for (int k = -1; k <= 1; ++k)
{
for (int l = -1; l <= 1; ++l)
{
for (int i1 = -1; i1 <= 4; ++i1)
{
if (k != 0 || i1 != 0 || l != 0)
{
int j1 = 100;
if (i1 > 1)
{
j1 += (i1 - 1) * 100;
}
BlockPos blockpos = pos.add(k, i1, l);
int k1 = this.getNeighborEncouragement(worldIn, blockpos);
if (k1 > 0)
{
int l1 = (k1 + 40 + worldIn.getDifficulty().getDifficultyId() * 7) / (i + 30);
if (flag1)
{
l1 /= 2;
}
if (l1 > 0 && rand.nextInt(j1) <= l1 && (!worldIn.isRaining() || !this.canDie(worldIn, blockpos)))
{
int i2 = i + rand.nextInt(5) / 4;
if (i2 > 15)
{
i2 = 15;
}
worldIn.setBlockState(blockpos, state.withProperty(AGE, Integer.valueOf(i2)), 3);
}
}
}
}
}
}
}
}
}
protected boolean canDie(World worldIn, BlockPos pos)
{
return worldIn.canLightningStrike(pos) || worldIn.canLightningStrike(pos.west()) || worldIn.canLightningStrike(pos.east()) || worldIn.canLightningStrike(pos.north()) || worldIn.canLightningStrike(pos.south());
}
public boolean requiresUpdates()
{
return false;
}
private int getFlammability(Block blockIn)
{
Integer integer = (Integer)this.flammabilities.get(blockIn);
return integer == null ? 0 : integer.intValue();
}
private int getEncouragement(Block blockIn)
{
Integer integer = (Integer)this.encouragements.get(blockIn);
return integer == null ? 0 : integer.intValue();
}
private void catchOnFire(World worldIn, BlockPos pos, int chance, Random random, int age)
{
int i = this.getFlammability(worldIn.getBlockState(pos).getBlock());
if (random.nextInt(chance) < i)
{
IBlockState iblockstate = worldIn.getBlockState(pos);
if (random.nextInt(age + 10) < 5 && !worldIn.canLightningStrike(pos))
{
int j = age + random.nextInt(5) / 4;
if (j > 15)
{
j = 15;
}
worldIn.setBlockState(pos, this.getDefaultState().withProperty(AGE, Integer.valueOf(j)), 3);
}
else
{
worldIn.setBlockToAir(pos);
}
if (iblockstate.getBlock() == Blocks.tnt)
{
Blocks.tnt.onBlockDestroyedByPlayer(worldIn, pos, iblockstate.withProperty(BlockTNT.EXPLODE, Boolean.valueOf(true)));
}
}
}
private boolean canNeighborCatchFire(World worldIn, BlockPos pos)
{
for (EnumFacing enumfacing : EnumFacing.values())
{
if (this.canCatchFire(worldIn, pos.offset(enumfacing)))
{
return true;
}
}
return false;
}
private int getNeighborEncouragement(World worldIn, BlockPos pos)
{
if (!worldIn.isAirBlock(pos))
{
return 0;
}
else
{
int i = 0;
for (EnumFacing enumfacing : EnumFacing.values())
{
i = Math.max(this.getEncouragement(worldIn.getBlockState(pos.offset(enumfacing)).getBlock()), i);
}
return i;
}
}
/**
* Returns if this block is collidable (only used by Fire). Args: x, y, z
*/
public boolean isCollidable()
{
return false;
}
/**
* Checks if the block can be caught on fire
*/
public boolean canCatchFire(IBlockAccess worldIn, BlockPos pos)
{
return this.getEncouragement(worldIn.getBlockState(pos).getBlock()) > 0;
}
public boolean canPlaceBlockAt(World worldIn, BlockPos pos)
{
return World.doesBlockHaveSolidTopSurface(worldIn, pos.down()) || this.canNeighborCatchFire(worldIn, pos);
}
/**
* Called when a neighboring block changes.
*/
public void onNeighborBlockChange(World worldIn, BlockPos pos, IBlockState state, Block neighborBlock)
{
if (!World.doesBlockHaveSolidTopSurface(worldIn, pos.down()) && !this.canNeighborCatchFire(worldIn, pos))
{
worldIn.setBlockToAir(pos);
}
}
public void onBlockAdded(World worldIn, BlockPos pos, IBlockState state)
{
if (worldIn.provider.getDimensionId() > 0 || !Blocks.portal.func_176548_d(worldIn, pos))
{
if (!World.doesBlockHaveSolidTopSurface(worldIn, pos.down()) && !this.canNeighborCatchFire(worldIn, pos))
{
worldIn.setBlockToAir(pos);
}
else
{
worldIn.scheduleUpdate(pos, this, this.tickRate(worldIn) + worldIn.rand.nextInt(10));
}
}
}
public void randomDisplayTick(World worldIn, BlockPos pos, IBlockState state, Random rand)
{
if (rand.nextInt(24) == 0)
{
worldIn.playSound((double)((float)pos.getX() + 0.5F), (double)((float)pos.getY() + 0.5F), (double)((float)pos.getZ() + 0.5F), "fire.fire", 1.0F + rand.nextFloat(), rand.nextFloat() * 0.7F + 0.3F, false);
}
if (!World.doesBlockHaveSolidTopSurface(worldIn, pos.down()) && !Blocks.fire.canCatchFire(worldIn, pos.down()))
{
if (Blocks.fire.canCatchFire(worldIn, pos.west()))
{
for (int j = 0; j < 2; ++j)
{
double d3 = (double)pos.getX() + rand.nextDouble() * 0.10000000149011612D;
double d8 = (double)pos.getY() + rand.nextDouble();
double d13 = (double)pos.getZ() + rand.nextDouble();
worldIn.spawnParticle(EnumParticleTypes.SMOKE_LARGE, d3, d8, d13, 0.0D, 0.0D, 0.0D, new int[0]);
}
}
if (Blocks.fire.canCatchFire(worldIn, pos.east()))
{
for (int k = 0; k < 2; ++k)
{
double d4 = (double)(pos.getX() + 1) - rand.nextDouble() * 0.10000000149011612D;
double d9 = (double)pos.getY() + rand.nextDouble();
double d14 = (double)pos.getZ() + rand.nextDouble();
worldIn.spawnParticle(EnumParticleTypes.SMOKE_LARGE, d4, d9, d14, 0.0D, 0.0D, 0.0D, new int[0]);
}
}
if (Blocks.fire.canCatchFire(worldIn, pos.north()))
{
for (int l = 0; l < 2; ++l)
{
double d5 = (double)pos.getX() + rand.nextDouble();
double d10 = (double)pos.getY() + rand.nextDouble();
double d15 = (double)pos.getZ() + rand.nextDouble() * 0.10000000149011612D;
worldIn.spawnParticle(EnumParticleTypes.SMOKE_LARGE, d5, d10, d15, 0.0D, 0.0D, 0.0D, new int[0]);
}
}
if (Blocks.fire.canCatchFire(worldIn, pos.south()))
{
for (int i1 = 0; i1 < 2; ++i1)
{
double d6 = (double)pos.getX() + rand.nextDouble();
double d11 = (double)pos.getY() + rand.nextDouble();
double d16 = (double)(pos.getZ() + 1) - rand.nextDouble() * 0.10000000149011612D;
worldIn.spawnParticle(EnumParticleTypes.SMOKE_LARGE, d6, d11, d16, 0.0D, 0.0D, 0.0D, new int[0]);
}
}
if (Blocks.fire.canCatchFire(worldIn, pos.up()))
{
for (int j1 = 0; j1 < 2; ++j1)
{
double d7 = (double)pos.getX() + rand.nextDouble();
double d12 = (double)(pos.getY() + 1) - rand.nextDouble() * 0.10000000149011612D;
double d17 = (double)pos.getZ() + rand.nextDouble();
worldIn.spawnParticle(EnumParticleTypes.SMOKE_LARGE, d7, d12, d17, 0.0D, 0.0D, 0.0D, new int[0]);
}
}
}
else
{
for (int i = 0; i < 3; ++i)
{
double d0 = (double)pos.getX() + rand.nextDouble();
double d1 = (double)pos.getY() + rand.nextDouble() * 0.5D + 0.5D;
double d2 = (double)pos.getZ() + rand.nextDouble();
worldIn.spawnParticle(EnumParticleTypes.SMOKE_LARGE, d0, d1, d2, 0.0D, 0.0D, 0.0D, new int[0]);
}
}
}
/**
* Get the MapColor for this Block and the given BlockState
*/
public MapColor getMapColor(IBlockState state)
{
return MapColor.tntColor;
}
public EnumWorldBlockLayer getBlockLayer()
{
return EnumWorldBlockLayer.CUTOUT;
}
/**
* Convert the given metadata into a BlockState for this Block
*/
public IBlockState getStateFromMeta(int meta)
{
return this.getDefaultState().withProperty(AGE, Integer.valueOf(meta));
}
/**
* Convert the BlockState into the correct metadata value
*/
public int getMetaFromState(IBlockState state)
{
return ((Integer)state.getValue(AGE)).intValue();
}
protected BlockState createBlockState()
{
return new BlockState(this, new IProperty[] {AGE, NORTH, EAST, SOUTH, WEST, UPPER, FLIP, ALT});
}
}
| 0 | 0.903154 | 1 | 0.903154 | game-dev | MEDIA | 0.980892 | game-dev | 0.750802 | 1 | 0.750802 |
OwlGamingCommunity/V | 2,587 | Source/owl_vehicles.client/Init.Client.cs | using System;
class Init_VehicleSystem : RAGE.Events.Script { Init_VehicleSystem() { OwlScriptManager.RegisterScript<VehicleSystem>(); } }
class VehicleSystem : OwlScript
{
public VehicleSystem()
{
try
{
CVehicleDefinition[] jsonData =
OwlJSON.DeserializeObject<CVehicleDefinition[]>(CVehicleData.VehicleData, EJsonTrackableIdentifier.VehicleDefs);
foreach (CVehicleDefinition vehicleDef in jsonData)
{
VehicleDefinitions.g_VehicleDefinitions.Add(vehicleDef.Index, vehicleDef);
}
}
catch (Exception e)
{
ExceptionHelper.SendException(e);
}
m_VehicleSystemGeneral = new VehicleSystemGeneral();
m_DirtSystem = new DirtSystem();
m_TurnSignals = new TurnSignals();
m_DrivingTest = new DrivingTest();
m_FuelStations = new FuelStations();
m_VehicleRepair = new VehicleRepair();
m_CarWash = new CarWash();
m_TowingSystem = new TowingSystem();
m_CruiseControl = new CruiseControl();
m_ModShop = new VehicleModShop();
m_VehicleCrusher = new VehicleCrusher();
m_VehiclesList = new VehiclesListUI();
}
public static VehicleSystemGeneral GetVehicleSystemGeneral() { return m_VehicleSystemGeneral; }
private static VehicleSystemGeneral m_VehicleSystemGeneral = null;
public static CruiseControl GetCruiseControl() { return m_CruiseControl; }
private static CruiseControl m_CruiseControl = null;
public static DirtSystem GetDirtSystem() { return m_DirtSystem; }
private static DirtSystem m_DirtSystem = null;
public static TurnSignals GetTurnSignals() { return m_TurnSignals; }
private static TurnSignals m_TurnSignals = null;
public static DrivingTest GetDrivingTest() { return m_DrivingTest; }
private static DrivingTest m_DrivingTest = null;
public static FuelStations GetFuelStations() { return m_FuelStations; }
private static FuelStations m_FuelStations = null;
public static VehicleRepair GetVehicleRepair() { return m_VehicleRepair; }
private static VehicleRepair m_VehicleRepair = null;
public static CarWash GetCarWash() { return m_CarWash; }
private static CarWash m_CarWash = null;
public static TowingSystem GetTowingSystem() { return m_TowingSystem; }
private static TowingSystem m_TowingSystem = null;
public static VehicleModShop GetVehicleModShop() { return m_ModShop; }
private static VehicleModShop m_ModShop = null;
public static VehicleCrusher GetVehicleCrusher() { return m_VehicleCrusher; }
private static VehicleCrusher m_VehicleCrusher = null;
public static VehiclesListUI GetVehiclesListUI() { return m_VehiclesList; }
private static VehiclesListUI m_VehiclesList = null;
} | 0 | 0.826769 | 1 | 0.826769 | game-dev | MEDIA | 0.86394 | game-dev | 0.790324 | 1 | 0.790324 |
PotRooms/StarResonanceData | 1,058 | lua/table/gen/DialoguePicTableMgr.lua | local DialoguePicTableRow
local mgr = require("utility.table_manager")
local TableInitUtility = Panda.TableInitUtility
local super = require("table.table_manager_base")
local DialoguePicTableMgr = class("DialoguePicTableMgr", super)
function DialoguePicTableMgr:ctor(ptr, fields)
super.ctor(self, ptr, fields)
end
function DialoguePicTableMgr:GetRow(key, notErrorWhenNotFound)
local ret = self.__rows[key]
if ret ~= nil then
return ret
end
ret = super.GetRow(self, key, "int")
if not ret then
if not notErrorWhenNotFound then
logError("DialoguePicTableMgr:GetRow key:{0} failed in scene:{1}", key, self.GetCurrentSceneId())
end
return nil
end
return ret
end
function DialoguePicTableMgr:GetDatas()
return super.GetDatas(self)
end
local wrapper
return {
__init = function(ptr, fields)
wrapper = DialoguePicTableMgr.new(ptr, fields)
end,
GetRow = function(key, notErrorWhenNotFound)
return wrapper:GetRow(key, notErrorWhenNotFound)
end,
GetDatas = function()
return wrapper:GetDatas()
end
}
| 0 | 0.813372 | 1 | 0.813372 | game-dev | MEDIA | 0.788802 | game-dev | 0.626151 | 1 | 0.626151 |
RaphaelIT7/gmod-holylib | 3,400 | source/ivp/ivp_surface_manager/ivp_compact_grid.hxx | // Copyright (C) Ipion Software GmbH 1999-2000. All rights reserved.
// IVP_EXPORT_PUBLIC
/********************************************************************************
* Filename: ivp_compact_grid.hxx
* Description: This file contains the most important class to describe a
* grid's geometrical (and thus physical) shape, the COMPACT
* GRID.
* Classes: IVP_Compact_Grid
* IVP_Compact_Grid_Element
********************************************************************************/
#ifndef _IVP_COMPACT_GRID_INCLUDED
#define _IVP_COMPACT_GRID_INCLUDED
/********************************************************************************
* Class: IVP_Compact_Grid_Element
* Description: an INTERNAL structure
*******************************************************************************/
class IVP_Compact_Grid_Element {
public:
short compact_ledge_index[2]; // maximum of two ledges for one square
};
/********************************************************************************
* Class: IVP_Compact_Grid
* Description: The compact grid class is the most important class for grids
* in the Ipion engine as it describes the geometrical topology
* and some additional basic values.
* Note: This class is just the HEADER for a far more complex (and
* internal) data structure. So DO NOT change any of these
* variables or you will certainly break the engine's neck! :-)
* Note: This structure has to be 16bit aligned!
* Note: Do not create a compact grid manually! Instead use the
* IVP_GridBuilder_Array class to create a compact grid.
* Important: Only use "ivp_free_aligned()" to free a compact grid!
*******************************************************************************/
class IVP_Compact_Grid {
public:
IVP_U_Float_Hesse center;
IVP_U_Matrix m_grid_f_object; // scales to grid, virtual grid size 1.0
// x and y are grid axles, z is height
// center is at 0,0
short n_rows; // number of grid's rows
short n_columns; // number of grid's columns
int n_compact_ledges; // number of ledges (i.e. convex subparts) in grid
IVP_FLOAT radius;
hk_intp byte_size;
IVP_FLOAT inv_grid_size;
int offset_grid_elements;
int offset_compact_ledge_array[1]; // array of offsets to compact ledges
// grid elements follow size n_rows * n_columns
// compact ledges follow size = sum of size of compact ledges
/******************************************************************************
* Method: get_grid_elements
* Description: INTERNAL METHOD
*****************************************************************************/
const IVP_Compact_Grid_Element *get_grid_elements() {
char *base = (char *)(((hk_intp)this) + this->offset_grid_elements);
return((const IVP_Compact_Grid_Element *)base);
}
/******************************************************************************
* Method: get_compact_ledge_at
* Description: INTERNAL METHOD
*****************************************************************************/
const IVP_Compact_Ledge *get_compact_ledge_at(int i) {
char *base = (char *)(((hk_intp)this) + this->offset_compact_ledge_array[i]);
return((const IVP_Compact_Ledge *)base);
}
};
#endif
| 0 | 0.819067 | 1 | 0.819067 | game-dev | MEDIA | 0.608747 | game-dev | 0.548889 | 1 | 0.548889 |
SlimeKnights/Mantle | 5,124 | src/main/java/slimeknights/mantle/data/GenericDataProvider.java | package slimeknights.mantle.data;
import com.google.common.hash.Hashing;
import com.google.common.hash.HashingOutputStream;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.stream.JsonWriter;
import com.mojang.serialization.Codec;
import com.mojang.serialization.JsonOps;
import lombok.RequiredArgsConstructor;
import net.minecraft.Util;
import net.minecraft.data.CachedOutput;
import net.minecraft.data.DataGenerator;
import net.minecraft.data.DataProvider;
import net.minecraft.data.PackOutput;
import net.minecraft.data.PackOutput.Target;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.util.GsonHelper;
import slimeknights.mantle.Mantle;
import slimeknights.mantle.util.JsonHelper;
import javax.annotation.Nullable;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Comparator;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.stream.Stream;
/** Generic logic to convert any serializable object into JSON. */
@RequiredArgsConstructor
public abstract class GenericDataProvider implements DataProvider {
protected final PackOutput.PathProvider pathProvider;
private final Gson gson;
public GenericDataProvider(PackOutput output, Target type, String folder, Gson gson) {
this(output.createPathProvider(type, folder), gson);
}
public GenericDataProvider(DataGenerator generator, Target type, String folder, Gson gson) {
this(generator.getPackOutput(), type, folder, gson);
}
public GenericDataProvider(PackOutput output, Target type, String folder) {
this(output, type, folder, JsonHelper.DEFAULT_GSON);
}
public GenericDataProvider(DataGenerator generator, Target type, String folder) {
this(generator, type, folder, JsonHelper.DEFAULT_GSON);
}
/**
* Saves the given object to JSON
* @param output Output for writing
* @param location Location relative to this data provider's root
* @param object Object to save, will be converted using this provider's GSON instance
*/
protected CompletableFuture<?> saveJson(CachedOutput output, ResourceLocation location, Object object, @Nullable Comparator<String> keyComparator) {
return saveStable(output, gson.toJsonTree(object), this.pathProvider.json(location), keyComparator).exceptionally(e -> {
Mantle.logger.error("Couldn't create data for {}", location, e);
return null;
});
}
/**
* Saves the given object to JSON
* @param output Output for writing
* @param location Location relative to this data provider's root
* @param object Object to save, will be converted using this provider's GSON instance
*/
protected CompletableFuture<?> saveJson(CachedOutput output, ResourceLocation location, Object object) {
return saveJson(output, location, object, DataProvider.KEY_COMPARATOR);
}
/**
* Saves the given object to JSON using a codec
* @param output Output for writing
* @param location Location relative to this data provider's root
* @param codec Codec to save the object
* @param object Object to save, will be converted using the passed codec
*/
protected <T> CompletableFuture<?> saveJson(CachedOutput output, ResourceLocation location, Codec<T> codec, T object) {
return saveJson(output, location, codec.encodeStart(JsonOps.INSTANCE, object).getOrThrow(false, Mantle.logger::error));
}
/** Combines a stream of completable futures into a single completable future */
public static CompletableFuture<?> allOf(Stream<CompletableFuture<?>> stream) {
return CompletableFuture.allOf(stream.toArray(CompletableFuture[]::new));
}
/** Combines a list of completable futures into a single completable future */
public static CompletableFuture<?> allOf(Collection<CompletableFuture<?>> tasks) {
return CompletableFuture.allOf(tasks.toArray(CompletableFuture[]::new));
}
/** Recreation of {@link DataProvider#saveStable(CachedOutput, JsonElement, Path)} that allows swapping tke key comparator */
@SuppressWarnings("UnstableApiUsage")
static CompletableFuture<?> saveStable(CachedOutput cache, JsonElement pJson, Path pPath, @Nullable Comparator<String> keyComparator) {
return CompletableFuture.runAsync(() -> {
try {
ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
HashingOutputStream hashingOutput = new HashingOutputStream(Hashing.sha1(), byteOutput);
try (JsonWriter writer = new JsonWriter(new OutputStreamWriter(hashingOutput, StandardCharsets.UTF_8))) {
writer.setSerializeNulls(false);
writer.setIndent(" ");
GsonHelper.writeValue(writer, pJson, keyComparator);
}
cache.writeIfNeeded(pPath, byteOutput.toByteArray(), hashingOutput.hash());
} catch (IOException exception) {
throw new CompletionException(exception);
}
}, Util.backgroundExecutor());
}
}
| 0 | 0.921607 | 1 | 0.921607 | game-dev | MEDIA | 0.386838 | game-dev | 0.925646 | 1 | 0.925646 |
riperiperi/FreeSO | 11,739 | TSOClient/tso.client/UI/Panels/Neighborhoods/UITop10Pedestal.cs | using FSO.Client.Controllers;
using FSO.Client.Rendering.City;
using FSO.Client.UI.Controls;
using FSO.Client.UI.Framework;
using FSO.Common.DataService;
using FSO.Common.DataService.Model;
using FSO.Common.Rendering.Framework.Model;
using FSO.Common.Utils;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Ninject;
using System;
using System.Collections.Generic;
namespace FSO.Client.UI.Panels.Neighborhoods
{
public class UITop10Pedestal : UIContainer
{
public bool AltColor;
public bool CastLeft;
public bool CastRight;
private Texture2D Tile;
private Texture2D TileFill;
private Texture2D TileTop;
private Texture2D TileBtm;
public UISim Sim { get; set; }
public Binding<Avatar> User { get; internal set; }
public Binding<Lot> Property { get; internal set; }
public string AvatarTooltip { get; set; } = "";
public string LotTooltip { get; set; } = "";
private LotThumbEntry ThumbLock;
private bool ShowTooltip;
//Mixing concerns here but binding avatar id is much nicer than lots of plumbing each time
private IClientDataService DataService;
private uint _AvatarId = 0;
public uint AvatarId
{
get { return _AvatarId; }
set
{
_AvatarId = value;
if (value == uint.MaxValue || value == 0)
{
GameThread.NextUpdate((x) =>
{
User.Value = null;
});
Sim.Visible = false;
}
else
{
DataService.Get<Avatar>(_AvatarId).ContinueWith(x =>
{
if (x.Result == null) { return; }
User.Value = x.Result;
});
DataService.Request(Server.DataService.Model.MaskedStruct.SimPage_Main, _AvatarId);
Sim.Visible = true;
LotId = 0;
}
}
}
private uint _LotId = 0;
public uint LotId
{
get { return _LotId; }
set
{
var last = _LotId;
_LotId = value;
if (value == uint.MaxValue || value == 0)
{
GameThread.NextUpdate((x) =>
{
Property.Value = null;
});
if (ThumbLock != null)
{
ThumbLock.Held--;
ThumbLock = null;
}
}
else
{
if (value == last) return;
DataService.Get<Lot>(_LotId).ContinueWith(x =>
{
if (x.Result == null) { return; }
Property.Value = x.Result;
});
DataService.Request(Server.DataService.Model.MaskedStruct.PropertyPage_LotInfo, _LotId);
AvatarId = 0;
if (ThumbLock != null) ThumbLock.Held--;
ThumbLock = FindController<CoreGameScreenController>().Terrain.LockLotThumb(value);
}
}
}
public float Height { get; set; }
public bool Hovered;
private bool LastMouseDown;
private bool Clicked;
public UITop10Pedestal()
{
DataService = FSOFacade.Kernel.Get<IClientDataService>();
var ui = Content.Content.Get().CustomUI;
TileFill = ui.Get("neighp_tilefill.png").Get(GameFacade.GraphicsDevice);
TileTop = ui.Get("neighp_tiletop.png").Get(GameFacade.GraphicsDevice);
TileBtm = ui.Get("neighp_tilebtm.png").Get(GameFacade.GraphicsDevice);
SetGraphics(false);
Sim = new UISim();
Sim.Avatar.BodyOutfitId = 2611340115981;
Sim.Avatar.HeadOutfitId = 5076651343885;
Sim.Size = new Microsoft.Xna.Framework.Vector2(64, 80);
Sim.AutoRotate = true;
Sim.Position = new Vector2(-32, (-80) + 16);
this.Add(Sim);
User = new Binding<Avatar>()
.WithBinding(this, "AvatarTooltip", "Avatar_Name")
.WithBinding(this, "Sim.Avatar.HeadOutfitId", "Avatar_Appearance.AvatarAppearance_HeadOutfitID")
.WithBinding(this, "Sim.Avatar.BodyOutfitId", "Avatar_Appearance.AvatarAppearance_BodyOutfitID")
.WithBinding(this, "Sim.Avatar.Appearance", "Avatar_Appearance.AvatarAppearance_SkinTone", (x) => {
if (x == null) return Vitaboy.AppearanceType.Light;
return (Vitaboy.AppearanceType)((byte)(x));
});
Property = new Binding<Lot>()
.WithBinding(this, "LotTooltip", "Lot_Name");
}
public override void Removed()
{
User.Dispose();
Property.Dispose();
base.Removed();
}
public override void Update(UpdateState state)
{
Sim.Position = new Vector2(-32, (-80) + 14 - Height);
Sim.TimeOffset = X*10000000;
base.Update(state);
if (!WillDraw()) return;
if (Hovered)
{
if (!ShowTooltip && (AvatarId > 0 || LotId > 0))
{
state.UIState.TooltipProperties.Show = true;
state.UIState.TooltipProperties.Color = Color.Black;
state.UIState.TooltipProperties.Opacity = 0;
state.UIState.TooltipProperties.Position = state.MouseState.Position.ToVector2();
state.UIState.Tooltip = (AvatarId > 0)?AvatarTooltip:LotTooltip;
ShowTooltip = true;
}
if (ShowTooltip)
{
if (state.UIState.TooltipProperties.Opacity < 1) state.UIState.TooltipProperties.Opacity += 0.1f;
state.UIState.TooltipProperties.UpdateDead = false;
}
if ((state.MouseState.LeftButton == ButtonState.Pressed) && !LastMouseDown)
{
if (LotId != 0)
{
FindController<CoreGameScreenController>().ShowLotPage(LotId);
}
else if (AvatarId != 0)
{
FindController<CoreGameScreenController>().ShowPersonPage(AvatarId);
}
Clicked = true;
FSO.HIT.HITVM.Get().PlaySoundEvent(Model.UISounds.Click);
}
} else if (ShowTooltip)
{
ShowTooltip = false;
}
if (state.MouseState.LeftButton != ButtonState.Pressed) Clicked = false;
Hovered = false;
//horiz check
var mouse = Parent.GlobalPoint(state.MouseState.Position.ToVector2());
if (Visible && mouse.X > X-32 && mouse.X < X+32)
{
if (mouse.Y > Y && mouse.Y < Y + 16)
{
//bottom region. check diagonal
var diff = (mouse.Y - Y)*2;
if (mouse.X > (X - 32) + diff && mouse.X < (X + 32) - diff)
Hovered = true;
}
else if (mouse.Y < Y - Height && mouse.Y > Y - (Height + 16))
{
//top region. check diagonal
var diff = ((Y-Height) - mouse.Y) * 2;
if (mouse.X > (X - 32) + diff && mouse.X < (X + 32) - diff)
Hovered = true;
}
else if (mouse.Y <= Y && mouse.Y >= Y-Height)
{
//box
Hovered = true;
}
}
if (Hovered) {
foreach (var child in Parent.GetChildren())
{
var ped = child as UITop10Pedestal;
if (ped != null && ped != this && ped.Hovered)
{
Hovered = false;
}
}
}
LastMouseDown = state.MouseState.LeftButton == ButtonState.Pressed;
}
public void SetGraphics(bool big)
{
var ui = Content.Content.Get().CustomUI;
Tile = ui.Get("neighp_tile.png").Get(GameFacade.GraphicsDevice);
}
public void SetPlace(int place)
{
var targH = 0;
if (place > 0 && place < 4)
{
targH = (4 - place) * 10;
}
GameFacade.Screens.Tween.To(this, 0.5f, new Dictionary<string, float> { { "Height", targH } }, TweenQuad.EaseOut);
}
public override void Draw(UISpriteBatch batch)
{
if (!Visible) return;
//draw the pedestal
var tintCol = (AltColor) ? new Color(217, 245, 255) : Color.White;
var halfW = Tile.Width / 2;
var halfH = Tile.Height / 2;
var halfV = new Vector2(-halfW, -halfH);
var scale = new Vector2(Tile.Width / TileFill.Width);
//shadow
DrawLocalTexture(batch, TileFill, null, new Vector2(1, 1) + halfV, scale, Color.Black);
//fill
var fillCol = new Color(new Color(164, 188, 210).ToVector4() * tintCol.ToVector4());
var shad = fillCol * 0.88f;
shad.A = 255;
DrawLocalTexture(batch, TileFill, null, halfV, scale, fillCol);
DrawLocalTexture(batch, TileFill, new Rectangle(TileFill.Width/2, 0, TileFill.Width/2, TileFill.Height), new Vector2(0, -halfH), scale, shad);
var pxWhite = TextureGenerator.GetPxWhite(batch.GraphicsDevice);
DrawLocalTexture(batch, pxWhite, null, new Vector2(-halfW, -Height), new Vector2(halfW, Height + 0.5f), fillCol);
DrawLocalTexture(batch, pxWhite, null, new Vector2(0, -Height), new Vector2(halfW, Height + 0.5f), shad);
//tile
DrawLocalTexture(batch, Tile, null, new Vector2(0, -Height) + halfV, Vector2.One, tintCol);
//bottom and top
var intensity = Math.Min(1f, Height / 10f);
DrawLocalTexture(batch, TileBtm, null, new Vector2(0, 6) + halfV, scale, tintCol*intensity);
DrawLocalTexture(batch, TileTop, null, new Vector2(0, 16-Height) + halfV, scale, tintCol * intensity);
if (Hovered)
{
var hoverCol = (Clicked)?(Color.Black*0.2f):(Color.White * 0.3f);
DrawLocalTexture(batch, TileFill, new Rectangle(0, 0, TileFill.Width, halfH), new Vector2(-halfW, -(halfH+Height)), scale, hoverCol);
DrawLocalTexture(batch, TileFill, new Rectangle(0, halfH, TileFill.Width, halfH), new Vector2(-halfW, 0), scale, hoverCol);
DrawLocalTexture(batch, pxWhite, null, new Vector2(-halfW, -Height), new Vector2(halfW*2, Height + 0.5f), hoverCol);
}
if (ThumbLock != null && ThumbLock.Loaded && ThumbLock.LotTexture != null)
{
var tex = ThumbLock.LotTexture;
DrawLocalTexture(batch, tex, null, new Vector2(-halfW, -(halfW+Height)), new Vector2((halfW * 2f)/tex.Width));
}
base.Draw(batch);
}
}
}
| 0 | 0.887125 | 1 | 0.887125 | game-dev | MEDIA | 0.85308 | game-dev | 0.991674 | 1 | 0.991674 |
W1lliam1337/digital-sdk | 14,795 | digital-sdk/features/auto_wall/auto_wall.cc | #include "auto_wall.hh"
void c_auto_wall::scale_damage( const c_game_trace& enter_trace, const c_weapon_info* weapon_info, float& dmg ) const {
// @ref: https://github.com/perilouswithadollarsign/cstrike15_src/blob/master/game/server/player.cpp#L1194
static auto mp_damage_scale_ct_head = g_interfaces->m_cvar->find_var( _( "mp_damage_scale_ct_head" ) );
static auto mp_damage_scale_t_head = g_interfaces->m_cvar->find_var( _( "mp_damage_scale_t_head" ) );
static auto mp_damage_scale_ct_body = g_interfaces->m_cvar->find_var( _( "mp_damage_scale_ct_body" ) );
static auto mp_damage_scale_t_body = g_interfaces->m_cvar->find_var( _( "mp_damage_scale_t_body" ) );
auto head_damage_scale = enter_trace.m_entity->team( ) == 3
? mp_damage_scale_ct_head->get_float( ) : enter_trace.m_entity->team( ) == 2
? mp_damage_scale_t_head->get_float( ) : 1.0f;
const auto body_damage_scale = enter_trace.m_entity->team( ) == 3
? mp_damage_scale_ct_body->get_float( ) : enter_trace.m_entity->team( ) == 2
? mp_damage_scale_t_body->get_float( ) : 1.0f;
if ( enter_trace.m_entity->is_heavy_armor( ) )
head_damage_scale *= 0.5f;
switch ( enter_trace.m_hit_group ) {
case hitgroup_head:
dmg *= weapon_info->m_headshot_multiplier * head_damage_scale;
break;
case hitgroup_chest:
case hitgroup_leftarm:
case hitgroup_rightarm:
case hitgroup_neck:
dmg *= body_damage_scale;
break;
case hitgroup_stomach:
dmg *= 1.25f * body_damage_scale;
break;
case hitgroup_leftleg:
case hitgroup_rightleg:
dmg *= 0.75f * body_damage_scale;
break;
default:
break;
}
if ( !enter_trace.m_entity->is_armored( enter_trace.m_hit_group ) )
return;
// @ida: module: server.dll; sig: 80 BF ? ? ? ? ? F3 0F 10 5C 24 ? F3 0F 10 35
float heavy_armor_bonus = 1.0f, armor_bonus = 0.5f, armor_ratio = weapon_info->m_armor_ratio * 0.5f;
if ( enter_trace.m_entity->is_heavy_armor( ) ) {
heavy_armor_bonus = 0.25f;
armor_bonus = 0.33f;
armor_ratio *= 0.20f;
}
float damage_to_health = dmg * armor_ratio;
const float damage_to_armor = ( dmg - damage_to_health ) * ( heavy_armor_bonus * armor_bonus );
if ( damage_to_armor > static_cast<float>( enter_trace.m_entity->armor_value( ) ) )
damage_to_health = dmg - static_cast<float>( enter_trace.m_entity->armor_value( ) ) / armor_bonus;
dmg = damage_to_health;
}
bool c_auto_wall::trace_to_exit( const c_game_trace& enter_trace, c_game_trace& exit_trace, vec3_t start,
vec3_t direction ) const {
// @ida: https://imgur.com/x3Qe12r
// module: server.dll; sig: F3 0F 5C CE F3 0F 11 5D ?
auto distance = 0.0f;
int v13{ };
vec3_t end{ };
while ( distance <= 90.0f ) {
distance += 4.0f;
end = start + direction * distance;
if ( !v13 )
v13 = g_interfaces->m_trace->get_point_contents( end, 0x4600400B, nullptr );
vec3_t cl_end = end - direction * 4.0f;
const auto contents = g_interfaces->m_trace->get_point_contents( end, 0x4600400B, nullptr );
if ( contents & 0x600400B && ( contents & 0x40000000 || v13 == contents ) )
continue;
static const auto trace_filter = g_modules->m_client_dll.get_address( _( "TraceFilter" ) ).offset( 0x3D ).as< std::uint32_t* >( );
const std::uint32_t filter[ 4 ] = { *trace_filter, reinterpret_cast< std::uint32_t >( exit_trace.m_entity ), 0,
0 };
g_interfaces->m_trace->trace_ray( ray_t( end, cl_end ), 0x4600400B, nullptr, &exit_trace );
if ( static auto var = g_interfaces->m_cvar->find_var( _( "sv_clip_penetration_traces_to_players" ) );
var->get_int( ) ) {
clip_trace_to_players( end, cl_end, ( c_trace_filter* ) ( filter ), &exit_trace, -60.0f );
}
if ( exit_trace.m_start_solid && exit_trace.m_surface.m_flags & surf_hitbox ) {
g_interfaces->m_trace->trace_ray( ray_t( end, start ), 0x600400B, ( c_trace_filter* ) ( filter ),
&exit_trace );
if ( exit_trace.did_hit( ) && !exit_trace.m_start_solid ) {
end = exit_trace.m_end;
return true;
}
continue;
}
if ( exit_trace.did_hit( ) && !exit_trace.m_start_solid ) {
if ( enter_trace.m_entity->is_breakable( ) && exit_trace.m_entity->is_breakable( ) )
return true;
if ( enter_trace.m_surface.m_flags & surf_nodraw
|| !( exit_trace.m_surface.m_flags & surf_nodraw )
&& exit_trace.m_plane.m_normal.dot( direction ) <= 1.0f ) {
start -= direction * exit_trace.m_fraction * 4.0f;
return true;
}
continue;
}
if ( !exit_trace.did_hit( ) || exit_trace.m_start_solid ) {
if ( enter_trace.m_entity != nullptr && enter_trace.m_entity->get_index( ) > 0
&& enter_trace.m_entity->is_breakable( ) ) {
exit_trace = enter_trace;
exit_trace.m_end = start + direction;
return true;
}
}
}
return false;
}
void c_auto_wall::clip_trace_to_players( const vec3_t& abs_start, const vec3_t& abs_end, c_trace_filter* filter,
c_game_trace* trace, const float min_range ) const {
static const auto clip_trace_to_players_fn = g_modules->m_client_dll.get_address( _( "ClipTraceToPlayers" ) ).as<
void( __thiscall* )( c_handle_entity*, vec3_t, vec3_t, unsigned int, i_trace_filter*, c_game_trace*, float )>( );
return clip_trace_to_players_fn( c_player::get_local( ), abs_start, abs_end, mask_shot_hull | contents_hitbox,
filter, trace, min_range );
}
bool c_auto_wall::handle_bullet_penetration( const c_weapon_info* weapon_data, const c_game_trace& enter_trace,
const vec3_t& direction, vec3_t& eye_pos, int& hits, float& current_dmg,
const float pen_power ) const {
// @ida:
// module: server.dll; sig: 39 07 75 1C;
// module: client.dll: sig: E8 ? ? ? ? 83 C4 40 84 C0;
c_game_trace exit_trace;
const auto enter_surface_data =
g_interfaces->m_phys_surface_props->get_surface_data( enter_trace.m_surface.m_surface_props );
const auto enter_material = enter_surface_data->m_game.m_material;
const bool is_solid_surf = enter_trace.m_contents >> 3 & contents_solid;
const bool is_light_surf = enter_trace.m_surface.m_flags >> 7 & surf_light;
const auto v85 = ( enter_trace.m_contents & 8 ) != 0;
const auto v86 = ( enter_trace.m_surface.m_flags & 0x80 ) != 0;
if ( !hits && !v85 && !v86 && enter_material != 89 && enter_material != 71 )
return false;
if ( !weapon_data->m_penetration
|| !trace_to_exit( enter_trace, exit_trace, enter_trace.m_end, direction )
&& !( g_interfaces->m_trace->get_point_contents( enter_trace.m_end, 0x600400B, nullptr ) & 0x600400B ) )
return false;
static auto var = g_interfaces->m_cvar->find_var( _( "sv_penetration_type" ) );
const int possible_hits = var->get_int( );
const auto exit_surface_data =
g_interfaces->m_phys_surface_props->get_surface_data( exit_trace.m_surface.m_surface_props );
const auto exit_material = exit_surface_data->m_game.m_material;
static auto ff_damage_bullet_penetration = g_interfaces->m_cvar->find_var( _( "ff_damage_bullet_penetration" ) );
static auto ff_damage_reduction_bullets = g_interfaces->m_cvar->find_var( _( "ff_damage_reduction_bullets" ) );
float combined_penetration_modifier{ };
float final_damage_modifier;
if ( possible_hits != 1 ) {
if ( is_solid_surf || is_light_surf ) {
combined_penetration_modifier = 1.0f;
final_damage_modifier = 0.99f;
} else {
final_damage_modifier = enter_surface_data->m_game.m_dmg_modifier;
combined_penetration_modifier =
std::fminf( enter_surface_data->m_game.m_pen_modifier, exit_surface_data->m_game.m_pen_modifier );
if ( enter_surface_data->m_game.m_dmg_modifier > enter_surface_data->m_game.m_jump_factor )
final_damage_modifier = enter_surface_data->m_game.m_jump_factor;
}
if ( enter_material == exit_material && ( exit_material == 87 || exit_material == 77 ) )
combined_penetration_modifier *= 2.0f;
if ( ( exit_trace.m_end - enter_trace.m_end ).length_sqr( ) > combined_penetration_modifier * pen_power )
return false;
current_dmg *= final_damage_modifier;
eye_pos = exit_trace.m_end;
--hits;
return true;
}
final_damage_modifier = 0.16f;
if ( !is_solid_surf && !is_light_surf ) {
if ( enter_material == 89 ) {
final_damage_modifier = 0.05f;
combined_penetration_modifier = 3.0f;
}
if ( enter_material != 71 ) {
// client.dll
const auto hit_ent = enter_trace.m_entity;
if ( hit_ent ) {
if ( hit_ent->is_player( ) && hit_ent->unk_thing( ) ) {
combined_penetration_modifier = exit_surface_data->m_game.m_pen_modifier;
final_damage_modifier = 0.16f;
}
}
if ( enter_material == 70 && ( ff_damage_reduction_bullets->get_float( ) == 0.0f && hit_ent ) ) {
// mp_teammates_are_enemies
const auto is_enemy = hit_ent != c_player::get_local( ) && hit_ent->team( ) != c_player::get_local( )->team( );
if ( hit_ent->is_player( ) && !is_enemy ) {
if ( ff_damage_bullet_penetration->get_float( ) == 0.0f )
return false;
combined_penetration_modifier = ff_damage_bullet_penetration->get_float( );
final_damage_modifier = 0.16f;
}
}
combined_penetration_modifier = ( enter_surface_data->m_game.m_pen_modifier + exit_surface_data->m_game.m_pen_modifier ) / 2.0f;
final_damage_modifier = 0.16f;
}
}
if ( enter_material != 89 && enter_material != 71 ) {
combined_penetration_modifier = 1.0f;
if ( enter_material == exit_material ) {
if ( exit_material == 87 || exit_material == 85 ) {
combined_penetration_modifier = 3.0f;
} else if ( exit_material == 76 ) {
combined_penetration_modifier = 2.0f;
}
}
}
const auto thickness = ( exit_trace.m_end - enter_trace.m_end ).length_sqr( );
const auto modifier = std::fmax( 1.0f / combined_penetration_modifier, 0.0f );
const auto lost_damage = std::fmax( modifier * thickness / 24.0f + current_dmg * final_damage_modifier
+ std::fmax( 3.75f / pen_power, 0.0f ) * 3.0f * modifier,
0.0f );
if ( lost_damage > current_dmg )
return false;
if ( lost_damage > 0.0f )
current_dmg -= lost_damage;
if ( current_dmg < 1.0f )
return false;
eye_pos = exit_trace.m_end;
--hits;
return true;
}
bool c_auto_wall::fire_bullet( c_player* const player, const vec3_t& direction, float& current_dmg, const vec3_t& point,
vec3_t& eye_pos, int& hits ) const {
const auto weapon = c_player::get_local( )->active_weapon( );
if ( !weapon )
return false;
const auto weapon_data = weapon->weapon_data( );
if ( !weapon_data )
return false;
c_game_trace enter_trace;
static const auto trace_filter = g_modules->m_client_dll.get_address( _( "TraceFilter" ) ).offset( 0x3D ).as< std::uint32_t* >( );
const std::uint32_t filter[ 4 ] = { *trace_filter, reinterpret_cast< std::uint32_t >( c_player::get_local( ) ), 0,
0 };
current_dmg = static_cast<float>( weapon_data->m_damage );
constexpr auto penetration_distance = 3000.0f;
auto penetration_power = 35.0f;
hits = 4;
static auto var = g_interfaces->m_cvar->find_var( _( "sv_penetration_type" ) );
if ( const int possible_hits = var->get_int( ); possible_hits == 1 ) {
penetration_power = weapon_data->m_penetration;
}
const float max_range = min( weapon_data->m_range, ( eye_pos - point ).length( ) );
const auto end = eye_pos + direction * max_range;
while ( current_dmg >= 1.0f ) {
g_interfaces->m_trace->trace_ray( ray_t( eye_pos, end ), mask_shot_hull | contents_hitbox,
( c_trace_filter* ) filter, &enter_trace );
if ( player )
clip_trace_to_players( eye_pos, end + direction * 40.0f, ( c_trace_filter* ) filter, &enter_trace, 0.0f );
const auto enter_surface_data =
g_interfaces->m_phys_surface_props->get_surface_data( enter_trace.m_surface.m_surface_props );
const auto enter_surf_penetration_modifier = enter_surface_data->m_game.m_pen_modifier;
const float distance_traced = ( enter_trace.m_end - eye_pos ).length( );
current_dmg *= std::pow( weapon_data->m_range_modifier, distance_traced / 500.f );
if ( enter_trace.m_fraction == 1.0f ) {
break;
}
if ( distance_traced > penetration_distance && weapon_data->m_penetration > 0.0f
|| enter_surf_penetration_modifier < 0.1f ) {
break;
}
// if ( *( v123 + 13196 ) == v83 ) {
// v115 = 4352;
// if ( *( hit_ent + 39649 ) )
// current_damage = 1.0;
// }
const auto can_do_damage = enter_trace.m_hit_group != hitgroup_gear && enter_trace.m_hit_group != hitgroup_generic;
const auto is_player = enter_trace.m_entity->is_player( );
const auto is_enemy = enter_trace.m_entity->team( ) != c_player::get_local( )->team( );
if ( can_do_damage && is_player && is_enemy ) {
scale_damage( enter_trace, weapon_data, current_dmg );
return true;
}
if ( !hits )
break;
if ( !handle_bullet_penetration( weapon_data, enter_trace, direction, eye_pos, hits, current_dmg,
penetration_power ) )
break;
}
return false;
} | 0 | 0.981992 | 1 | 0.981992 | game-dev | MEDIA | 0.940343 | game-dev | 0.95393 | 1 | 0.95393 |
SavageLabs/SavageFactions | 2,250 | src/main/java/com/massivecraft/factions/cmd/CmdBanlist.java | package com.massivecraft.factions.cmd;
import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.FPlayers;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.Factions;
import com.massivecraft.factions.struct.BanInfo;
import com.massivecraft.factions.struct.Permission;
import com.massivecraft.factions.zcore.util.TL;
import java.util.ArrayList;
import java.util.List;
/**
* This class was originally written by Dariasc (FactionsUUID)
**/
public class CmdBanlist extends FCommand {
public CmdBanlist() {
super();
this.aliases.add("banlist");
this.aliases.add("bans");
this.aliases.add("banl");
this.optionalArgs.put("faction", "faction");
this.requirements = new CommandRequirements.Builder(Permission.BAN)
.playerOnly()
.memberOnly()
.build();
}
@Override
public void perform(CommandContext context) {
Faction target = context.faction;
if (!context.args.isEmpty()) {
target = context.argAsFaction(0);
}
if (target == Factions.getInstance().getWilderness()) {
context.sender.sendMessage(TL.COMMAND_BANLIST_NOFACTION.toString());
return;
}
if (target == null) {
context.sender.sendMessage(TL.COMMAND_BANLIST_INVALID.format(context.argAsString(0)));
return;
}
List<String> lines = new ArrayList<>();
lines.add(TL.COMMAND_BANLIST_HEADER.format(target.getBannedPlayers().size(), target.getTag(context.faction)));
int i = 1;
for (BanInfo info : target.getBannedPlayers()) {
FPlayer banned = FPlayers.getInstance().getById(info.getBanned());
FPlayer banner = FPlayers.getInstance().getById(info.getBanner());
String timestamp = TL.sdf.format(info.getTime());
lines.add(TL.COMMAND_BANLIST_ENTRY.format(i, banned.getName(), banner.getName(), timestamp));
i++;
}
for (String s : lines) {
context.fPlayer.getPlayer().sendMessage(s);
}
}
@Override
public TL getUsageTranslation() {
return TL.COMMAND_BANLIST_DESCRIPTION;
}
} | 0 | 0.685394 | 1 | 0.685394 | game-dev | MEDIA | 0.983496 | game-dev | 0.934872 | 1 | 0.934872 |
MirzaBeig/Boids | 5,284 | Assets/Mirza Beig/Boids/Boids2D_GroupForceFields.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Boids2D_GroupForceFields : MonoBehaviour
{
[System.Serializable]
public struct GroupForceField
{
public Vector3 targetPosition;
public Vector3 boidsAverageVelocity;
public ParticleSystemForceField psForceField;
public readonly Transform Transform
{
get { return psForceField.transform; }
}
public readonly GameObject GameObject
{
get { return psForceField.gameObject; }
}
public readonly void LerpToTargetPosition(float t, float teleportThreshold)
{
float distanceToTarget = Vector3.Distance(Transform.position, targetPosition);
if (distanceToTarget > teleportThreshold)
{
Transform.position = targetPosition;
}
else
{
Transform.position = Vector3.Lerp(Transform.position, targetPosition, t);
}
}
}
Boids2D_Simulator simulator;
List<GroupForceField> forceFields;
public ParticleSystem[] typeParticleSystems;
[Space]
public int maxGroupCount = 32;
public int startingForceFieldCapacity = 32;
[Space]
public float forceFieldLerpSpeed = 10.0f;
public float forceFieldTeleportThreshold = 0.0f;
[Space]
public ParticleSystemForceField forceFieldPrefab;
void Start()
{
simulator = GetComponent<Boids2D_Simulator>();
forceFields = new List<GroupForceField>();
for (int i = 0; i < startingForceFieldCapacity; i++)
{
ParticleSystemForceField forceField = Instantiate(forceFieldPrefab);
GroupForceField groupForceField = new()
{
psForceField = forceField
};
groupForceField.GameObject.SetActive(false);
forceFields.Add(groupForceField);
}
}
void Update()
{
for (int i = 0; i < forceFields.Count; i++)
{
GroupForceField forceField = forceFields[i];
if (!forceField.GameObject.activeSelf)
{
continue;
}
forceField.LerpToTargetPosition(Time.deltaTime * forceFieldLerpSpeed, forceFieldTeleportThreshold);
}
}
void FixedUpdate()
{
for (int i = 0; i < forceFields.Count; i++)
{
GroupForceField forceField = forceFields[i];
forceField.GameObject.SetActive(false);
}
for (int i = 0; i < typeParticleSystems.Length; i++)
{
typeParticleSystems[i].externalForces.RemoveAllInfluences();
}
for (int i = 0; i < Mathf.Min(forceFields.Count, simulator.boidGroups.Count); i++)
{
List<int> group = simulator.boidGroups[i];
int groupCount = group.Count;
Vector2 averagePosition = Vector2.zero;
Vector2 averageVelocity = Vector2.zero;
Boid firstBoidInGroup = simulator.boids[group[0]];
int groupType = firstBoidInGroup.type;
for (int j = 0; j < groupCount; j++)
{
Boid boid = simulator.boids[group[j]];
averagePosition += boid.position;
averageVelocity += boid.velocity;
}
averagePosition /= groupCount;
averageVelocity /= groupCount;
// Force field.
GroupForceField forceField = forceFields[i];
forceField.GameObject.SetActive(true);
forceField.targetPosition = averagePosition;
float normalizedGroupCount = groupCount / (float)maxGroupCount;
ParticleSystem.MinMaxCurve gravity = forceField.psForceField.gravity;
gravity.constant = forceFieldPrefab.gravity.constant * normalizedGroupCount;
forceField.psForceField.endRange = forceFieldPrefab.endRange * normalizedGroupCount;
if (gravity.constant > forceFieldPrefab.gravity.constant)
{
gravity.constant = forceFieldPrefab.gravity.constant;
}
if (forceField.psForceField.endRange > forceFieldPrefab.endRange)
{
forceField.psForceField.endRange = forceFieldPrefab.endRange;
}
//gravity.constant = Mathf.Min(gravity.constant, forceFieldPrefab.gravity.constant);
//forceField.psForceField.endRange = Mathf.Min(forceField.psForceField.endRange, forceFieldPrefab.endRange);
forceField.psForceField.gravity = gravity;
forceField.boidsAverageVelocity = averageVelocity;
forceFields[i] = forceField;
// Particle system.
ParticleSystem particleSystem = typeParticleSystems[groupType];
particleSystem.externalForces.AddInfluence(forceField.psForceField);
}
for (int i = 0; i < forceFields.Count; i++)
{
GroupForceField forceField = forceFields[i];
if (forceField.GameObject.activeSelf)
{
Debug.DrawRay(forceField.Transform.position, forceField.boidsAverageVelocity.normalized * 2.0f, Color.yellow);
}
}
}
}
| 0 | 0.761602 | 1 | 0.761602 | game-dev | MEDIA | 0.911527 | game-dev | 0.954148 | 1 | 0.954148 |
IntellectualSites/FastAsyncWorldEdit | 3,852 | worldedit-core/src/main/java/com/fastasyncworldedit/core/function/mask/ImageBrushMask.java | package com.fastasyncworldedit.core.function.mask;
import com.fastasyncworldedit.core.command.tool.brush.ImageBrush;
import com.fastasyncworldedit.core.math.MutableVector3;
import com.fastasyncworldedit.core.util.TextureUtil;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.function.mask.AbstractExtentMask;
import com.sk89q.worldedit.function.mask.Mask;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.math.Vector3;
import com.sk89q.worldedit.math.transform.Transform;
import com.sk89q.worldedit.world.block.BlockType;
public class ImageBrushMask extends AbstractExtentMask {
private final MutableVector3 mutable = new MutableVector3();
private final Mask solid;
private final BlockVector3 center;
private final Transform transform;
private final double scale;
private final double centerImageX;
private final double centerImageZ;
private final int width;
private final int height;
private final ImageBrush.ColorFunction colorFunction;
private final EditSession session;
private final TextureUtil texture;
public ImageBrushMask(
Mask solid,
BlockVector3 center,
Transform transform,
double scale,
double centerImageX,
double centerImageZ,
int width,
int height,
ImageBrush.ColorFunction colorFunction,
EditSession session,
TextureUtil texture
) {
super(session);
this.solid = solid;
this.center = center;
this.transform = transform;
this.scale = scale;
this.centerImageX = centerImageX;
this.centerImageZ = centerImageZ;
this.width = width;
this.height = height;
this.colorFunction = colorFunction;
this.session = session;
this.texture = texture;
}
@Override
public boolean test(Extent extent, BlockVector3 vector) {
return test(vector);
}
@Override
public boolean test(BlockVector3 vector) {
if (solid.test(vector)) {
int dx = vector.x() - center.x();
int dy = vector.y() - center.y();
int dz = vector.z() - center.z();
Vector3 pos1 = transform.apply(mutable.setComponents(dx - 0.5, dy - 0.5, dz - 0.5));
int x1 = (int) (pos1.x() * scale + centerImageX);
int z1 = (int) (pos1.z() * scale + centerImageZ);
Vector3 pos2 = transform.apply(mutable.setComponents(dx + 0.5, dy + 0.5, dz + 0.5));
int x2 = (int) (pos2.x() * scale + centerImageX);
int z2 = (int) (pos2.z() * scale + centerImageZ);
if (x2 < x1) {
int tmp = x1;
x1 = x2;
x2 = tmp;
}
if (z2 < z1) {
int tmp = z1;
z1 = z2;
z2 = tmp;
}
if (x1 >= width || x2 < 0 || z1 >= height || z2 < 0) {
return false;
}
int color = colorFunction.call(x1, z1, x2, z2, session, vector);
if (color != 0) {
BlockType block = texture.getNearestBlock(color);
if (block != null) {
session.setBlock(vector, block.getDefaultState());
}
}
return true;
}
return false;
}
@Override
public Mask copy() {
return new ImageBrushMask(
solid.copy(),
center.toImmutable(),
transform,
scale,
centerImageX,
centerImageZ,
width,
height,
colorFunction,
session,
texture
);
}
}
| 0 | 0.917701 | 1 | 0.917701 | game-dev | MEDIA | 0.486811 | game-dev,graphics-rendering | 0.931865 | 1 | 0.931865 |
Fluorohydride/ygopro-scripts | 2,265 | c43598843.lua | --ギミック・パペット-テラー・ベビー
function c43598843.initial_effect(c)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(43598843,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_SUMMON_SUCCESS)
e1:SetTarget(c43598843.sptg)
e1:SetOperation(c43598843.spop)
c:RegisterEffect(e1)
--protection
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(43598843,1))
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_GRAVE)
e2:SetCost(aux.bfgcost)
e2:SetOperation(c43598843.target)
e2:SetOperation(c43598843.operation)
c:RegisterEffect(e2)
end
function c43598843.spfilter(c,e,tp)
return c:IsSetCard(0x1083) and not c:IsCode(43598843) and c:IsCanBeSpecialSummoned(e,0,tp,false,false,POS_FACEUP_DEFENSE)
end
function c43598843.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c43598843.spfilter(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingTarget(c43598843.spfilter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c43598843.spfilter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c43598843.spop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP_DEFENSE)
end
end
function c43598843.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetFlagEffect(tp,43598843)==0 end
end
function c43598843.operation(e,tp,eg,ep,ev,re,r,rp)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_CHAINING)
e1:SetOperation(c43598843.actop)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
Duel.RegisterFlagEffect(tp,43598843,RESET_PHASE+PHASE_END,0,1)
end
function c43598843.actop(e,tp,eg,ep,ev,re,r,rp)
local rc=re:GetHandler()
if re:IsActiveType(TYPE_MONSTER) and rc:IsSetCard(0x1083) and ep==tp then
Duel.SetChainLimit(c43598843.chainlm)
end
end
function c43598843.chainlm(e,rp,tp)
return tp==rp
end
| 0 | 0.927506 | 1 | 0.927506 | game-dev | MEDIA | 0.981972 | game-dev | 0.946006 | 1 | 0.946006 |
javafxports/openjdk-jfx | 4,765 | modules/javafx.web/src/main/native/Source/JavaScriptCore/runtime/ErrorInstance.h | /*
* Copyright (C) 1999-2000 Harri Porten (porten@kde.org)
* Copyright (C) 2008-2017 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#pragma once
#include "JSDestructibleObject.h"
#include "RuntimeType.h"
#include "StackFrame.h"
namespace JSC {
class ErrorInstance : public JSDestructibleObject {
public:
typedef JSDestructibleObject Base;
const static unsigned StructureFlags = Base::StructureFlags | OverridesGetOwnPropertySlot | OverridesGetPropertyNames;
enum SourceTextWhereErrorOccurred { FoundExactSource, FoundApproximateSource };
typedef String (*SourceAppender) (const String& originalMessage, const String& sourceText, RuntimeType, SourceTextWhereErrorOccurred);
DECLARE_EXPORT_INFO;
static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
{
return Structure::create(vm, globalObject, prototype, TypeInfo(ErrorInstanceType, StructureFlags), info());
}
static ErrorInstance* create(ExecState* exec, VM& vm, Structure* structure, const String& message, SourceAppender appender = nullptr, RuntimeType type = TypeNothing, bool useCurrentFrame = true)
{
ErrorInstance* instance = new (NotNull, allocateCell<ErrorInstance>(vm.heap)) ErrorInstance(vm, structure);
instance->m_sourceAppender = appender;
instance->m_runtimeTypeForCause = type;
instance->finishCreation(exec, vm, message, useCurrentFrame);
return instance;
}
static ErrorInstance* create(ExecState*, Structure*, JSValue message, SourceAppender = nullptr, RuntimeType = TypeNothing, bool useCurrentFrame = true);
bool hasSourceAppender() const { return !!m_sourceAppender; }
SourceAppender sourceAppender() const { return m_sourceAppender; }
void setSourceAppender(SourceAppender appender) { m_sourceAppender = appender; }
void clearSourceAppender() { m_sourceAppender = nullptr; }
void setRuntimeTypeForCause(RuntimeType type) { m_runtimeTypeForCause = type; }
RuntimeType runtimeTypeForCause() const { return m_runtimeTypeForCause; }
void clearRuntimeTypeForCause() { m_runtimeTypeForCause = TypeNothing; }
void setStackOverflowError() { m_stackOverflowError = true; }
bool isStackOverflowError() const { return m_stackOverflowError; }
void setOutOfMemoryError() { m_outOfMemoryError = true; }
bool isOutOfMemoryError() const { return m_outOfMemoryError; }
JS_EXPORT_PRIVATE String sanitizedToString(ExecState*);
Vector<StackFrame>* stackTrace() { return m_stackTrace.get(); }
bool materializeErrorInfoIfNeeded(VM&);
bool materializeErrorInfoIfNeeded(VM&, PropertyName);
template<typename CellType, SubspaceAccess mode>
static IsoSubspace* subspaceFor(VM& vm)
{
return vm.errorInstanceSpace<mode>();
}
void finalizeUnconditionally(VM&);
protected:
explicit ErrorInstance(VM&, Structure*);
void finishCreation(ExecState*, VM&, const String&, bool useCurrentFrame = true);
static void destroy(JSCell*);
static bool getOwnPropertySlot(JSObject*, ExecState*, PropertyName, PropertySlot&);
static void getOwnNonIndexPropertyNames(JSObject*, ExecState*, PropertyNameArray&, EnumerationMode);
static void getStructurePropertyNames(JSObject*, ExecState*, PropertyNameArray&, EnumerationMode);
static bool defineOwnProperty(JSObject*, ExecState*, PropertyName, const PropertyDescriptor&, bool shouldThrow);
static bool put(JSCell*, ExecState*, PropertyName, JSValue, PutPropertySlot&);
static bool deleteProperty(JSCell*, ExecState*, PropertyName);
void computeErrorInfo(VM&);
SourceAppender m_sourceAppender { nullptr };
std::unique_ptr<Vector<StackFrame>> m_stackTrace;
unsigned m_line;
unsigned m_column;
String m_sourceURL;
String m_stackString;
RuntimeType m_runtimeTypeForCause { TypeNothing };
bool m_stackOverflowError { false };
bool m_outOfMemoryError { false };
bool m_errorInfoMaterialized { false };
};
} // namespace JSC
| 0 | 0.903836 | 1 | 0.903836 | game-dev | MEDIA | 0.296645 | game-dev | 0.559816 | 1 | 0.559816 |
Necron-Dev/YqlossClientMixin | 4,285 | src/main/kotlin/yqloss/yqlossclientmixinkt/module/sackcounter/SackCounter.kt | /*
* Copyright (C) 2025 Yqloss
*
* This file is part of Yqloss Client (Mixin).
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 (GPLv2)
* 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 Yqloss Client (Mixin). If not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0.html>.
*/
package yqloss.yqlossclientmixinkt.module.sackcounter
import net.minecraft.client.gui.GuiScreen
import net.minecraft.client.gui.inventory.GuiChest
import net.minecraft.event.HoverEvent
import net.yqloss.uktil.event.EventRegistry
import net.yqloss.uktil.event.register
import net.yqloss.uktil.scope.longRet
import yqloss.yqlossclientmixinkt.api.internalLowerChestInventory
import yqloss.yqlossclientmixinkt.event.minecraft.YCMinecraftEvent
import yqloss.yqlossclientmixinkt.event.minecraft.YCPacketEvent
import yqloss.yqlossclientmixinkt.module.*
import yqloss.yqlossclientmixinkt.util.MC
import yqloss.yqlossclientmixinkt.util.trimStyle
val INFO_SACK_COUNTER = moduleInfo<SackCounterOptions>("sack_counter", "Sack Counter")
private val REGEX_SACK_WINDOW = Regex("^.*Sack.*$")
private val REGEX_STORED_LORE = Regex("^Stored: ([0-9,]+)/.*$")
private val REGEX_SACKS_MESSAGE = Regex("^\\[Sacks] .*?item.*? \\(Last .*?\\)$")
private val REGEX_SACKS_INCREMENT = Regex("^\\+([0-9,]+) ([A-Za-z0-9 \\-]+?) \\(.*\\)$")
object SackCounter : YCModuleBase<SackCounterOptions>(INFO_SACK_COUNTER) {
private val nameToCountMap = mutableMapOf<String, Int>()
fun getCount(name: String) = nameToCountMap[name]
val available get() = enabled && inWorld && inSkyBlock
private fun ensure(screen: GuiScreen?): GuiChest {
available || longRet
val chest = screen as? GuiChest ?: longRet
isWindowTitled(chest, REGEX_SACK_WINDOW) || longRet
return chest
}
override val registerEvents: EventRegistry.() -> Unit
get() = {
super.registerEvents(this)
register<YCMinecraftEvent.Tick.Pre> {
val chest = ensure(MC.currentScreen)
val inventory = chest.internalLowerChestInventory
repeat(inventory.sizeInventory) { i ->
val itemStack = inventory.getStackInSlot(i) ?: return@repeat
val name = itemStack.displayName.trimStyle
itemStack.getTooltip(MC.thePlayer, false).forEach { line ->
REGEX_STORED_LORE.matchEntire(line.trimStyle)?.let { result ->
val count = result.groupValues[1].replace(",", "").toIntOrNull() ?: return@forEach
nameToCountMap[name] = count
}
}
}
}
register<YCPacketEvent.S02.Chat.Pre> { event ->
val message = event.component.formattedText.trimStyle
REGEX_SACKS_MESSAGE.matches(message) || longRet
event.component.siblings.forEach { sibling ->
val hoverEvent = sibling.chatStyle.chatHoverEvent ?: return@forEach
hoverEvent.action === HoverEvent.Action.SHOW_TEXT || return@forEach
val lines = hoverEvent.value?.formattedText?.trimStyle?.split('\n') ?: return@forEach
var anyIncrement = false
lines.forEach { line ->
REGEX_SACKS_INCREMENT.matchEntire(line.trimStyle)?.let { result ->
val count = result.groupValues[1].replace(",", "").toIntOrNull() ?: return@forEach
val name = result.groupValues[2]
nameToCountMap.computeIfPresent(name) { _, last -> last + count }
anyIncrement = true
}
}
if (anyIncrement) return@register
}
}
}
}
| 0 | 0.819691 | 1 | 0.819691 | game-dev | MEDIA | 0.810689 | game-dev | 0.944959 | 1 | 0.944959 |
SasLuca/rayfork | 13,653 | tests/platform-independent-tests/platform-layers/sdl/sdl/src/events/SDL_touch.c | /*
Simple DirectMedia Layer
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "../SDL_internal.h"
/* General touch handling code for SDL */
#include "SDL_assert.h"
#include "SDL_events.h"
#include "SDL_events_c.h"
#include "../video/SDL_sysvideo.h"
static int SDL_num_touch = 0;
static SDL_Touch **SDL_touchDevices = NULL;
/* for mapping touch events to mice */
#define SYNTHESIZE_TOUCH_TO_MOUSE 1
#if SYNTHESIZE_TOUCH_TO_MOUSE
static SDL_bool finger_touching = SDL_FALSE;
static SDL_FingerID track_fingerid;
static SDL_TouchID track_touchid;
#endif
/* Public functions */
int
SDL_TouchInit(void)
{
return (0);
}
int
SDL_GetNumTouchDevices(void)
{
return SDL_num_touch;
}
SDL_TouchID
SDL_GetTouchDevice(int index)
{
if (index < 0 || index >= SDL_num_touch) {
SDL_SetError("Unknown touch device index %d", index);
return 0;
}
return SDL_touchDevices[index]->id;
}
static int
SDL_GetTouchIndex(SDL_TouchID id)
{
int index;
SDL_Touch *touch;
for (index = 0; index < SDL_num_touch; ++index) {
touch = SDL_touchDevices[index];
if (touch->id == id) {
return index;
}
}
return -1;
}
SDL_Touch *
SDL_GetTouch(SDL_TouchID id)
{
int index = SDL_GetTouchIndex(id);
if (index < 0 || index >= SDL_num_touch) {
if (SDL_GetVideoDevice()->ResetTouch != NULL) {
SDL_SetError("Unknown touch id %d, resetting", (int) id);
(SDL_GetVideoDevice()->ResetTouch)(SDL_GetVideoDevice());
} else {
SDL_SetError("Unknown touch device id %d, cannot reset", (int) id);
}
return NULL;
}
return SDL_touchDevices[index];
}
SDL_TouchDeviceType
SDL_GetTouchDeviceType(SDL_TouchID id)
{
SDL_Touch *touch = SDL_GetTouch(id);
if (touch) {
return touch->type;
}
return SDL_TOUCH_DEVICE_INVALID;
}
static int
SDL_GetFingerIndex(const SDL_Touch * touch, SDL_FingerID fingerid)
{
int index;
for (index = 0; index < touch->num_fingers; ++index) {
if (touch->fingers[index]->id == fingerid) {
return index;
}
}
return -1;
}
static SDL_Finger *
SDL_GetFinger(const SDL_Touch * touch, SDL_FingerID id)
{
int index = SDL_GetFingerIndex(touch, id);
if (index < 0 || index >= touch->num_fingers) {
return NULL;
}
return touch->fingers[index];
}
int
SDL_GetNumTouchFingers(SDL_TouchID touchID)
{
SDL_Touch *touch = SDL_GetTouch(touchID);
if (touch) {
return touch->num_fingers;
}
return 0;
}
SDL_Finger *
SDL_GetTouchFinger(SDL_TouchID touchID, int index)
{
SDL_Touch *touch = SDL_GetTouch(touchID);
if (!touch) {
return NULL;
}
if (index < 0 || index >= touch->num_fingers) {
SDL_SetError("Unknown touch finger");
return NULL;
}
return touch->fingers[index];
}
int
SDL_AddTouch(SDL_TouchID touchID, SDL_TouchDeviceType type, const char *name)
{
SDL_Touch **touchDevices;
int index;
index = SDL_GetTouchIndex(touchID);
if (index >= 0) {
return index;
}
/* Add the touch to the list of touch */
touchDevices = (SDL_Touch **) SDL_realloc(SDL_touchDevices,
(SDL_num_touch + 1) * sizeof(*touchDevices));
if (!touchDevices) {
return SDL_OutOfMemory();
}
SDL_touchDevices = touchDevices;
index = SDL_num_touch;
SDL_touchDevices[index] = (SDL_Touch *) SDL_malloc(sizeof(*SDL_touchDevices[index]));
if (!SDL_touchDevices[index]) {
return SDL_OutOfMemory();
}
/* Added touch to list */
++SDL_num_touch;
/* we're setting the touch properties */
SDL_touchDevices[index]->id = touchID;
SDL_touchDevices[index]->type = type;
SDL_touchDevices[index]->num_fingers = 0;
SDL_touchDevices[index]->max_fingers = 0;
SDL_touchDevices[index]->fingers = NULL;
/* Record this touch device for gestures */
/* We could do this on the fly in the gesture code if we wanted */
SDL_GestureAddTouch(touchID);
return index;
}
static int
SDL_AddFinger(SDL_Touch *touch, SDL_FingerID fingerid, float x, float y, float pressure)
{
SDL_Finger *finger;
if (touch->num_fingers == touch->max_fingers) {
SDL_Finger **new_fingers;
new_fingers = (SDL_Finger **)SDL_realloc(touch->fingers, (touch->max_fingers+1)*sizeof(*touch->fingers));
if (!new_fingers) {
return SDL_OutOfMemory();
}
touch->fingers = new_fingers;
touch->fingers[touch->max_fingers] = (SDL_Finger *)SDL_malloc(sizeof(*finger));
if (!touch->fingers[touch->max_fingers]) {
return SDL_OutOfMemory();
}
touch->max_fingers++;
}
finger = touch->fingers[touch->num_fingers++];
finger->id = fingerid;
finger->x = x;
finger->y = y;
finger->pressure = pressure;
return 0;
}
static int
SDL_DelFinger(SDL_Touch* touch, SDL_FingerID fingerid)
{
SDL_Finger *temp;
int index = SDL_GetFingerIndex(touch, fingerid);
if (index < 0) {
return -1;
}
touch->num_fingers--;
temp = touch->fingers[index];
touch->fingers[index] = touch->fingers[touch->num_fingers];
touch->fingers[touch->num_fingers] = temp;
return 0;
}
int
SDL_SendTouch(SDL_TouchID id, SDL_FingerID fingerid, SDL_Window * window,
SDL_bool down, float x, float y, float pressure)
{
int posted;
SDL_Finger *finger;
SDL_Mouse *mouse;
SDL_Touch* touch = SDL_GetTouch(id);
if (!touch) {
return -1;
}
mouse = SDL_GetMouse();
#if SYNTHESIZE_TOUCH_TO_MOUSE
/* SDL_HINT_TOUCH_MOUSE_EVENTS: controlling whether touch events should generate synthetic mouse events */
{
if (mouse->touch_mouse_events) {
/* FIXME: maybe we should only restrict to a few SDL_TouchDeviceType */
if (id != SDL_MOUSE_TOUCHID) {
if (window) {
if (down) {
if (finger_touching == SDL_FALSE) {
int pos_x = (int)(x * (float)window->w);
int pos_y = (int)(y * (float)window->h);
if (pos_x < 0) pos_x = 0;
if (pos_x > window->w - 1) pos_x = window->w - 1;
if (pos_y < 0) pos_y = 0;
if (pos_y > window->h - 1) pos_y = window->h - 1;
SDL_SendMouseMotion(window, SDL_TOUCH_MOUSEID, 0, pos_x, pos_y);
SDL_SendMouseButton(window, SDL_TOUCH_MOUSEID, SDL_PRESSED, SDL_BUTTON_LEFT);
}
} else {
if (finger_touching == SDL_TRUE && track_touchid == id && track_fingerid == fingerid) {
SDL_SendMouseButton(window, SDL_TOUCH_MOUSEID, SDL_RELEASED, SDL_BUTTON_LEFT);
}
}
}
if (down) {
if (finger_touching == SDL_FALSE) {
finger_touching = SDL_TRUE;
track_touchid = id;
track_fingerid = fingerid;
}
} else {
if (finger_touching == SDL_TRUE && track_touchid == id && track_fingerid == fingerid) {
finger_touching = SDL_FALSE;
}
}
}
}
}
#endif
/* SDL_HINT_MOUSE_TOUCH_EVENTS: if not set, discard synthetic touch events coming from platform layer */
if (mouse->mouse_touch_events == 0) {
if (id == SDL_MOUSE_TOUCHID) {
return 0;
}
}
finger = SDL_GetFinger(touch, fingerid);
if (down) {
if (finger) {
/* This finger is already down */
return 0;
}
if (SDL_AddFinger(touch, fingerid, x, y, pressure) < 0) {
return 0;
}
posted = 0;
if (SDL_GetEventState(SDL_FINGERDOWN) == SDL_ENABLE) {
SDL_Event event;
event.tfinger.type = SDL_FINGERDOWN;
event.tfinger.touchId = id;
event.tfinger.fingerId = fingerid;
event.tfinger.x = x;
event.tfinger.y = y;
event.tfinger.dx = 0;
event.tfinger.dy = 0;
event.tfinger.pressure = pressure;
event.tfinger.windowID = window ? SDL_GetWindowID(window) : 0;
posted = (SDL_PushEvent(&event) > 0);
}
} else {
if (!finger) {
/* This finger is already up */
return 0;
}
posted = 0;
if (SDL_GetEventState(SDL_FINGERUP) == SDL_ENABLE) {
SDL_Event event;
event.tfinger.type = SDL_FINGERUP;
event.tfinger.touchId = id;
event.tfinger.fingerId = fingerid;
/* I don't trust the coordinates passed on fingerUp */
event.tfinger.x = finger->x;
event.tfinger.y = finger->y;
event.tfinger.dx = 0;
event.tfinger.dy = 0;
event.tfinger.pressure = pressure;
event.tfinger.windowID = window ? SDL_GetWindowID(window) : 0;
posted = (SDL_PushEvent(&event) > 0);
}
SDL_DelFinger(touch, fingerid);
}
return posted;
}
int
SDL_SendTouchMotion(SDL_TouchID id, SDL_FingerID fingerid, SDL_Window * window,
float x, float y, float pressure)
{
SDL_Touch *touch;
SDL_Finger *finger;
SDL_Mouse *mouse;
int posted;
float xrel, yrel, prel;
touch = SDL_GetTouch(id);
if (!touch) {
return -1;
}
mouse = SDL_GetMouse();
#if SYNTHESIZE_TOUCH_TO_MOUSE
/* SDL_HINT_TOUCH_MOUSE_EVENTS: controlling whether touch events should generate synthetic mouse events */
{
if (mouse->touch_mouse_events) {
if (id != SDL_MOUSE_TOUCHID) {
if (window) {
if (finger_touching == SDL_TRUE && track_touchid == id && track_fingerid == fingerid) {
int pos_x = (int)(x * (float)window->w);
int pos_y = (int)(y * (float)window->h);
if (pos_x < 0) pos_x = 0;
if (pos_x > window->w - 1) pos_x = window->w - 1;
if (pos_y < 0) pos_y = 0;
if (pos_y > window->h - 1) pos_y = window->h - 1;
SDL_SendMouseMotion(window, SDL_TOUCH_MOUSEID, 0, pos_x, pos_y);
}
}
}
}
}
#endif
/* SDL_HINT_MOUSE_TOUCH_EVENTS: if not set, discard synthetic touch events coming from platform layer */
if (mouse->mouse_touch_events == 0) {
if (id == SDL_MOUSE_TOUCHID) {
return 0;
}
}
finger = SDL_GetFinger(touch,fingerid);
if (!finger) {
return SDL_SendTouch(id, fingerid, window, SDL_TRUE, x, y, pressure);
}
xrel = x - finger->x;
yrel = y - finger->y;
prel = pressure - finger->pressure;
/* Drop events that don't change state */
if (xrel == 0.0f && yrel == 0.0f && prel == 0.0f) {
#if 0
printf("Touch event didn't change state - dropped!\n");
#endif
return 0;
}
/* Update internal touch coordinates */
finger->x = x;
finger->y = y;
finger->pressure = pressure;
/* Post the event, if desired */
posted = 0;
if (SDL_GetEventState(SDL_FINGERMOTION) == SDL_ENABLE) {
SDL_Event event;
event.tfinger.type = SDL_FINGERMOTION;
event.tfinger.touchId = id;
event.tfinger.fingerId = fingerid;
event.tfinger.x = x;
event.tfinger.y = y;
event.tfinger.dx = xrel;
event.tfinger.dy = yrel;
event.tfinger.pressure = pressure;
event.tfinger.windowID = window ? SDL_GetWindowID(window) : 0;
posted = (SDL_PushEvent(&event) > 0);
}
return posted;
}
void
SDL_DelTouch(SDL_TouchID id)
{
int i;
int index = SDL_GetTouchIndex(id);
SDL_Touch *touch = SDL_GetTouch(id);
if (!touch) {
return;
}
for (i = 0; i < touch->max_fingers; ++i) {
SDL_free(touch->fingers[i]);
}
SDL_free(touch->fingers);
SDL_free(touch);
SDL_num_touch--;
SDL_touchDevices[index] = SDL_touchDevices[SDL_num_touch];
/* Delete this touch device for gestures */
SDL_GestureDelTouch(id);
}
void
SDL_TouchQuit(void)
{
int i;
for (i = SDL_num_touch; i--; ) {
SDL_DelTouch(SDL_touchDevices[i]->id);
}
SDL_assert(SDL_num_touch == 0);
SDL_free(SDL_touchDevices);
SDL_touchDevices = NULL;
SDL_GestureQuit();
}
/* vi: set ts=4 sw=4 expandtab: */
| 0 | 0.690003 | 1 | 0.690003 | game-dev | MEDIA | 0.90173 | game-dev | 0.60668 | 1 | 0.60668 |
QuickShop-Community/QuickShop-Hikari | 3,254 | quickshop-bukkit/src/main/java/com/ghostchu/quickshop/shop/interaction/behaviors/TradeDirect.java | package com.ghostchu.quickshop.shop.interaction.behaviors;
/*
* QuickShop-Hikari
* Copyright (C) 2025 Daniel "creatorfromhell" Vidmar
*
* 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 <http://www.gnu.org/licenses/>.
*/
import com.ghostchu.quickshop.QuickShop;
import com.ghostchu.quickshop.api.QuickShopAPI;
import com.ghostchu.quickshop.api.shop.Shop;
import com.ghostchu.quickshop.api.shop.interaction.InteractionBehavior;
import com.ghostchu.quickshop.api.shop.interaction.InteractionClick;
import com.ghostchu.quickshop.api.shop.interaction.InteractionType;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.player.PlayerInteractEvent;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import static com.ghostchu.quickshop.util.ShopUtil.buyFromShop;
import static com.ghostchu.quickshop.util.ShopUtil.sellToShop;
/**
* TradeDirect
*
* @author creatorfromhell
* @since 6.2.0.11
*/
public class TradeDirect implements InteractionBehavior {
/**
* Retrieves the identifier associated with this InteractionBehavior.
*
* @return the identifier as a String.
*/
@Override
public String identifier() {
return "TRADE_DIRECT";
}
/**
* Used to handle interactions that a player has with a shop.
*
* @param shop The shop involved in the interaction, not null.
* @param player The player involved in the interaction, not null.
* @param event The PlayerInteractEvent that triggered the interaction, not null.
* @param clickType The type of click that triggered the interaction, not null.
* @param interaction The type of interaction that occurred, can be null.
*/
@Override
public void handle(final @NotNull QuickShopAPI plugin, final @Nullable Shop shop, final @NotNull Player player, final @NotNull PlayerInteractEvent event, final @NotNull InteractionClick clickType, final @Nullable InteractionType interaction) {
if(shop == null) {
return;
}
if(shop.isFrozen()) {
((QuickShop)plugin).text().of(event.getPlayer(), "shop-cannot-trade-when-freezing").send();
return;
}
if(shop.isBuying()) {
if(sellToShop(event.getPlayer(), shop, true, false)) {
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
}
return;
}
if(shop.isSelling()) {
if(buyFromShop(event.getPlayer(), shop, true, false)) {
event.setCancelled(true);
event.setUseInteractedBlock(Event.Result.DENY);
event.setUseItemInHand(Event.Result.DENY);
}
}
}
}
| 0 | 0.83917 | 1 | 0.83917 | game-dev | MEDIA | 0.907114 | game-dev | 0.921345 | 1 | 0.921345 |
7oSkaaa/LeetCode_DailyChallenge_2023 | 2,283 | 06- June/02- Detonate the Maximum Bombs/02- Detonate the Maximum Bombs (Ahmed Hossam).cpp | // Author: Ahmed Hossam
class Solution {
public:
vector<vector<int>> adj; // Adjacency list representing the graph.
vector<bool> vis; // Boolean array to keep track of visited nodes.
// Function to check if a circle is intersect another circle.
bool isIntersect(const vector<int>& a, const vector<int>& b){
int X = (a[0] - b[0]), Y = (a[1] - b[1]), R = a[2];
return (1ll * R * R) >= (1ll * X * X) + (1ll * Y * Y);
}
// Depth-first search function to calculate the length of a path.
int dfs(int u){
vis[u] = true; // Mark the current node as visited.
int pathLength = 1; // Initialize the path length to 1 for the current node.
for(auto& v : adj[u]){ // Iterate through the adjacent nodes of the current node.
if(!vis[v]) // If the adjacent node is not visited, recursively call dfs on it.
pathLength += dfs(v); // Add the path length of the adjacent node to the current path length.
}
return pathLength; // Return the total path length.
}
// Function to build the adjacency list based on the given bombs coordinates.
void build_adj(const vector<vector<int>>& bombs){
int n = bombs.size();
adj = vector<vector<int>>(n + 5); // Initialize the adjacency list.
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(i != j && isIntersect(bombs[i], bombs[j])){ // Check if bomb j is intersect bomb i.
adj[i].push_back(j); // Add j to the adjacency list of i.
}
}
}
}
// Function to calculate the maximum detonation path length.
int maximumDetonation(const vector<vector<int>>& bombs) {
int n = bombs.size(); // Get the number of bombs.
build_adj(bombs); // Build the adjacency list.
int maxPathLength = 0; // Initialize the maximum path length to 0.
for(int i = 0; i < n; i++){ // Iterate through each bomb.
vis = vector<bool>(n + 5); // Reset the visited array.
maxPathLength = max(maxPathLength, dfs(i)); // Calculate the maximum path length starting from bomb i.
}
return maxPathLength; // Return the maximum path length.
}
};
| 0 | 0.89573 | 1 | 0.89573 | game-dev | MEDIA | 0.251272 | game-dev | 0.923669 | 1 | 0.923669 |
Gegy/Terrarium | 2,750 | src/main/java/net/gegy1000/earth/client/gui/preview/WorldPreview.java | package net.gegy1000.earth.client.gui.preview;
import net.gegy1000.earth.client.terrain.TerrainMesh;
import net.gegy1000.earth.client.terrain.TerrainMeshData;
import net.gegy1000.justnow.executor.CurrentThreadExecutor;
import net.gegy1000.justnow.future.Cancelable;
import net.gegy1000.justnow.future.Future;
import net.gegy1000.terrarium.server.world.TerrariumWorldType;
import net.gegy1000.terrarium.server.world.data.source.DataSourceReader;
import net.gegy1000.terrarium.server.world.generator.customization.GenerationSettings;
import java.util.concurrent.atomic.AtomicInteger;
public final class WorldPreview implements AutoCloseable {
public static final int RADIUS = 16 * 16;
public static final int SIZE = RADIUS * 2 + 1;
public static final int GRANULARITY = 2;
private final AtomicInteger referenceCount = new AtomicInteger(1);
private TerrainMesh mesh;
private Cancelable<TerrainMeshData> meshFuture;
public void rebuild(TerrariumWorldType worldType, GenerationSettings settings) {
if (this.meshFuture != null) {
this.meshFuture.cancel();
DataSourceReader.INSTANCE.cancelLoading();
}
this.meshFuture = Future.cancelable(PreviewMeshBuilder.build(worldType, settings));
}
public void render() {
Cancelable<TerrainMeshData> future = this.meshFuture;
if (future != null) {
if (this.advanceMeshFuture(future)) {
this.meshFuture = null;
}
}
TerrainMesh mesh = this.mesh;
if (mesh != null) {
mesh.render();
}
}
private boolean advanceMeshFuture(Future<TerrainMeshData> future) {
TerrainMeshData data = CurrentThreadExecutor.advance(future);
if (data != null) {
this.uploadMesh(data);
return true;
} else {
return false;
}
}
private void uploadMesh(TerrainMeshData data) {
if (this.mesh != null) {
this.mesh.delete();
}
this.mesh = data.upload();
}
public void delete() {
if (this.mesh != null) {
this.mesh.delete();
}
if (this.meshFuture != null) {
this.meshFuture.cancel();
}
this.referenceCount.set(0);
DataSourceReader.INSTANCE.clear();
}
public WorldPreview retain() {
this.referenceCount.getAndIncrement();
return this;
}
public void release() {
if (this.referenceCount.decrementAndGet() <= 0) {
this.delete();
}
}
public boolean isGenerateInactive() {
return this.meshFuture == null;
}
@Override
public void close() {
this.release();
}
}
| 0 | 0.519357 | 1 | 0.519357 | game-dev | MEDIA | 0.724812 | game-dev | 0.735312 | 1 | 0.735312 |
mastercomfig/tf2-patches-old | 2,040 | src/game/client/hud_pdump.h | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#ifndef HUD_PDUMP_H
#define HUD_PDUMP_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui_controls/Panel.h>
#include "hudelement.h"
namespace vgui
{
class IScheme;
};
class CPDumpPanel : public CHudElement, public vgui::Panel
{
DECLARE_CLASS_SIMPLE( CPDumpPanel, vgui::Panel );
public:
enum
{
DUMP_CLASSNAME_SIZE = 128,
DUMP_STRING_SIZE = 128,
};
CPDumpPanel( const char *pElementName );
~CPDumpPanel();
DECLARE_MULTIPLY_INHERITED();
virtual void ApplySettings( KeyValues *inResourceData );
virtual void ApplySchemeSettings( vgui::IScheme *pScheme );
virtual void Paint( void );
virtual bool ShouldDraw();
// Remove dump info
void Clear();
void DumpEntity( C_BaseEntity *ent, int commands_acknowledged );
void DumpComparision( const char *classname, const char *fieldname, const char *fieldtype,
bool networked, bool noterrorchecked, bool differs, bool withintolerance, const char *value );
private:
void PredictionDumpColor( bool networked, bool errorchecked, bool differs, bool withintolerance,
int& r, int& g, int& b, int& a );
//-----------------------------------------------------------------------------
// Purpose: Stores some info about the various fields of an entity for display
//-----------------------------------------------------------------------------
struct DumpInfo
{
char classname[ DUMP_CLASSNAME_SIZE ];
bool networked;
char fieldstring[ DUMP_STRING_SIZE ];
bool differs;
bool withintolerance;
bool noterrorchecked;
};
CUtlVector< DumpInfo > m_DumpEntityInfo;
EHANDLE m_hDumpEntity;
CPanelAnimationVar( vgui::HFont, m_FontSmall, "ItemFont", "DefaultVerySmall" );
CPanelAnimationVar( vgui::HFont, m_FontMedium, "LabelFont", "DefaultSmall" );
CPanelAnimationVar( vgui::HFont, m_FontBig, "TitleFont", "Trebuchet24" );
};
CPDumpPanel *GetPDumpPanel();
#endif // HUD_PDUMP_H
| 0 | 0.953327 | 1 | 0.953327 | game-dev | MEDIA | 0.709555 | game-dev | 0.596234 | 1 | 0.596234 |
TeamTwilight/twilightforest-fabric | 4,492 | src/main/java/twilightforest/world/components/structures/minotaurmaze/MazeRoomSpawnerChestsComponent.java | package twilightforest.world.components.structures.minotaurmaze;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.util.RandomSource;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.StructureManager;
import net.minecraft.world.level.WorldGenLevel;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.chunk.ChunkGenerator;
import net.minecraft.world.level.levelgen.structure.BoundingBox;
import net.minecraft.world.level.levelgen.structure.pieces.StructurePieceSerializationContext;
import twilightforest.init.TFBlocks;
import twilightforest.init.TFEntities;
import twilightforest.init.TFStructurePieceTypes;
import twilightforest.loot.TFLootTables;
public class MazeRoomSpawnerChestsComponent extends MazeRoomComponent {
public MazeRoomSpawnerChestsComponent(StructurePieceSerializationContext ctx, CompoundTag nbt) {
super(TFStructurePieceTypes.TFMMRSC.get(), nbt);
}
public MazeRoomSpawnerChestsComponent(int i, RandomSource rand, int x, int y, int z) {
super(TFStructurePieceTypes.TFMMRSC.get(), i, rand, x, y, z);
}
@Override
public void postProcess(WorldGenLevel world, StructureManager manager, ChunkGenerator generator, RandomSource rand, BoundingBox sbb, ChunkPos chunkPosIn, BlockPos blockPos) {
super.postProcess(world, manager, generator, rand, sbb, chunkPosIn, blockPos);
// 4 pillar enclosures
placePillarEnclosure(world, sbb, 3, 3);
placePillarEnclosure(world, sbb, 10, 3);
placePillarEnclosure(world, sbb, 3, 10);
placePillarEnclosure(world, sbb, 10, 10);
// spawner
setSpawner(world, 4, 2, 4, sbb, TFEntities.MINOTAUR.get());
// treasure
this.placeTreasureAtCurrentPosition(world, 4, 2, 11, TFLootTables.LABYRINTH_ROOM, sbb);
// treasure
this.placeTreasureAtCurrentPosition(world, 11, 2, 4, TFLootTables.LABYRINTH_ROOM, sbb);
// trap
placeBlock(world, Blocks.OAK_PRESSURE_PLATE.defaultBlockState(), 11, 1, 11, sbb);
placeBlock(world, Blocks.TNT.defaultBlockState(), 10, 0, 11, sbb);
placeBlock(world, Blocks.TNT.defaultBlockState(), 11, 0, 10, sbb);
placeBlock(world, Blocks.TNT.defaultBlockState(), 11, 0, 12, sbb);
placeBlock(world, Blocks.TNT.defaultBlockState(), 12, 0, 11, sbb);
}
private void placePillarEnclosure(WorldGenLevel world, BoundingBox sbb,
int dx, int dz) {
for (int y = 1; y < 5; y++) {
final BlockState chiselledMazeBlock = TFBlocks.CUT_MAZESTONE.get().defaultBlockState();
placeBlock(world, chiselledMazeBlock, dx, y, dz, sbb);
placeBlock(world, chiselledMazeBlock, dx + 2, y, dz, sbb);
placeBlock(world, chiselledMazeBlock, dx, y, dz + 2, sbb);
placeBlock(world, chiselledMazeBlock, dx + 2, y, dz + 2, sbb);
}
placeBlock(world, Blocks.OAK_PLANKS.defaultBlockState(), dx + 1, 1, dz + 1, sbb);
placeBlock(world, Blocks.OAK_PLANKS.defaultBlockState(), dx + 1, 4, dz + 1, sbb);
final BlockState defaultState = Blocks.OAK_STAIRS.defaultBlockState();
placeBlock(world, getStairState(defaultState, Direction.NORTH, false), dx + 1, 1, dz, sbb);
placeBlock(world, getStairState(defaultState, Direction.WEST, false), dx, 1, dz + 1, sbb);
placeBlock(world, getStairState(defaultState, Direction.EAST, false), dx + 2, 1, dz + 1, sbb);
placeBlock(world, getStairState(defaultState, Direction.SOUTH, false), dx + 1, 1, dz + 2, sbb);
placeBlock(world, getStairState(defaultState, Direction.NORTH, true), dx + 1, 4, dz, sbb);
placeBlock(world, getStairState(defaultState, Direction.WEST, true), dx, 4, dz + 1, sbb);
placeBlock(world, getStairState(defaultState, Direction.EAST, true), dx + 2, 4, dz + 1, sbb);
placeBlock(world, getStairState(defaultState, Direction.SOUTH, true), dx + 1, 4, dz + 2, sbb);
placeBlock(world, Blocks.IRON_BARS.defaultBlockState(), dx + 1, 2, dz, sbb);
placeBlock(world, Blocks.IRON_BARS.defaultBlockState(), dx, 2, dz + 1, sbb);
placeBlock(world, Blocks.IRON_BARS.defaultBlockState(), dx + 2, 2, dz + 1, sbb);
placeBlock(world, Blocks.IRON_BARS.defaultBlockState(), dx + 1, 2, dz + 2, sbb);
placeBlock(world, Blocks.IRON_BARS.defaultBlockState(), dx + 1, 3, dz, sbb);
placeBlock(world, Blocks.IRON_BARS.defaultBlockState(), dx, 3, dz + 1, sbb);
placeBlock(world, Blocks.IRON_BARS.defaultBlockState(), dx + 2, 3, dz + 1, sbb);
placeBlock(world, Blocks.IRON_BARS.defaultBlockState(), dx + 1, 3, dz + 2, sbb);
}
}
| 0 | 0.903666 | 1 | 0.903666 | game-dev | MEDIA | 0.992594 | game-dev | 0.734787 | 1 | 0.734787 |
ixray-team/ixray-1.6-stcop | 2,366 | gamedata/configs/scripts/pripyat/smart/pri_a17.ltx | [smart_terrain]
squad_id = 25
max_population = 1
arrive_dist = 100
respawn_params = respawn@pri_a17
[respawn@pri_a17]
spawn_chimera
[spawn_chimera]
spawn_squads = simulation_chimera_pripyat
spawn_num = {+pri_a17_actor_bring_gauss_rifle}1, 0
[exclusive]
pri_a17_sim_chimera = pripyat\pri_a17_sim_chimera.ltx
pri_a17_military_captain_tarasov = pripyat\pri_a17_military_captain_tarasov.ltx
pri_a17_military_prapor_valentyr = pripyat\pri_a17_military_prapor_valentyr.ltx
pri_a17_military_sergeant_morozov = pripyat\pri_a17_military_sergeant_morozov.ltx
pri_a17_military_lieutenant_podorojniy = pripyat\pri_a17_military_lieutenant_podorojniy.ltx
pri_a17_military_captain_tarasov_dead = pripyat\pri_a17_military_captain_tarasov.ltx
pri_a17_military_prapor_valentyr_dead = pripyat\pri_a17_military_prapor_valentyr.ltx
pri_a17_military_sergeant_morozov_dead = pripyat\pri_a17_military_sergeant_morozov.ltx
pri_a17_military_lieutenant_podorojniy_dead = pripyat\pri_a17_military_lieutenant_podorojniy.ltx
pri_a17_monolith_patrol_1 = pripyat\pri_a17_monolith_logic.ltx
pri_a17_monolith_patrol_2 = pripyat\pri_a17_monolith_logic.ltx
pri_a17_monolith_patrol_lead = pripyat\pri_a17_monolith_logic.ltx
pri_a17_monolith_patrol_1_dead = pripyat\pri_a17_monolith_logic.ltx
pri_a17_monolith_patrol_2_dead = pripyat\pri_a17_monolith_logic.ltx
pri_a17_monolith_patrol_lead_dead = pripyat\pri_a17_monolith_logic.ltx
pri_a17_monolith_preacher = pripyat\pri_a17_monolith_logic.ltx
pri_a17_monolith_ambusher_1 = pripyat\pri_a17_monolith_logic.ltx
pri_a17_monolith_ambusher_2 = pripyat\pri_a17_monolith_logic.ltx
pri_a17_monolith_ambusher_3 = pripyat\pri_a17_monolith_logic.ltx
pri_a17_monolith_ambusher_4 = pripyat\pri_a17_monolith_logic.ltx
pri_a17_monolith_ambusher_5 = pripyat\pri_a17_monolith_logic.ltx
pri_a17_monolith_ambusher_6 = pripyat\pri_a17_monolith_logic.ltx
pri_a17_monolith_ambusher_7 = pripyat\pri_a17_monolith_logic.ltx
pri_a17_monolith_ambusher_8 = pripyat\pri_a17_monolith_logic.ltx
pri_a17_monolith_ambusher_9 = pripyat\pri_a17_monolith_logic.ltx
pri_a17_monolith_ambusher_10 = pripyat\pri_a17_monolith_logic.ltx
pri_a17_monolith_sniper_1 = pripyat\pri_a17_monolith_logic.ltx
pri_a17_monolith_sniper_2 = pripyat\pri_a17_monolith_logic.ltx
pri_a17_monolith_sniper_3 = pripyat\pri_a17_monolith_logic.ltx
pri_a17_monolith_sniper_4 = pripyat\pri_a17_monolith_logic.ltx
| 0 | 0.659349 | 1 | 0.659349 | game-dev | MEDIA | 0.983025 | game-dev | 0.64039 | 1 | 0.64039 |
hornet-gt/hornet | 5,081 | primitives/LoadBalancing/VertexBasedKernel.cuh | /**
* @author Federico Busato <br>
* Univerity of Verona, Dept. of Computer Science <br>
* federico.busato@univr.it
* @date September, 2017
* @version v2
*
* @copyright Copyright © 2017 Hornet. All rights reserved.
*
* @license{<blockquote>
* 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 copyright holder 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 HOLDER 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.
* </blockquote>}
*
* @file
*/
namespace hornets_nest {
namespace load_balancing {
namespace kernel {
/**
* @brief
*/
template<unsigned VW_SIZE, typename HornetDevice, typename Operator, typename vid_t>
__global__
void vertexBasedVertexPairsKernel(HornetDevice hornet,
const vid_t* __restrict__ d_input,
int num_vertices,
Operator op) {
int group_id = (blockIdx.x * blockDim.x + threadIdx.x) / VW_SIZE;
int stride = (gridDim.x * blockDim.x) / VW_SIZE;
int group_lane = threadIdx.x % VW_SIZE;
for (auto i = group_id; i < num_vertices; i += stride) {
__syncthreads();
const auto& src = hornet.vertex(d_input[i]);
for (auto j = group_lane; j < src.degree(); j += VW_SIZE) {
const auto& edge = src.edge(j);
const auto& dst = hornet.vertex(edge.dst_id());
op(src, dst);
}
__syncthreads();
}
}
/**
* @brief
*/
template<unsigned VW_SIZE, typename HornetDevice, typename Operator, typename vid_t>
__global__
void vertexBasedKernel(HornetDevice hornet,
const vid_t* __restrict__ d_input,
int num_vertices,
Operator op) {
int group_id = (blockIdx.x * blockDim.x + threadIdx.x) / VW_SIZE;
int stride = (gridDim.x * blockDim.x) / VW_SIZE;
int group_lane = threadIdx.x % VW_SIZE;
for (auto i = group_id; i < num_vertices; i += stride) {
__syncthreads();
const auto& vertex = hornet.vertex(d_input[i]);
for (auto j = group_lane; j < vertex.degree(); j += VW_SIZE) {
const auto& edge = vertex.edge(j);
op(vertex, edge);
}
__syncthreads();
}
}
/**
* @brief
*/
template<unsigned VW_SIZE, typename HornetDevice, typename Operator>
__global__
void vertexBasedKernel(HornetDevice hornet, Operator op) {
int group_id = (blockIdx.x * blockDim.x + threadIdx.x) / VW_SIZE;
int stride = (gridDim.x * blockDim.x) / VW_SIZE;
int group_lane = threadIdx.x % VW_SIZE;
for (auto i = group_id; i < hornet.nV(); i += stride) {
const auto& vertex = hornet.vertex(i);
for (auto j = group_lane; j < vertex.degree(); j += VW_SIZE) {
const auto& edge = vertex.edge(j);
op(vertex, edge);
}
}
}
/**
* @brief
*/
template<unsigned VW_SIZE, typename HornetDevice, typename Operator>
__global__
void vertexBasedVertexPairsKernel(HornetDevice hornet, Operator op) {
int group_id = (blockIdx.x * blockDim.x + threadIdx.x) / VW_SIZE;
int stride = (gridDim.x * blockDim.x) / VW_SIZE;
int group_lane = threadIdx.x % VW_SIZE;
for (auto i = group_id; i < hornet.nV(); i += stride) {
const auto& src = hornet.vertex(i);
for (auto j = group_lane; j < src.degree(); j += VW_SIZE) {
const auto& edge = src.edge(j);
const auto& dst = hornet.vertex(edge.dst_id());
op(src, dst);
}
}
}
} // kernel
} // namespace load_balancing
} // namespace hornets_nest
| 0 | 0.7956 | 1 | 0.7956 | game-dev | MEDIA | 0.265852 | game-dev | 0.850327 | 1 | 0.850327 |
PacktPublishing/Unity-5.x-Animation-Cookbook | 1,198 | Assets/Chapter 04/Recipe 01/Scripts/SetSpeedFromAgent.cs | using UnityEngine;
using System.Collections;
public class SetSpeedFromAgent : MonoBehaviour {
//We store the reference to the NavmeshAgent component in this variable
NavMeshAgent agent;
//We store the reference to the Animator component in this variable
Animator anim;
void Start () {
//We assign the NavMeshAgent component to our agent variable
agent = GetComponent<NavMeshAgent>();
//We assign the Animator component to our anim variable
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update () {
if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
{
agent.speed = 4f;
}
else
{
agent.speed = 1f;
}
//We set the "Speed" parameter of the Animator Controller to the magnitude of the agent's velocity.
//This is used by the Blend Tree to blend between walk and run animations.
//We are using the damp time (0.2 seconds) to damp any sudden changes and make sure our blends look smooth.
anim.SetFloat("Speed", agent.desiredVelocity.magnitude, 0.2f, Time.deltaTime);
}
}
| 0 | 0.72136 | 1 | 0.72136 | game-dev | MEDIA | 0.889447 | game-dev | 0.691644 | 1 | 0.691644 |
paritytech/subxt | 1,594 | historic/src/utils/either.rs | macro_rules! either {
($name:ident( $fst:ident, $($variant:ident),* )) => {
pub enum $name<$fst, $($variant),*> {
$fst($fst),
$($variant($variant),)*
}
impl<$fst, $($variant),*> Iterator for $name<$fst, $($variant),*>
where
$fst: Iterator,
$($variant: Iterator<Item = $fst::Item>,)*
{
type Item = $fst::Item;
fn next(&mut self) -> Option<Self::Item> {
match self {
$name::$fst(inner) => inner.next(),
$( $name::$variant(inner) => inner.next(), )*
}
}
}
impl <$fst, $($variant),*> futures::stream::Stream for $name<$fst, $($variant),*>
where
$fst: futures::stream::Stream,
$($variant: futures::stream::Stream<Item = $fst::Item>,)*
{
type Item = $fst::Item;
fn poll_next(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
use std::pin::Pin;
// SAFETY: This is safe because we never move the inner value out of the Pin.
unsafe {
match self.get_unchecked_mut() {
$name::$fst(inner) => Pin::new_unchecked(inner).poll_next(cx),
$( $name::$variant(inner) => Pin::new_unchecked(inner).poll_next(cx), )*
}
}
}
}
}
}
either!(Either(A, B));
| 0 | 0.814313 | 1 | 0.814313 | game-dev | MEDIA | 0.260717 | game-dev | 0.64306 | 1 | 0.64306 |
ds58/Panilla | 1,394 | api/src/main/java/com/ruinscraft/panilla/api/nbt/checks/NbtCheck_ChargedProjectiles.java | package com.ruinscraft.panilla.api.nbt.checks;
import com.ruinscraft.panilla.api.IPanilla;
import com.ruinscraft.panilla.api.config.PStrictness;
import com.ruinscraft.panilla.api.nbt.INbtTagCompound;
import com.ruinscraft.panilla.api.nbt.INbtTagList;
import com.ruinscraft.panilla.api.nbt.NbtDataType;
public class NbtCheck_ChargedProjectiles extends NbtCheck {
public NbtCheck_ChargedProjectiles() {
super("ChargedProjectiles", PStrictness.AVERAGE);
}
@Override
public NbtCheckResult check(INbtTagCompound tag, String itemName, IPanilla panilla) {
NbtCheckResult result = NbtCheckResult.PASS;
INbtTagList chargedProjectiles = tag.getList("ChargedProjectiles", NbtDataType.COMPOUND);
for (int i = 0; i < chargedProjectiles.size(); i++) {
INbtTagCompound chargedProjectile = chargedProjectiles.getCompound(i);
if (chargedProjectile.hasKey("tag")) {
INbtTagCompound chargedProjectileTag = chargedProjectile.getCompound("tag");
if (chargedProjectileTag.hasKey("Potion")) {
String potion = chargedProjectileTag.getString("Potion");
if (potion.endsWith("empty")) {
result = NbtCheckResult.FAIL;
break;
}
}
}
}
return result;
}
}
| 0 | 0.704284 | 1 | 0.704284 | game-dev | MEDIA | 0.867923 | game-dev | 0.830687 | 1 | 0.830687 |
v7b1/vb.mi-dev | 1,944 | source/mutableSources32/marbles/ramp/ramp_generator.h | // Copyright 2015 Emilie Gillet.
//
// Author: Emilie Gillet (emilie.o.gillet@gmail.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// See http://creativecommons.org/licenses/MIT/ for more information.
//
// -----------------------------------------------------------------------------
//
// Simple ramp generator.
#ifndef MARBLES_RAMP_RAMP_GENERATOR_H_
#define MARBLES_RAMP_RAMP_GENERATOR_H_
#include "stmlib/stmlib.h"
namespace marbles {
class RampGenerator {
public:
RampGenerator() { }
~RampGenerator() { }
void Init() {
phase_ = 0.0f;
}
void Render(float frequency, float* out, size_t size) {
while (size--) {
phase_ += frequency;
if (phase_ >= 1.0f) {
phase_ -= 1.0f;
}
*out++ = phase_;
}
}
private:
float phase_;
DISALLOW_COPY_AND_ASSIGN(RampGenerator);
};
} // namespace marbles
#endif // MARBLES_RAMP_RAMP_GENERATOR_H_
| 0 | 0.710647 | 1 | 0.710647 | game-dev | MEDIA | 0.439473 | game-dev,graphics-rendering | 0.766579 | 1 | 0.766579 |
Goob-Station/Goob-Station-MRP | 13,745 | Content.Shared/Customization/Systems/CharacterRequirements.Profile.cs | using System.Linq;
using Content.Shared.Clothing.Loadouts.Prototypes;
using Content.Shared.Humanoid;
using Content.Shared.Humanoid.Prototypes;
using Content.Shared.Mind;
using Content.Shared.Preferences;
using Content.Shared.Prototypes;
using Content.Shared.Roles;
using Content.Shared.Traits;
using JetBrains.Annotations;
using Robust.Shared.Configuration;
using Robust.Shared.Enums;
using Robust.Shared.Physics;
using Robust.Shared.Prototypes;
using Robust.Shared.Serialization;
namespace Content.Shared.Customization.Systems;
/// <summary>
/// Requires the profile to be within an age range
/// </summary>
[UsedImplicitly, Serializable, NetSerializable]
public sealed partial class CharacterAgeRequirement : CharacterRequirement
{
[DataField(required: true)]
public int Min;
[DataField]
public int Max = Int32.MaxValue;
public override bool IsValid(
JobPrototype job,
HumanoidCharacterProfile profile,
Dictionary<string, TimeSpan> playTimes,
bool whitelisted,
IPrototype prototype,
IEntityManager entityManager,
IPrototypeManager prototypeManager,
IConfigurationManager configManager,
out string? reason,
int depth = 0,
MindComponent? mind = null
)
{
var localeString = "";
if (Max == Int32.MaxValue || Min <= 0)
localeString = Max == Int32.MaxValue ? "character-age-requirement-minimum-only" : "character-age-requirement-maximum-only";
else
localeString = "character-age-requirement-range";
reason = Loc.GetString(
localeString,
("inverted", Inverted),
("min", Min),
("max", Max));
return profile.Age >= Min && profile.Age <= Max;
}
}
/// <summary>
/// Requires the profile to be a certain gender
/// </summary>
[UsedImplicitly, Serializable, NetSerializable]
public sealed partial class CharacterGenderRequirement : CharacterRequirement
{
[DataField(required: true)]
public Gender Gender;
public override bool IsValid(
JobPrototype job,
HumanoidCharacterProfile profile,
Dictionary<string, TimeSpan> playTimes,
bool whitelisted,
IPrototype prototype,
IEntityManager entityManager,
IPrototypeManager prototypeManager,
IConfigurationManager configManager,
out string? reason,
int depth = 0,
MindComponent? mind = null
)
{
reason = Loc.GetString(
"character-gender-requirement",
("inverted", Inverted),
("gender", Loc.GetString($"humanoid-profile-editor-pronouns-{Gender.ToString().ToLower()}-text")));
return profile.Gender == Gender;
}
}
/// <summary>
/// Requires the profile to be a certain sex
/// </summary>
[UsedImplicitly, Serializable, NetSerializable]
public sealed partial class CharacterSexRequirement : CharacterRequirement
{
[DataField(required: true)]
public Sex Sex;
public override bool IsValid(
JobPrototype job,
HumanoidCharacterProfile profile,
Dictionary<string, TimeSpan> playTimes,
bool whitelisted,
IPrototype prototype,
IEntityManager entityManager,
IPrototypeManager prototypeManager,
IConfigurationManager configManager,
out string? reason,
int depth = 0,
MindComponent? mind = null
)
{
reason = Loc.GetString(
"character-sex-requirement",
("inverted", Inverted),
("sex", Loc.GetString($"humanoid-profile-editor-sex-{Sex.ToString().ToLower()}-text")));
return profile.Sex == Sex;
}
}
/// <summary>
/// Requires the profile to be a certain species
/// </summary>
[UsedImplicitly, Serializable, NetSerializable]
public sealed partial class CharacterSpeciesRequirement : CharacterRequirement
{
[DataField(required: true)]
public List<ProtoId<SpeciesPrototype>> Species;
public override bool IsValid(
JobPrototype job,
HumanoidCharacterProfile profile,
Dictionary<string, TimeSpan> playTimes,
bool whitelisted,
IPrototype prototype,
IEntityManager entityManager,
IPrototypeManager prototypeManager,
IConfigurationManager configManager,
out string? reason,
int depth = 0,
MindComponent? mind = null
)
{
const string color = "green";
reason = Loc.GetString(
"character-species-requirement",
("inverted", Inverted),
("species", $"[color={color}]{string.Join($"[/color], [color={color}]",
Species.Select(s => Loc.GetString(prototypeManager.Index(s).Name)))}[/color]"));
return Species.Contains(profile.Species);
}
}
/// <summary>
/// Requires the profile to be within a certain height range
/// </summary>
[UsedImplicitly, Serializable, NetSerializable]
public sealed partial class CharacterHeightRequirement : CharacterRequirement
{
/// <summary>
/// The minimum height of the profile in centimeters
/// </summary>
[DataField]
public float Min = int.MinValue;
/// <summary>
/// The maximum height of the profile in centimeters
/// </summary>
[DataField]
public float Max = int.MaxValue;
public override bool IsValid(
JobPrototype job,
HumanoidCharacterProfile profile,
Dictionary<string, TimeSpan> playTimes,
bool whitelisted,
IPrototype prototype,
IEntityManager entityManager,
IPrototypeManager prototypeManager,
IConfigurationManager configManager,
out string? reason,
int depth = 0,
MindComponent? mind = null
)
{
const string color = "yellow";
var species = prototypeManager.Index<SpeciesPrototype>(profile.Species);
reason = Loc.GetString(
"character-height-requirement",
("inverted", Inverted),
("color", color),
("min", Min),
("max", Max));
var height = profile.Height * species.AverageHeight;
return height >= Min && height <= Max;
}
}
/// <summary>
/// Requires the profile to be within a certain width range
/// </summary>
[UsedImplicitly, Serializable, NetSerializable]
public sealed partial class CharacterWidthRequirement : CharacterRequirement
{
/// <summary>
/// The minimum width of the profile in centimeters
/// </summary>
[DataField]
public float Min = int.MinValue;
/// <summary>
/// The maximum width of the profile in centimeters
/// </summary>
[DataField]
public float Max = int.MaxValue;
public override bool IsValid(
JobPrototype job,
HumanoidCharacterProfile profile,
Dictionary<string, TimeSpan> playTimes,
bool whitelisted,
IPrototype prototype,
IEntityManager entityManager,
IPrototypeManager prototypeManager,
IConfigurationManager configManager,
out string? reason,
int depth = 0,
MindComponent? mind = null
)
{
const string color = "yellow";
var species = prototypeManager.Index<SpeciesPrototype>(profile.Species);
reason = Loc.GetString(
"character-width-requirement",
("inverted", Inverted),
("color", color),
("min", Min),
("max", Max));
var width = profile.Width * species.AverageWidth;
return width >= Min && width <= Max;
}
}
/// <summary>
/// Requires the profile to be within a certain weight range
/// </summary>
[UsedImplicitly, Serializable, NetSerializable]
public sealed partial class CharacterWeightRequirement : CharacterRequirement
{
/// <summary>
/// Minimum weight of the profile in kilograms
/// </summary>
[DataField]
public float Min = int.MinValue;
/// <summary>
/// Maximum weight of the profile in kilograms
/// </summary>
[DataField]
public float Max = int.MaxValue;
public override bool IsValid(
JobPrototype job,
HumanoidCharacterProfile profile,
Dictionary<string, TimeSpan> playTimes,
bool whitelisted,
IPrototype prototype,
IEntityManager entityManager,
IPrototypeManager prototypeManager,
IConfigurationManager configManager,
out string? reason,
int depth = 0,
MindComponent? mind = null
)
{
const string color = "green";
var species = prototypeManager.Index<SpeciesPrototype>(profile.Species);
prototypeManager.Index(species.Prototype).TryGetComponent<FixturesComponent>(out var fixture);
if (fixture == null)
{
reason = null;
return false;
}
var weight = MathF.Round(
MathF.PI * MathF.Pow(
fixture.Fixtures["fix1"].Shape.Radius
* ((profile.Width + profile.Height) / 2),
2)
* fixture.Fixtures["fix1"].Density);
reason = Loc.GetString(
"character-weight-requirement",
("inverted", Inverted),
("color", color),
("min", Min),
("max", Max));
return weight >= Min && weight <= Max;
}
}
/// <summary>
/// Requires the profile to have one of the specified traits
/// </summary>
[UsedImplicitly, Serializable, NetSerializable]
public sealed partial class CharacterTraitRequirement : CharacterRequirement
{
[DataField(required: true)]
public List<ProtoId<TraitPrototype>> Traits;
public override bool IsValid(
JobPrototype job,
HumanoidCharacterProfile profile,
Dictionary<string, TimeSpan> playTimes,
bool whitelisted,
IPrototype prototype,
IEntityManager entityManager,
IPrototypeManager prototypeManager,
IConfigurationManager configManager,
out string? reason,
int depth = 0,
MindComponent? mind = null
)
{
const string color = "lightblue";
reason = Loc.GetString(
"character-trait-requirement",
("inverted", Inverted),
("traits", $"[color={color}]{string.Join($"[/color], [color={color}]",
Traits.Select(t => Loc.GetString($"trait-name-{t}")))}[/color]"));
return Traits.Any(t => profile.TraitPreferences.Contains(t.ToString()));
}
}
/// <summary>
/// Requires the profile to have one of the specified loadouts
/// </summary>
[UsedImplicitly, Serializable, NetSerializable]
public sealed partial class CharacterLoadoutRequirement : CharacterRequirement
{
[DataField(required: true)]
public List<ProtoId<LoadoutPrototype>> Loadouts;
public override bool IsValid(
JobPrototype job,
HumanoidCharacterProfile profile,
Dictionary<string, TimeSpan> playTimes,
bool whitelisted,
IPrototype prototype,
IEntityManager entityManager,
IPrototypeManager prototypeManager,
IConfigurationManager configManager,
out string? reason,
int depth = 0,
MindComponent? mind = null
)
{
const string color = "lightblue";
reason = Loc.GetString(
"character-loadout-requirement",
("inverted", Inverted),
("loadouts", $"[color={color}]{string.Join($"[/color], [color={color}]",
Loadouts.Select(l => Loc.GetString($"loadout-name-{l}")))}[/color]"));
return Loadouts.Any(l => profile.LoadoutPreferences.Select(l => l.LoadoutName).Contains(l.ToString()));
}
}
/// <summary>
/// Requires the profile to not have any more than X of the specified traits, loadouts, etc, in a group
/// </summary>
[UsedImplicitly, Serializable, NetSerializable]
public sealed partial class CharacterItemGroupRequirement : CharacterRequirement
{
[DataField(required: true)]
public ProtoId<CharacterItemGroupPrototype> Group;
public override bool IsValid(
JobPrototype job,
HumanoidCharacterProfile profile,
Dictionary<string, TimeSpan> playTimes,
bool whitelisted,
IPrototype prototype,
IEntityManager entityManager,
IPrototypeManager prototypeManager,
IConfigurationManager configManager,
out string? reason,
int depth = 0,
MindComponent? mind = null
)
{
var group = prototypeManager.Index(Group);
// Get the count of items in the group that are in the profile
var items = group.Items.Select(item => item.TryGetValue(profile, prototypeManager, out _) ? item.ID : null)
.Where(id => id != null)
.ToList();
var count = items.Count;
// If prototype is selected, decrease the count. Or increase it via negative number. Not my monkey, not my circus.
if (items.ToList().Contains(prototype.ID))
{
// This disgusting ELIF nest requires an engine PR to make less terrible.
if (prototypeManager.TryIndex<LoadoutPrototype>(prototype.ID, out var loadoutPrototype))
count -= loadoutPrototype.Slots;
else if (prototypeManager.TryIndex<TraitPrototype>(prototype.ID, out var traitPrototype))
count -= traitPrototype.ItemGroupSlots;
else count--;
}
reason = Loc.GetString(
"character-item-group-requirement",
("inverted", Inverted),
("group", Loc.GetString($"character-item-group-{Group}")),
("max", group.MaxItems));
return !Inverted ? count < group.MaxItems : count >= group.MaxItems - 1;
}
}
| 0 | 0.794586 | 1 | 0.794586 | game-dev | MEDIA | 0.688437 | game-dev | 0.629643 | 1 | 0.629643 |
ReikaKalseki/ChromatiCraft | 30,074 | TileEntity/Acquisition/TileEntityMiner.java | /*******************************************************************************
* @author Reika Kalseki
*
* Copyright 2017
*
* All rights reserved.
* Distribution of the software in any form is only allowed with
* explicit, prior permission from the owner.
******************************************************************************/
package Reika.ChromatiCraft.TileEntity.Acquisition;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.particle.EntityFX;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.MathHelper;
import net.minecraft.world.ChunkCoordIntPair;
import net.minecraft.world.World;
import Reika.ChromatiCraft.ChromatiCraft;
import Reika.ChromatiCraft.API.Interfaces.MinerBlock;
import Reika.ChromatiCraft.Auxiliary.Interfaces.OwnedTile;
import Reika.ChromatiCraft.Base.TileEntity.ChargedCrystalPowered;
import Reika.ChromatiCraft.Base.TileEntity.TileEntityAdjacencyUpgrade;
import Reika.ChromatiCraft.Base.TileEntity.TileEntityAdjacencyUpgrade.AdjacencyCheckHandlerImpl;
import Reika.ChromatiCraft.Block.Worldgen.BlockTieredOre;
import Reika.ChromatiCraft.Magic.ElementTagCompound;
import Reika.ChromatiCraft.Registry.ChromaItems;
import Reika.ChromatiCraft.Registry.ChromaPackets;
import Reika.ChromatiCraft.Registry.ChromaSounds;
import Reika.ChromatiCraft.Registry.ChromaTiles;
import Reika.ChromatiCraft.Registry.CrystalElement;
import Reika.ChromatiCraft.Render.Particle.EntityCCBlurFX;
import Reika.ChromatiCraft.Render.Particle.EntityCenterBlurFX;
import Reika.ChromatiCraft.TileEntity.AOE.Effect.TileEntityRangeBoost;
import Reika.DragonAPI.APIPacketHandler.PacketIDs;
import Reika.DragonAPI.DragonAPIInit;
import Reika.DragonAPI.ModList;
import Reika.DragonAPI.Auxiliary.ChunkManager;
import Reika.DragonAPI.Base.BlockTieredResource;
import Reika.DragonAPI.Instantiable.StepTimer;
import Reika.DragonAPI.Instantiable.Data.Immutable.BlockKey;
import Reika.DragonAPI.Instantiable.Data.Immutable.Coordinate;
import Reika.DragonAPI.Instantiable.Data.Maps.ItemHashMap;
import Reika.DragonAPI.Instantiable.Effects.EntityBlurFX;
import Reika.DragonAPI.Instantiable.IO.CustomRecipeList;
import Reika.DragonAPI.Interfaces.Block.SemiUnbreakable;
import Reika.DragonAPI.Interfaces.Block.SpecialOreBlock;
import Reika.DragonAPI.Interfaces.Registry.OreType;
import Reika.DragonAPI.Interfaces.TileEntity.ChunkLoadingTile;
import Reika.DragonAPI.Libraries.ReikaInventoryHelper;
import Reika.DragonAPI.Libraries.ReikaNBTHelper.NBTTypes;
import Reika.DragonAPI.Libraries.IO.ReikaPacketHelper;
import Reika.DragonAPI.Libraries.IO.ReikaSoundHelper;
import Reika.DragonAPI.Libraries.Java.ReikaJavaLibrary;
import Reika.DragonAPI.Libraries.Java.ReikaRandomHelper;
import Reika.DragonAPI.Libraries.Registry.ReikaItemHelper;
import Reika.DragonAPI.Libraries.Registry.ReikaOreHelper;
import Reika.DragonAPI.Libraries.World.ReikaBlockHelper;
import Reika.DragonAPI.Libraries.World.ReikaWorldHelper;
import Reika.DragonAPI.ModInteract.ItemHandlers.ForestryHandler;
import Reika.DragonAPI.ModInteract.ItemHandlers.HexcraftHandler;
import Reika.DragonAPI.ModRegistry.ModOreList;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class TileEntityMiner extends ChargedCrystalPowered implements OwnedTile, ChunkLoadingTile {
public static final int MAXRANGE = 128;
private boolean digging = false;
private boolean digReady = false;
private boolean finishedDigging = false;
private int range = MAXRANGE;
private int readX = 0;
private int readY = 0;
private int readZ = 0;
private double particleX;
private double particleY;
private double particleVX;
private double particleVY;
public int progress;
private boolean dropFlag = false;
private long lastWarning;
private boolean preparedScanning;
private static final int TICKSTEP = 2048;
private int index;
private StepTimer miningTimer = new StepTimer(5);
private static final ElementTagCompound required = new ElementTagCompound();
private static final HashMap<BlockKey, MineralCategory> customMappings = new HashMap();
public static final AdjacencyCheckHandlerImpl speed = TileEntityAdjacencyUpgrade.getOrCreateAdjacencyCheckHandler(CrystalElement.LIGHTBLUE, null);
private static final AdjacencyCheckHandlerImpl fortuneSilk = TileEntityAdjacencyUpgrade.getOrCreateAdjacencyCheckHandler(CrystalElement.PURPLE, "Add fortune/silk touch", ChromaTiles.MINER);
private static final AdjacencyCheckHandlerImpl adjRange = TileEntityAdjacencyUpgrade.getOrCreateAdjacencyCheckHandler(CrystalElement.LIME, TileEntityRangeBoost.basicRangeUpgradeable.getDescription(), ChromaTiles.MINER);
private final EnumMap<MineralCategory, ArrayList<Coordinate>> coords = new EnumMap(MineralCategory.class);
private final ItemHashMap<ItemDisplay> found = new ItemHashMap(); //pre-unified for display
private MineralCategory selectedCategory = null;
private boolean silkTouch;
private int fortuneLevel;
static {
required.addTag(CrystalElement.YELLOW, 50);
required.addTag(CrystalElement.LIME, 30);
required.addTag(CrystalElement.GRAY, 20);
required.addTag(CrystalElement.BROWN, 40);
}
@Override
public ElementTagCompound getRequiredEnergy() {
return required.copy();
}
@Override
public ChromaTiles getTile() {
return ChromaTiles.MINER;
}
public int getReadX() {
return readX;
}
public int getReadY() {
return readY;
}
public int getReadZ() {
return readZ;
}
public int getRange() {
return range;
}
@Override
public void onFirstTick(World world, int x, int y, int z) {
super.onFirstTick(world, x, y, z);
this.updateRange();
this.calcSilkTouchAndFortune();
digging = digReady = dropFlag = false;
readY = 0;
}
@Override
public void updateEntity(World world, int x, int y, int z, int meta) {
if (!world.isRemote) {
if (dropFlag) {
if (this.getTicksExisted()%20 == 0) {
this.doDropWarning(world, x, y, z);
}
}
else {
if (digging && !coords.isEmpty()) {
this.calcSilkTouchAndFortune();
if (selectedCategory != null) {
//this.prepareChunkloading();
miningTimer.update();
if (miningTimer.checkCap()) {
if (this.hasEnergy(required)) {
ArrayList<Coordinate> li = coords.get(selectedCategory);
Coordinate c = index >= 0 && index < li.size() ? li.get(index) : null;
if (c != null) {
int dx = c.xCoord;
int dy = c.yCoord;
int dz = c.zCoord;
Block id = this.parseBlock(world.getBlock(dx, dy, dz));
int meta2 = world.getBlockMetadata(dx, dy, dz);
//ReikaJavaLibrary.pConsole(readX+":"+dx+", "+dy+", "+readZ+":"+dz+" > "+ores.getSize(), Side.SERVER);
this.removeFound(world, dx, dy, dz, id, meta2, selectedCategory);
if (id instanceof SpecialOreBlock) {
this.dropSpecialOreBlock(world, x, y, z, dx, dy, dz, (SpecialOreBlock)id, meta2);
}
else if (this.isTieredResource(world, dx, dy, dz, id, meta2)) {
this.dropTieredResource(world, x, y, z, dx, dy, dz, id, meta2);
}
else if (id instanceof MinerBlock) {
this.dropMineableBlock(world, x, y, z, dx, dy, dz, id, meta2);
}
else {
this.dropBlock(world, x, y, z, dx, dy, dz, id, meta2);
}
this.useEnergy(required.copy().scale(this.getEnergyCostScale()));
//ReikaJavaLibrary.pConsole("Mining "+id+":"+meta2+" @ "+dx+","+dy+","+dz+"; index="+index);
}
index++;
if (index >= li.size()) {
this.finishDigging();
}
}
}
}
}
else if (!digReady && !finishedDigging) {
this.prepareScanning();
for (int i = 0; i < TICKSTEP; i++) {
int dx = x+readX;
int dy = readY;
int dz = z+readZ;
ReikaWorldHelper.forceGenAndPopulate(world, dx, dz);
Block id = this.parseBlock(world.getBlock(dx, dy, dz));
int meta2 = world.getBlockMetadata(dx, dy, dz);
//ReikaJavaLibrary.pConsole(readX+":"+dx+", "+dy+", "+readZ+":"+dz+" > "+ores.getSize(), Side.SERVER);
MineralCategory mc = this.getMiningCategory(world, dx, dy, dz, id, meta2);
if (mc != null && coords.containsKey(mc)) {
Coordinate c = new Coordinate(dx, dy, dz);
if (coords.get(mc).add(c)) {
coords.get(MineralCategory.ANY).add(c);
this.addFound(world, dx, dy, dz, id, meta2, mc);
}
}
this.updateReadPosition();
if (readY >= worldObj.getActualHeight()) {
this.prepareDigging();
}
}
}
progress = readY;
}
}
if (world.isRemote && this.isTickingNaturally())
this.spawnParticles(world, x, y, z);
}
private void prepareScanning() {
if (!preparedScanning) {
preparedScanning = true;
ChunkManager.instance.loadChunks(this);
for (MineralCategory mc : MineralCategory.list) {
coords.put(mc, new ArrayList());
}
}
}
private void prepareDigging() {
digReady = true;
readX = 0;
readY = 0;
readZ = 0;
index = 0;
ChunkManager.instance.unloadChunks(this);
}
private void finishDigging() {
digging = false;
finishedDigging = true;
index = 0;
if (selectedCategory == MineralCategory.ANY || this.hasDepletedAllBlocks()) {
digReady = false;
coords.clear();
found.clear();
}
ChromaSounds.CRAFTDONE.playSoundAtBlock(this);
selectedCategory = null;
//ReikaJavaLibrary.pConsole(found);
this.syncAllData(true);
this.scheduleBlockUpdate(5);
//ChunkManager.instance.unloadChunks(this);
}
private boolean hasDepletedAllBlocks() {
for (ArrayList<Coordinate> li : coords.values()) {
if (!li.isEmpty())
return false;
}
return true;
}
private Block parseBlock(Block b) {
if (b == Blocks.lit_redstone_ore)
return Blocks.redstone_ore;
return b;
}
/*
private boolean shouldMine(Block id, int meta2) {
if (id == Blocks.glowstone)
return true;
if (id == Blocks.mob_spawner) //need an item
;//return true;
return false;
}
*/
private MineralCategory getMiningCategory(World world, int x, int y, int z, Block b, int meta) {
if (b == Blocks.air || b == Blocks.stone || b == Blocks.netherrack || b == Blocks.end_stone || b == Blocks.dirt || b == Blocks.grass)
return null;
if (b == Blocks.glowstone)
return MineralCategory.MISC_UNDERGROUND_VALUABLE;
//if (b == Blocks.mob_spawner) //need an item
// ;//return true;
if (Item.getItemFromBlock(b) == null)
return null;
if (b instanceof SemiUnbreakable && ((SemiUnbreakable)b).isUnbreakable(world, x, y, z, meta))
return null;
OreType ore = ReikaOreHelper.getEntryByOreDict(new ItemStack(b, meta));
if (ore != null) {
switch(ore.getRarity()) {
case EVERYWHERE:
case COMMON:
return MineralCategory.UBIQUITOUS_ORE;
case AVERAGE:
return MineralCategory.COMMON_ORE;
case SCATTERED:
return MineralCategory.UNCOMMON_ORE;
case SCARCE:
case RARE:
return MineralCategory.RARE_ORE;
}
}
ore = ModOreList.getModOreFromOre(b, meta);
if (ore != null) {
switch(ore.getRarity()) {
case EVERYWHERE:
case COMMON:
return MineralCategory.UBIQUITOUS_ORE;
case AVERAGE:
return MineralCategory.COMMON_ORE;
case SCATTERED:
return MineralCategory.UNCOMMON_ORE;
case SCARCE:
case RARE:
return MineralCategory.RARE_ORE;
}
}
if (this.isTieredResource(world, x, y, z, b, meta)) {
return b instanceof BlockTieredOre ? MineralCategory.UNCOMMON_ORE : MineralCategory.MISC_UNDERGROUND_VALUABLE;
}
else if (b instanceof MinerBlock && ((MinerBlock)b).isMineable(meta)) {
return MineralCategory.from(((MinerBlock)b).getCategory());
}
else if (b == ForestryHandler.BlockEntry.HIVE.getBlock() || b == GameRegistry.findBlock(ModList.MAGICBEES.modLabel, "hive") || b == GameRegistry.findBlock("ExtraBees", "hive")) {
return MineralCategory.MISC_UNDERGROUND_VALUABLE;
}
else if (ModList.HEXCRAFT.isLoaded() && HexcraftHandler.getActiveHandler().isWorldGenMonolith(b)) {
return MineralCategory.MISC_UNDERGROUND_VALUABLE;
}
MineralCategory cat = customMappings.get(new BlockKey(b, meta));
return cat;
}
public float getDigCompletion() {
return this.isReady() ? 1 : (float)progress/worldObj.getActualHeight();
}
public boolean isReady() {
return digReady && selectedCategory != null;
}
private void removeFound(World world, int x, int y, int z, Block b, int meta, MineralCategory mc) {
if (Item.getItemFromBlock(b) == null)
return;
ItemStack is = new ItemStack(b, 1, meta);
if (b instanceof SpecialOreBlock) {
is = ((SpecialOreBlock)b).getDisplayItem(world, x, y, z);
}
else if (ReikaBlockHelper.isOre(b, meta)) {
ReikaOreHelper ore = ReikaOreHelper.getEntryByOreDict(is);
ModOreList mod = ModOreList.getModOreFromOre(is);
if (ore != null) {
is = ore.getOreBlock();
}
else if (mod != null && mod != ModOreList.CERTUSQUARTZ) {
is = mod.getFirstOreBlock();
}
}
ItemDisplay i = found.get(is);
if (i != null) {
if (i.amount > 1)
i.amount--;
else
found.remove(is);
}
//ReikaJavaLibrary.pConsole("Removed "+b+":"+meta+" from cache, now have "+found.get(is));
}
private void addFound(World world, int x, int y, int z, Block b, int meta, MineralCategory mc) {
if (b != null && Item.getItemFromBlock(b) == null) {
ChromatiCraft.logger.logError("Block "+b+" has no item to drop when mined???");
return;
}
ItemStack is = new ItemStack(b, 1, meta);
if (b instanceof SpecialOreBlock) {
is = ((SpecialOreBlock)b).getDisplayItem(world, x, y, z);
}
else if (ReikaBlockHelper.isOre(b, meta)) {
ReikaOreHelper ore = ReikaOreHelper.getEntryByOreDict(is);
ModOreList mod = ModOreList.getModOreFromOre(is);
if (ore != null) {
is = ore.getOreBlock();
}
else if (mod != null && mod != ModOreList.CERTUSQUARTZ) {
is = mod.getFirstOreBlock();
}
}
ItemDisplay i = found.get(is);
if (i == null) {
i = new ItemDisplay(mc, is);
found.put(is, i);
}
i.amount++;
//ReikaJavaLibrary.pConsole("Found "+b+":"+meta+" @ "+x+","+y+","+z+"; have "+(i+1));
}
public Collection<ItemDisplay> getFound() {
return Collections.unmodifiableCollection(found.values());
}
public EnumMap<MineralCategory, ArrayList<ItemDisplay>> getFoundByCategory() {
EnumMap<MineralCategory, ArrayList<ItemDisplay>> map = new EnumMap(MineralCategory.class);
for (ItemDisplay i : found.values()) {
ArrayList<ItemDisplay> li = map.get(i.category);
if (li == null) {
li = new ArrayList();
map.put(i.category, li);
}
li.add(i);
}
for (ArrayList li : map.values())
Collections.sort(li);
return map;
}
public ItemDisplay getNumberFound(ItemStack is) {
return found.get(is);
}
private boolean isTieredResource(World world, int x, int y, int z, Block id, int meta) {
EntityPlayer ep = this.getPlacer();
return ep != null && id instanceof BlockTieredResource && ((BlockTieredResource)id).isPlayerSufficientTier(world, x, y, z, ep);
}
@SideOnly(Side.CLIENT)
private void spawnParticles(World world, int x, int y, int z) {
double px = x+particleX;
double py = y+particleY;
double pz = z;
int color = CrystalElement.getBlendedColor(this.getTicksExisted(), 40);
EntityBlurFX fx = new EntityCCBlurFX(world, px, py, pz).setScale(0.5F).setLife(40).setColor(color);
Minecraft.getMinecraft().effectRenderer.addEffect(fx);
px = x+1-particleX;
py = y+1-particleY;
fx = new EntityCCBlurFX(world, px, py, pz).setScale(0.5F).setLife(40).setColor(color);
Minecraft.getMinecraft().effectRenderer.addEffect(fx);
pz = z+1;
px = x+1-particleX;
py = y+particleY;
fx = new EntityCCBlurFX(world, px, py, pz).setScale(0.5F).setLife(40).setColor(color);
Minecraft.getMinecraft().effectRenderer.addEffect(fx);
px = x+particleX;
py = y+1-particleY;
fx = new EntityCCBlurFX(world, px, py, pz).setScale(0.5F).setLife(40).setColor(color);
Minecraft.getMinecraft().effectRenderer.addEffect(fx);
px = x;
pz = z+particleX;
py = y+particleY;
fx = new EntityCCBlurFX(world, px, py, pz).setScale(0.5F).setLife(40).setColor(color);
Minecraft.getMinecraft().effectRenderer.addEffect(fx);
pz = z+1-particleX;
py = y+1-particleY;
fx = new EntityCCBlurFX(world, px, py, pz).setScale(0.5F).setLife(40).setColor(color);
Minecraft.getMinecraft().effectRenderer.addEffect(fx);
px = x+1;
pz = z+1-particleX;
py = y+particleY;
fx = new EntityCCBlurFX(world, px, py, pz).setScale(0.5F).setLife(40).setColor(color);
Minecraft.getMinecraft().effectRenderer.addEffect(fx);
pz = z+particleX;
py = y+1-particleY;
fx = new EntityCCBlurFX(world, px, py, pz).setScale(0.5F).setLife(40).setColor(color);
Minecraft.getMinecraft().effectRenderer.addEffect(fx);
double d = 0.05;
particleX += particleVX;
particleY += particleVY;
particleX = MathHelper.clamp_double(particleX, 0, 1);
particleY = MathHelper.clamp_double(particleY, 0, 1);
if (particleX == 1 && particleY == 0) {
particleVX = 0;
particleVY = d;
}
if (particleY == 1 && particleY == 1) {
particleVX = -d;
particleVY = 0;
}
if (particleX == 0 && particleY == 1) {
particleVX = 0;
particleVY = -d;
}
if (particleX == 0 && particleY == 0) {
particleVX = d;
particleVY = 0;
}
}
private void dropSpecialOreBlock(World world, int x, int y, int z, int dx, int dy, int dz, SpecialOreBlock id, int meta2) {
if (silkTouch) {
this.dropItems(world, x, y, z, ReikaJavaLibrary.makeListFrom(id.getSilkTouchVersion(world, dx, dy, dz)));
}
else {
this.dropItems(world, x, y, z, id.getDrops(world, dx, dy, dz, fortuneLevel));
}
id.getReplacementBlock(world, dx, dy, dz).place(world, dx, dy, dz);
}
private void dropBlock(World world, int x, int y, int z, int dx, int dy, int dz, Block id, int meta2) {
if (silkTouch) {
this.dropItems(world, x, y, z, ReikaJavaLibrary.makeListFrom(new ItemStack(id, 1, meta2)));
}
else {
this.dropItems(world, x, y, z, id.getDrops(world, dx, dy, dz, meta2, fortuneLevel));
}
this.getFillerBlock(world, dx, dy, dz, id, meta2).place(world, dx, dy, dz);
ReikaSoundHelper.playBreakSound(world, dx, dy, dz, id);
ReikaPacketHelper.sendDataPacketWithRadius(DragonAPIInit.packetChannel, PacketIDs.BREAKPARTICLES.ordinal(), world, dx, dy, dz, 128, Block.getIdFromBlock(id), meta2);
}
private void dropTieredResource(World world, int x, int y, int z, int dx,int dy, int dz, Block id, int meta2) {
Collection<ItemStack> li = ((BlockTieredResource)id).getHarvestResources(world, dx, dy, dz, 10, this.getPlacer());
this.dropItems(world, x, y, z, li);
this.getFillerBlock(world, dx, dy, dz, id, meta2).place(world, dx, dy, dz);
ReikaSoundHelper.playBreakSound(world, dx, dy, dz, id);
ReikaPacketHelper.sendDataPacketWithRadius(DragonAPIInit.packetChannel, PacketIDs.BREAKPARTICLES.ordinal(), world, dx, dy, dz, 128, Block.getIdFromBlock(id), meta2);
}
private void dropMineableBlock(World world, int x, int y, int z, int dx, int dy, int dz, Block id, int meta2) {
if (silkTouch && ((MinerBlock)id).allowSilkTouch(meta2)) {
this.dropItems(world, x, y, z, ReikaJavaLibrary.makeListFrom(new ItemStack(id, 1, meta2)));
}
else {
this.dropItems(world, x, y, z, ((MinerBlock)id).getHarvestItems(world, dx, dy, dz, meta2, fortuneLevel));
}
this.getFillerBlock(world, dx, dy, dz, id, meta2).place(world, dx, dy, dz);
ReikaSoundHelper.playBreakSound(world, dx, dy, dz, id);
ReikaPacketHelper.sendDataPacketWithRadius(DragonAPIInit.packetChannel, PacketIDs.BREAKPARTICLES.ordinal(), world, dx, dy, dz, 128, Block.getIdFromBlock(id), meta2);
}
private BlockKey getFillerBlock(World world, int dx, int dy, int dz, Block id, int meta2) {
if (id instanceof MinerBlock)
return new BlockKey(((MinerBlock)id).getReplacedBlock(world, dx, dy, dz));
if (!id.getMaterial().isSolid())
return new BlockKey(Blocks.air);
if (id == Blocks.glowstone)
return new BlockKey(Blocks.air);
if (id == Blocks.mob_spawner)
return new BlockKey(Blocks.air);
if (world.provider.dimensionId == -1)
return new BlockKey(Blocks.netherrack);
if (world.provider.dimensionId == 1)
return new BlockKey(Blocks.end_stone);
return new BlockKey(Blocks.stone);
}
public boolean hasCrystal() {
return ChromaItems.STORAGE.matchWith(inv[0]);
}
private void calcSilkTouchAndFortune() {
int lvl = fortuneSilk.getAdjacentUpgrade(this);
silkTouch = lvl > 5;
fortuneLevel = lvl+1;
}
@Override
public void onAdjacentUpdate(World world, int x, int y, int z, Block b) {
this.calcSilkTouchAndFortune();
this.updateRange();
super.onAdjacentUpdate(world, x, y, z, b);
}
private void dropItems(World world, int x, int y, int z, Collection<ItemStack> li) {
for (ItemStack is : li) {
if (is == null || is.getItem() == null) {
BlockKey bk = BlockKey.getAt(world, x, y, z);
ChromatiCraft.logger.logError("Block "+bk+" @ "+x+", "+y+", "+z+" dropped a stack of null! This is a bug on their end!");
continue;
}
boolean flag = true;
for (int i = 0; i < 6 && flag; i++) {
TileEntity te = this.getAdjacentTileEntity(dirs[i]);
if (te instanceof IInventory) {
if (ReikaInventoryHelper.addToIInv(is, (IInventory)te))
flag = false;
}
}
if (flag) {
ReikaItemHelper.dropItem(world, x+0.5, y+1.5, z+0.5, is);
dropFlag = true;
this.doDropWarning(world, x, y, z);
}
}
}
private void doDropWarning(World world, int x, int y, int z) {
if (lastWarning != world.getTotalWorldTime()) {
ChromaSounds.ERROR.playSoundAtBlock(this);
ReikaPacketHelper.sendDataPacketWithRadius(ChromatiCraft.packetChannel, ChromaPackets.MINERJAM.ordinal(), this, 32);
}
lastWarning = world.getTotalWorldTime();
}
@SideOnly(Side.CLIENT)
public void doWarningParticles(World world, int x, int y, int z) {
int n = 2+rand.nextInt(6);
for (int i = 0; i < n; i++) {
double rx = x+rand.nextDouble();
double ry = y+rand.nextDouble();
double rz = z+rand.nextDouble();
int l = 10+rand.nextInt(20);
float g = -(float)ReikaRandomHelper.getRandomPlusMinus(0.0625, 0.03125);
EntityFX fx = new EntityCenterBlurFX(world, rx, ry, rz).setGravity(g).setLife(l);
Minecraft.getMinecraft().effectRenderer.addEffect(fx);
}
}
private void updateReadPosition() {
boolean flag1 = false;
boolean flag2 = false;
readX++;
if (readX > range) {
readX = -range;
flag1 = true;
}
if (flag1) {
readZ++;
//ReikaJavaLibrary.pConsole(readY+" > "+readZ+":"+range+" > "+ores.getSize(), Side.SERVER);
if (readZ > range) {
readZ = -range;
flag2 = true;
}
if (flag2) {
readY++;
}
}
}
public boolean triggerDigging() {
if (this.isReady()) {
digging = true;
dropFlag = false;
ChromaSounds.USE.playSoundAtBlock(this);
return true;
}
ChromaSounds.ERROR.playSoundAtBlock(this);
return false;
}
public void setCategory(int idx) {
selectedCategory = MineralCategory.list[idx];
this.syncAllData(false);
}
@Override
protected void animateWithTick(World world, int x, int y, int z) {
}
@Override
public void readFromNBT(NBTTagCompound NBT) {
super.readFromNBT(NBT);
//NBTTagList li = NBT.getTagList("coords", NBTTypes.COMPOUND.ID);
//for (Object o : li.tagList) {
// NBTTagCompound tag = (NBTTagCompound)o;
// Coordinate c = Coordinate.readTag(tag);
// coords.add(c);
//}
readX = NBT.getInteger("rx");
readY = NBT.getInteger("ry");
readZ = NBT.getInteger("rz");
}
@Override
public void writeToNBT(NBTTagCompound NBT) {
super.writeToNBT(NBT);
//NBTTagList li = new NBTTagList();
//for (Coordinate c : coords) {
// NBTTagCompound tag = c.writeToTag();
// li.appendTag(tag);
//}
//NBT.setTag("coords", li);
NBT.setInteger("rx", readX);
NBT.setInteger("ry", readY);
NBT.setInteger("rz", readZ);
}
@Override
protected void readSyncTag(NBTTagCompound NBT) {
super.readSyncTag(NBT);
digging = NBT.getBoolean("dig");
digReady = NBT.getBoolean("dig2");
finishedDigging = NBT.getBoolean("finish");
index = NBT.getInteger("index");
dropFlag = NBT.getBoolean("dropped");
silkTouch = NBT.getBoolean("silk");
fortuneLevel = NBT.getInteger("fortune");
found.clear();
NBTTagList li = NBT.getTagList("count", NBTTypes.COMPOUND.ID);
for (Object o : li.tagList) {
NBTTagCompound tag = (NBTTagCompound)o;
ItemDisplay is = ItemDisplay.readFromNBT(tag);
found.put(is.item, is);
}
int mode = NBT.getInteger("mode");
selectedCategory = mode >= 0 ? MineralCategory.list[mode] : null;
}
@Override
protected void writeSyncTag(NBTTagCompound NBT) {
super.writeSyncTag(NBT);
NBT.setBoolean("dig", digging);
NBT.setBoolean("dig2", digReady);
NBT.setInteger("index", index);
NBT.setBoolean("finish", finishedDigging);
NBT.setBoolean("silk", silkTouch);
NBT.setInteger("fortune", fortuneLevel);
NBTTagList li = new NBTTagList();
for (ItemDisplay is : found.values()) {
NBTTagCompound tag = new NBTTagCompound();
is.writeToNBT(tag);
li.appendTag(tag);
}
NBT.setTag("count", li);
NBT.setBoolean("dropped", dropFlag);
NBT.setInteger("mode", selectedCategory != null ? selectedCategory.ordinal() : -1);
}
@Override
public int getSizeInventory() {
return 1;
}
@Override
public int getInventoryStackLimit() {
return 1;
}
@Override
protected boolean canExtractOtherItem(int slot, ItemStack is, int side) {
return false;
}
@Override
protected boolean isItemValidForOtherSlot(int slot, ItemStack is) {
return false;
}
@Override
public void breakBlock() {
ChunkManager.instance.unloadChunks(this);
}
@Override
public Collection<ChunkCoordIntPair> getChunksToLoad() {
return ChunkManager.getChunkSquare(xCoord, zCoord, range >> 4);
}
@Override
public float getCostModifier() {
float f = 1;
if (silkTouch) {
f *= 8;
}
f *= 1+fortuneLevel/4F;
return f;
}
@Override
public boolean usesColor(CrystalElement e) {
return required.contains(e);
}
private void updateRange() {
int oldrange = range;
double r = 1;
int val = adjRange.getAdjacentUpgrade(this);
if (val > 0)
r = TileEntityRangeBoost.getFactor(val-1);
range = (int)(MAXRANGE*r);
if (range != oldrange && !digging) {
readX = 0;
readY = 0;
readZ = 0;
digReady = false;
found.clear();
coords.clear();
}
}
public boolean hasSilkTouch() {
return silkTouch;
}
public int getFortune() {
return fortuneLevel;
}
public MineralCategory getCategory() {
return selectedCategory;
}
public int getTotalFound(MineralCategory mc) {
return coords.isEmpty() ? 0 : coords.get(mc).size();
}
@Override
public void getTagsToWriteToStack(NBTTagCompound NBT) {
this.writeOwnerData(NBT);
}
@Override
public void setDataFromItemStackTag(ItemStack is) {
this.readOwnerData(is);
}
@Override
public void addTooltipInfo(List li, boolean shift) {
}
public static void loadCustomMappings() {
for (String s : ChromatiCraft.config.getMinerBlockExtras()) {
try {
String[] parts = s.split("#");
parts[0] = parts[0].trim();
if (parts[0].equalsIgnoreCase("none"))
continue;
for (ItemStack is : CustomRecipeList.parseItemCollection(Arrays.asList(parts[0]), false)) {
customMappings.put(BlockKey.fromItem(is), MineralCategory.valueOf(parts[1].toUpperCase(Locale.ENGLISH)));
}
}
catch (Exception e) {
ChromatiCraft.logger.logError("Failed to parse custom mineral extractor mapping '"+s+"'");
e.printStackTrace();
}
}
}
public static enum MineralCategory {
UBIQUITOUS_ORE("Ubiquitous Ore"),
COMMON_ORE("Common Ore"),
UNCOMMON_ORE("Uncommon Ore"),
RARE_ORE("Rare Ore"),
MISC_UNDERGROUND("Misc Material"),
MISC_UNDERGROUND_VALUABLE("Misc Valuable"),
ANY("Any");
private static final MineralCategory[] list = values();
public final String displayName;
private MineralCategory(String s) {
displayName = s;
}
public static MineralCategory from(Reika.ChromatiCraft.API.Interfaces.MinerBlock.MineralCategory category) {
return list[category.ordinal()];
}
}
public static class ItemDisplay implements Comparable<ItemDisplay> {
private int amount = 0;
public final MineralCategory category;
private final ItemStack item;
private ItemDisplay(MineralCategory mc, ItemStack is) {
category = mc;
item = is;
}
public int getAmount() {
return amount;
}
public ItemStack getDisplayItem() {
return item.copy();
}
public void writeToNBT(NBTTagCompound tag) {
tag.setInteger("amt", amount);
tag.setInteger("cat", category.ordinal());
item.writeToNBT(tag);
}
public static ItemDisplay readFromNBT(NBTTagCompound tag) {
int amt = tag.getInteger("amt");
int cat = tag.getInteger("cat");
ItemStack is = ItemStack.loadItemStackFromNBT(tag);
ItemDisplay id = new ItemDisplay(MineralCategory.list[cat], is);
id.amount = amt;
return id;
}
@Override
public int compareTo(ItemDisplay o) {
if (o.category != category) {
return category.compareTo(o.category);
}
else {
if (o.item.getItem() != item.getItem()) {
Block b1 = Block.getBlockFromItem(item.getItem());
Block b2 = Block.getBlockFromItem(o.item.getItem());
if (b1 != null && b2 != null) {
if (b1 instanceof BlockTieredResource) {
return Integer.MAX_VALUE;
}
else if (b2 instanceof BlockTieredResource) {
return Integer.MIN_VALUE;
}
}
}
return ReikaItemHelper.comparator.compare(item, o.item);
}
}
}
}
| 0 | 0.945096 | 1 | 0.945096 | game-dev | MEDIA | 0.968684 | game-dev | 0.952268 | 1 | 0.952268 |
goblimos/Molten-Aim-25 | 13,705 | src/addons/fps-hands/fps-hands.gd | @icon("icon.svg")
extends Node3D
signal give_damage(obj:Node3D, damage:float, point:Vector3)
signal update_ammo(magazine:int, inventory_ammo:int, ammo_type:String)
signal firing()
signal reloading()
signal meleeing()
signal taking_weapon()
#region Export vars
@export var inventory : Dictionary = {
"weapons" = [[0,-1],],
"ammo" = {
"none" = 0,
"9mm" = 0,
"rifle" = 0,
"shell" = 0,
},
}
@export var melee_damage : float = 100
@export var left_handed : bool = false
@export var realistic_reloading : bool = false
@export var show_muzzle_smoke : bool = true
@export_flags_3d_physics var collision_mask = 1
@export_group("Camera")
@export var camera : Camera3D
@export var recoil : bool = true
@export_subgroup("Recoil configs")
## What to rotate on X axis with recoil (most of the time the camera)
@export var node_recoil_x : Node3D
## What to rotate on Y axis with recoil (most of the time the character)
@export var node_recoil_y : Node3D
## How many seconds recoil have to be
@export var recoil_time : float = .2
@export var recoil_x_clamp_max : float = 1.4
@export var recoil_x_clamp_min : float = -1.4
@export_subgroup("")
@export var sway : bool = true
@export_subgroup("Sway configs")
@export var sway_look_sens : float = 50.0
@export var sway_move_sens : float = 80.0
@export_subgroup("")
@export var shake : bool = true
@export_subgroup("Shake configs")
@export var shake_strength : float = 0.5
@export var shake_decay : float = 3.0
@export var shake_max_offset := Vector2(.01, .01)
@export var shake_max_roll : float = 0.01
@export_group("Multipliers")
@export var delta_multiplier : float = 1.0
@export var damage_multiplier : float = 1.0
@export_group("Actions")
@export var action_fire : String = "fire"
@export var action_reload : String = "reload"
@export var action_melee : String = "melee"
@export var action_ads : String = "aim"
@export var action_next_weapon : String = "next_weapon"
@export var action_previous_weapon : String = "previous_weapon"
#endregion
# Plugin scene nodes
var FireRayCast : RayCast3D
var MeleeRayCast : RayCast3D
var bulletholeScene : PackedScene = preload("decals/bullethole/bullethole.tscn")
var scratchScene : PackedScene = preload("decals/scratch/scratch.tscn")
var muzzleFlashScene : PackedScene = preload("muzzleflash/MuzzleFlash.tscn")
var muzzleSmokeScene : PackedScene = preload("muzzlesmoke/MuzzleSmoke.tscn")
var bulletScene : PackedScene = preload("res://addons/fps-hands/bullet/bullet.tscn")
var weapons : Array[PackedScene] = [
preload("fps-knife/fps-knife.tscn"),
preload("fps-c19/fps-c19.tscn"),
preload("fps-smg45/fps-smg45.tscn"),
preload("fps-ak/fps-ak.tscn"),
preload("fps-lmg63/fps-lmg63.tscn"),
preload("fps-sawnoff/fps-sawnoff.tscn"),
]
var weapon_index : int # current weapon index
var weapon_change : int # weapon to take after hide weapon
var weapon : Node3D
var animation : AnimationTree
var state_machine : AnimationNodeStateMachinePlayback
var muzzlePoint : Node3D
var start_pos : Vector3
var ads_pos : Vector3
var ads : bool = false
var max_magazine : int
var magazine : int
var sway_rotation_target : Vector3
var recoiling : Vector2 = Vector2.ZERO
var recoil_target : Vector2
var recoil_to_left : bool = false
var shake_current : float = 0.0
# Add nodes and settings to plugin scene
func _enter_tree() -> void:
MeleeRayCast = RayCast3D.new()
MeleeRayCast.target_position = Vector3(0,0,1)
MeleeRayCast.collision_mask = collision_mask
add_child(MeleeRayCast)
FireRayCast = RayCast3D.new()
FireRayCast.target_position = Vector3(0,0,0)
FireRayCast.collision_mask = collision_mask
add_child(FireRayCast)
func _ready() -> void:
if sway and camera:
top_level = true
take_weapon(0)
func update_inventory():
inventory["weapons"][weapon_index][1] = magazine
update_ammo.emit(magazine, inventory["ammo"][weapon.get_meta("ammo_type", "none")], weapon.get_meta("ammo_type", "none"))
func aim(toggle:bool=true) -> void:
if toggle and (state_machine.get_current_node() != "idle" and state_machine.get_current_node() != "fire"):
return
if !ads and toggle:
ads = true
elif ads:
ads = false
func add_decal(pos:Vector3, normal:Vector3, decal:PackedScene, father:Node3D) -> void:
var bullethole : Decal = decal.instantiate()
father.add_child(bullethole)
bullethole.global_position = pos
if normal != Vector3.UP:
bullethole.look_at(pos + Vector3.UP, normal)
bullethole.rotate(normal, randf_range(0, 2*PI))
func melee_attack(raycast:RayCast3D, damage:float) -> void:
var collider = raycast.get_collider()
if collider != null:
damage *= damage_multiplier
if collider is RigidBody3D or collider is CharacterBody3D:
give_damage.emit(collider, damage, raycast.get_collision_point())
if not (collider is CharacterBody3D):
add_decal(raycast.get_collision_point(), raycast.get_collision_normal(), scratchScene, collider)
func _on_bullet_collision(obj:Node3D, damage:float, point:Vector3, collision_normal:Vector3) -> void:
if obj is RigidBody3D or obj is CharacterBody3D:
give_damage.emit(obj, damage*damage_multiplier, point)
if not (obj is CharacterBody3D):
add_decal(point, collision_normal, bulletholeScene, obj)
func fire_bullet(raycast:RayCast3D, damage:float) -> void:
if muzzlePoint:
var bullet_instance : Node3D = bulletScene.instantiate()
bullet_instance.position = muzzlePoint.global_position
bullet_instance.transform.basis = get_parent().global_transform.basis
bullet_instance.damage = weapon.get_meta("damage")
bullet_instance.distance = weapon.get_meta("range")
bullet_instance.collision_mask = collision_mask
bullet_instance.connect("collision", _on_bullet_collision)
if raycast.is_colliding():
bullet_instance.look_at_from_position(muzzlePoint.global_position, raycast.get_collision_point())
get_tree().root.add_child(bullet_instance)
func muzzle_flash():
if muzzlePoint:
var muzzleFlash : Node3D = muzzleFlashScene.instantiate()
muzzleFlash.scale /= weapon.scale
muzzlePoint.add_child(muzzleFlash)
func muzzle_smoke():
if muzzlePoint and show_muzzle_smoke:
var muzzleSmoke : Node3D = muzzleSmokeScene.instantiate()
muzzleSmoke.scale /= weapon.scale
muzzlePoint.add_child(muzzleSmoke)
func add_recoil():
if recoil and weapon.get_meta("recoil_x",0)+weapon.get_meta("recoil_y",0)>0:
recoiling = Vector2(recoil_time, recoil_time)
var recoil_x:float = randf_range(weapon.get_meta("recoil_x",0)*.2, weapon.get_meta("recoil_x",0))
var recoil_y:float = randf_range(-weapon.get_meta("recoil_y",0), weapon.get_meta("recoil_y",0))
recoil_target.x = clampf(node_recoil_x.rotation.x + recoil_x, recoil_x_clamp_min, recoil_x_clamp_max)
recoil_target.y = node_recoil_y.rotation.y + recoil_y
if recoil_y >= 0:
recoil_to_left = true
else:
recoil_to_left = false
func add_camera_shake(amount:float):
if shake and camera and weapon.get_meta("recoil_x",0)+weapon.get_meta("recoil_y",0)>0:
shake_current = min(shake_current+amount, 1.0)
func camera_shake():
if shake and camera:
var amount = pow(shake_current, 2)
camera.rotation.z = shake_max_roll * amount * randf_range(-1, 1)
camera.h_offset = shake_max_offset.x * amount * randf_range(-1, 1)
camera.v_offset = shake_max_offset.y * amount * randf_range(-1, 1)
func take_weapon(inventory_index:int) -> void:
inventory_index = wrapi(inventory_index, 0, inventory["weapons"].size())
var inventory_weapon = inventory["weapons"][inventory_index]
var index = inventory_weapon[0] # Weapon index of weapons array
index = clampi(index, 0, weapons.size()-1)
# Add weapon to scene in there is none
if !weapon or !weapon.is_inside_tree():
weapon = weapons[index].instantiate()
weapon.visible = false # avoid first frame in wrong position
if left_handed:
weapon.position.x = -weapon.position.x
weapon.scale.x = -weapon.scale.x
add_child(weapon)
# If it's the same as the current weapon, do nothing
elif weapon_index == inventory_index:
return
# If there is already a weapon, hide it then change it
else:
weapon_change = inventory_index
state_machine.travel("hide")
return
weapon_index = inventory_index
weapon_change = inventory_index
animation = weapon.get_node("AnimationTree")
state_machine = animation["parameters/playback"]
muzzlePoint = weapon.find_child("MuzzlePoint")
start_pos = weapon.position
ads_pos = weapon.get_meta("ads_pos", start_pos)
max_magazine = weapon.get_meta("max_magazine",0)
magazine = inventory_weapon[1]
if magazine == -1:
magazine = max_magazine
update_inventory()
FireRayCast.target_position.z = weapon.get_meta("range")
animation.connect("animation_finished", _on_animation_tree_animation_finished)
animation.connect("animation_started", _on_animation_tree_animation_started)
func hide_weapon() -> void:
animation.disconnect("animation_finished", _on_animation_tree_animation_finished)
animation.disconnect("animation_started", _on_animation_tree_animation_started)
if weapon_change != weapon_index:
weapon.connect("tree_exited", take_weapon.bind(weapon_change))
weapon.queue_free()
func _input(_event) -> void:
if weapon != null:
# Single fire
if !weapon.get_meta("auto", false):
if Input.is_action_just_pressed(action_fire) and (magazine > 0 or max_magazine == 0):
state_machine.travel("fire")
# Actions
if Input.is_action_just_pressed(action_melee):
state_machine.travel("melee")
if Input.is_action_just_pressed(action_reload) and magazine != max_magazine:
if inventory["ammo"][weapon.get_meta("ammo_type", "none")] > 0:
if magazine > 0 and "reload_full" in animation.get_animation_list():
state_machine.travel("reload_full")
else:
state_machine.travel("reload")
if Input.is_action_just_pressed(action_ads):
aim()
if Input.is_action_just_pressed(action_next_weapon):
take_weapon(weapon_index+1)
if Input.is_action_just_pressed(action_previous_weapon):
take_weapon(weapon_index-1)
func _process(delta) -> void:
if weapon != null:
# ADS animation
if ads and weapon.position != ads_pos:
weapon.position = weapon.position.move_toward(ads_pos, weapon.get_meta("delta",1.5)*delta_multiplier*delta)
if !ads and weapon.position != start_pos:
weapon.position = weapon.position.move_toward(start_pos, weapon.get_meta("delta",1.5)*delta_multiplier*delta)
# Automatic fire
if weapon.get_meta("auto", false):
if Input.is_action_pressed(action_fire) and (magazine > 0 or max_magazine == 0):
state_machine.travel("fire")
func _physics_process(delta) -> void:
# Recoil
if recoiling.x + recoiling.y > 0 and recoil and node_recoil_x and node_recoil_y:
# If player moves camera more than recoil, we don't need it
if node_recoil_x.rotation.x > recoil_target.x:
recoiling.x = 0
elif recoiling.x > 0:
recoiling.x -= delta
node_recoil_x.rotation.x = lerp_angle(node_recoil_x.rotation.x, recoil_target.x, delta*15)
# Y recoil must be faster to avoid interrupting too much camera movement
if recoiling.y > 0 and ((recoil_to_left and node_recoil_y.rotation.y < recoil_target.y) or \
(not recoil_to_left and node_recoil_y.rotation.y > recoil_target.y)):
recoiling.y /= 2
recoiling.y -= delta
node_recoil_y.rotation.y = lerp_angle(node_recoil_y.rotation.y, recoil_target.y, delta*25)
# Sway
if sway and camera:
sway_rotation_target = camera.global_rotation.reflect(Vector3(0,1,0))
sway_rotation_target.y -= PI
rotation.y = lerp_angle(rotation.y, sway_rotation_target.y, delta*sway_look_sens)
rotation.x = lerp_angle(rotation.x, sway_rotation_target.x, delta*sway_look_sens)
rotation.z = lerp_angle(rotation.z, sway_rotation_target.z, delta*sway_look_sens)
position = position.lerp(camera.global_position, delta*sway_move_sens)
# Shake
if shake and camera and shake_current > 0:
shake_current = max(shake_current - shake_decay * delta, 0)
camera_shake()
func _on_animation_tree_animation_finished(anim_name: StringName) -> void:
# Reload magazine
if anim_name == "reload" or anim_name == "reload_full":
if realistic_reloading:
if inventory["ammo"][weapon.get_meta("ammo_type", "none")] >= max_magazine:
inventory["ammo"][weapon.get_meta("ammo_type", "none")] -= max_magazine
magazine = max_magazine
else:
magazine = inventory["ammo"][weapon.get_meta("ammo_type", "none")]
inventory["ammo"][weapon.get_meta("ammo_type", "none")] = 0
else:
if inventory["ammo"][weapon.get_meta("ammo_type", "none")] >= max_magazine-magazine:
inventory["ammo"][weapon.get_meta("ammo_type", "none")] -= max_magazine-magazine
magazine = max_magazine
else:
magazine += inventory["ammo"][weapon.get_meta("ammo_type", "none")]
inventory["ammo"][weapon.get_meta("ammo_type", "none")] = 0
update_inventory()
# Remove weapon
if anim_name == "hide":
hide_weapon()
# Stop recoil
if anim_name == "fire":
recoiling = Vector2.ZERO
func _on_animation_tree_animation_started(anim_name: StringName) -> void:
# Show weapon on animationTree start
if anim_name == "take" and !weapon.visible:
weapon.visible = true
# If any animation other than idle and fire starts, do not aim
if anim_name != "idle" and anim_name != "fire":
aim(false)
if anim_name == "fire":
firing.emit()
if max_magazine != 0:
magazine -= 1
update_inventory()
if weapon.get_meta("melee", false):
melee_attack(FireRayCast, weapon.get_meta("damage"))
else:
fire_bullet(FireRayCast, weapon.get_meta("damage"))
muzzle_flash()
muzzle_smoke()
add_recoil()
add_camera_shake(shake_strength)
if anim_name == "melee":
meleeing.emit()
melee_attack(MeleeRayCast, melee_damage)
if anim_name == "take":
taking_weapon.emit()
if anim_name == "reload" or anim_name == "reload_full":
reloading.emit()
| 0 | 0.953551 | 1 | 0.953551 | game-dev | MEDIA | 0.997469 | game-dev | 0.827275 | 1 | 0.827275 |
amtep/tiger | 68,292 | src/ck3/effect_validation.rs | use crate::block::{Block, BV};
use crate::ck3::data::legends::LegendChronicle;
use crate::ck3::tables::misc::{
BANNED_TITLE_HISTORY_TYPES, LEGEND_QUALITY, OUTBREAK_INTENSITIES, TITLE_HISTORY_TYPES,
};
use crate::ck3::validate::{
validate_random_culture, validate_random_faith, validate_random_traits_list,
};
use crate::context::ScopeContext;
use crate::desc::validate_desc;
use crate::effect::{validate_effect, validate_effect_internal};
use crate::effect_validation::validate_random_list;
use crate::everything::Everything;
use crate::helpers::{stringify_choices, stringify_list, TigerHashSet};
use crate::item::Item;
use crate::lowercase::Lowercase;
use crate::report::{err, warn, ErrorKey, Severity};
use crate::scopes::Scopes;
use crate::script_value::{validate_non_dynamic_script_value, validate_script_value};
use crate::token::Token;
use crate::tooltipped::Tooltipped;
use crate::trigger::{validate_target, validate_target_ok_this};
use crate::validate::{
validate_duration, validate_identifier, validate_mandatory_duration,
validate_optional_duration, validate_optional_duration_int, validate_possibly_named_color,
ListType,
};
use crate::validator::{Validator, ValueValidator};
pub fn validate_add_activity_log_entry(
key: &Token,
block: &Block,
data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
tooltipped: Tooltipped,
) {
let caller = Lowercase::new(key.as_str());
vd.req_field("key");
vd.req_field("character");
if let Some(token) = vd.field_value("key") {
let loca = format!("{token}_title");
data.verify_exists_implied(Item::Localization, &loca, token);
}
vd.field_script_value("score", sc);
vd.field_validated_block("tags", |b, data| {
let mut vd = Validator::new(b, data);
vd.values(); // TODO
});
vd.field_bool("show_in_conclusion");
vd.field_target("character", sc, Scopes::Character);
vd.field_target("target", sc, Scopes::Character);
vd.field_target("location", sc, Scopes::Province);
vd.field_target("artifact", sc, Scopes::Artifact);
// effects can be put directly in this block
validate_effect_internal(&caller, ListType::None, block, data, sc, &mut vd, tooltipped);
}
pub fn validate_add_artifact_history(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("type");
vd.req_field("recipient");
vd.field_item("type", Item::ArtifactHistory);
vd.field_date("date");
vd.field_target("actor", sc, Scopes::Character);
vd.field_target("recipient", sc, Scopes::Character);
vd.field_target("location", sc, Scopes::Province);
}
pub fn validate_add_artifact_title_history(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("target");
vd.req_field("date");
vd.field_target("target", sc, Scopes::LandedTitle);
vd.field_date("date");
}
pub fn validate_add_from_contribution(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.field_script_value("prestige", sc);
vd.field_script_value("gold", sc);
vd.field_script_value("piety", sc);
vd.field_validated_block("opinion", |block, data| {
let mut vd = Validator::new(block, data);
vd.field_item("modifier", Item::OpinionModifier);
});
}
pub fn validate_add_hook(
_key: &Token,
_block: &Block,
data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("type");
vd.req_field("target");
vd.field_item("type", Item::Hook);
vd.field_target("target", sc, Scopes::Character);
if let Some(token) = vd.field_value("secret") {
if !data.item_exists(Item::Secret, token.as_str()) {
validate_target(token, data, sc, Scopes::Secret);
}
}
validate_optional_duration(&mut vd, sc);
}
pub fn validate_add_opinion(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("modifier");
vd.req_field("target");
vd.field_item("modifier", Item::OpinionModifier);
vd.field_target("target", sc, Scopes::Character);
vd.field_script_value("opinion", sc); // undocumented
validate_optional_duration(&mut vd, sc);
}
pub fn validate_add_relation_flag(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("relation");
vd.req_field("flag");
vd.req_field("target");
vd.field_item("relation", Item::Relation);
// TODO: check that the flag belongs to the relation
vd.field_value("flag");
vd.field_target("target", sc, Scopes::Character);
}
pub fn validate_scheme_cooldown(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("target");
vd.req_field("type");
vd.field_target("target", sc, Scopes::Character);
vd.field_item("type", Item::Scheme);
validate_optional_duration_int(&mut vd);
}
pub fn validate_scheme_modifier(
key: &Token,
block: &Block,
data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("type");
if let Some(token) = vd.field_value("type") {
data.verify_exists(Item::Modifier, token);
data.database.validate_call(Item::Modifier, token, block, data, sc);
data.database.validate_property_use(Item::Modifier, token, data, key, key.as_str());
}
validate_optional_duration(&mut vd, sc);
}
pub fn validate_add_secret(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("type");
vd.field_item("type", Item::Secret);
vd.field_target("target", sc, Scopes::Character);
if let Some(name) = vd.field_identifier("save_scope_as", "scope name") {
sc.define_name_token(name.as_str(), Scopes::Secret, name);
}
}
pub fn validate_guest_subset(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("name");
vd.req_field("target");
vd.field_item("name", Item::GuestSubset);
vd.field_target("target", sc, Scopes::Character);
vd.field_item("phase", Item::ActivityPhase);
}
pub fn validate_add_trait_xp(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("trait");
vd.req_field("value");
// TODO: if the trait is an Item, verify that the TraitTrack belongs to this trait
vd.field_item_or_target("trait", sc, Item::Trait, Scopes::Trait);
vd.field_item("track", Item::TraitTrack);
vd.field_script_value("value", sc);
}
/// Used by a variety of `add_..._modifier` effects
pub fn validate_add_modifier(
key: &Token,
bv: &BV,
data: &Everything,
sc: &mut ScopeContext,
_tooltipped: Tooltipped,
) {
let caller = key.as_str().to_ascii_lowercase();
let visible = caller == "add_character_modifier"
|| caller == "add_house_modifier"
|| caller == "add_dynasty_modifier"
|| caller == "add_county_modifier"
|| caller == "add_house_unity_modifier"
|| caller == "add_legend_county_modifier"
|| caller == "add_legend_owner_modifier"
|| caller == "add_legend_province_modifier";
match bv {
BV::Value(token) => {
data.verify_exists(Item::Modifier, token);
if visible {
data.verify_exists(Item::Localization, token);
}
let block = Block::new(key.loc);
data.database.validate_call(Item::Modifier, token, &block, data, sc);
data.database.validate_property_use(Item::Modifier, token, data, key, key.as_str());
}
BV::Block(block) => {
let mut vd = Validator::new(block, data);
vd.set_case_sensitive(false);
vd.req_field("modifier");
if let Some(token) = vd.field_value("modifier") {
data.verify_exists(Item::Modifier, token);
if visible && !block.has_key("desc") {
data.verify_exists(Item::Localization, token);
}
data.database.validate_call(Item::Modifier, token, block, data, sc);
data.database.validate_property_use(Item::Modifier, token, data, key, key.as_str());
}
vd.field_validated_sc("desc", sc, validate_desc);
validate_optional_duration(&mut vd, sc);
}
}
}
pub fn validate_add_truce(
_key: &Token,
block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("character");
vd.field_target("character", sc, Scopes::Character);
vd.field_bool("override");
vd.field_choice("result", &["white_peace", "victory", "defeat"]);
vd.field_item("casus_belli", Item::CasusBelli);
vd.field_validated_sc("name", sc, validate_desc);
vd.field_target("war", sc, Scopes::War);
validate_optional_duration(&mut vd, sc);
if block.has_key("war") && block.has_key("casus_belli") {
let msg = "cannot use both `war` and `casus_belli`";
err(ErrorKey::Validation).msg(msg).loc(block).push();
}
}
pub fn validate_add_unity(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("value");
vd.req_field("character");
vd.field_script_value("value", sc);
vd.field_target("character", sc, Scopes::Character);
vd.field_validated_sc("desc", sc, validate_desc);
}
pub fn validate_assign_council_task(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("council_task");
vd.req_field("target");
vd.field_target("council_task", sc, Scopes::CouncilTask);
vd.field_target("target", sc, Scopes::Character);
vd.field_bool("fire_on_actions");
}
pub fn validate_assign_councillor_type(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("type");
vd.req_field("target");
vd.field_item("type", Item::CouncilPosition);
vd.field_target("target", sc, Scopes::Character);
vd.field_bool("fire_on_actions");
vd.field_bool("remove_existing_councillor");
}
pub fn validate_battle_event(
_key: &Token,
_block: &Block,
data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("left_portrait");
vd.req_field("key");
if let Some(token) = vd.field_value("key") {
let loca = format!("{token}_friendly");
data.verify_exists_implied(Item::Localization, &loca, token);
let loca = format!("{token}_enemy");
data.verify_exists_implied(Item::Localization, &loca, token);
}
vd.field_target("left_portrait", sc, Scopes::Character);
vd.field_target("right_portrait", sc, Scopes::Character);
vd.field_value("type"); // TODO, undocumented
vd.field_bool("target_right"); // undocumented
}
pub fn validate_change_cultural_acceptance(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("target");
vd.req_field("value");
vd.field_target("target", sc, Scopes::Culture);
vd.field_script_value("value", sc);
vd.field_validated_sc("desc", sc, validate_desc);
}
pub fn validate_change_liege(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("liege");
vd.req_field("change");
vd.field_target("liege", sc, Scopes::Character);
vd.field_target("change", sc, Scopes::TitleAndVassalChange);
}
pub fn validate_change_struggle_phase(
_key: &Token,
bv: &BV,
data: &Everything,
_sc: &mut ScopeContext,
_tooltipped: Tooltipped,
) {
match bv {
BV::Value(token) => {
data.verify_exists(Item::StrugglePhase, token);
}
BV::Block(block) => {
let mut vd = Validator::new(block, data);
vd.set_case_sensitive(false);
vd.req_field("struggle_phase");
vd.req_field("with_transition");
vd.field_item("struggle_phase", Item::StrugglePhase);
vd.field_bool("with_transition");
}
}
}
pub fn validate_change_struggle_phase_duration(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("duration");
vd.field_validated_block_sc("duration", sc, |block, data, sc| {
if let Some(bv) = block.get_field("points") {
validate_script_value(bv, data, sc);
} else {
validate_duration(block, data, sc);
}
});
}
pub fn validate_change_title_holder(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("holder");
vd.req_field("change");
vd.field_target("holder", sc, Scopes::Character);
vd.field_target("change", sc, Scopes::TitleAndVassalChange);
vd.field_bool("take_baronies");
vd.field_target("government_base", sc, Scopes::Character);
}
pub fn validate_change_trait_rank(
key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
let caller = key.as_str().to_ascii_lowercase();
vd.req_field("trait");
vd.req_field("rank");
// TODO: check that it's a rankable trait
vd.field_item("trait", Item::Trait);
vd.field_script_value("rank", sc);
if caller == "change_trait_rank" {
vd.field_script_value("max", sc);
}
}
pub fn validate_copy_localized_text(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("key");
vd.req_field("target");
vd.field_value("key");
vd.field_target("target", sc, Scopes::Character);
}
pub fn validate_create_accolade(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("knight");
vd.req_field("primary");
vd.req_field("secondary");
vd.field_target("knight", sc, Scopes::Character);
vd.field_item("primary", Item::AccoladeType);
vd.field_item("secondary", Item::AccoladeType);
vd.field_item("name", Item::Localization);
}
pub fn validate_create_artifact(
key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
let caller = key.as_str().to_ascii_lowercase();
vd.field_validated_sc("name", sc, validate_desc);
vd.field_validated_sc("description", sc, validate_desc);
vd.field_item("rarity", Item::ArtifactRarity);
vd.field_item("type", Item::ArtifactType);
vd.multi_field_item("modifier", Item::Modifier);
vd.field_script_value("durability", sc);
vd.field_script_value("max_durability", sc);
vd.field_bool("decaying");
vd.multi_field_validated_block_sc("history", sc, validate_artifact_history);
vd.field_item("template", Item::ArtifactTemplate);
vd.field_item("visuals", Item::ArtifactVisual);
vd.field_bool("generate_history");
vd.field_script_value("quality", sc);
vd.field_script_value("wealth", sc);
vd.field_target("creator", sc, Scopes::Character);
vd.field_target(
"visuals_source",
sc,
Scopes::LandedTitle | Scopes::Dynasty | Scopes::DynastyHouse,
);
if caller == "create_artifact" {
if let Some(name) = vd.field_identifier("save_scope_as", "scope name") {
sc.define_name_token(name.as_str(), Scopes::Artifact, name);
}
vd.field_target("title_history", sc, Scopes::LandedTitle);
vd.field_date("title_history_date");
} else {
vd.ban_field("save_scope_as", || "`create_artifact`");
vd.ban_field("title_history", || "`create_artifact`");
vd.ban_field("title_history_date", || "`create_artifact`");
}
}
pub fn validate_create_character(
_key: &Token,
block: &Block,
data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
// docs say save_event_target instead of save_scope
vd.replaced_field("save_event_target_as", "save_scope_as");
vd.replaced_field("save_temporary_event_target_as", "save_temporary_scope_as");
if let Some(name) = vd.field_identifier("save_scope_as", "scope name") {
sc.define_name_token(name.as_str(), Scopes::Character, name);
}
if let Some(name) = vd.field_identifier("save_temporary_scope_as", "scope name") {
sc.define_name_token(name.as_str(), Scopes::Character, name);
}
vd.field_validated_sc("name", sc, validate_desc);
vd.field_script_value("age", sc);
if let Some(token) = vd.field_value("gender") {
if !token.is("male") && !token.is("female") {
validate_target_ok_this(token, data, sc, Scopes::Character);
}
}
vd.field_script_value("gender_female_chance", sc);
vd.field_target_ok_this("opposite_gender", sc, Scopes::Character);
vd.multi_field_item("trait", Item::Trait);
vd.multi_field_validated_block_sc("random_traits_list", sc, validate_random_traits_list);
vd.field_bool("random_traits");
vd.field_script_value("health", sc);
vd.field_script_value("fertility", sc);
vd.field_target_ok_this("mother", sc, Scopes::Character);
vd.field_target_ok_this("father", sc, Scopes::Character);
vd.field_target_ok_this("real_father", sc, Scopes::Character);
vd.req_field_one_of(&["location", "employer"]);
vd.field_target_ok_this("employer", sc, Scopes::Character);
vd.field_target_ok_this("location", sc, Scopes::Province);
if let Some(token) = vd.field_value("template") {
// undocumented
data.verify_exists(Item::CharacterTemplate, token);
data.validate_call(Item::CharacterTemplate, token, block, sc);
}
vd.field_item("template", Item::CharacterTemplate); // undocumented
vd.field_target_ok_this("template_character", sc, Scopes::Character);
vd.field_item_or_target("faith", sc, Item::Faith, Scopes::Faith);
vd.field_validated_block_sc("random_faith", sc, validate_random_faith);
vd.field_item_or_target("random_faith_in_religion", sc, Item::Religion, Scopes::Faith);
vd.field_item_or_target("culture", sc, Item::Culture, Scopes::Culture);
vd.field_validated_block_sc("random_culture", sc, validate_random_culture);
// TODO: figure out what a culture group is, and whether this key still works at all
vd.field_value("random_culture_in_group");
vd.field_item_or_target("dynasty_house", sc, Item::House, Scopes::DynastyHouse);
if let Some(token) = vd.field_value("dynasty") {
if !token.is("generate") && !token.is("inherit") && !token.is("none") {
validate_target(token, data, sc, Scopes::Dynasty);
}
}
vd.field_validated_value("ethnicity", |_, mut vd| {
vd.maybe_is("culture");
vd.maybe_is("mother");
vd.maybe_is("father");
vd.maybe_is("parents");
vd.item(Item::Ethnicity);
});
// TODO: Find out the syntax of this. Docs are unclear, no examples in vanilla.
vd.field_block("ethnicities");
vd.field_script_value("diplomacy", sc);
vd.field_script_value("intrigue", sc);
vd.field_script_value("martial", sc);
vd.field_script_value("learning", sc);
vd.field_script_value("prowess", sc);
vd.field_script_value("stewardship", sc);
vd.field_validated_key_block("after_creation", |key, block, data| {
sc.open_scope(Scopes::Character, key.clone());
validate_effect(block, data, sc, Tooltipped::No); // TODO: verify
sc.close();
});
}
pub fn validate_create_character_memory(
key: &Token,
block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("type");
vd.field_item("type", Item::MemoryType);
// TODO: also check that all participants are specified
vd.field_validated_block("participants", |b, data| {
let mut vd = Validator::new(b, data);
let memtype = block.get_field_value("type");
vd.unknown_value_fields(|key, token| {
if let Some(memtype) = memtype {
if !data.item_has_property(Item::MemoryType, memtype.as_str(), key.as_str()) {
let msg =
format!("memory type `{memtype}` does not define participant `{key}`");
warn(ErrorKey::Validation).msg(msg).loc(key).push();
}
}
validate_target_ok_this(token, data, sc, Scopes::Character);
});
});
vd.field_validated_block_sc("duration", sc, validate_duration);
sc.define_name("new_memory", Scopes::CharacterMemory, key);
}
pub fn validate_create_confederation(
key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.field_validated_sc("name", sc, validate_desc);
sc.define_name("new_confederation", Scopes::Confederation, key);
}
pub fn validate_create_dynamic_title(
key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("tier");
vd.req_field("name");
vd.field_choice("tier", &["duchy", "kingdom", "empire"]);
vd.field_validated_sc("name", sc, validate_desc);
vd.advice_field("adjective", "changed to adj in 1.13");
vd.field_validated_sc("adj", sc, validate_desc);
vd.field_validated_sc("pre", sc, validate_desc);
vd.field_validated_sc("article", sc, validate_desc);
sc.define_name("new_title", Scopes::LandedTitle, key);
}
pub fn validate_create_nomad_title(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.field_validated_sc("name", sc, validate_desc);
vd.field_validated_sc("prefix", sc, validate_desc);
vd.field_validated_sc("adjective", sc, validate_desc);
vd.field_target("holder", sc, Scopes::Character);
vd.field_item("government", Item::GovernmentType);
if let Some(name) = vd.field_identifier("save_scope_as", "scope name") {
sc.define_name_token(name.as_str(), Scopes::LandedTitle, name);
}
}
pub fn validate_create_holy_order(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("leader");
vd.req_field("capital");
vd.field_target("leader", sc, Scopes::Character);
vd.field_target("capital", sc, Scopes::LandedTitle);
vd.field_item("name", Item::Localization);
vd.field_item("coat_of_arms", Item::Coa);
if let Some(name) = vd.field_identifier("save_scope_as", "scope name") {
sc.define_name_token(name.as_str(), Scopes::HolyOrder, name);
}
if let Some(name) = vd.field_identifier("save_temporary_scope_as", "scope name") {
sc.define_name_token(name.as_str(), Scopes::HolyOrder, name);
}
}
pub fn validate_create_title_and_vassal_change(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("type");
vd.req_field("save_scope_as");
if let Some(history_type) = vd.field_value("type") {
let valid_types: Vec<_> = TITLE_HISTORY_TYPES
.iter()
.filter(|t| !BANNED_TITLE_HISTORY_TYPES.contains(t))
.copied()
.collect();
if BANNED_TITLE_HISTORY_TYPES.contains(&history_type.as_str()) {
let msg = format!(
"types {} cannot be used from script",
stringify_list(BANNED_TITLE_HISTORY_TYPES)
);
let info = format!("choose_from {}", stringify_choices(&valid_types));
err(ErrorKey::Choice).msg(msg).info(info).loc(history_type).push();
} else {
vd.field_choice("type", &valid_types);
}
}
if let Some(name) = vd.field_identifier("save_scope_as", "scope name") {
sc.define_name_token(name.as_str(), Scopes::TitleAndVassalChange, name);
}
vd.field_bool("add_claim_on_loss");
}
pub fn validate_delay_travel_plan(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.field_bool("add");
validate_optional_duration(&mut vd, sc);
}
pub fn validate_divide_war_chest(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.field_bool("defenders");
vd.field_script_value("fraction", sc);
vd.field_bool("gold");
vd.field_bool("piety");
vd.field_bool("prestige");
}
pub fn validate_duel(
key: &Token,
block: &Block,
data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
tooltipped: Tooltipped,
) {
vd.field_item("skill", Item::Skill);
vd.field_list_items("skills", Item::Skill);
vd.field_target("target", sc, Scopes::Character);
vd.field_script_value("value", sc);
vd.field_item("localization", Item::EffectLocalization);
vd.field_validated_value("challenge_variable", |_, mut vd| {
vd.identifier("variable name");
let loca = format!("{}_name", vd.value());
data.verify_exists_implied(Item::Localization, &loca, vd.value());
vd.accept();
});
vd.field_validated_list("challenge_variables", |token, data| {
validate_identifier(token, "variable name", Severity::Error);
let loca = format!("{token}_name");
data.verify_exists_implied(Item::Localization, &loca, token);
});
sc.define_name("duel_value", Scopes::Value, key);
validate_random_list(key, block, data, sc, vd, tooltipped);
}
pub fn validate_faction_start_war(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.field_target("title", sc, Scopes::LandedTitle);
}
pub fn validate_force_add_to_agent_slot(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.field_target("agent_slot", sc, Scopes::AgentSlot);
validate_optional_duration(&mut vd, sc);
}
pub fn validate_force_vote_as(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.field_target("target", sc, Scopes::Character);
validate_optional_duration(&mut vd, sc);
}
pub fn validate_imprison(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.field_target("target", sc, Scopes::Character);
vd.field_item("type", Item::PrisonType);
// The docs also have a "reason" key, but no indication what it is
}
pub fn validate_join_faction_forced(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.field_target("faction", sc, Scopes::Faction);
vd.field_target("forced_by", sc, Scopes::Character);
validate_optional_duration(&mut vd, sc);
}
pub fn validate_make_pregnant(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.field_target("father", sc, Scopes::Character);
vd.field_integer("number_of_children");
vd.field_bool("known_bastard");
}
pub fn validate_move_budget_gold(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.field_script_value("gold", sc);
let choices = &["budget_war_chest", "budget_reserved", "budget_short_term", "budget_long_term"];
vd.field_choice("from", choices);
vd.field_choice("to", choices);
}
pub fn validate_open_interaction_window(
key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
let caller = key.as_str().to_ascii_lowercase();
vd.req_field("interaction");
vd.req_field("actor");
vd.req_field("recipient");
vd.field_value("interaction"); // TODO
vd.field_bool("redirect");
vd.field_target_ok_this("actor", sc, Scopes::Character);
vd.field_target_ok_this("recipient", sc, Scopes::Character);
vd.field_target_ok_this("secondary_actor", sc, Scopes::Character);
vd.field_target_ok_this("secondary_recipient", sc, Scopes::Character);
if caller == "open_interaction_window" {
vd.field_target("target_title", sc, Scopes::LandedTitle);
}
if caller == "run_interaction" {
vd.field_choice("execute_threshold", &["accept", "maybe", "decline"]);
vd.field_choice("send_threshold", &["accept", "maybe", "decline"]);
}
}
pub fn validate_pay_gold(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("target");
vd.field_target("target", sc, Scopes::Character);
vd.field_script_value("gold", sc);
// undocumented; it means multiply the gold amount by (whose?) yearly income
vd.field_bool("yearly_income");
}
pub fn validate_pay_income(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("target");
vd.field_target("target", sc, Scopes::Character);
validate_optional_duration(&mut vd, sc);
}
pub fn validate_current_phase_guest_subset(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("name");
vd.req_field("target");
vd.field_item("name", Item::GuestSubset);
vd.field_target("target", sc, Scopes::Character);
}
pub fn validate_remove_opinion(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("target");
vd.req_field("modifier");
vd.field_target("target", sc, Scopes::Character);
vd.field_item("modifier", Item::OpinionModifier);
vd.field_bool("single");
}
pub fn validate_replace_court_position(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("recipient");
vd.req_field("court_position");
vd.field_target("recipient", sc, Scopes::Character);
vd.field_target("holder", sc, Scopes::Character);
vd.field_item("court_position", Item::CourtPosition);
}
pub fn validate_revoke_court_position(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("court_position");
vd.field_item("court_position", Item::CourtPosition);
vd.field_target("recipient", sc, Scopes::Character);
vd.field_target("holder", sc, Scopes::Character);
}
pub fn validate_save_opinion_value(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("name");
vd.req_field("target");
if let Some(name) = vd.field_value("name") {
sc.define_name_token(name.as_str(), Scopes::Value, name);
}
vd.field_target("target", sc, Scopes::Character);
}
pub fn validate_scheme_freeze(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.field_item("reason", Item::Localization);
validate_optional_duration(&mut vd, sc);
}
pub fn validate_set_council_task(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("task_type");
// TODO: figure out for which task types `target` is required
vd.field_item("task_type", Item::CouncilTask);
// This has been verified as of 1.9.2, it does require a Province here and not a LandedTitle
vd.field_target("target", sc, Scopes::Character | Scopes::Province);
}
pub fn validate_set_culture_name(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("noun");
vd.field_validated_sc("noun", sc, validate_desc);
vd.field_validated_sc("collective_noun", sc, validate_desc);
vd.field_validated_sc("prefix", sc, validate_desc);
}
pub fn validate_set_death_reason(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("death_reason");
vd.field_item("death_reason", Item::DeathReason);
vd.field_target("killer", sc, Scopes::Character);
vd.field_target("artifact", sc, Scopes::Artifact);
}
pub fn validate_set_ghw_target(
key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
let caller = key.as_str().to_ascii_lowercase();
vd.req_field("target_character");
vd.req_field("target_title");
vd.field_target("target_character", sc, Scopes::Character);
vd.field_target("target_title", sc, Scopes::LandedTitle);
if caller == "start_great_holy_war" {
vd.field_script_value("delay", sc);
vd.field_target("war", sc, Scopes::War);
}
}
pub fn validate_set_legend_chapter(
_key: &Token,
_block: &Block,
_data: &Everything,
_sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.field_item("name", Item::LegendChapter);
vd.field_item("localization_key", Item::Localization);
}
pub fn validate_set_legend_property(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.field_item("name", Item::LegendProperty);
// TODO: look up possible scope types from the legend properties
vd.field_target("target", sc, Scopes::all());
}
pub fn validate_setup_cb(
key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
let caller = key.as_str().to_ascii_lowercase();
vd.req_field("attacker");
vd.req_field("defender");
// vd.req_field("change"); is optional if you just want it to set scope:cb_prestige_factor
vd.field_target("attacker", sc, Scopes::Character);
vd.field_target("defender", sc, Scopes::Character);
vd.field_target("change", sc, Scopes::TitleAndVassalChange);
vd.field_bool("victory");
if caller == "setup_claim_cb" {
vd.req_field("claimant");
vd.field_target("claimant", sc, Scopes::Character);
vd.field_bool("take_occupied");
vd.field_bool("civil_war");
vd.field_choice("titles", &["target_titles", "faction_titles"]);
} else if caller == "setup_de_jure_cb" {
vd.field_target("title", sc, Scopes::LandedTitle);
} else if caller == "setup_invasion_cb" {
vd.field_identifier("titles", "list name");
vd.field_bool("take_occupied");
vd.field_target("claimant", sc, Scopes::Character);
}
sc.define_name("cb_prestige_factor", Scopes::Value, key);
}
pub fn validate_spawn_army(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
// TODO: either levies or men_at_arms
vd.req_field("location");
vd.field_script_value("levies", sc);
vd.multi_field_validated_block("men_at_arms", |b, data| {
let mut vd = Validator::new(b, data);
vd.req_field("type");
vd.field_item("type", Item::MenAtArms);
vd.field_script_value("men", sc);
vd.field_script_value("stacks", sc);
vd.field_bool("inheritable"); // undocumented
});
vd.field_target("location", sc, Scopes::Province);
vd.field_target("origin", sc, Scopes::Province);
vd.field_target("war", sc, Scopes::War);
vd.field_bool("war_keep_on_attacker_victory");
vd.field_bool("inheritable");
vd.field_bool("uses_supply");
vd.field_target("army", sc, Scopes::Army);
if let Some(name) = vd.field_identifier("save_scope_as", "scope name") {
sc.define_name_token(name.as_str(), Scopes::Army, name);
}
if let Some(name) = vd.field_identifier("save_temporary_scope_as", "scope name") {
sc.define_name_token(name.as_str(), Scopes::Army, name);
}
vd.field_validated_sc("name", sc, validate_desc);
}
pub fn validate_start_scheme(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("type");
vd.req_field_one_of(&[
"target_character",
"target_title",
"target_culture",
"target_faith",
"targets_nothing",
]);
vd.field_item("type", Item::Scheme);
vd.field_target("contract", sc, Scopes::TaskContract);
vd.advice_field("target", "replaced with target_character in 1.13");
vd.field_target("target_character", sc, Scopes::Character);
vd.field_target("target_title", sc, Scopes::LandedTitle);
vd.field_target("target_culture", sc, Scopes::Culture);
vd.field_target("target_faith", sc, Scopes::Faith);
vd.field_bool("targets_nothing");
// undocumented
// TODO: verify if still valid in 1.13
vd.field_target("artifact", sc, Scopes::Artifact);
}
pub fn validate_start_struggle(
_key: &Token,
_block: &Block,
_data: &Everything,
_sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("struggle_type");
vd.req_field("start_phase");
vd.field_item("struggle_type", Item::Struggle);
vd.field_item("start_phase", Item::StrugglePhase);
}
pub fn validate_start_travel_plan(
_key: &Token,
_block: &Block,
data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("destination");
for token in vd.multi_field_value("destination") {
validate_target(token, data, sc, Scopes::Province);
}
vd.field_target("travel_leader", sc, Scopes::Character);
for token in vd.multi_field_value("companion") {
validate_target(token, data, sc, Scopes::Character);
}
vd.field_bool("travel_with_domicile");
vd.field_bool("can_cancel_planning");
vd.field_bool("players_use_planner");
vd.field_bool("return_trip");
vd.field_event("on_arrival_event", sc);
vd.field_action("on_arrival_on_action", sc);
vd.field_event("on_start_event", sc);
vd.field_action("on_start_on_action", sc);
vd.field_event("on_travel_planner_cancel_event", sc);
vd.field_action("on_travel_planner_cancel_on_action", sc);
vd.field_choice("on_arrival_destinations", &["all", "first", "last", "all_but_last"]);
}
pub fn validate_start_war(
_key: &Token,
_block: &Block,
data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.field_item("casus_belli", Item::CasusBelli);
vd.field_item("cb", Item::CasusBelli);
vd.field_target("target", sc, Scopes::Character);
vd.field_target_ok_this("claimant", sc, Scopes::Character);
for token in vd.multi_field_value("target_title") {
validate_target(token, data, sc, Scopes::LandedTitle);
}
}
pub fn validate_stress_impact(
_key: &Token,
_block: &Block,
data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.field_script_value("base", sc);
vd.unknown_fields(|token, bv| {
data.verify_exists(Item::Trait, token);
validate_non_dynamic_script_value(bv, data);
});
}
pub fn validate_try_create_important_action(
_key: &Token,
_block: &Block,
data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("important_action_type");
vd.field_item("important_action_type", Item::ImportantAction);
vd.unknown_value_fields(|_, value| {
validate_target_ok_this(value, data, sc, Scopes::all_but_none());
});
}
pub fn validate_try_create_suggestion(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("suggestion_type");
vd.field_item("suggestion_type", Item::Suggestion);
vd.field_target_ok_this("actor", sc, Scopes::Character);
vd.field_target_ok_this("recipient", sc, Scopes::Character);
vd.field_target_ok_this("secondary_actor", sc, Scopes::Character);
vd.field_target_ok_this("secondary_recipient", sc, Scopes::Character);
vd.field_target_ok_this("landed_title", sc, Scopes::LandedTitle);
}
pub fn validate_contract_set_obligation_level(
_key: &Token,
_block: &Block,
data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("type");
vd.req_field("level");
if let Some(token) = vd.field_value("type") {
if !data.item_exists(Item::SubjectContract, token.as_str()) {
validate_target(token, data, sc, Scopes::VassalContract);
}
}
if let Some(token) = vd.field_value("level") {
if !token.is_integer()
&& !data.item_exists(Item::SubjectContractObligationLevel, token.as_str())
{
validate_target(token, data, sc, Scopes::VassalObligationLevel);
}
}
}
pub fn validate_add_artifact_modifier(
_key: &Token,
mut vd: ValueValidator,
_sc: &mut ScopeContext,
_tooltipped: Tooltipped,
) {
vd.item(Item::Modifier);
// TODO validate `property_use`
// TODO: this causes hundreds of warnings. Probably because the tooltip tracking isn't smart enough to figure out
// things like "scope:newly_created_artifact does not exist yet at tooltipping time, so the body of the if won't
// be tooltipped here".
//
// if tooltipped.is_tooltipped() {
// data.verify_exists(Item::Localization, value);
// }
}
pub fn validate_generate_coa(
_key: &Token,
mut vd: ValueValidator,
_sc: &mut ScopeContext,
_tooltipped: Tooltipped,
) {
vd.maybe_is("yes");
vd.item(Item::CoaTemplateList);
}
pub fn validate_set_coa(
_key: &Token,
mut vd: ValueValidator,
sc: &mut ScopeContext,
_tooltipped: Tooltipped,
) {
let options = Scopes::LandedTitle | Scopes::Dynasty | Scopes::DynastyHouse;
vd.item_or_target(sc, Item::Coa, options);
}
pub fn validate_set_focus(
_key: &Token,
mut vd: ValueValidator,
_sc: &mut ScopeContext,
_tooltipped: Tooltipped,
) {
vd.maybe_is("no");
vd.item(Item::Focus);
}
pub fn validate_set_title_name(
_key: &Token,
mut vd: ValueValidator,
_sc: &mut ScopeContext,
_tooltipped: Tooltipped,
) {
vd.item(Item::Localization);
vd.item_used_with_suffix(Item::Localization, "_adj");
}
pub fn validate_activate_struggle_catalyst(
_key: &Token,
bv: &BV,
data: &Everything,
sc: &mut ScopeContext,
_tooltipped: Tooltipped,
) {
match bv {
BV::Value(token) => data.verify_exists(Item::Catalyst, token),
BV::Block(block) => {
let mut vd = Validator::new(block, data);
vd.set_case_sensitive(false);
vd.req_field("catalyst");
vd.req_field("character");
vd.field_item("catalyst", Item::Catalyst);
vd.field_target("character", sc, Scopes::Character);
}
}
}
pub fn validate_add_character_flag(
_key: &Token,
bv: &BV,
data: &Everything,
sc: &mut ScopeContext,
_tooltipped: Tooltipped,
) {
match bv {
BV::Value(_token) => (),
BV::Block(block) => {
let mut vd = Validator::new(block, data);
vd.set_case_sensitive(false);
vd.req_field("flag");
vd.multi_field_value("flag");
validate_optional_duration(&mut vd, sc);
}
}
}
pub fn validate_add_dead_character_flag(
_key: &Token,
block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.set_case_sensitive(false);
vd.req_field("flag");
vd.multi_field_value("flag");
validate_mandatory_duration(block, &mut vd, sc);
}
pub fn validate_begin_create_holding(
_key: &Token,
bv: &BV,
data: &Everything,
sc: &mut ScopeContext,
_tooltipped: Tooltipped,
) {
match bv {
BV::Value(token) => data.verify_exists(Item::HoldingType, token),
BV::Block(block) => {
let mut vd = Validator::new(block, data);
vd.set_case_sensitive(false);
vd.req_field("type");
vd.field_item("type", Item::HoldingType);
vd.field_validated_block("refund_cost", |b, data| {
let mut vd = Validator::new(b, data);
vd.set_case_sensitive(false);
vd.field_script_value("gold", sc);
vd.field_script_value("prestige", sc);
vd.field_script_value("piety", sc);
});
}
}
}
pub fn validate_change_first_name(
_key: &Token,
bv: &BV,
data: &Everything,
sc: &mut ScopeContext,
_tooltipped: Tooltipped,
) {
match bv {
BV::Value(token) => {
if data.item_exists(Item::Localization, token.as_str()) {
data.mark_used(Item::Localization, token.as_str());
} else {
validate_target(token, data, sc, Scopes::Flag);
}
}
BV::Block(block) => {
let mut vd = Validator::new(block, data);
vd.set_case_sensitive(false);
vd.req_field("template_character");
vd.field_target("template_character", sc, Scopes::Character);
}
}
}
pub fn validate_close_view(
_key: &Token,
bv: &BV,
data: &Everything,
sc: &mut ScopeContext,
_tooltipped: Tooltipped,
) {
match bv {
BV::Value(_token) => (), // TODO
BV::Block(block) => {
let mut vd = Validator::new(block, data);
vd.set_case_sensitive(false);
vd.req_field("view");
vd.field_value("view"); // TODO
vd.field_target("player", sc, Scopes::Character);
}
}
}
pub fn validate_create_alliance(
_key: &Token,
bv: &BV,
data: &Everything,
sc: &mut ScopeContext,
_tooltipped: Tooltipped,
) {
match bv {
BV::Value(token) => {
validate_target(token, data, sc, Scopes::Character);
}
BV::Block(block) => {
let mut vd = Validator::new(block, data);
vd.set_case_sensitive(false);
vd.req_field("target");
vd.field_target("target", sc, Scopes::Character);
vd.field_target_ok_this("allied_through_owner", sc, Scopes::Character);
vd.field_target("allied_through_target", sc, Scopes::Character);
}
}
}
pub fn validate_create_epidemic_outbreak(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("type");
vd.req_field("intensity");
vd.field_item("type", Item::EpidemicType);
vd.field_choice("intensity", OUTBREAK_INTENSITIES);
if let Some(name) = vd.field_identifier("save_scope_as", "scope name") {
sc.define_name_token(name.as_str(), Scopes::Epidemic, name);
}
}
pub fn validate_create_inspiration(
_key: &Token,
bv: &BV,
data: &Everything,
sc: &mut ScopeContext,
_tooltipped: Tooltipped,
) {
match bv {
BV::Value(token) => data.verify_exists(Item::Inspiration, token),
BV::Block(block) => {
let mut vd = Validator::new(block, data);
vd.set_case_sensitive(false);
vd.req_field("type");
vd.field_item("type", Item::Inspiration);
vd.field_script_value("gold", sc);
}
}
}
pub fn validate_create_story(
_key: &Token,
bv: &BV,
data: &Everything,
sc: &mut ScopeContext,
_tooltipped: Tooltipped,
) {
match bv {
BV::Value(token) => data.verify_exists(Item::Story, token),
BV::Block(block) => {
let mut vd = Validator::new(block, data);
vd.set_case_sensitive(false);
vd.req_field("type");
vd.field_item("type", Item::Story);
if let Some(name) = vd.field_identifier("save_scope_as", "scope name") {
sc.define_name_token(name.as_str(), Scopes::StoryCycle, name);
}
if let Some(name) = vd.field_identifier("save_temporary_scope_as", "scope name") {
sc.define_name_token(name.as_str(), Scopes::StoryCycle, name);
}
}
}
}
pub fn validate_death(
_key: &Token,
bv: &BV,
data: &Everything,
sc: &mut ScopeContext,
_tooltipped: Tooltipped,
) {
match bv {
BV::Value(token) => {
if !token.is("natural") {
let msg = "expected `death = natural`";
warn(ErrorKey::Validation).msg(msg).loc(token).push();
}
}
BV::Block(block) => {
let mut vd = Validator::new(block, data);
vd.set_case_sensitive(false);
vd.req_field("death_reason");
vd.field_item("death_reason", Item::DeathReason);
vd.field_target("killer", sc, Scopes::Character);
vd.field_target("artifact", sc, Scopes::Artifact);
}
}
}
pub fn validate_open_view(
key: &Token,
bv: &BV,
data: &Everything,
sc: &mut ScopeContext,
_tooltipped: Tooltipped,
) {
match bv {
BV::Value(_token) => (), // TODO
BV::Block(block) => {
let mut vd = Validator::new(block, data);
vd.set_case_sensitive(false);
vd.req_field("view");
vd.field_value("view"); // TODO
vd.field_value("view_message"); // TODO
vd.field_target("player", sc, Scopes::Character);
if key.is("open_view_data") {
vd.field_target("secondary_actor", sc, Scopes::Character); // undocumented
vd.field_target("data", sc, Scopes::all_but_none()); // undocumented
}
}
}
}
pub fn validate_remove_courtier_or_guest(
_key: &Token,
bv: &BV,
data: &Everything,
sc: &mut ScopeContext,
_tooltipped: Tooltipped,
) {
match bv {
BV::Value(token) => {
validate_target(token, data, sc, Scopes::Character);
}
BV::Block(block) => {
let mut vd = Validator::new(block, data);
vd.set_case_sensitive(false);
vd.req_field("character");
vd.field_target("character", sc, Scopes::Character);
vd.field_target("new_location", sc, Scopes::Province);
}
}
}
pub fn validate_set_dead_character_variable(
_key: &Token,
block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("name");
vd.field_identifier("name", "variable name");
vd.field_validated("value", |bv, data| match bv {
BV::Value(token) => {
validate_target_ok_this(token, data, sc, Scopes::all_but_none());
}
BV::Block(_) => validate_script_value(bv, data, sc),
});
validate_mandatory_duration(block, &mut vd, sc);
}
pub fn validate_set_location(
_key: &Token,
bv: &BV,
data: &Everything,
sc: &mut ScopeContext,
_tooltipped: Tooltipped,
) {
match bv {
BV::Value(token) => {
validate_target(token, data, sc, Scopes::Province);
}
BV::Block(block) => {
let mut vd = Validator::new(block, data);
vd.set_case_sensitive(false);
vd.req_field("location");
vd.field_target("location", sc, Scopes::Province);
vd.field_bool("stick_to_location");
}
}
}
pub fn validate_set_owner(
_key: &Token,
bv: &BV,
data: &Everything,
sc: &mut ScopeContext,
_tooltipped: Tooltipped,
) {
match bv {
BV::Value(token) => {
validate_target(token, data, sc, Scopes::Character);
}
BV::Block(block) => {
let mut vd = Validator::new(block, data);
vd.set_case_sensitive(false);
vd.req_field("target");
vd.field_target("target", sc, Scopes::Character);
vd.multi_field_validated_block_sc("history", sc, validate_artifact_history);
vd.field_bool("generate_history");
}
}
}
pub fn validate_set_relation(
_key: &Token,
bv: &BV,
data: &Everything,
sc: &mut ScopeContext,
_tooltipped: Tooltipped,
) {
match bv {
BV::Value(token) => {
validate_target(token, data, sc, Scopes::Character);
}
BV::Block(block) => {
let mut vd = Validator::new(block, data);
vd.set_case_sensitive(false);
vd.req_field("target");
// Sometimes both are used and I don't know what that means. TODO: verify
// vd.req_field_one_of(&["reason", "copy_reason"]);
vd.field_target("target", sc, Scopes::Character);
// TODO: {reason}_corresponding is also a loca
vd.field_item("reason", Item::Localization);
vd.field_item("copy_reason", Item::Relation);
vd.field_target("province", sc, Scopes::Province);
vd.field_target("involved_character", sc, Scopes::Character);
}
}
}
fn validate_artifact_history(block: &Block, data: &Everything, sc: &mut ScopeContext) {
let mut vd = Validator::new(block, data);
vd.set_case_sensitive(false);
vd.req_field("type");
vd.field_item("type", Item::ArtifactHistory);
vd.field_date("date");
vd.field_target("actor", sc, Scopes::Character);
vd.field_target("recipient", sc, Scopes::Character);
vd.field_target("location", sc, Scopes::Province);
}
pub fn validate_end_struggle(
_value: &Token,
mut vd: ValueValidator,
_sc: &mut ScopeContext,
_tooltipped: Tooltipped,
) {
vd.maybe_is("yes");
vd.item(Item::Localization); // undocumented
}
pub fn validate_create_legend(
key: &Token,
_block: &Block,
data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("type");
vd.field_item("type", Item::LegendType);
vd.req_field("quality");
vd.field_choice("quality", LEGEND_QUALITY);
vd.req_field("chronicle");
vd.req_field("properties");
vd.field_item("chronicle", Item::LegendChronicle);
if let Some(chronicle_token) = vd.field_value("chronicle").cloned() {
data.verify_exists(Item::LegendChronicle, &chronicle_token);
if let Some((_, _, chronicle)) =
data.get_item::<LegendChronicle>(Item::LegendChronicle, chronicle_token.as_str())
{
vd.field_validated_key_block("properties", |key, block, data| {
let mut found_properties = TigerHashSet::default();
let mut vd = Validator::new(block, data);
vd.unknown_value_fields(|key, value| {
if let Some(scopes) = chronicle.properties.get(key).copied() {
found_properties.insert(key.clone());
validate_target(value, data, sc, scopes);
} else {
let msg =
format!("property {key} not found in {chronicle_token} chronicle");
err(ErrorKey::Validation).msg(msg).loc(key).push();
}
});
for property in chronicle.properties.keys() {
if !found_properties.contains(property) {
let msg = format!("chronicle property {property} missing from properties");
err(ErrorKey::Validation)
.msg(msg)
.loc(key)
.loc_msg(property, "defined here")
.push();
}
}
});
}
}
// This validation function is used for both create_legend and create_legend_seed
if key.is("create_legend") {
vd.field_target("protagonist", sc, Scopes::Character);
if let Some(name) = vd.field_identifier("save_scope_as", "scope name") {
sc.define_name_token(name.as_str(), Scopes::Legend, name);
}
}
}
pub fn validate_change_maa_regiment_size(
_key: &Token,
bv: &BV,
data: &Everything,
sc: &mut ScopeContext,
_tooltipped: Tooltipped,
) {
match bv {
BV::Value(_) => validate_script_value(bv, data, sc),
BV::Block(block) => {
let mut vd = Validator::new(block, data);
vd.set_case_sensitive(false);
vd.req_field("size");
vd.field_script_value("size", sc);
vd.field_bool("reinforce");
}
}
}
pub fn validate_create_adventurer_title(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("name");
vd.req_field("holder");
vd.field_validated_sc("name", sc, validate_desc);
vd.field_target("holder", sc, Scopes::Character);
vd.field_validated_sc("prefix", sc, validate_desc);
vd.field_validated_sc("adjective", sc, validate_desc);
vd.field_item("government", Item::GovernmentType);
if let Some(name) = vd.field_identifier("save_scope_as", "scope name") {
sc.define_name_token(name.as_str(), Scopes::LandedTitle, name);
}
// undocumented
vd.field_validated_sc("article", sc, validate_desc);
}
pub fn validate_start_best_war(
_key: &Token,
_block: &Block,
_data: &Everything,
_sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
fn sc_builder(key: &Token) -> ScopeContext {
let mut sc = ScopeContext::new(Scopes::Character, key);
sc.define_name("target_character", Scopes::Character, key);
sc.define_name("target_title", Scopes::LandedTitle, key);
sc.define_list("target_titles", Scopes::LandedTitle, key);
sc.define_name("claimant", Scopes::Character, key);
sc.define_name("casus_belli_type", Scopes::CasusBelliType, key);
sc.define_name("has_hostage", Scopes::Bool, key);
sc.define_name("score", Scopes::Value, key);
sc
}
vd.field_list_items("cb", Item::CasusBelli);
vd.field_bool("recalculate_cb_targets");
vd.field_trigger_builder("is_valid", Tooltipped::No, sc_builder);
vd.field_effect_builder("on_success", Tooltipped::No, sc_builder);
vd.field_effect_builder("on_failure", Tooltipped::No, sc_builder);
}
pub fn validate_create_maa_regiment(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field_one_of(&["type", "type_of"]);
vd.field_item("type", Item::MenAtArms);
vd.field_target("type_of", sc, Scopes::Regiment);
vd.field_bool("check_can_recruit");
vd.field_target("title", sc, Scopes::LandedTitle);
vd.field_integer("size");
}
pub fn validate_create_task_contract(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("task_contract_type");
vd.req_field("task_contract_tier");
vd.req_field("location");
vd.field_item("task_contract_type", Item::TaskContractType);
vd.advice_field(
"task_task_contract_tier",
"docs say `task_task_contract_tier` but it's `task_contract_tier`",
);
vd.field_script_value("task_contract_tier", sc);
vd.field_target("location", sc, Scopes::Province);
vd.field_target("task_contract_employer", sc, Scopes::Character);
vd.field_target("destination", sc, Scopes::Province);
vd.field_target("target", sc, Scopes::Character);
if let Some(name) = vd.field_identifier("save_scope_as", "scope name") {
sc.define_name_token(name.as_str(), Scopes::TaskContract, name);
}
// undocumented
if let Some(name) = vd.field_identifier("save_temporary_scope_as", "scope name") {
sc.define_name_token(name.as_str(), Scopes::TaskContract, name);
}
}
pub fn validate_give_noble_family_title(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.field_validated_sc("name", sc, validate_desc);
vd.field_validated_sc("article", sc, validate_desc);
vd.field_item("government", Item::GovernmentType);
if let Some(name) = vd.field_identifier("save_scope_as", "scope name") {
sc.define_name_token(name.as_str(), Scopes::LandedTitle, name);
}
}
pub fn validate_contracts_for_area(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.field_target("location", sc, Scopes::Province);
vd.field_script_value("amount", sc);
vd.field_list_items("group", Item::TaskContractGroup);
}
pub fn validate_change_appointment_investment(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("target");
vd.req_field("value");
vd.field_target("target", sc, Scopes::Character);
vd.field_target("investor", sc, Scopes::Character);
vd.field_script_value("value", sc);
}
pub fn validate_set_important_location(
key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.field_target("title", sc, Scopes::LandedTitle);
// TODO: set scopes for fired events and actions
// "Events and onactions are fired with this scope:
// root - title top liege
// scope:county - important location
// scope:title - higher tier title that is interested in the county
// In enter realm:
// scope:changed_top_liege - former top liege of the important location
// In leave realm:
// scope:changed_top_liege - new top liege of the important location"
let mut sc = ScopeContext::new(Scopes::Character, key);
sc.define_name("county", Scopes::LandedTitle, key);
sc.define_name("title", Scopes::LandedTitle, key);
sc.define_name("changed_top_liege", Scopes::Character, key);
vd.field_event("enter_realm_event", &mut sc);
vd.field_action("enter_realm_on_action", &sc);
vd.field_event("leave_realm_event", &mut sc);
vd.field_action("leave_realm_on_action", &sc);
}
pub fn validate_appoint_court_position(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("court_position");
vd.req_field("recipient");
vd.field_item_or_target("court_position", sc, Item::CourtPosition, Scopes::CourtPositionType);
vd.field_target("recipient", sc, Scopes::Character);
}
pub fn validate_add_takeover_phase_duration(
_key: &Token,
block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.field_item("phase", Item::SituationPhase);
validate_mandatory_duration(block, &mut vd, sc);
}
pub fn validate_add_takeover_phase_points(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.field_item("phase", Item::SituationPhase);
vd.field_script_value("points", sc);
}
pub fn validate_change_phase(
_key: &Token,
bv: &BV,
data: &Everything,
_sc: &mut ScopeContext,
_tooltipped: Tooltipped,
) {
match bv {
BV::Value(value) => {
data.verify_exists(Item::SituationPhase, value);
}
BV::Block(block) => {
let mut vd = Validator::new(block, data);
vd.field_item("phase", Item::SituationPhase);
}
}
}
pub fn validate_raze_county(
_key: &Token,
_block: &Block,
_data: &Everything,
_sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.field_item("holding_type", Item::HoldingType);
vd.field_bool("purge_secondary_holdings");
vd.multi_field_item("excluded_holding_type", Item::HoldingType);
}
pub fn validate_start_tributary(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.field_item("contract_group", Item::SubjectContractGroup);
vd.field_target("suzerain", sc, Scopes::Character);
}
pub fn validate_start_situation(
_key: &Token,
_block: &Block,
_data: &Everything,
sc: &mut ScopeContext,
mut vd: Validator,
_tooltipped: Tooltipped,
) {
vd.req_field("type");
vd.field_item("type", Item::Situation);
vd.field_item("start_phase", Item::SituationPhase);
if let Some(name) = vd.field_identifier("save_scope_as", "scope name") {
sc.define_name_token(name.as_str(), Scopes::Situation, name);
}
if let Some(name) = vd.field_identifier("save_temporary_scope_as", "scope name") {
sc.define_name_token(name.as_str(), Scopes::Situation, name);
}
vd.multi_field_validated_block("sub_region", |block, data| {
let mut vd = Validator::new(block, data);
vd.req_field("key");
vd.field_item("key", Item::SituationSubRegion);
vd.field_item("start_phase", Item::SituationPhase);
vd.field_list_items("geographical_regions", Item::Region);
vd.field_validated("map_color", validate_possibly_named_color);
});
}
pub fn validate_situation_catalyst(
_key: &Token,
bv: &BV,
data: &Everything,
sc: &mut ScopeContext,
_tooltipped: Tooltipped,
) {
match bv {
BV::Value(value) => {
data.verify_exists(Item::SituationCatalyst, value);
}
BV::Block(block) => {
let mut vd = Validator::new(block, data);
vd.req_field("catalyst");
vd.field_item("catalyst", Item::SituationCatalyst);
vd.field_target("character", sc, Scopes::Character);
}
}
}
| 0 | 0.925392 | 1 | 0.925392 | game-dev | MEDIA | 0.451475 | game-dev | 0.92733 | 1 | 0.92733 |
hogwarts-mp/mod | 12,749 | code/client/src/sdk/Runtime/CoreUObject/Private/UObject/SavePackage/SavePackageUtilities.h | // Copyright Epic Games, Inc. All Rights Reserved.
#pragma once
#include "Containers/Array.h"
#include "Containers/Map.h"
#include "Containers/Set.h"
#include "Containers/StringFwd.h"
#include "HAL/ThreadSingleton.h"
#include "ProfilingDebugging/CookStats.h"
#include "Serialization/ArchiveObjectCrc32.h"
#include "Serialization/ArchiveStackTrace.h"
#include "Serialization/FileRegions.h"
#include "UObject/NameTypes.h"
#include "UObject/UObjectMarks.h"
// This file contains private utilities shared by UPackage::Save and UPackage::Save2
class FMD5;
class FSavePackageContext;
template<typename StateType> class TAsyncWorkSequence;
DECLARE_LOG_CATEGORY_EXTERN(LogSavePackage, Log, All);
struct FLargeMemoryDelete
{
void operator()(uint8* Ptr) const
{
if (Ptr)
{
FMemory::Free(Ptr);
}
}
};
typedef TUniquePtr<uint8, FLargeMemoryDelete> FLargeMemoryPtr;
enum class EAsyncWriteOptions
{
None = 0,
WriteFileToDisk = 0x01,
ComputeHash = 0x02
};
ENUM_CLASS_FLAGS(EAsyncWriteOptions)
struct FScopedSavingFlag
{
FScopedSavingFlag(bool InSavingConcurrent);
~FScopedSavingFlag();
bool bSavingConcurrent;
};
struct FSavePackageDiffSettings
{
int32 MaxDiffsToLog;
bool bIgnoreHeaderDiffs;
bool bSaveForDiff;
FSavePackageDiffSettings(bool bDiffing);
};
struct FCanSkipEditorReferencedPackagesWhenCooking
{
bool bCanSkipEditorReferencedPackagesWhenCooking;
FCanSkipEditorReferencedPackagesWhenCooking();
FORCEINLINE operator bool() const { return bCanSkipEditorReferencedPackagesWhenCooking; }
};
/**
* Helper structure to encapsulate sorting a linker's export table alphabetically, taking into account conforming to other linkers.
* @note Save2 should not have to use this sorting long term
*/
struct FObjectExportSortHelper
{
private:
struct FObjectFullName
{
public:
FObjectFullName(const UObject* Object, const UObject* Root);
FObjectFullName(FObjectFullName&& InFullName);
FName ClassName;
TArray<FName> Path;
};
public:
FObjectExportSortHelper() : bUseFObjectFullName(false) {}
/**
* Sorts exports alphabetically. If a package is specified to be conformed against, ensures that the order
* of the exports match the order in which the corresponding exports occur in the old package.
*
* @param Linker linker containing the exports that need to be sorted
* @param LinkerToConformTo optional linker to conform against.
*/
void SortExports(FLinkerSave* Linker, FLinkerLoad* LinkerToConformTo = nullptr, bool InbUseFObjectFullName = false);
private:
/** Comparison function used by Sort */
bool operator()(const FObjectExport& A, const FObjectExport& B) const;
/** the linker that we're sorting exports for */
friend struct TDereferenceWrapper<FObjectExport, FObjectExportSortHelper>;
bool bUseFObjectFullName;
TMap<UObject*, FObjectFullName> ObjectToObjectFullNameMap;
/**
* Map of UObject => full name; optimization for sorting.
*/
TMap<UObject*, FString> ObjectToFullNameMap;
};
/**
* Helper struct used during cooking to validate EDL dependencies
*/
struct FEDLCookChecker : public TThreadSingleton<FEDLCookChecker>
{
void SetActiveIfNeeded();
void Reset();
void AddImport(UObject* Import, UPackage* ImportingPackage);
void AddExport(UObject* Export);
void AddArc(UObject* DepObject, bool bDepIsSerialize, UObject* Export, bool bExportIsSerialize);
static void StartSavingEDLCookInfoForVerification();
static void Verify(bool bFullReferencesExpected);
private:
typedef uint32 FEDLNodeID;
static const FEDLNodeID NodeIDInvalid = static_cast<FEDLNodeID>(-1);
struct FEDLNodeData;
public: // FEDLNodeHash is public only so that GetTypeHash can be defined
enum class EObjectEvent : uint8
{
Create,
Serialize
};
/**
* Wrapper aroundan FEDLNodeData (or around a UObject when searching for an FEDLNodeData corresponding to the UObject)
* that provides the hash-by-objectpath to lookup the FEDLNodeData for an objectpath.
*/
struct FEDLNodeHash
{
FEDLNodeHash(); // creates an uninitialized node; only use this to provide as an out parameter
FEDLNodeHash(const TArray<FEDLNodeData>* InNodes, FEDLNodeID InNodeID, EObjectEvent InObjectEvent);
FEDLNodeHash(const UObject* InObject, EObjectEvent InObjectEvent);
bool operator==(const FEDLNodeHash& Other) const;
friend uint32 GetTypeHash(const FEDLNodeHash& A);
FName GetName() const;
bool TryGetParent(FEDLNodeHash& Parent) const;
EObjectEvent GetObjectEvent() const;
void SetNodes(const TArray<FEDLNodeData>* InNodes);
private:
static FName ObjectNameFirst(const FEDLNodeHash& InNode, uint32& OutNodeID, const UObject*& OutObject);
static FName ObjectNameNext(const FEDLNodeHash& InNode, uint32& OutNodeID, const UObject*& OutObject);
union
{
/**
* The array of nodes from the FEDLCookChecker; this is how we lookup the node for the FEDLNodeData.
* Because the FEDLNodeData are elements in an array which can resize and therefore reallocate the nodes, we cannot store the pointer to the node.
* Only used if bIsNode is true.
*/
const TArray<FEDLNodeData>* Nodes;
/** Pointer to the Object we are looking up, if this hash was created during lookup-by-objectpath for an object */
const UObject* Object;
};
/** The identifier for the FEDLNodeData this hash is wrapping. Only used if bIsNode is true. */
FEDLNodeID NodeID;
/** True if this hash is wrapping an FEDLNodeData, false if it is wrapping a UObject. */
bool bIsNode;
EObjectEvent ObjectEvent;
};
private:
/**
* Node representing either the Create event or Serialize event of a UObject in the graph of runtime dependencies between UObjects.
*/
struct FEDLNodeData
{
// Note that order of the variables is important to reduce alignment waste in the size of FEDLNodeData.
/** Name of the UObject represented by this node; full objectpath name is obtainable by combining parent data with the name. */
FName Name;
/** Index of this node in the FEDLCookChecker's Nodes array. This index is used to provide a small-memory-usage identifier for the node. */
FEDLNodeID ID;
/**
* Tracks references to this node's UObjects from other packages (which is the reverse of the references from each node that we track in NodePrereqs.)
* We only need this information from each package, so we track by package name instead of node id.
*/
TArray<FName> ImportingPackagesSorted;
/**
* ID of the node representing the UObject parent of this node's UObject. NodeIDInvalid if the UObject has no parent.
* The ParentID always refers to the node for the Create event of the parent UObject.
*/
uint32 ParentID;
/** True if this node represents the Serialize event on the UObject, false if it represents the Create event. */
EObjectEvent ObjectEvent;
/** True if the UObject represented by this node has been exported by a SavePackage call; used to verify that the imports requested by packages are present somewhere in the cook. */
bool bIsExport;
FEDLNodeData(FEDLNodeID InID, FEDLNodeID InParentID, FName InName, EObjectEvent InObjectEvent);
FEDLNodeData(FEDLNodeID InID, FEDLNodeID InParentID, FName InName, FEDLNodeData&& Other);
FEDLNodeHash GetNodeHash(const FEDLCookChecker& Owner) const;
FString ToString(const FEDLCookChecker& Owner) const;
void AppendPathName(const FEDLCookChecker& Owner, FStringBuilderBase& Result) const;
void Merge(FEDLNodeData&& Other);
};
enum class EInternalConstruct
{
Type
};
FEDLCookChecker();
FEDLCookChecker(EInternalConstruct);
FEDLNodeID FindOrAddNode(const FEDLNodeHash& NodeLookup);
FEDLNodeID FindOrAddNode(FEDLNodeData&& NodeData, const FEDLCookChecker& OldOwnerOfNode, FEDLNodeID ParentIDInThis, bool& bNew);
FEDLNodeID FindNode(const FEDLNodeHash& NodeHash);
void Merge(FEDLCookChecker&& Other);
bool CheckForCyclesInner(TSet<FEDLNodeID>& Visited, TSet<FEDLNodeID>& Stack, const FEDLNodeID& Visit, FEDLNodeID& FailNode);
void AddDependency(FEDLNodeID SourceID, FEDLNodeID TargetID);
/**
* All the FEDLNodeDatas that have been created for this checker. These are allocated as elements of an array rather than pointers to reduce cputime and
* memory due to many small allocations, and to provide index-based identifiers. Nodes are not deleted during the lifetime of the checker.
*/
TArray<FEDLNodeData> Nodes;
/** A map to lookup the node for a UObject or for the corresponding node in another thread's FEDLCookChecker. */
TMap<FEDLNodeHash, FEDLNodeID> NodeHashToNodeID;
/** The graph of dependencies between nodes. */
TMultiMap<FEDLNodeID, FEDLNodeID> NodePrereqs;
/** True if the EDLCookChecker should be active; it is turned off if the runtime will not be using EDL. */
bool bIsActive;
/** When cooking with concurrent saving, each thread has its own FEDLCookChecker, and these are merged after the cook is complete. */
static FCriticalSection CookCheckerInstanceCritical;
static TArray<FEDLCookChecker*> CookCheckerInstances;
friend TThreadSingleton<FEDLCookChecker>;
};
#if WITH_EDITORONLY_DATA
/**
* Archive to calculate a checksum on an object's serialized data stream, but only of its non-editor properties.
*/
class FArchiveObjectCrc32NonEditorProperties : public FArchiveObjectCrc32
{
using Super = FArchiveObjectCrc32;
public:
FArchiveObjectCrc32NonEditorProperties()
: EditorOnlyProp(0)
{
}
virtual FString GetArchiveName() const
{
return TEXT("FArchiveObjectCrc32NonEditorProperties");
}
virtual void Serialize(void* Data, int64 Length);
private:
int32 EditorOnlyProp;
};
#else
class COREUOBJECT_API FArchiveObjectCrc32NonEditorProperties : public FArchiveObjectCrc32
{
};
#endif
// Utility functions used by both UPackage::Save and/or UPackage::Save2
namespace SavePackageUtilities
{
extern const FName NAME_World;
extern const FName NAME_Level;
extern const FName NAME_PrestreamPackage;
void GetBlueprintNativeCodeGenReplacement(UObject* InObj, UClass*& ObjClass, UObject*& ObjOuter, FName& ObjName, const ITargetPlatform* TargetPlatform);
void IncrementOutstandingAsyncWrites();
void DecrementOutstandingAsyncWrites();
void SaveThumbnails(UPackage* InOuter, FLinkerSave* Linker, FStructuredArchive::FSlot Slot);
void SaveBulkData(FLinkerSave* Linker, const UPackage* InOuter, const TCHAR* Filename, const ITargetPlatform* TargetPlatform,
FSavePackageContext* SavePackageContext, const bool bTextFormat, const bool bDiffing, const bool bComputeHash, TAsyncWorkSequence<FMD5>& AsyncWriteAndHashSequence, int64& TotalPackageSizeUncompressed);
void SaveWorldLevelInfo(UPackage* InOuter, FLinkerSave* Linker, FStructuredArchive::FRecord Record);
EObjectMark GetExcludedObjectMarksForTargetPlatform(const class ITargetPlatform* TargetPlatform);
bool HasUnsaveableOuter(UObject* InObj, UPackage* InSavingPackage);
void CheckObjectPriorToSave(FArchiveUObject& Ar, UObject* InObj, UPackage* InSavingPackage);
void ConditionallyExcludeObjectForTarget(UObject* Obj, EObjectMark ExcludedObjectMarks, const ITargetPlatform* TargetPlatform);
void FindMostLikelyCulprit(TArray<UObject*> BadObjects, UObject*& MostLikelyCulprit, const FProperty*& PropertyRef);
void AddFileToHash(FString const& Filename, FMD5& Hash);
void WriteToFile(const FString& Filename, const uint8* InDataPtr, int64 InDataSize);
void AsyncWriteFile(TAsyncWorkSequence<FMD5>& AsyncWriteAndHashSequence, FLargeMemoryPtr Data, const int64 DataSize, const TCHAR* Filename, EAsyncWriteOptions Options, TArrayView<const FFileRegion> InFileRegions);
void AsyncWriteFileWithSplitExports(TAsyncWorkSequence<FMD5>& AsyncWriteAndHashSequence, FLargeMemoryPtr Data, const int64 DataSize, const int64 HeaderSize, const TCHAR* Filename, EAsyncWriteOptions Options, TArrayView<const FFileRegion> InFileRegions);
void GetCDOSubobjects(UObject* CDO, TArray<UObject*>& Subobjects);
}
#if ENABLE_COOK_STATS
struct FSavePackageStats
{
static int32 NumPackagesSaved;
static double SavePackageTimeSec;
static double TagPackageExportsPresaveTimeSec;
static double TagPackageExportsTimeSec;
static double FullyLoadLoadersTimeSec;
static double ResetLoadersTimeSec;
static double TagPackageExportsGetObjectsWithOuter;
static double TagPackageExportsGetObjectsWithMarks;
static double SerializeImportsTimeSec;
static double SortExportsSeekfreeInnerTimeSec;
static double SerializeExportsTimeSec;
static double SerializeBulkDataTimeSec;
static double AsyncWriteTimeSec;
static double MBWritten;
static TMap<FName, FArchiveDiffStats> PackageDiffStats;
static int32 NumberOfDifferentPackages;
static FCookStatsManager::FAutoRegisterCallback RegisterCookStats;
static void AddSavePackageStats(FCookStatsManager::AddStatFuncRef AddStat);
static void MergeStats(const TMap<FName, FArchiveDiffStats>& ToMerge);
};
#endif
| 0 | 0.875123 | 1 | 0.875123 | game-dev | MEDIA | 0.380096 | game-dev | 0.619639 | 1 | 0.619639 |
Shestak/ShestakUI | 2,685 | ShestakUI/Modules/Skins/Blizzard/PvPMatch.lua | local T, C, L, _ = unpack(select(2, ...))
if C.skins.blizzard_frames ~= true then return end
----------------------------------------------------------------------------------------
-- PVPMatch skin
----------------------------------------------------------------------------------------
local function LoadSkin()
-- Macro to show the PVPMatchScoreboard: /run PVPMatchScoreboard:Show()
local PVPMatchScoreboard = _G.PVPMatchScoreboard
PVPMatchScoreboard:StripTextures()
PVPMatchScoreboard:DisableDrawLayer("BORDER")
PVPMatchScoreboard:CreateBackdrop("Transparent")
PVPMatchScoreboard.Content:StripTextures()
T.SkinScrollBar(PVPMatchScoreboard.Content.ScrollBar)
T.SkinCloseButton(PVPMatchScoreboard.CloseButton)
for i = 1, 3 do
T.SkinTab(_G.PVPMatchScoreboard.Content.TabContainer.TabGroup["Tab"..i])
end
-- Macro to show the PVPMatchResults: /run PVPMatchResults:Show()
local PVPMatchResults = _G.PVPMatchResults
PVPMatchResults:StripTextures()
PVPMatchResults:DisableDrawLayer("BORDER")
PVPMatchResults:CreateBackdrop("Transparent")
PVPMatchResults.content:StripTextures()
PVPMatchResults.content.tabContainer:StripTextures()
T.SkinScrollBar(PVPMatchResults.content.scrollBar)
T.SkinCloseButton(PVPMatchResults.CloseButton)
PVPMatchResults.buttonContainer.leaveButton:SkinButton()
PVPMatchResults.buttonContainer.requeueButton:SkinButton()
for i = 1, 3 do
T.SkinTab(_G.PVPMatchResults.content.tabContainer.tabGroup["tab"..i])
end
local honor = PVPMatchResults.content.earningsContainer.progressContainer.honor.button
honor.CircleMask:Hide()
honor.Ring:Hide()
honor.Icon:SkinIcon()
PVPMatchResults.content.earningsContainer.progressContainer.honor:SetScale(1)
local conquest = PVPMatchResults.content.earningsContainer.progressContainer.conquest.button
conquest.CircleMask:Hide()
conquest.Ring:Hide()
conquest.Icon:SkinIcon()
PVPMatchResults.content.earningsContainer.progressContainer.conquest:SetScale(1)
hooksecurefunc(PVPMatchResults, "AddItemReward", function()
for itemFrame in PVPMatchResults.itemPool:EnumerateActive() do
itemFrame.IconBorder:Hide()
itemFrame.IconBorderDropShadow:SetAlpha(0)
itemFrame:SetScale(1)
if not itemFrame.backdrop then
itemFrame.Icon:SkinIcon()
end
local atlas = itemFrame.IconBorder:GetAtlas()
local r, g, b = unpack(C.media.border_color)
if atlas:find("green") then
r, g, b = GetItemQualityColor(2)
elseif atlas:find("blue") then
r, g, b = GetItemQualityColor(3)
elseif atlas:find("purple") then
r, g, b = GetItemQualityColor(4)
end
itemFrame.backdrop:SetBackdropBorderColor(r, g, b)
end
end)
end
tinsert(T.SkinFuncs["ShestakUI"], LoadSkin) | 0 | 0.890189 | 1 | 0.890189 | game-dev | MEDIA | 0.849492 | game-dev | 0.927441 | 1 | 0.927441 |
DeltaV-Station/Delta-v | 1,597 | Content.Shared/Xenoarchaeology/Artifact/XAT/XATDeathSystem.cs | using Content.Shared.Mobs;
using Content.Shared.Xenoarchaeology.Artifact.Components;
using Content.Shared.Xenoarchaeology.Artifact.XAT.Components;
namespace Content.Shared.Xenoarchaeology.Artifact.XAT;
/// <summary>
/// System for xeno artifact trigger that requires death of some mob near artifact.
/// </summary>
public sealed class XATDeathSystem : BaseXATSystem<XATDeathComponent>
{
[Dependency] private readonly SharedTransformSystem _transform = default!;
private EntityQuery<XenoArtifactComponent> _xenoArtifactQuery;
/// <inheritdoc/>
public override void Initialize()
{
base.Initialize();
_xenoArtifactQuery = GetEntityQuery<XenoArtifactComponent>();
SubscribeLocalEvent<MobStateChangedEvent>(OnMobStateChanged);
}
private void OnMobStateChanged(MobStateChangedEvent args)
{
if (args.NewMobState != MobState.Dead)
return;
var targetCoords = Transform(args.Target).Coordinates;
var query = EntityQueryEnumerator<XATDeathComponent, XenoArtifactNodeComponent>();
while (query.MoveNext(out var uid, out var comp, out var node))
{
if (node.Attached == null)
continue;
var artifact = _xenoArtifactQuery.Get(GetEntity(node.Attached.Value));
if (!CanTrigger(artifact, (uid, node)))
continue;
var artifactCoords = Transform(artifact).Coordinates;
if (_transform.InRange(targetCoords, artifactCoords, comp.Range))
Trigger(artifact, (uid, comp, node));
}
}
}
| 0 | 0.962178 | 1 | 0.962178 | game-dev | MEDIA | 0.976357 | game-dev | 0.898273 | 1 | 0.898273 |
jlnaudin/x-drone | 23,297 | MissionPlanner-master/Joystick.cs | using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using log4net;
using Microsoft.DirectX.DirectInput;
using System.Reflection;
namespace MissionPlanner
{
public class Joystick : IDisposable
{
private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
Device joystick;
JoystickState state;
public bool enabled = false;
byte[] buttonpressed = new byte[128];
public string name;
public bool elevons = false;
public static Joystick self;
struct JoyChannel
{
public int channel;
public joystickaxis axis;
public bool reverse;
public int expo;
}
struct JoyButton
{
public int buttonno;
public string mode;
}
~Joystick()
{
try
{
if (joystick != null)
joystick.Unacquire();
}
catch { }
}
public Joystick()
{
self = this;
}
JoyChannel[] JoyChannels = new JoyChannel[9]; // we are base 1
JoyButton[] JoyButtons = new JoyButton[128]; // base 0
public static DeviceList getDevices()
{
return Manager.GetDevices(DeviceClass.GameControl, EnumDevicesFlags.AttachedOnly);
}
public bool start(string name)
{
self.name = name;
DeviceList joysticklist = Manager.GetDevices(DeviceClass.GameControl, EnumDevicesFlags.AttachedOnly);
bool found = false;
foreach (DeviceInstance device in joysticklist)
{
if (device.ProductName == name)
{
joystick = new Device(device.InstanceGuid);
found = true;
break;
}
}
if (!found)
return false;
joystick.SetDataFormat(DeviceDataFormat.Joystick);
joystick.Acquire();
enabled = true;
System.Threading.Thread t11 = new System.Threading.Thread(new System.Threading.ThreadStart(mainloop))
{
Name = "Joystick loop",
Priority = System.Threading.ThreadPriority.AboveNormal,
IsBackground = true
};
t11.Start();
return true;
}
public static joystickaxis getMovingAxis(string name, int threshold)
{
self.name = name;
DeviceList joysticklist = Manager.GetDevices(DeviceClass.GameControl, EnumDevicesFlags.AttachedOnly);
bool found = false;
Device joystick = null;
foreach (DeviceInstance device in joysticklist)
{
if (device.ProductName == name)
{
joystick = new Device(device.InstanceGuid);
found = true;
break;
}
}
if (!found)
return joystickaxis.ARx;
joystick.SetDataFormat(DeviceDataFormat.Joystick);
joystick.Acquire();
CustomMessageBox.Show("Please ensure you have calibrated your joystick in Windows first");
joystick.Poll();
JoystickState obj = joystick.CurrentJoystickState;
Hashtable values = new Hashtable();
Type type = obj.GetType();
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
values[property.Name] = int.Parse(property.GetValue(obj, null).ToString());
}
values["Slider1"] = obj.GetSlider()[0];
values["Slider2"] = obj.GetSlider()[1];
CustomMessageBox.Show("Please move the joystick axis you want assigned to this function after clicking ok");
DateTime start = DateTime.Now;
while (start.AddSeconds(10) > DateTime.Now)
{
joystick.Poll();
JoystickState nextstate = joystick.CurrentJoystickState;
int[] slider = nextstate.GetSlider();
type = nextstate.GetType();
properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
//Console.WriteLine("Name: " + property.Name + ", Value: " + property.GetValue(obj, null));
log.InfoFormat("test name {0} old {1} new {2} ", property.Name, values[property.Name], int.Parse(property.GetValue(nextstate, null).ToString()));
log.InfoFormat("{0} {1}", (int)values[property.Name], (int.Parse(property.GetValue(nextstate, null).ToString()) + threshold));
if ((int)values[property.Name] > (int.Parse(property.GetValue(nextstate, null).ToString()) + threshold) ||
(int)values[property.Name] < (int.Parse(property.GetValue(nextstate, null).ToString()) - threshold))
{
log.Info(property.Name);
joystick.Unacquire();
return (joystickaxis)Enum.Parse(typeof(joystickaxis), property.Name);
}
}
// slider1
if ((int)values["Slider1"] > (slider[0] + threshold) ||
(int)values["Slider1"] < (slider[0] - threshold))
{
joystick.Unacquire();
return joystickaxis.Slider1;
}
// slider2
if ((int)values["Slider2"] > (slider[1] + threshold) ||
(int)values["Slider2"] < (slider[1] - threshold))
{
joystick.Unacquire();
return joystickaxis.Slider2;
}
}
CustomMessageBox.Show("No valid option was detected");
return joystickaxis.None;
}
public static int getPressedButton(string name)
{
self.name = name;
DeviceList joysticklist = Manager.GetDevices(DeviceClass.GameControl, EnumDevicesFlags.AttachedOnly);
bool found = false;
Device joystick = null;
foreach (DeviceInstance device in joysticklist)
{
if (device.ProductName == name)
{
joystick = new Device(device.InstanceGuid);
found = true;
break;
}
}
if (!found)
return -1;
joystick.SetDataFormat(DeviceDataFormat.Joystick);
joystick.Acquire();
joystick.Poll();
CustomMessageBox.Show("Please press the joystick button you want assigned to this function after clicking ok");
DateTime start = DateTime.Now;
while (start.AddSeconds(10) > DateTime.Now)
{
joystick.Poll();
JoystickState nextstate = joystick.CurrentJoystickState;
byte[] buttons = nextstate.GetButtons();
for (int a = 0; a < joystick.Caps.NumberButtons; a++)
{
if (buttons[a] > 0)
return a;
}
}
CustomMessageBox.Show("No valid option was detected");
return -1;
}
public void setReverse(int channel, bool reverse)
{
JoyChannels[channel].reverse = reverse;
}
public void setAxis(int channel, joystickaxis axis)
{
JoyChannels[channel].axis = axis;
}
public void setChannel(int channel, joystickaxis axis, bool reverse, int expo)
{
JoyChannel joy = new JoyChannel();
joy.axis = axis;
joy.channel = channel;
joy.expo = expo;
joy.reverse = reverse;
JoyChannels[channel] = joy;
}
public void setButton(int arrayoffset, int buttonid, string mode1)
{
JoyButtons[arrayoffset] = new JoyButton()
{
buttonno = buttonid,
mode = mode1
};
}
public void changeButton(int buttonid, int newid)
{
JoyButtons[buttonid].buttonno = newid;
}
public int getHatSwitchDirection()
{
return (state.GetPointOfView())[0];
}
public int getNumberPOV()
{
return joystick.Caps.NumberPointOfViews;
}
int BOOL_TO_SIGN(bool input)
{
if (input == true)
{
return -1;
}
else
{
return 1;
}
}
/// <summary>
/// Updates the rcoverride values and controls the mode changes
/// </summary>
void mainloop()
{
while (enabled)
{
try
{
System.Threading.Thread.Sleep(50);
//joystick stuff
joystick.Poll();
state = joystick.CurrentJoystickState;
int[] slider = state.GetSlider();
if (elevons)
{
//g.channel_roll.set_pwm(BOOL_TO_SIGN(g.reverse_elevons) * (BOOL_TO_SIGN(g.reverse_ch2_elevon) * int(ch2_temp - elevon2_trim) - BOOL_TO_SIGN(g.reverse_ch1_elevon) * int(ch1_temp - elevon1_trim)) / 2 + 1500);
//g.channel_pitch.set_pwm( (BOOL_TO_SIGN(g.reverse_ch2_elevon) * int(ch2_temp - elevon2_trim) + BOOL_TO_SIGN(g.reverse_ch1_elevon) * int(ch1_temp - elevon1_trim)) / 2 + 1500);
ushort roll = pickchannel(1, JoyChannels[1].axis, false, JoyChannels[1].expo);
ushort pitch = pickchannel(2, JoyChannels[2].axis, false, JoyChannels[2].expo);
if (getJoystickAxis(1) != Joystick.joystickaxis.None)
MainV2.comPort.MAV.cs.rcoverridech1 = (ushort)(BOOL_TO_SIGN(JoyChannels[1].reverse) * ((int)(pitch - 1500) - (int)(roll - 1500)) / 2 + 1500);
if (getJoystickAxis(2) != Joystick.joystickaxis.None)
MainV2.comPort.MAV.cs.rcoverridech2 = (ushort)(BOOL_TO_SIGN(JoyChannels[2].reverse) * ((int)(pitch - 1500) + (int)(roll - 1500)) / 2 + 1500);
}
else
{
if (getJoystickAxis(1) != Joystick.joystickaxis.None)
MainV2.comPort.MAV.cs.rcoverridech1 = pickchannel(1, JoyChannels[1].axis, JoyChannels[1].reverse, JoyChannels[1].expo);//(ushort)(((int)state.Rz / 65.535) + 1000);
if (getJoystickAxis(2) != Joystick.joystickaxis.None)
MainV2.comPort.MAV.cs.rcoverridech2 = pickchannel(2, JoyChannels[2].axis, JoyChannels[2].reverse, JoyChannels[2].expo);//(ushort)(((int)state.Y / 65.535) + 1000);
}
if (getJoystickAxis(3) != Joystick.joystickaxis.None)
MainV2.comPort.MAV.cs.rcoverridech3 = pickchannel(3, JoyChannels[3].axis, JoyChannels[3].reverse, JoyChannels[3].expo);//(ushort)(1000 - ((int)slider[0] / 65.535) + 1000);
if (getJoystickAxis(4) != Joystick.joystickaxis.None)
MainV2.comPort.MAV.cs.rcoverridech4 = pickchannel(4, JoyChannels[4].axis, JoyChannels[4].reverse, JoyChannels[4].expo);//(ushort)(((int)state.X / 65.535) + 1000);
if (getJoystickAxis(5) != Joystick.joystickaxis.None)
MainV2.comPort.MAV.cs.rcoverridech5 = pickchannel(5, JoyChannels[5].axis, JoyChannels[5].reverse, JoyChannels[5].expo);
if (getJoystickAxis(6) != Joystick.joystickaxis.None)
MainV2.comPort.MAV.cs.rcoverridech6 = pickchannel(6, JoyChannels[6].axis, JoyChannels[6].reverse, JoyChannels[6].expo);
if (getJoystickAxis(7) != Joystick.joystickaxis.None)
MainV2.comPort.MAV.cs.rcoverridech7 = pickchannel(7, JoyChannels[7].axis, JoyChannels[7].reverse, JoyChannels[7].expo);
if (getJoystickAxis(8) != Joystick.joystickaxis.None)
MainV2.comPort.MAV.cs.rcoverridech8 = pickchannel(8, JoyChannels[8].axis, JoyChannels[8].reverse, JoyChannels[8].expo);
foreach (JoyButton but in JoyButtons)
{
if (but.buttonno != -1 && getButtonState(but.buttonno))
{
string mode = but.mode;
if (mode != null)
{
MainV2.instance.BeginInvoke((System.Windows.Forms.MethodInvoker)delegate()
{
try
{
MainV2.comPort.setMode(mode);
}
catch { CustomMessageBox.Show("Failed to change Modes"); }
});
}
}
}
//Console.WriteLine("{0} {1} {2} {3}", MainV2.comPort.MAV.cs.rcoverridech1, MainV2.comPort.MAV.cs.rcoverridech2, MainV2.comPort.MAV.cs.rcoverridech3, MainV2.comPort.MAV.cs.rcoverridech4);
}
catch (Exception ex) { log.Info("Joystick thread error " + ex.ToString()); } // so we cant fall out
}
}
public enum joystickaxis
{
None,
Pass,
ARx,
ARy,
ARz,
AX,
AY,
AZ,
FRx,
FRy,
FRz,
FX,
FY,
FZ,
Rx,
Ry,
Rz,
VRx,
VRy,
VRz,
VX,
VY,
VZ,
X,
Y,
Z,
Slider1,
Slider2
}
const int RESXu = 1024;
const int RESXul = 1024;
const int RESXl = 1024;
const int RESKul = 100;
/*
ushort expou(ushort x, ushort k)
{
// k*x*x*x + (1-k)*x
return ((ulong)x*x*x/0x10000*k/(RESXul*RESXul/0x10000) + (RESKul-k)*x+RESKul/2)/RESKul;
}
// expo-funktion:
// ---------------
// kmplot
// f(x,k)=exp(ln(x)*k/10) ;P[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
// f(x,k)=x*x*x*k/10 + x*(1-k/10) ;P[0,1,2,3,4,5,6,7,8,9,10]
// f(x,k)=x*x*k/10 + x*(1-k/10) ;P[0,1,2,3,4,5,6,7,8,9,10]
// f(x,k)=1+(x-1)*(x-1)*(x-1)*k/10 + (x-1)*(1-k/10) ;P[0,1,2,3,4,5,6,7,8,9,10]
short expo(short x, short k)
{
if (k == 0) return x;
short y;
bool neg = x < 0;
if (neg) x = -x;
if (k < 0)
{
y = RESXu - expou((ushort)(RESXu - x), (ushort)-k);
}
else
{
y = expou((ushort)x, (ushort)k);
}
return neg ? -y : y;
}
*/
public Device AcquireJoystick(string name)
{
DeviceList joysticklist = Manager.GetDevices(DeviceClass.GameControl, EnumDevicesFlags.AttachedOnly);
bool found = false;
foreach (DeviceInstance device in joysticklist)
{
if (device.ProductName == name)
{
joystick = new Device(device.InstanceGuid);
found = true;
break;
}
}
if (!found)
return null;
joystick.SetDataFormat(DeviceDataFormat.Joystick);
joystick.Acquire();
return joystick;
}
public void UnAcquireJoyStick()
{
if (joystick == null)
return;
joystick.Unacquire();
}
bool getButtonState(int buttonno)
{
byte[] buts = state.GetButtons();
bool ans = buts[buttonno] > 0 && buttonpressed[buttonno] == 0; // press check + debounce
buttonpressed[buttonno] = buts[buttonno]; // set only this button
return ans;
}
public int getNumButtons()
{
if (joystick == null)
return 0;
return joystick.Caps.NumberButtons;
}
public joystickaxis getJoystickAxis(int channel)
{
try
{
return JoyChannels[channel].axis;
}
catch { return joystickaxis.None; }
}
public bool isButtonPressed(int buttonno)
{
byte[] buts = state.GetButtons();
if (buts == null || JoyButtons[buttonno].buttonno < 0)
return false;
return buts[JoyButtons[buttonno].buttonno] > 0;
}
public ushort getValueForChannel(int channel, string name)
{
if (joystick == null)
return 0;
joystick.Poll();
state = joystick.CurrentJoystickState;
ushort ans = pickchannel(channel, JoyChannels[channel].axis, JoyChannels[channel].reverse, JoyChannels[channel].expo);
log.DebugFormat("{0} = {1} = {2}", channel, ans, state.X);
return ans;
}
ushort pickchannel(int chan, joystickaxis axis, bool rev, int expo)
{
int min, max, trim = 0;
if (MainV2.comPort.MAV.param.Count > 0)
{
try
{
min = (int)(float)(MainV2.comPort.MAV.param["RC" + chan + "_MIN"]);
max = (int)(float)(MainV2.comPort.MAV.param["RC" + chan + "_MAX"]);
trim = (int)(float)(MainV2.comPort.MAV.param["RC" + chan + "_TRIM"]);
}
catch
{
min = 1000;
max = 2000;
trim = 1500;
}
}
else
{
min = 1000;
max = 2000;
trim = 1500;
}
if (chan == 3)
{
trim = (min + max) / 2;
// trim = min; // throttle
}
int range = Math.Abs(max - min);
int working = 0;
switch (axis)
{
case joystickaxis.None:
working = ushort.MaxValue / 2;
break;
case joystickaxis.Pass:
working = (int)(((float)(trim - min) / range) * ushort.MaxValue);
break;
case joystickaxis.ARx:
working = state.ARx;
break;
case joystickaxis.ARy:
working = state.ARy;
break;
case joystickaxis.ARz:
working = state.ARz;
break;
case joystickaxis.AX:
working = state.AX;
break;
case joystickaxis.AY:
working = state.AY;
break;
case joystickaxis.AZ:
working = state.AZ;
break;
case joystickaxis.FRx:
working = state.FRx;
break;
case joystickaxis.FRy:
working = state.FRy;
break;
case joystickaxis.FRz:
working = state.FRz;
break;
case joystickaxis.FX:
working = state.FX;
break;
case joystickaxis.FY:
working = state.FY;
break;
case joystickaxis.FZ:
working = state.FZ;
break;
case joystickaxis.Rx:
working = state.Rx;
break;
case joystickaxis.Ry:
working = state.Ry;
break;
case joystickaxis.Rz:
working = state.Rz;
break;
case joystickaxis.VRx:
working = state.VRx;
break;
case joystickaxis.VRy:
working = state.VRy;
break;
case joystickaxis.VRz:
working = state.VRz;
break;
case joystickaxis.VX:
working = state.VX;
break;
case joystickaxis.VY:
working = state.VY;
break;
case joystickaxis.VZ:
working = state.VZ;
break;
case joystickaxis.X:
working = state.X;
break;
case joystickaxis.Y:
working = state.Y;
break;
case joystickaxis.Z:
working = state.Z;
break;
case joystickaxis.Slider1:
int[] slider = state.GetSlider();
working = slider[0];
break;
case joystickaxis.Slider2:
int[] slider1 = state.GetSlider();
working = slider1[1];
break;
}
// between 0 and 65535 - convert to int -500 to 500
working = (int)(working / 65.535) - 500;
if (rev)
working *= -1;
// calc scale from actualy pwm range
float scale = range / 1000.0f;
// save for later
int raw = working;
double B = 4 * (expo / 100.0);
double A = 1 - 0.25 * B;
double t_in = working / 1000.0;
double t_out = 0;
double mid = trim / 1000.0;
t_out = A * (t_in) + B * Math.Pow((t_in), 3);
t_out = mid + t_out * scale;
// Console.WriteLine("tin {0} tout {1}",t_in,t_out);
working = (int)(t_out * 1000);
if (expo == 0)
{
working = (int)(raw) + trim;
}
//add limits to movement
working = Math.Max(min, working);
working = Math.Min(max, working);
return (ushort)working;
}
public void Dispose()
{
if (joystick != null)
joystick.Dispose();
}
}
} | 0 | 0.840586 | 1 | 0.840586 | game-dev | MEDIA | 0.740845 | game-dev | 0.772581 | 1 | 0.772581 |
AirFoundation/Naven-NoAuth | 6,823 | src/main/java/net/minecraft/client/renderer/entity/RenderDragon.java | package net.minecraft.client.renderer.entity;
import net.minecraft.client.model.ModelDragon;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.WorldRenderer;
import net.minecraft.client.renderer.entity.layers.LayerEnderDragonDeath;
import net.minecraft.client.renderer.entity.layers.LayerEnderDragonEyes;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.entity.boss.BossStatus;
import net.minecraft.entity.boss.EntityDragon;
import net.minecraft.util.MathHelper;
import net.minecraft.util.ResourceLocation;
public class RenderDragon extends RenderLiving<EntityDragon> {
private static final ResourceLocation enderDragonCrystalBeamTextures = new ResourceLocation("textures/entity/endercrystal/endercrystal_beam.png");
private static final ResourceLocation enderDragonExplodingTextures = new ResourceLocation("textures/entity/enderdragon/dragon_exploding.png");
private static final ResourceLocation enderDragonTextures = new ResourceLocation("textures/entity/enderdragon/dragon.png");
protected ModelDragon modelDragon;
public RenderDragon(RenderManager renderManagerIn) {
super(renderManagerIn, new ModelDragon(0.0F), 0.5F);
this.modelDragon = (ModelDragon) this.mainModel;
this.addLayer(new LayerEnderDragonEyes(this));
this.addLayer(new LayerEnderDragonDeath());
}
protected void rotateCorpse(EntityDragon bat, float p_77043_2_, float p_77043_3_, float partialTicks) {
float f = (float) bat.getMovementOffsets(7, partialTicks)[0];
float f1 = (float) (bat.getMovementOffsets(5, partialTicks)[1] - bat.getMovementOffsets(10, partialTicks)[1]);
GlStateManager.rotate(-f, 0.0F, 1.0F, 0.0F);
GlStateManager.rotate(f1 * 10.0F, 1.0F, 0.0F, 0.0F);
GlStateManager.translate(0.0F, 0.0F, 1.0F);
if (bat.deathTime > 0) {
float f2 = ((float) bat.deathTime + partialTicks - 1.0F) / 20.0F * 1.6F;
f2 = MathHelper.sqrt_float(f2);
if (f2 > 1.0F) {
f2 = 1.0F;
}
GlStateManager.rotate(f2 * this.getDeathMaxRotation(bat), 0.0F, 0.0F, 1.0F);
}
}
protected void renderModel(EntityDragon entitylivingbaseIn, float p_77036_2_, float p_77036_3_, float p_77036_4_, float p_77036_5_, float p_77036_6_, float scaleFactor) {
if (entitylivingbaseIn.deathTicks > 0) {
float f = (float) entitylivingbaseIn.deathTicks / 200.0F;
GlStateManager.depthFunc(515);
GlStateManager.enableAlpha();
GlStateManager.alphaFunc(516, f);
this.bindTexture(enderDragonExplodingTextures);
this.mainModel.render(entitylivingbaseIn, p_77036_2_, p_77036_3_, p_77036_4_, p_77036_5_, p_77036_6_, scaleFactor);
GlStateManager.alphaFunc(516, 0.1F);
GlStateManager.depthFunc(514);
}
this.bindEntityTexture(entitylivingbaseIn);
this.mainModel.render(entitylivingbaseIn, p_77036_2_, p_77036_3_, p_77036_4_, p_77036_5_, p_77036_6_, scaleFactor);
if (entitylivingbaseIn.hurtTime > 0) {
GlStateManager.depthFunc(514);
GlStateManager.disableTexture2D();
GlStateManager.enableBlend();
GlStateManager.blendFunc(770, 771);
GlStateManager.color(1.0F, 0.0F, 0.0F, 0.5F);
this.mainModel.render(entitylivingbaseIn, p_77036_2_, p_77036_3_, p_77036_4_, p_77036_5_, p_77036_6_, scaleFactor);
GlStateManager.enableTexture2D();
GlStateManager.disableBlend();
GlStateManager.depthFunc(515);
}
}
public void doRender(EntityDragon entity, double x, double y, double z, float entityYaw, float partialTicks) {
BossStatus.setBossStatus(entity, false);
super.doRender(entity, x, y, z, entityYaw, partialTicks);
if (entity.healingEnderCrystal != null) {
this.drawRechargeRay(entity, x, y, z, partialTicks);
}
}
protected void drawRechargeRay(EntityDragon dragon, double p_180574_2_, double p_180574_4_, double p_180574_6_, float p_180574_8_) {
float f = (float) dragon.healingEnderCrystal.innerRotation + p_180574_8_;
float f1 = MathHelper.sin(f * 0.2F) / 2.0F + 0.5F;
f1 = (f1 * f1 + f1) * 0.2F;
float f2 = (float) (dragon.healingEnderCrystal.posX - dragon.posX - (dragon.prevPosX - dragon.posX) * (double) (1.0F - p_180574_8_));
float f3 = (float) ((double) f1 + dragon.healingEnderCrystal.posY - 1.0D - dragon.posY - (dragon.prevPosY - dragon.posY) * (double) (1.0F - p_180574_8_));
float f4 = (float) (dragon.healingEnderCrystal.posZ - dragon.posZ - (dragon.prevPosZ - dragon.posZ) * (double) (1.0F - p_180574_8_));
float f5 = MathHelper.sqrt_float(f2 * f2 + f4 * f4);
float f6 = MathHelper.sqrt_float(f2 * f2 + f3 * f3 + f4 * f4);
GlStateManager.pushMatrix();
GlStateManager.translate((float) p_180574_2_, (float) p_180574_4_ + 2.0F, (float) p_180574_6_);
GlStateManager.rotate((float) (-Math.atan2(f4, f2)) * 180.0F / (float) Math.PI - 90.0F, 0.0F, 1.0F, 0.0F);
GlStateManager.rotate((float) (-Math.atan2(f5, f3)) * 180.0F / (float) Math.PI - 90.0F, 1.0F, 0.0F, 0.0F);
Tessellator tessellator = Tessellator.getInstance();
WorldRenderer worldrenderer = tessellator.getWorldRenderer();
RenderHelper.disableStandardItemLighting();
GlStateManager.disableCull();
this.bindTexture(enderDragonCrystalBeamTextures);
GlStateManager.shadeModel(7425);
float f7 = 0.0F - ((float) dragon.ticksExisted + p_180574_8_) * 0.01F;
float f8 = MathHelper.sqrt_float(f2 * f2 + f3 * f3 + f4 * f4) / 32.0F - ((float) dragon.ticksExisted + p_180574_8_) * 0.01F;
worldrenderer.begin(5, DefaultVertexFormats.POSITION_TEX_COLOR);
int i = 8;
for (int j = 0; j <= 8; ++j) {
float f9 = MathHelper.sin((float) (j % 8) * (float) Math.PI * 2.0F / 8.0F) * 0.75F;
float f10 = MathHelper.cos((float) (j % 8) * (float) Math.PI * 2.0F / 8.0F) * 0.75F;
float f11 = (float) (j % 8) / 8.0F;
worldrenderer.pos(f9 * 0.2F, f10 * 0.2F, 0.0D).tex(f11, f8).color(0, 0, 0, 255).endVertex();
worldrenderer.pos(f9, f10, f6).tex(f11, f7).color(255, 255, 255, 255).endVertex();
}
tessellator.draw();
GlStateManager.enableCull();
GlStateManager.shadeModel(7424);
RenderHelper.enableStandardItemLighting();
GlStateManager.popMatrix();
}
protected ResourceLocation getEntityTexture(EntityDragon entity) {
return enderDragonTextures;
}
}
| 0 | 0.773062 | 1 | 0.773062 | game-dev | MEDIA | 0.766309 | game-dev,graphics-rendering | 0.988661 | 1 | 0.988661 |
samuelcardillo/MMORPGMaker-MV | 6,028 | server/modules/messages/aGive.js | /* global MMO_Core */
exports.initialize = function() {
// agive playerName[1] itemType[2] itemId/amount[3] amount[4]
exports.use = async function(args, initiator) {
if (initiator.playerData.permission < 100) {
return MMO_Core.socket.modules.messages.sendToPlayer(initiator, "System", "You don't have the permission to use this command.", "error");
}
const players = await MMO_Core.socket.modules.player.subs.player.getPlayers();
const amount = parseInt((args[4] !== undefined) ? args[4] : args[3]);
const itemId = parseInt(args[3]);
const targetsName = args[1].toLowerCase();
if (players[targetsName] === undefined) {
return MMO_Core.socket.modules.messages.sendToPlayer(initiator, "System", "Could not find the player.", "error");
}
if (isNaN(args[3])) {
return MMO_Core.socket.modules.messages.sendToPlayer(initiator, "System", "Value is not valid.", "error");
}
if (args.length < 4) {
return MMO_Core.socket.modules.messages.sendToPlayer(initiator, "System", "Not enough arguments.", "error");
}
if (args[2] === "gold") {
players[targetsName].playerData.stats.gold += amount;
MMO_Core.socket.modules.messages.sendToPlayer(players[targetsName], "System", `${initiator.playerData.username} gave you ${args[3]} gold!`, "action");
MMO_Core.socket.modules.messages.sendToPlayer(initiator, "System", `You gave ${args[3]} gold to ${players[targetsName].playerData.username}!`, "action");
} else if (args[2] === "skills") {
if (itemId > 0) {
if (players[targetsName].playerData.stats[args[2]].includes(itemId)) {
return MMO_Core.socket.modules.messages.sendToPlayer(initiator, "System", `${players[targetsName].playerData.username} already has this skill.`, "action");
} else {
players[targetsName].playerData.stats.skills.push(itemId);
}
MMO_Core.socket.modules.messages.sendToPlayer(players[targetsName], "System", `${initiator.playerData.username} gave you ${itemId} Skill!`, "action");
MMO_Core.socket.modules.messages.sendToPlayer(initiator, "System", `You gave skill ${itemId} to ${players[targetsName].playerData.username}!`, "action");
} else {
players[targetsName].playerData.stats.skills = players[targetsName].playerData.stats.skills.filter(skill => {
if (skill !== -itemId) {
return skill;
}
});
MMO_Core.socket.modules.messages.sendToPlayer(players[targetsName], "System", `${initiator.playerData.username} removed ${itemId} skill from you!`, "action");
MMO_Core.socket.modules.messages.sendToPlayer(initiator, "System", `You removed skill ${itemId} from ${players[targetsName].playerData.username}!`, "action");
}
} else if (args[2] === "levels") {
players[targetsName].playerData.stats.level += amount;
MMO_Core.socket.modules.messages.sendToPlayer(players[targetsName], "System", `${initiator.playerData.username} gave you ${amount} levels!`, "action");
MMO_Core.socket.modules.messages.sendToPlayer(initiator, "System", `You gave ${amount} levels to ${players[targetsName].playerData.username}!`, "action");
} else if (args[2] === "permission") {
if (initiator.playerData.permission < amount) {
return MMO_Core.socket.modules.messages.sendToPlayer(initiator, "System", "You don't have the permission to give that amount of permission!", "error");
}
players[targetsName].playerData.permission = amount;
MMO_Core.socket.modules.messages.sendToPlayer(players[targetsName], "System", `${initiator.playerData.username} gave you ${amount} permission!`, "action");
MMO_Core.socket.modules.messages.sendToPlayer(initiator, "System", `You gave ${amount} permission level to ${players[targetsName].playerData.username}!`, "action");
} else if (args[2] === "exp") {
players[targetsName].playerData.stats.exp[1] += amount;
MMO_Core.socket.modules.messages.sendToPlayer(players[targetsName], "System", `${initiator.playerData.username} gave you ${amount} exp!`, "action");
MMO_Core.socket.modules.messages.sendToPlayer(initiator, "System", `You gave ${amount} exp to ${players[targetsName].playerData.username}!`, "action");
} else {
if (args[2] !== "weapons" && args[2] !== "items" && args[2] !== "armors") {
return MMO_Core.socket.modules.messages.sendToPlayer(initiator, "System", "Item type is not valid.", "error");
}
if (isNaN(args[4])) {
return MMO_Core.socket.modules.messages.sendToPlayer(initiator, "System", "Value is not valid.", "error");
}
if (players[targetsName].playerData.stats[args[2]][itemId]) {
players[targetsName].playerData.stats[args[2]][itemId] += amount;
} else {
players[targetsName].playerData.stats[args[2]][itemId] = amount;
}
MMO_Core.socket.modules.messages.sendToPlayer(initiator, "System", "username: " + targetsName + ", " + args[2] + "ID: " + args[3] + ", with amount: " + args[4], "action");
MMO_Core.socket.modules.messages.sendToPlayer(players[targetsName], "System", `${initiator.playerData.username} gave you ${args[3]} in the amount of ${args[4]}!`, "action");
}
MMO_Core.database.savePlayer({
username: players[targetsName].playerData.username,
stats: players[targetsName].playerData.stats,
permission: players[targetsName].playerData.permission
}, (e) => {
MMO_Core.socket.modules.player.subs.player.refreshData(players[targetsName]);
});
};
};
| 0 | 0.830448 | 1 | 0.830448 | game-dev | MEDIA | 0.781255 | game-dev | 0.796039 | 1 | 0.796039 |
Sgt-Imalas/Sgt_Imalas-Oni-Mods | 7,350 | UL_UniversalLyzer/MultiConverterElectrolyzer.cs | using System;
using UnityEngine;
using static UL_UniversalLyzer.ModAssets;
namespace UL_UniversalLyzer
{
public class MultiConverterElectrolyzer : StateMachineComponent<MultiConverterElectrolyzer.StatesInstance>
{
[SerializeField]
public bool hasMeter = true;
[SerializeField]
public CellOffset emissionOffset = CellOffset.none;
[MyCmpAdd]
private Storage storage;
[MyCmpGet]
public ElementConverter converter;
[MyCmpReq]
private Operational operational;
private MeterController meter;
[MyCmpGet]
KBatchedAnimController controller;
[MyCmpGet]
EnergyConsumer energyConsumer;
[MyCmpGet]
Building building;
public override void OnSpawn()
{
if (this.hasMeter)
this.meter = new MeterController(controller, "U2H_meter_target", "meter", Meter.Offset.Behind, Grid.SceneLayer.NoLayer, new Vector3(-0.4f, 0.5f, -0.1f), new string[4]
{
"U2H_meter_target",
"U2H_meter_tank",
"U2H_meter_waterbody",
"U2H_meter_level"
});
this.smi.StartSM();
UpdateColor();
this.UpdateMeter();
Tutorial.Instance.oxygenGenerators.Add(this.gameObject);
}
public override void OnCleanUp()
{
Tutorial.Instance.oxygenGenerators.Remove(this.gameObject);
base.OnCleanUp();
}
public void UpdateMeter()
{
if (!this.hasMeter)
return;
this.meter.SetPositionPercent(Mathf.Clamp01(this.storage.MassStored() / this.storage.capacityKg));
UpdateColor();
}
public void UpdateColor()
{
var liquid = storage.FindFirstWithMass(GameTags.AnyWater, 0.2f);
if (liquid != null && liquid.TryGetComponent<PrimaryElement>(out var element))
{
var color = element.Element.substance.conduitColour;
meter.SetSymbolTint("u2h_meter_waterlevel", color);
meter.SetSymbolTint("u2h_meter_waterbody", color);
controller.SetSymbolTint("u1h_fxbubbles", color);
controller.SetSymbolTint("filterwater", color);
controller.SetSymbolTint("bub", color);
}
}
private bool RoomForPressure => !GameUtil.FloodFillCheck(new Func<int, MultiConverterElectrolyzer, bool>(MultiConverterElectrolyzer.OverPressure), this, Grid.OffsetCell(Grid.PosToCell(this.transform.GetPosition()), this.emissionOffset), 3, true, true);
private static bool OverPressure(int cell, MultiConverterElectrolyzer MultiConverterElectrolyzer) => (double)Grid.Mass[cell] >
(Config.Instance.PerLiquidSettings ? MultiConverterElectrolyzer.LastActiveConfig.OverpressurisationThreshold : ModAssets.ElectrolyzerConfigurations[SimHashes.Water].OverpressurisationThreshold);
public class StatesInstance :
GameStateMachine<States, StatesInstance, MultiConverterElectrolyzer, object>.GameInstance
{
public StatesInstance(MultiConverterElectrolyzer smi)
: base(smi)
{
}
}
public class States :
GameStateMachine<States, StatesInstance, MultiConverterElectrolyzer>
{
public State disabled;
public State waiting;
public State converting;
public State overpressure;
public override void InitializeStates(out BaseState default_state)
{
default_state = disabled;
this.root
.EventTransition(GameHashes.OperationalChanged, this.disabled, smi => !smi.master.operational.IsOperational)
.EventHandler(GameHashes.OnStorageChange, smi => smi.master.UpdateMeter());
this.disabled
.EventTransition(GameHashes.OperationalChanged, this.waiting, smi => smi.master.operational.IsOperational);
this.waiting
.Enter("Waiting", smi => smi.master.operational.SetActive(false))
.EventTransition(GameHashes.OnStorageChange, this.converting, smi => smi.master.HasEnoughMassToStartConverting())
.Transition(this.overpressure, smi => !smi.master.RoomForPressure)
.Update((smi, dt) =>
{
smi.master.UpdateConverter();
smi.master.UpdateColor();
})
.UpdateTransition(converting, (smi, dt) => smi.master.HasEnoughMassToStartConverting())
;
this.converting.Enter("Ready", smi => smi.master.operational.SetActive(true))
.Transition(this.waiting, smi => !smi.master.CanConvertAtAll())
.Transition(this.overpressure, smi => !smi.master.RoomForPressure);
this.overpressure
.Enter("OverPressure", smi => smi.master.operational.SetActive(false))
.ToggleStatusItem(Db.Get().BuildingStatusItems.PressureOk)
.Transition(this.converting, smi => smi.master.RoomForPressure);
}
}
private bool CanConvertAtAll() => converter.CanConvertAtAll();
private bool HasEnoughMassToStartConverting() => converter.HasEnoughMassToStartConverting();
ElectrolyzerConfiguration LastActiveConfig = ModAssets.ElectrolyzerConfigurations[SimHashes.Water];
private void UpdateConverter()
{
if (storage.items.Count == 0) return;
var liquid = storage.FindFirstWithMass(GameTags.AnyWater, 0.1f);
if (liquid != null && liquid.TryGetComponent<PrimaryElement>(out var element) && converter.smi.IsInsideState(converter.smi.sm.disabled))
{
var lastVal = LastActiveConfig;
if (ModAssets.ElectrolyzerConfigurations.ContainsKey(element.ElementID))
{
LastActiveConfig = ModAssets.ElectrolyzerConfigurations[element.ElementID];
}
else if (LastActiveConfig != ModAssets.ElectrolyzerConfigurations[SimHashes.Water])
{
LastActiveConfig = ModAssets.ElectrolyzerConfigurations[SimHashes.Water];
}
if (LastActiveConfig != lastVal)
{
CleaningUpOldAccumulators();
converter.consumedElements = LastActiveConfig.InputElements.ToArray();
if (!Config.Instance.PerLiquidSettings)
{
var waterElements = ElectrolyzerConfigurations[SimHashes.Water].OutputElements;
var elements = LastActiveConfig.OutputElements;
ElementConverter.OutputElement[] outputs = new ElementConverter.OutputElement[elements.Count];
for (int i = 0; i< elements.Count; i++)
{
var outputElement = elements[i];
outputElement.minOutputTemperature = waterElements[i].minOutputTemperature;
outputs[i] = outputElement;
}
converter.outputElements = outputs;
}
else
converter.outputElements = LastActiveConfig.OutputElements.ToArray();
CreatingNewAccumulators();
if (Config.Instance.PerLiquidSettings)
{
energyConsumer.BaseWattageRating = LastActiveConfig.PowerConsumption;
}
else
{
energyConsumer.BaseWattageRating = ModAssets.ElectrolyzerConfigurations[SimHashes.Water].PowerConsumption;
}
}
}
}
private void CleaningUpOldAccumulators()
{
for (int i = converter.consumedElements.Length - 1; i >= 0; i--)
{
Game.Instance.accumulators.Remove(converter.consumedElements[i].Accumulator);
}
for (int i = converter.outputElements.Length - 1; i >= 0; i--)
{
Game.Instance.accumulators.Remove(converter.outputElements[i].accumulator);
}
}
private void CreatingNewAccumulators()
{
for (int i = 0; i < converter.consumedElements.Length; i++)
{
converter.consumedElements[i].Accumulator = Game.Instance.accumulators.Add("ElementsConsumed", converter);
}
converter.totalDiseaseWeight = 0f;
for (int j = 0; j < converter.outputElements.Length; j++)
{
converter.outputElements[j].accumulator = Game.Instance.accumulators.Add("OutputElements", converter);
converter.totalDiseaseWeight += converter.outputElements[j].diseaseWeight;
}
}
}
}
| 0 | 0.938436 | 1 | 0.938436 | game-dev | MEDIA | 0.838178 | game-dev | 0.960769 | 1 | 0.960769 |
savatkinv/VoxelGame | 3,157 | VoxelGame_UnityProject/Assets/VoxelGame/Voxel/Scripts/ChunkView/ChunkElement.cs | using VoxelGame.Voxel;
using System;
using System.Collections.Generic;
using UnityEngine;
namespace VoxelGame.Voxel
{
public class ChunkElement
{
public bool IsInited { get; private set; }
public bool HasCollider { get; private set; }
public ChunkElementMeshData MeshData { get; private set; }
private GameObject gameObject;
private MeshRenderer meshRenderer;
private MeshFilter meshFilter;
private MeshCollider meshCollider;
public ChunkElement(bool hasCollider)
{
this.HasCollider = hasCollider;
}
public void Init(Vector2Int coords, Vector3 postition, Material material, Transform parent, string prefix, string customLayer = null)
{
if (IsInited)
return;
gameObject = new GameObject($"{prefix} <{coords.x},{coords.y}>");
gameObject.transform.position = postition;
gameObject.transform.SetParent(parent);
meshFilter = gameObject.AddComponent<MeshFilter>();
meshRenderer = gameObject.AddComponent<MeshRenderer>();
meshRenderer.material = material;
MeshData = new ChunkElementMeshData();
meshFilter.sharedMesh = MeshData.mesh;
if (customLayer != null)
gameObject.layer = LayerMask.NameToLayer(customLayer);
IsInited = true;
}
public void Delete()
{
if (!IsInited)
return;
MeshData.mesh.Clear();
MeshData = null;
if (meshCollider != null)
GameObject.Destroy(meshCollider.sharedMesh);
GameObject.Destroy(meshFilter.sharedMesh);
GameObject.Destroy(meshRenderer.sharedMaterial);
GameObject.Destroy(gameObject);
IsInited = false;
}
public void AddFadeAnimation()
{
if (IsInited)
gameObject.AddComponent<ChunkFade>();
}
public void UpdateMesh()
{
if (!IsInited)
return;
if (MeshData == null)
return;
if (MeshData.mesh == null)
return;
MeshData.mesh.Clear();
if (MeshData.verts.Count != MeshData.vertexColors.Count)
return;
MeshData.mesh.SetVertices(MeshData.verts);
MeshData.mesh.SetTriangles(MeshData.tris, 0);
MeshData.mesh.SetUVs(0, MeshData.uvs);
MeshData.mesh.SetColors(MeshData.vertexColors);
MeshData.mesh.RecalculateNormals();
MeshData.mesh.Optimize();
MeshData.Clear();
if (HasCollider)
CreateModelCollider();
}
private void CreateModelCollider()
{
if (gameObject == null)
return;
if (meshCollider == null)
{
meshCollider = gameObject.AddComponent<MeshCollider>();
}
meshCollider.sharedMesh = MeshData.mesh.triangles.Length > 0 ? MeshData.mesh : null;
}
}
} | 0 | 0.770557 | 1 | 0.770557 | game-dev | MEDIA | 0.72054 | game-dev,graphics-rendering | 0.785392 | 1 | 0.785392 |
magefree/mage | 1,286 | Mage.Sets/src/mage/cards/c/CollarTheCulprit.java |
package mage.cards.c;
import java.util.UUID;
import mage.abilities.effects.common.DestroyTargetEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.ComparisonType;
import mage.filter.common.FilterCreaturePermanent;
import mage.filter.predicate.mageobject.ToughnessPredicate;
import mage.target.TargetPermanent;
import mage.target.common.TargetCreaturePermanent;
/**
* @author Ryan-Saklad
*/
public final class CollarTheCulprit extends CardImpl {
private static final FilterCreaturePermanent filter = new FilterCreaturePermanent("creature with toughness 4 or greater");
static {
filter.add(new ToughnessPredicate(ComparisonType.MORE_THAN, 3));
}
public CollarTheCulprit(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.INSTANT}, "{3}{W}");
// Destroy target creature with toughness 4 or greater.
this.getSpellAbility().addEffect(new DestroyTargetEffect());
this.getSpellAbility().addTarget(new TargetPermanent(filter));
}
private CollarTheCulprit(final CollarTheCulprit card) {
super(card);
}
@Override
public CollarTheCulprit copy() {
return new CollarTheCulprit(this);
}
}
| 0 | 0.951516 | 1 | 0.951516 | game-dev | MEDIA | 0.888499 | game-dev | 0.979046 | 1 | 0.979046 |
FoxsterDev/DevAccelerationSystem | 1,183 | DevAccelerationSystem/Assets/DevAccelerationSystem/Editor/Core/ScriptableObjectExtension.cs | using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace DevAccelerationSystem.Core
{
public static class ScriptableObjectExtension
{
public static void SaveChanges( this ScriptableObject so, bool forceUpdateAssetDatabase)
{
EditorUtility.SetDirty(so);
AssetDatabase.SaveAssetIfDirty(so);
if (forceUpdateAssetDatabase)
{
AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);
}
}
// Generic method to load all ScriptableObjects of a specific type
public static List<T> LoadAllAssetsOfType<T>() where T : ScriptableObject
{
var assets = new List<T>(1);
var guids = AssetDatabase.FindAssets("t:" + typeof(T).Name);
foreach (string guid in guids)
{
string assetPath = AssetDatabase.GUIDToAssetPath(guid);
T asset = AssetDatabase.LoadAssetAtPath<T>(assetPath);
if (asset != null)
{
assets.Add(asset);
}
}
return assets;
}
}
} | 0 | 0.835576 | 1 | 0.835576 | game-dev | MEDIA | 0.927262 | game-dev | 0.968794 | 1 | 0.968794 |
CalamityTeam/CalamityModPublic | 2,268 | Projectiles/Magic/SoulPiercerBeam.cs | using CalamityMod.Buffs.DamageOverTime;
using Microsoft.Xna.Framework;
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
namespace CalamityMod.Projectiles.Magic
{
public class SoulPiercerBeam : ModProjectile, ILocalizedModType
{
public new string LocalizationCategory => "Projectiles.Magic";
public override string Texture => "CalamityMod/Projectiles/InvisibleProj";
public override void SetDefaults()
{
Projectile.width = 4;
Projectile.height = 4;
Projectile.friendly = true;
Projectile.DamageType = DamageClass.Magic;
Projectile.ignoreWater = true;
Projectile.penetrate = -1;
Projectile.extraUpdates = 100;
Projectile.timeLeft = 360;
Projectile.usesLocalNPCImmunity = true;
Projectile.localNPCHitCooldown = -1;
}
public override void AI()
{
Projectile.localAI[0] += 1f;
if (Projectile.localAI[0] > 9f)
{
Vector2 projPos = Projectile.position;
projPos -= Projectile.velocity;
Projectile.alpha = 255;
int godSlay = Dust.NewDust(projPos, 1, 1, DustID.ShadowbeamStaff, 0f, 0f, 0, default, 0.5f);
Main.dust[godSlay].position = projPos;
Main.dust[godSlay].scale = Main.rand.Next(70, 110) * 0.014f;
Main.dust[godSlay].velocity *= 0.2f;
}
}
public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone)
{
target.AddBuff(ModContent.BuffType<GodSlayerInferno>(), 180);
var source = Projectile.GetSource_FromThis();
for (int x = 0; x < 5; x++)
{
if (Projectile.owner == Main.myPlayer && Projectile.numHits == 0)
CalamityUtils.ProjectileBarrage(source, Projectile.Center, target.Center, true, -500f, 500f, 0f, 500f, 10f, ModContent.ProjectileType<SoulPiercerBolt>(), Projectile.damage, 0f, Projectile.owner, false, 0f);
}
}
public override void OnHitPlayer(Player target, Player.HurtInfo info) => target.AddBuff(ModContent.BuffType<GodSlayerInferno>(), 180);
}
}
| 0 | 0.867586 | 1 | 0.867586 | game-dev | MEDIA | 0.996414 | game-dev | 0.977451 | 1 | 0.977451 |
larsjsol/NavGrid | 1,277 | Source/Navgrid/Classes/NavGridGameState.h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/GameStateBase.h"
#include "GenericTeamAgentInterface.h"
#include "TurnManager.h"
#include "NavGridGameState.generated.h"
class ANavGrid;
/**
*
*/
UCLASS()
class NAVGRID_API ANavGridGameState : public AGameStateBase
{
GENERATED_BODY()
public:
UFUNCTION(BlueprintCallable, Category = "NavGrid")
virtual ANavGrid* GetNavGrid();
template <class T>
T* GetNavGrid() { return Cast<T>(GetNavGrid()); }
UFUNCTION(BlueprintCallable, Category = "NavGrid")
virtual ATurnManager* GetTurnManager();
template <class T>
T *GetTurnManager() { return Cast<T>(GetTurnManager()); }
DECLARE_MULTICAST_DELEGATE_TwoParams(FOnPawnEnterTile, class AGridPawn *, class UNavTileComponent *);
FOnPawnEnterTile &OnPawnEnterTile() { return PawnEnterTileDelegate; }
private:
FOnPawnEnterTile PawnEnterTileDelegate;
protected:
/* spawn the default turn manager object, override this if you need to modify it */
virtual ATurnManager* SpawnTurnManager();
/* spawn the default navgrid object, override this if you need to modify it */
virtual ANavGrid* SpawnNavGrid();
UPROPERTY()
ANavGrid* Grid;
UPROPERTY()
ATurnManager *TurnManager;
};
| 0 | 0.777892 | 1 | 0.777892 | game-dev | MEDIA | 0.920971 | game-dev | 0.602307 | 1 | 0.602307 |
XFactHD/FramedBlocks | 5,339 | src/main/java/io/github/xfacthd/framedblocks/client/model/unbaked/UnbakedStandaloneFramedBlockModel.java | package io.github.xfacthd.framedblocks.client.model.unbaked;
import com.google.common.collect.Maps;
import com.google.gson.JsonParseException;
import com.mojang.logging.LogUtils;
import com.mojang.serialization.JsonOps;
import io.github.xfacthd.framedblocks.api.model.standalone.CachingModel;
import io.github.xfacthd.framedblocks.api.model.standalone.StandaloneModelFactory;
import io.github.xfacthd.framedblocks.api.model.standalone.StandaloneWrapperKey;
import io.github.xfacthd.framedblocks.api.model.util.ModelUtils;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.block.model.BlockModelDefinition;
import net.minecraft.client.renderer.block.model.BlockStateModel;
import net.minecraft.client.resources.model.ModelBaker;
import net.minecraft.resources.FileToIdConverter;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.packs.resources.Resource;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.util.StrictJsonParser;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import net.neoforged.neoforge.client.model.standalone.UnbakedStandaloneModel;
import org.slf4j.Logger;
import java.io.Reader;
import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
public final class UnbakedStandaloneFramedBlockModel<T extends CachingModel> implements UnbakedStandaloneModel<T>
{
private static final Logger LOGGER = LogUtils.getLogger();
private static final Map<StandaloneWrapperKey<?>, CachingModel> BAKED_MODELS = new ConcurrentHashMap<>();
private static final FileToIdConverter BLOCKSTATE_LISTER = FileToIdConverter.json(StandaloneWrapperKey.STANDALONE_DEFINITION_FOLDER);
private final StandaloneWrapperKey<T> wrapperKey;
private final StandaloneModelFactory<T> modelFactory;
private final Map<BlockState, BlockStateModel.UnbakedRoot> unbakedModels;
@SuppressWarnings("unchecked")
public UnbakedStandaloneFramedBlockModel(StandaloneWrapperKey<?> wrapperKey, StandaloneModelFactory<?> modelFactory)
{
this.wrapperKey = (StandaloneWrapperKey<T>) wrapperKey;
this.modelFactory = (StandaloneModelFactory<T>) modelFactory;
this.unbakedModels = loadModelDefinition(wrapperKey);
}
@Override
public T bake(ModelBaker baker)
{
Function<BlockState, BlockStateModel> modelProvider;
if (unbakedModels.isEmpty())
{
BlockStateModel missing = baker.compute(ModelUtils.MISSING_MODEL_KEY);
modelProvider = $ -> missing;
}
else
{
modelProvider = state -> unbakedModels.get(state).bake(state, baker);
}
List<BlockState> states = wrapperKey.block().value().getStateDefinition().getPossibleStates();
Map<BlockState, BlockStateModel> bakedModels = Maps.toMap(states, modelProvider::apply);
T model = modelFactory.create(bakedModels);
BAKED_MODELS.put(wrapperKey, model);
return model;
}
@Override
public void resolveDependencies(Resolver resolver)
{
unbakedModels.values().forEach(model -> model.resolveDependencies(resolver));
}
private static Map<BlockState, BlockStateModel.UnbakedRoot> loadModelDefinition(StandaloneWrapperKey<?> wrapperKey)
{
ResourceManager resourceManager = Minecraft.getInstance().getResourceManager();
ResourceLocation file = wrapperKey.definitionFile();
List<Resource> resources = resourceManager.getResourceStack(BLOCKSTATE_LISTER.idToFile(file));
if (resources.isEmpty())
{
LOGGER.error("Specified standalone model definition file '{}' does not exist", file);
return Map.of();
}
List<LoadedDefinition> definitions = new ArrayList<>(resources.size());
for (Resource resource : resources)
{
try (Reader reader = resource.openAsReader())
{
BlockModelDefinition definition = BlockModelDefinition.CODEC
.parse(JsonOps.INSTANCE, StrictJsonParser.parse(reader))
.getOrThrow(JsonParseException::new);
definitions.add(new LoadedDefinition(resource.sourcePackId(), definition));
}
catch (Exception e)
{
LOGGER.error("Failed to load standalone model definition {} from pack {}", file, resource.sourcePackId(), e);
}
}
StateDefinition<Block, BlockState> stateDefinition = wrapperKey.block().value().getStateDefinition();
Map<BlockState, BlockStateModel.UnbakedRoot> models = new IdentityHashMap<>(stateDefinition.getPossibleStates().size());
for (LoadedDefinition definition : definitions)
{
models.putAll(definition.contents.instantiate(stateDefinition, () -> file + "/" + definition.source));
}
return models;
}
public static void clearCaches()
{
BAKED_MODELS.values().forEach(CachingModel::clearCache);
}
private record LoadedDefinition(String source, BlockModelDefinition contents) {}
}
| 0 | 0.732576 | 1 | 0.732576 | game-dev | MEDIA | 0.901516 | game-dev,graphics-rendering | 0.741447 | 1 | 0.741447 |
checkedc/checkedc-clang | 3,146 | lldb/include/lldb/Target/InstrumentationRuntime.h | //===-- InstrumentationRuntime.h --------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#ifndef LLDB_TARGET_INSTRUMENTATIONRUNTIME_H
#define LLDB_TARGET_INSTRUMENTATIONRUNTIME_H
#include <map>
#include <vector>
#include "lldb/Core/PluginInterface.h"
#include "lldb/Utility/StructuredData.h"
#include "lldb/lldb-forward.h"
#include "lldb/lldb-private.h"
#include "lldb/lldb-types.h"
namespace lldb_private {
typedef std::map<lldb::InstrumentationRuntimeType,
lldb::InstrumentationRuntimeSP>
InstrumentationRuntimeCollection;
class InstrumentationRuntime
: public std::enable_shared_from_this<InstrumentationRuntime>,
public PluginInterface {
/// The instrumented process.
lldb::ProcessWP m_process_wp;
/// The module containing the instrumentation runtime.
lldb::ModuleSP m_runtime_module;
/// The breakpoint in the instrumentation runtime.
lldb::user_id_t m_breakpoint_id;
/// Indicates whether or not breakpoints have been registered in the
/// instrumentation runtime.
bool m_is_active;
protected:
InstrumentationRuntime(const lldb::ProcessSP &process_sp)
: m_process_wp(), m_runtime_module(), m_breakpoint_id(0),
m_is_active(false) {
if (process_sp)
m_process_wp = process_sp;
}
lldb::ProcessSP GetProcessSP() { return m_process_wp.lock(); }
lldb::ModuleSP GetRuntimeModuleSP() { return m_runtime_module; }
void SetRuntimeModuleSP(lldb::ModuleSP module_sp) {
m_runtime_module = std::move(module_sp);
}
lldb::user_id_t GetBreakpointID() const { return m_breakpoint_id; }
void SetBreakpointID(lldb::user_id_t ID) { m_breakpoint_id = ID; }
void SetActive(bool IsActive) { m_is_active = IsActive; }
/// Return a regular expression which can be used to identify a valid version
/// of the runtime library.
virtual const RegularExpression &GetPatternForRuntimeLibrary() = 0;
/// Check whether \p module_sp corresponds to a valid runtime library.
virtual bool CheckIfRuntimeIsValid(const lldb::ModuleSP module_sp) = 0;
/// Register a breakpoint in the runtime library and perform any other
/// necessary initialization. The runtime library
/// is guaranteed to be loaded.
virtual void Activate() = 0;
public:
static void ModulesDidLoad(lldb_private::ModuleList &module_list,
Process *process,
InstrumentationRuntimeCollection &runtimes);
/// Look for the instrumentation runtime in \p module_list. Register and
/// activate the runtime if this hasn't already
/// been done.
void ModulesDidLoad(lldb_private::ModuleList &module_list);
bool IsActive() const { return m_is_active; }
virtual lldb::ThreadCollectionSP
GetBacktracesFromExtendedStopInfo(StructuredData::ObjectSP info);
};
} // namespace lldb_private
#endif // LLDB_TARGET_INSTRUMENTATIONRUNTIME_H
| 0 | 0.927146 | 1 | 0.927146 | game-dev | MEDIA | 0.400447 | game-dev | 0.730394 | 1 | 0.730394 |
golangpoland/meetup_golang_warsaw | 44,807 | 2019/2019_22_Meetup/Intro/plugin/css/reveal.scss | /*!
* reveal.js
* http://revealjs.com
* MIT licensed
*
* Copyright (C) 2018 Hakim El Hattab, http://hakim.se
*/
/*********************************************
* RESET STYLES
*********************************************/
html, body, .reveal div, .reveal span, .reveal applet, .reveal object, .reveal iframe,
.reveal h1, .reveal h2, .reveal h3, .reveal h4, .reveal h5, .reveal h6, .reveal p, .reveal blockquote, .reveal pre,
.reveal a, .reveal abbr, .reveal acronym, .reveal address, .reveal big, .reveal cite, .reveal code,
.reveal del, .reveal dfn, .reveal em, .reveal img, .reveal ins, .reveal kbd, .reveal q, .reveal s, .reveal samp,
.reveal small, .reveal strike, .reveal strong, .reveal sub, .reveal sup, .reveal tt, .reveal var,
.reveal b, .reveal u, .reveal center,
.reveal dl, .reveal dt, .reveal dd, .reveal ol, .reveal ul, .reveal li,
.reveal fieldset, .reveal form, .reveal label, .reveal legend,
.reveal table, .reveal caption, .reveal tbody, .reveal tfoot, .reveal thead, .reveal tr, .reveal th, .reveal td,
.reveal article, .reveal aside, .reveal canvas, .reveal details, .reveal embed,
.reveal figure, .reveal figcaption, .reveal footer, .reveal header, .reveal hgroup,
.reveal menu, .reveal nav, .reveal output, .reveal ruby, .reveal section, .reveal summary,
.reveal time, .reveal mark, .reveal audio, .reveal video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
.reveal article, .reveal aside, .reveal details, .reveal figcaption, .reveal figure,
.reveal footer, .reveal header, .reveal hgroup, .reveal menu, .reveal nav, .reveal section {
display: block;
}
/*********************************************
* GLOBAL STYLES
*********************************************/
html,
body {
width: 100%;
height: 100%;
overflow: hidden;
}
body {
position: relative;
line-height: 1;
background-color: #fff;
color: #000;
}
/*********************************************
* VIEW FRAGMENTS
*********************************************/
.reveal .slides section .fragment {
opacity: 0;
visibility: hidden;
transition: all .2s ease;
&.visible {
opacity: 1;
visibility: inherit;
}
}
.reveal .slides section .fragment.grow {
opacity: 1;
visibility: inherit;
&.visible {
transform: scale( 1.3 );
}
}
.reveal .slides section .fragment.shrink {
opacity: 1;
visibility: inherit;
&.visible {
transform: scale( 0.7 );
}
}
.reveal .slides section .fragment.zoom-in {
transform: scale( 0.1 );
&.visible {
transform: none;
}
}
.reveal .slides section .fragment.fade-out {
opacity: 1;
visibility: inherit;
&.visible {
opacity: 0;
visibility: hidden;
}
}
.reveal .slides section .fragment.semi-fade-out {
opacity: 1;
visibility: inherit;
&.visible {
opacity: 0.5;
visibility: inherit;
}
}
.reveal .slides section .fragment.strike {
opacity: 1;
visibility: inherit;
&.visible {
text-decoration: line-through;
}
}
.reveal .slides section .fragment.fade-up {
transform: translate(0, 20%);
&.visible {
transform: translate(0, 0);
}
}
.reveal .slides section .fragment.fade-down {
transform: translate(0, -20%);
&.visible {
transform: translate(0, 0);
}
}
.reveal .slides section .fragment.fade-right {
transform: translate(-20%, 0);
&.visible {
transform: translate(0, 0);
}
}
.reveal .slides section .fragment.fade-left {
transform: translate(20%, 0);
&.visible {
transform: translate(0, 0);
}
}
.reveal .slides section .fragment.fade-in-then-out,
.reveal .slides section .fragment.current-visible {
opacity: 0;
visibility: hidden;
&.current-fragment {
opacity: 1;
visibility: inherit;
}
}
.reveal .slides section .fragment.fade-in-then-semi-out {
opacity: 0;
visibility: hidden;
&.visible {
opacity: 0.5;
visibility: inherit;
}
&.current-fragment {
opacity: 1;
visibility: inherit;
}
}
.reveal .slides section .fragment.highlight-red,
.reveal .slides section .fragment.highlight-current-red,
.reveal .slides section .fragment.highlight-green,
.reveal .slides section .fragment.highlight-current-green,
.reveal .slides section .fragment.highlight-blue,
.reveal .slides section .fragment.highlight-current-blue {
opacity: 1;
visibility: inherit;
}
.reveal .slides section .fragment.highlight-red.visible {
color: #ff2c2d
}
.reveal .slides section .fragment.highlight-green.visible {
color: #17ff2e;
}
.reveal .slides section .fragment.highlight-blue.visible {
color: #1b91ff;
}
.reveal .slides section .fragment.highlight-current-red.current-fragment {
color: #ff2c2d
}
.reveal .slides section .fragment.highlight-current-green.current-fragment {
color: #17ff2e;
}
.reveal .slides section .fragment.highlight-current-blue.current-fragment {
color: #1b91ff;
}
/*********************************************
* DEFAULT ELEMENT STYLES
*********************************************/
/* Fixes issue in Chrome where italic fonts did not appear when printing to PDF */
.reveal:after {
content: '';
font-style: italic;
}
.reveal iframe {
z-index: 1;
}
/** Prevents layering issues in certain browser/transition combinations */
.reveal a {
position: relative;
}
.reveal .stretch {
max-width: none;
max-height: none;
}
.reveal pre.stretch code {
height: 100%;
max-height: 100%;
box-sizing: border-box;
}
/*********************************************
* CONTROLS
*********************************************/
@keyframes bounce-right {
0%, 10%, 25%, 40%, 50% {transform: translateX(0);}
20% {transform: translateX(10px);}
30% {transform: translateX(-5px);}
}
@keyframes bounce-down {
0%, 10%, 25%, 40%, 50% {transform: translateY(0);}
20% {transform: translateY(10px);}
30% {transform: translateY(-5px);}
}
$controlArrowSize: 3.6em;
$controlArrowSpacing: 1.4em;
$controlArrowLength: 2.6em;
$controlArrowThickness: 0.5em;
$controlsArrowAngle: 45deg;
$controlsArrowAngleHover: 40deg;
$controlsArrowAngleActive: 36deg;
@mixin controlsArrowTransform( $angle ) {
&:before {
transform: translateX(($controlArrowSize - $controlArrowLength)/2) translateY(($controlArrowSize - $controlArrowThickness)/2) rotate( $angle );
}
&:after {
transform: translateX(($controlArrowSize - $controlArrowLength)/2) translateY(($controlArrowSize - $controlArrowThickness)/2) rotate( -$angle );
}
}
.reveal .controls {
$spacing: 12px;
display: none;
position: absolute;
top: auto;
bottom: $spacing;
right: $spacing;
left: auto;
z-index: 1;
color: #000;
pointer-events: none;
font-size: 10px;
button {
position: absolute;
padding: 0;
background-color: transparent;
border: 0;
outline: 0;
cursor: pointer;
color: currentColor;
transform: scale(.9999);
transition: color 0.2s ease,
opacity 0.2s ease,
transform 0.2s ease;
z-index: 2; // above slides
pointer-events: auto;
font-size: inherit;
visibility: hidden;
opacity: 0;
-webkit-appearance: none;
-webkit-tap-highlight-color: rgba( 0, 0, 0, 0 );
}
.controls-arrow:before,
.controls-arrow:after {
content: '';
position: absolute;
top: 0;
left: 0;
width: $controlArrowLength;
height: $controlArrowThickness;
border-radius: $controlArrowThickness/2;
background-color: currentColor;
transition: all 0.15s ease, background-color 0.8s ease;
transform-origin: floor(($controlArrowThickness/2)*10)/10 50%;
will-change: transform;
}
.controls-arrow {
position: relative;
width: $controlArrowSize;
height: $controlArrowSize;
@include controlsArrowTransform( $controlsArrowAngle );
&:hover {
@include controlsArrowTransform( $controlsArrowAngleHover );
}
&:active {
@include controlsArrowTransform( $controlsArrowAngleActive );
}
}
.navigate-left {
right: $controlArrowSize + $controlArrowSpacing*2;
bottom: $controlArrowSpacing + $controlArrowSize/2;
transform: translateX( -10px );
}
.navigate-right {
right: 0;
bottom: $controlArrowSpacing + $controlArrowSize/2;
transform: translateX( 10px );
.controls-arrow {
transform: rotate( 180deg );
}
&.highlight {
animation: bounce-right 2s 50 both ease-out;
}
}
.navigate-up {
right: $controlArrowSpacing + $controlArrowSize/2;
bottom: $controlArrowSpacing*2 + $controlArrowSize;
transform: translateY( -10px );
.controls-arrow {
transform: rotate( 90deg );
}
}
.navigate-down {
right: $controlArrowSpacing + $controlArrowSize/2;
bottom: 0;
transform: translateY( 10px );
.controls-arrow {
transform: rotate( -90deg );
}
&.highlight {
animation: bounce-down 2s 50 both ease-out;
}
}
// Back arrow style: "faded":
// Deemphasize backwards navigation arrows in favor of drawing
// attention to forwards navigation
&[data-controls-back-arrows="faded"] .navigate-left.enabled,
&[data-controls-back-arrows="faded"] .navigate-up.enabled {
opacity: 0.3;
&:hover {
opacity: 1;
}
}
// Back arrow style: "hidden":
// Never show arrows for backwards navigation
&[data-controls-back-arrows="hidden"] .navigate-left.enabled,
&[data-controls-back-arrows="hidden"] .navigate-up.enabled {
opacity: 0;
visibility: hidden;
}
// Any control button that can be clicked is "enabled"
.enabled {
visibility: visible;
opacity: 0.9;
cursor: pointer;
transform: none;
}
// Any control button that leads to showing or hiding
// a fragment
.enabled.fragmented {
opacity: 0.5;
}
.enabled:hover,
.enabled.fragmented:hover {
opacity: 1;
}
}
// Adjust the layout when there are no vertical slides
.reveal:not(.has-vertical-slides) .controls .navigate-left {
bottom: $controlArrowSpacing;
right: 0.5em + $controlArrowSpacing + $controlArrowSize;
}
.reveal:not(.has-vertical-slides) .controls .navigate-right {
bottom: $controlArrowSpacing;
right: 0.5em;
}
// Adjust the layout when there are no horizontal slides
.reveal:not(.has-horizontal-slides) .controls .navigate-up {
right: $controlArrowSpacing;
bottom: $controlArrowSpacing + $controlArrowSize;
}
.reveal:not(.has-horizontal-slides) .controls .navigate-down {
right: $controlArrowSpacing;
bottom: 0.5em;
}
// Invert arrows based on background color
.reveal.has-dark-background .controls {
color: #fff;
}
.reveal.has-light-background .controls {
color: #000;
}
// Disable active states on touch devices
.reveal.no-hover .controls .controls-arrow:hover,
.reveal.no-hover .controls .controls-arrow:active {
@include controlsArrowTransform( $controlsArrowAngle );
}
// Edge aligned controls layout
@media screen and (min-width: 500px) {
$spacing: 8px;
.reveal .controls[data-controls-layout="edges"] {
& {
top: 0;
right: 0;
bottom: 0;
left: 0;
}
.navigate-left,
.navigate-right,
.navigate-up,
.navigate-down {
bottom: auto;
right: auto;
}
.navigate-left {
top: 50%;
left: $spacing;
margin-top: -$controlArrowSize/2;
}
.navigate-right {
top: 50%;
right: $spacing;
margin-top: -$controlArrowSize/2;
}
.navigate-up {
top: $spacing;
left: 50%;
margin-left: -$controlArrowSize/2;
}
.navigate-down {
bottom: $spacing;
left: 50%;
margin-left: -$controlArrowSize/2;
}
}
}
/*********************************************
* PROGRESS BAR
*********************************************/
.reveal .progress {
position: absolute;
display: none;
height: 3px;
width: 100%;
bottom: 0;
left: 0;
z-index: 10;
background-color: rgba( 0, 0, 0, 0.2 );
color: #fff;
}
.reveal .progress:after {
content: '';
display: block;
position: absolute;
height: 10px;
width: 100%;
top: -10px;
}
.reveal .progress span {
display: block;
height: 100%;
width: 0px;
background-color: currentColor;
transition: width 800ms cubic-bezier(0.260, 0.860, 0.440, 0.985);
}
/*********************************************
* SLIDE NUMBER
*********************************************/
.reveal .slide-number {
position: absolute;
display: block;
right: 8px;
bottom: 8px;
z-index: 31;
font-family: Helvetica, sans-serif;
font-size: 12px;
line-height: 1;
color: #fff;
background-color: rgba( 0, 0, 0, 0.4 );
padding: 5px;
}
.reveal .slide-number a {
color: currentColor;
}
.reveal .slide-number-delimiter {
margin: 0 3px;
}
/*********************************************
* SLIDES
*********************************************/
.reveal {
position: relative;
width: 100%;
height: 100%;
overflow: hidden;
touch-action: none;
}
// Mobile Safari sometimes overlays a header at the top
// of the page when in landscape mode. Using fixed
// positioning ensures that reveal.js reduces its height
// when this header is visible.
@media only screen and (orientation : landscape) {
.reveal.ua-iphone {
position: fixed;
}
}
.reveal .slides {
position: absolute;
width: 100%;
height: 100%;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
pointer-events: none;
overflow: visible;
z-index: 1;
text-align: center;
perspective: 600px;
perspective-origin: 50% 40%;
}
.reveal .slides>section {
-ms-perspective: 600px;
}
.reveal .slides>section,
.reveal .slides>section>section {
display: none;
position: absolute;
width: 100%;
padding: 20px 0px;
pointer-events: auto;
z-index: 10;
transform-style: flat;
transition: transform-origin 800ms cubic-bezier(0.260, 0.860, 0.440, 0.985),
transform 800ms cubic-bezier(0.260, 0.860, 0.440, 0.985),
visibility 800ms cubic-bezier(0.260, 0.860, 0.440, 0.985),
opacity 800ms cubic-bezier(0.260, 0.860, 0.440, 0.985);
}
/* Global transition speed settings */
.reveal[data-transition-speed="fast"] .slides section {
transition-duration: 400ms;
}
.reveal[data-transition-speed="slow"] .slides section {
transition-duration: 1200ms;
}
/* Slide-specific transition speed overrides */
.reveal .slides section[data-transition-speed="fast"] {
transition-duration: 400ms;
}
.reveal .slides section[data-transition-speed="slow"] {
transition-duration: 1200ms;
}
.reveal .slides>section.stack {
padding-top: 0;
padding-bottom: 0;
pointer-events: none;
}
.reveal .slides>section.present,
.reveal .slides>section>section.present {
display: block;
z-index: 11;
opacity: 1;
}
.reveal .slides>section:empty,
.reveal .slides>section>section:empty,
.reveal .slides>section[data-background-interactive],
.reveal .slides>section>section[data-background-interactive] {
pointer-events: none;
}
.reveal.center,
.reveal.center .slides,
.reveal.center .slides section {
min-height: 0 !important;
}
/* Don't allow interaction with invisible slides */
.reveal .slides>section.future,
.reveal .slides>section>section.future,
.reveal .slides>section.past,
.reveal .slides>section>section.past {
pointer-events: none;
}
.reveal.overview .slides>section,
.reveal.overview .slides>section>section {
pointer-events: auto;
}
.reveal .slides>section.past,
.reveal .slides>section.future,
.reveal .slides>section>section.past,
.reveal .slides>section>section.future {
opacity: 0;
}
/*********************************************
* Mixins for readability of transitions
*********************************************/
@mixin transition-global($style) {
.reveal .slides section[data-transition=#{$style}],
.reveal.#{$style} .slides section:not([data-transition]) {
@content;
}
}
@mixin transition-stack($style) {
.reveal .slides section[data-transition=#{$style}].stack,
.reveal.#{$style} .slides section.stack {
@content;
}
}
@mixin transition-horizontal-past($style) {
.reveal .slides>section[data-transition=#{$style}].past,
.reveal .slides>section[data-transition~=#{$style}-out].past,
.reveal.#{$style} .slides>section:not([data-transition]).past {
@content;
}
}
@mixin transition-horizontal-future($style) {
.reveal .slides>section[data-transition=#{$style}].future,
.reveal .slides>section[data-transition~=#{$style}-in].future,
.reveal.#{$style} .slides>section:not([data-transition]).future {
@content;
}
}
@mixin transition-vertical-past($style) {
.reveal .slides>section>section[data-transition=#{$style}].past,
.reveal .slides>section>section[data-transition~=#{$style}-out].past,
.reveal.#{$style} .slides>section>section:not([data-transition]).past {
@content;
}
}
@mixin transition-vertical-future($style) {
.reveal .slides>section>section[data-transition=#{$style}].future,
.reveal .slides>section>section[data-transition~=#{$style}-in].future,
.reveal.#{$style} .slides>section>section:not([data-transition]).future {
@content;
}
}
/*********************************************
* SLIDE TRANSITION
* Aliased 'linear' for backwards compatibility
*********************************************/
@each $stylename in slide, linear {
.reveal.#{$stylename} section {
backface-visibility: hidden;
}
@include transition-horizontal-past(#{$stylename}) {
transform: translate(-150%, 0);
}
@include transition-horizontal-future(#{$stylename}) {
transform: translate(150%, 0);
}
@include transition-vertical-past(#{$stylename}) {
transform: translate(0, -150%);
}
@include transition-vertical-future(#{$stylename}) {
transform: translate(0, 150%);
}
}
/*********************************************
* CONVEX TRANSITION
* Aliased 'default' for backwards compatibility
*********************************************/
@each $stylename in default, convex {
@include transition-stack(#{$stylename}) {
transform-style: preserve-3d;
}
@include transition-horizontal-past(#{$stylename}) {
transform: translate3d(-100%, 0, 0) rotateY(-90deg) translate3d(-100%, 0, 0);
}
@include transition-horizontal-future(#{$stylename}) {
transform: translate3d(100%, 0, 0) rotateY(90deg) translate3d(100%, 0, 0);
}
@include transition-vertical-past(#{$stylename}) {
transform: translate3d(0, -300px, 0) rotateX(70deg) translate3d(0, -300px, 0);
}
@include transition-vertical-future(#{$stylename}) {
transform: translate3d(0, 300px, 0) rotateX(-70deg) translate3d(0, 300px, 0);
}
}
/*********************************************
* CONCAVE TRANSITION
*********************************************/
@include transition-stack(concave) {
transform-style: preserve-3d;
}
@include transition-horizontal-past(concave) {
transform: translate3d(-100%, 0, 0) rotateY(90deg) translate3d(-100%, 0, 0);
}
@include transition-horizontal-future(concave) {
transform: translate3d(100%, 0, 0) rotateY(-90deg) translate3d(100%, 0, 0);
}
@include transition-vertical-past(concave) {
transform: translate3d(0, -80%, 0) rotateX(-70deg) translate3d(0, -80%, 0);
}
@include transition-vertical-future(concave) {
transform: translate3d(0, 80%, 0) rotateX(70deg) translate3d(0, 80%, 0);
}
/*********************************************
* ZOOM TRANSITION
*********************************************/
@include transition-global(zoom) {
transition-timing-function: ease;
}
@include transition-horizontal-past(zoom) {
visibility: hidden;
transform: scale(16);
}
@include transition-horizontal-future(zoom) {
visibility: hidden;
transform: scale(0.2);
}
@include transition-vertical-past(zoom) {
transform: translate(0, -150%);
}
@include transition-vertical-future(zoom) {
transform: translate(0, 150%);
}
/*********************************************
* CUBE TRANSITION
*
* WARNING:
* this is deprecated and will be removed in a
* future version.
*********************************************/
.reveal.cube .slides {
perspective: 1300px;
}
.reveal.cube .slides section {
padding: 30px;
min-height: 700px;
backface-visibility: hidden;
box-sizing: border-box;
transform-style: preserve-3d;
}
.reveal.center.cube .slides section {
min-height: 0;
}
.reveal.cube .slides section:not(.stack):before {
content: '';
position: absolute;
display: block;
width: 100%;
height: 100%;
left: 0;
top: 0;
background: rgba(0,0,0,0.1);
border-radius: 4px;
transform: translateZ( -20px );
}
.reveal.cube .slides section:not(.stack):after {
content: '';
position: absolute;
display: block;
width: 90%;
height: 30px;
left: 5%;
bottom: 0;
background: none;
z-index: 1;
border-radius: 4px;
box-shadow: 0px 95px 25px rgba(0,0,0,0.2);
transform: translateZ(-90px) rotateX( 65deg );
}
.reveal.cube .slides>section.stack {
padding: 0;
background: none;
}
.reveal.cube .slides>section.past {
transform-origin: 100% 0%;
transform: translate3d(-100%, 0, 0) rotateY(-90deg);
}
.reveal.cube .slides>section.future {
transform-origin: 0% 0%;
transform: translate3d(100%, 0, 0) rotateY(90deg);
}
.reveal.cube .slides>section>section.past {
transform-origin: 0% 100%;
transform: translate3d(0, -100%, 0) rotateX(90deg);
}
.reveal.cube .slides>section>section.future {
transform-origin: 0% 0%;
transform: translate3d(0, 100%, 0) rotateX(-90deg);
}
/*********************************************
* PAGE TRANSITION
*
* WARNING:
* this is deprecated and will be removed in a
* future version.
*********************************************/
.reveal.page .slides {
perspective-origin: 0% 50%;
perspective: 3000px;
}
.reveal.page .slides section {
padding: 30px;
min-height: 700px;
box-sizing: border-box;
transform-style: preserve-3d;
}
.reveal.page .slides section.past {
z-index: 12;
}
.reveal.page .slides section:not(.stack):before {
content: '';
position: absolute;
display: block;
width: 100%;
height: 100%;
left: 0;
top: 0;
background: rgba(0,0,0,0.1);
transform: translateZ( -20px );
}
.reveal.page .slides section:not(.stack):after {
content: '';
position: absolute;
display: block;
width: 90%;
height: 30px;
left: 5%;
bottom: 0;
background: none;
z-index: 1;
border-radius: 4px;
box-shadow: 0px 95px 25px rgba(0,0,0,0.2);
-webkit-transform: translateZ(-90px) rotateX( 65deg );
}
.reveal.page .slides>section.stack {
padding: 0;
background: none;
}
.reveal.page .slides>section.past {
transform-origin: 0% 0%;
transform: translate3d(-40%, 0, 0) rotateY(-80deg);
}
.reveal.page .slides>section.future {
transform-origin: 100% 0%;
transform: translate3d(0, 0, 0);
}
.reveal.page .slides>section>section.past {
transform-origin: 0% 0%;
transform: translate3d(0, -40%, 0) rotateX(80deg);
}
.reveal.page .slides>section>section.future {
transform-origin: 0% 100%;
transform: translate3d(0, 0, 0);
}
/*********************************************
* FADE TRANSITION
*********************************************/
.reveal .slides section[data-transition=fade],
.reveal.fade .slides section:not([data-transition]),
.reveal.fade .slides>section>section:not([data-transition]) {
transform: none;
transition: opacity 0.5s;
}
.reveal.fade.overview .slides section,
.reveal.fade.overview .slides>section>section {
transition: none;
}
/*********************************************
* NO TRANSITION
*********************************************/
@include transition-global(none) {
transform: none;
transition: none;
}
/*********************************************
* PAUSED MODE
*********************************************/
.reveal .pause-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: black;
visibility: hidden;
opacity: 0;
z-index: 100;
transition: all 1s ease;
}
.reveal .pause-overlay .resume-button {
position: absolute;
bottom: 20px;
right: 20px;
color: #ccc;
border-radius: 2px;
padding: 6px 14px;
border: 2px solid #ccc;
font-size: 16px;
background: transparent;
cursor: pointer;
&:hover {
color: #fff;
border-color: #fff;
}
}
.reveal.paused .pause-overlay {
visibility: visible;
opacity: 1;
}
/*********************************************
* FALLBACK
*********************************************/
.no-transforms {
overflow-y: auto;
}
.no-transforms .reveal .slides {
position: relative;
width: 80%;
height: auto !important;
top: 0;
left: 50%;
margin: 0;
text-align: center;
}
.no-transforms .reveal .controls,
.no-transforms .reveal .progress {
display: none !important;
}
.no-transforms .reveal .slides section {
display: block !important;
opacity: 1 !important;
position: relative !important;
height: auto;
min-height: 0;
top: 0;
left: -50%;
margin: 70px 0;
transform: none;
}
.no-transforms .reveal .slides section section {
left: 0;
}
.reveal .no-transition,
.reveal .no-transition * {
transition: none !important;
}
/*********************************************
* PER-SLIDE BACKGROUNDS
*********************************************/
.reveal .backgrounds {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
perspective: 600px;
}
.reveal .slide-background {
display: none;
position: absolute;
width: 100%;
height: 100%;
opacity: 0;
visibility: hidden;
overflow: hidden;
background-color: rgba( 0, 0, 0, 0 );
transition: all 800ms cubic-bezier(0.260, 0.860, 0.440, 0.985);
}
.reveal .slide-background-content {
position: absolute;
width: 100%;
height: 100%;
background-position: 50% 50%;
background-repeat: no-repeat;
background-size: cover;
}
.reveal .slide-background.stack {
display: block;
}
.reveal .slide-background.present {
opacity: 1;
visibility: visible;
z-index: 2;
}
.print-pdf .reveal .slide-background {
opacity: 1 !important;
visibility: visible !important;
}
/* Video backgrounds */
.reveal .slide-background video {
position: absolute;
width: 100%;
height: 100%;
max-width: none;
max-height: none;
top: 0;
left: 0;
object-fit: cover;
}
.reveal .slide-background[data-background-size="contain"] video {
object-fit: contain;
}
/* Immediate transition style */
.reveal[data-background-transition=none]>.backgrounds .slide-background,
.reveal>.backgrounds .slide-background[data-background-transition=none] {
transition: none;
}
/* Slide */
.reveal[data-background-transition=slide]>.backgrounds .slide-background,
.reveal>.backgrounds .slide-background[data-background-transition=slide] {
opacity: 1;
backface-visibility: hidden;
}
.reveal[data-background-transition=slide]>.backgrounds .slide-background.past,
.reveal>.backgrounds .slide-background.past[data-background-transition=slide] {
transform: translate(-100%, 0);
}
.reveal[data-background-transition=slide]>.backgrounds .slide-background.future,
.reveal>.backgrounds .slide-background.future[data-background-transition=slide] {
transform: translate(100%, 0);
}
.reveal[data-background-transition=slide]>.backgrounds .slide-background>.slide-background.past,
.reveal>.backgrounds .slide-background>.slide-background.past[data-background-transition=slide] {
transform: translate(0, -100%);
}
.reveal[data-background-transition=slide]>.backgrounds .slide-background>.slide-background.future,
.reveal>.backgrounds .slide-background>.slide-background.future[data-background-transition=slide] {
transform: translate(0, 100%);
}
/* Convex */
.reveal[data-background-transition=convex]>.backgrounds .slide-background.past,
.reveal>.backgrounds .slide-background.past[data-background-transition=convex] {
opacity: 0;
transform: translate3d(-100%, 0, 0) rotateY(-90deg) translate3d(-100%, 0, 0);
}
.reveal[data-background-transition=convex]>.backgrounds .slide-background.future,
.reveal>.backgrounds .slide-background.future[data-background-transition=convex] {
opacity: 0;
transform: translate3d(100%, 0, 0) rotateY(90deg) translate3d(100%, 0, 0);
}
.reveal[data-background-transition=convex]>.backgrounds .slide-background>.slide-background.past,
.reveal>.backgrounds .slide-background>.slide-background.past[data-background-transition=convex] {
opacity: 0;
transform: translate3d(0, -100%, 0) rotateX(90deg) translate3d(0, -100%, 0);
}
.reveal[data-background-transition=convex]>.backgrounds .slide-background>.slide-background.future,
.reveal>.backgrounds .slide-background>.slide-background.future[data-background-transition=convex] {
opacity: 0;
transform: translate3d(0, 100%, 0) rotateX(-90deg) translate3d(0, 100%, 0);
}
/* Concave */
.reveal[data-background-transition=concave]>.backgrounds .slide-background.past,
.reveal>.backgrounds .slide-background.past[data-background-transition=concave] {
opacity: 0;
transform: translate3d(-100%, 0, 0) rotateY(90deg) translate3d(-100%, 0, 0);
}
.reveal[data-background-transition=concave]>.backgrounds .slide-background.future,
.reveal>.backgrounds .slide-background.future[data-background-transition=concave] {
opacity: 0;
transform: translate3d(100%, 0, 0) rotateY(-90deg) translate3d(100%, 0, 0);
}
.reveal[data-background-transition=concave]>.backgrounds .slide-background>.slide-background.past,
.reveal>.backgrounds .slide-background>.slide-background.past[data-background-transition=concave] {
opacity: 0;
transform: translate3d(0, -100%, 0) rotateX(-90deg) translate3d(0, -100%, 0);
}
.reveal[data-background-transition=concave]>.backgrounds .slide-background>.slide-background.future,
.reveal>.backgrounds .slide-background>.slide-background.future[data-background-transition=concave] {
opacity: 0;
transform: translate3d(0, 100%, 0) rotateX(90deg) translate3d(0, 100%, 0);
}
/* Zoom */
.reveal[data-background-transition=zoom]>.backgrounds .slide-background,
.reveal>.backgrounds .slide-background[data-background-transition=zoom] {
transition-timing-function: ease;
}
.reveal[data-background-transition=zoom]>.backgrounds .slide-background.past,
.reveal>.backgrounds .slide-background.past[data-background-transition=zoom] {
opacity: 0;
visibility: hidden;
transform: scale(16);
}
.reveal[data-background-transition=zoom]>.backgrounds .slide-background.future,
.reveal>.backgrounds .slide-background.future[data-background-transition=zoom] {
opacity: 0;
visibility: hidden;
transform: scale(0.2);
}
.reveal[data-background-transition=zoom]>.backgrounds .slide-background>.slide-background.past,
.reveal>.backgrounds .slide-background>.slide-background.past[data-background-transition=zoom] {
opacity: 0;
visibility: hidden;
transform: scale(16);
}
.reveal[data-background-transition=zoom]>.backgrounds .slide-background>.slide-background.future,
.reveal>.backgrounds .slide-background>.slide-background.future[data-background-transition=zoom] {
opacity: 0;
visibility: hidden;
transform: scale(0.2);
}
/* Global transition speed settings */
.reveal[data-transition-speed="fast"]>.backgrounds .slide-background {
transition-duration: 400ms;
}
.reveal[data-transition-speed="slow"]>.backgrounds .slide-background {
transition-duration: 1200ms;
}
/*********************************************
* OVERVIEW
*********************************************/
.reveal.overview {
perspective-origin: 50% 50%;
perspective: 700px;
.slides {
// Fixes overview rendering errors in FF48+, not applied to
// other browsers since it degrades performance
-moz-transform-style: preserve-3d;
}
.slides section {
height: 100%;
top: 0 !important;
opacity: 1 !important;
overflow: hidden;
visibility: visible !important;
cursor: pointer;
box-sizing: border-box;
}
.slides section:hover,
.slides section.present {
outline: 10px solid rgba(150,150,150,0.4);
outline-offset: 10px;
}
.slides section .fragment {
opacity: 1;
transition: none;
}
.slides section:after,
.slides section:before {
display: none !important;
}
.slides>section.stack {
padding: 0;
top: 0 !important;
background: none;
outline: none;
overflow: visible;
}
.backgrounds {
perspective: inherit;
// Fixes overview rendering errors in FF48+, not applied to
// other browsers since it degrades performance
-moz-transform-style: preserve-3d;
}
.backgrounds .slide-background {
opacity: 1;
visibility: visible;
// This can't be applied to the slide itself in Safari
outline: 10px solid rgba(150,150,150,0.1);
outline-offset: 10px;
}
.backgrounds .slide-background.stack {
overflow: visible;
}
}
// Disable transitions transitions while we're activating
// or deactivating the overview mode.
.reveal.overview .slides section,
.reveal.overview-deactivating .slides section {
transition: none;
}
.reveal.overview .backgrounds .slide-background,
.reveal.overview-deactivating .backgrounds .slide-background {
transition: none;
}
/*********************************************
* RTL SUPPORT
*********************************************/
.reveal.rtl .slides,
.reveal.rtl .slides h1,
.reveal.rtl .slides h2,
.reveal.rtl .slides h3,
.reveal.rtl .slides h4,
.reveal.rtl .slides h5,
.reveal.rtl .slides h6 {
direction: rtl;
font-family: sans-serif;
}
.reveal.rtl pre,
.reveal.rtl code {
direction: ltr;
}
.reveal.rtl ol,
.reveal.rtl ul {
text-align: right;
}
.reveal.rtl .progress span {
float: right
}
/*********************************************
* PARALLAX BACKGROUND
*********************************************/
.reveal.has-parallax-background .backgrounds {
transition: all 0.8s ease;
}
/* Global transition speed settings */
.reveal.has-parallax-background[data-transition-speed="fast"] .backgrounds {
transition-duration: 400ms;
}
.reveal.has-parallax-background[data-transition-speed="slow"] .backgrounds {
transition-duration: 1200ms;
}
/*********************************************
* LINK PREVIEW OVERLAY
*********************************************/
.reveal .overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 1000;
background: rgba( 0, 0, 0, 0.9 );
opacity: 0;
visibility: hidden;
transition: all 0.3s ease;
}
.reveal .overlay.visible {
opacity: 1;
visibility: visible;
}
.reveal .overlay .spinner {
position: absolute;
display: block;
top: 50%;
left: 50%;
width: 32px;
height: 32px;
margin: -16px 0 0 -16px;
z-index: 10;
background-image: url(data:image/gif;base64,R0lGODlhIAAgAPMAAJmZmf%2F%2F%2F6%2Bvr8nJybW1tcDAwOjo6Nvb26ioqKOjo7Ozs%2FLy8vz8%2FAAAAAAAAAAAACH%2FC05FVFNDQVBFMi4wAwEAAAAh%2FhpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh%2BQQJCgAAACwAAAAAIAAgAAAE5xDISWlhperN52JLhSSdRgwVo1ICQZRUsiwHpTJT4iowNS8vyW2icCF6k8HMMBkCEDskxTBDAZwuAkkqIfxIQyhBQBFvAQSDITM5VDW6XNE4KagNh6Bgwe60smQUB3d4Rz1ZBApnFASDd0hihh12BkE9kjAJVlycXIg7CQIFA6SlnJ87paqbSKiKoqusnbMdmDC2tXQlkUhziYtyWTxIfy6BE8WJt5YJvpJivxNaGmLHT0VnOgSYf0dZXS7APdpB309RnHOG5gDqXGLDaC457D1zZ%2FV%2FnmOM82XiHRLYKhKP1oZmADdEAAAh%2BQQJCgAAACwAAAAAIAAgAAAE6hDISWlZpOrNp1lGNRSdRpDUolIGw5RUYhhHukqFu8DsrEyqnWThGvAmhVlteBvojpTDDBUEIFwMFBRAmBkSgOrBFZogCASwBDEY%2FCZSg7GSE0gSCjQBMVG023xWBhklAnoEdhQEfyNqMIcKjhRsjEdnezB%2BA4k8gTwJhFuiW4dokXiloUepBAp5qaKpp6%2BHo7aWW54wl7obvEe0kRuoplCGepwSx2jJvqHEmGt6whJpGpfJCHmOoNHKaHx61WiSR92E4lbFoq%2BB6QDtuetcaBPnW6%2BO7wDHpIiK9SaVK5GgV543tzjgGcghAgAh%2BQQJCgAAACwAAAAAIAAgAAAE7hDISSkxpOrN5zFHNWRdhSiVoVLHspRUMoyUakyEe8PTPCATW9A14E0UvuAKMNAZKYUZCiBMuBakSQKG8G2FzUWox2AUtAQFcBKlVQoLgQReZhQlCIJesQXI5B0CBnUMOxMCenoCfTCEWBsJColTMANldx15BGs8B5wlCZ9Po6OJkwmRpnqkqnuSrayqfKmqpLajoiW5HJq7FL1Gr2mMMcKUMIiJgIemy7xZtJsTmsM4xHiKv5KMCXqfyUCJEonXPN2rAOIAmsfB3uPoAK%2B%2BG%2Bw48edZPK%2BM6hLJpQg484enXIdQFSS1u6UhksENEQAAIfkECQoAAAAsAAAAACAAIAAABOcQyEmpGKLqzWcZRVUQnZYg1aBSh2GUVEIQ2aQOE%2BG%2BcD4ntpWkZQj1JIiZIogDFFyHI0UxQwFugMSOFIPJftfVAEoZLBbcLEFhlQiqGp1Vd140AUklUN3eCA51C1EWMzMCezCBBmkxVIVHBWd3HHl9JQOIJSdSnJ0TDKChCwUJjoWMPaGqDKannasMo6WnM562R5YluZRwur0wpgqZE7NKUm%2BFNRPIhjBJxKZteWuIBMN4zRMIVIhffcgojwCF117i4nlLnY5ztRLsnOk%2BaV%2BoJY7V7m76PdkS4trKcdg0Zc0tTcKkRAAAIfkECQoAAAAsAAAAACAAIAAABO4QyEkpKqjqzScpRaVkXZWQEximw1BSCUEIlDohrft6cpKCk5xid5MNJTaAIkekKGQkWyKHkvhKsR7ARmitkAYDYRIbUQRQjWBwJRzChi9CRlBcY1UN4g0%2FVNB0AlcvcAYHRyZPdEQFYV8ccwR5HWxEJ02YmRMLnJ1xCYp0Y5idpQuhopmmC2KgojKasUQDk5BNAwwMOh2RtRq5uQuPZKGIJQIGwAwGf6I0JXMpC8C7kXWDBINFMxS4DKMAWVWAGYsAdNqW5uaRxkSKJOZKaU3tPOBZ4DuK2LATgJhkPJMgTwKCdFjyPHEnKxFCDhEAACH5BAkKAAAALAAAAAAgACAAAATzEMhJaVKp6s2nIkolIJ2WkBShpkVRWqqQrhLSEu9MZJKK9y1ZrqYK9WiClmvoUaF8gIQSNeF1Er4MNFn4SRSDARWroAIETg1iVwuHjYB1kYc1mwruwXKC9gmsJXliGxc%2BXiUCby9ydh1sOSdMkpMTBpaXBzsfhoc5l58Gm5yToAaZhaOUqjkDgCWNHAULCwOLaTmzswadEqggQwgHuQsHIoZCHQMMQgQGubVEcxOPFAcMDAYUA85eWARmfSRQCdcMe0zeP1AAygwLlJtPNAAL19DARdPzBOWSm1brJBi45soRAWQAAkrQIykShQ9wVhHCwCQCACH5BAkKAAAALAAAAAAgACAAAATrEMhJaVKp6s2nIkqFZF2VIBWhUsJaTokqUCoBq%2BE71SRQeyqUToLA7VxF0JDyIQh%2FMVVPMt1ECZlfcjZJ9mIKoaTl1MRIl5o4CUKXOwmyrCInCKqcWtvadL2SYhyASyNDJ0uIiRMDjI0Fd30%2FiI2UA5GSS5UDj2l6NoqgOgN4gksEBgYFf0FDqKgHnyZ9OX8HrgYHdHpcHQULXAS2qKpENRg7eAMLC7kTBaixUYFkKAzWAAnLC7FLVxLWDBLKCwaKTULgEwbLA4hJtOkSBNqITT3xEgfLpBtzE%2FjiuL04RGEBgwWhShRgQExHBAAh%2BQQJCgAAACwAAAAAIAAgAAAE7xDISWlSqerNpyJKhWRdlSAVoVLCWk6JKlAqAavhO9UkUHsqlE6CwO1cRdCQ8iEIfzFVTzLdRAmZX3I2SfZiCqGk5dTESJeaOAlClzsJsqwiJwiqnFrb2nS9kmIcgEsjQydLiIlHehhpejaIjzh9eomSjZR%2BipslWIRLAgMDOR2DOqKogTB9pCUJBagDBXR6XB0EBkIIsaRsGGMMAxoDBgYHTKJiUYEGDAzHC9EACcUGkIgFzgwZ0QsSBcXHiQvOwgDdEwfFs0sDzt4S6BK4xYjkDOzn0unFeBzOBijIm1Dgmg5YFQwsCMjp1oJ8LyIAACH5BAkKAAAALAAAAAAgACAAAATwEMhJaVKp6s2nIkqFZF2VIBWhUsJaTokqUCoBq%2BE71SRQeyqUToLA7VxF0JDyIQh%2FMVVPMt1ECZlfcjZJ9mIKoaTl1MRIl5o4CUKXOwmyrCInCKqcWtvadL2SYhyASyNDJ0uIiUd6GGl6NoiPOH16iZKNlH6KmyWFOggHhEEvAwwMA0N9GBsEC6amhnVcEwavDAazGwIDaH1ipaYLBUTCGgQDA8NdHz0FpqgTBwsLqAbWAAnIA4FWKdMLGdYGEgraigbT0OITBcg5QwPT4xLrROZL6AuQAPUS7bxLpoWidY0JtxLHKhwwMJBTHgPKdEQAACH5BAkKAAAALAAAAAAgACAAAATrEMhJaVKp6s2nIkqFZF2VIBWhUsJaTokqUCoBq%2BE71SRQeyqUToLA7VxF0JDyIQh%2FMVVPMt1ECZlfcjZJ9mIKoaTl1MRIl5o4CUKXOwmyrCInCKqcWtvadL2SYhyASyNDJ0uIiUd6GAULDJCRiXo1CpGXDJOUjY%2BYip9DhToJA4RBLwMLCwVDfRgbBAaqqoZ1XBMHswsHtxtFaH1iqaoGNgAIxRpbFAgfPQSqpbgGBqUD1wBXeCYp1AYZ19JJOYgH1KwA4UBvQwXUBxPqVD9L3sbp2BNk2xvvFPJd%2BMFCN6HAAIKgNggY0KtEBAAh%2BQQJCgAAACwAAAAAIAAgAAAE6BDISWlSqerNpyJKhWRdlSAVoVLCWk6JKlAqAavhO9UkUHsqlE6CwO1cRdCQ8iEIfzFVTzLdRAmZX3I2SfYIDMaAFdTESJeaEDAIMxYFqrOUaNW4E4ObYcCXaiBVEgULe0NJaxxtYksjh2NLkZISgDgJhHthkpU4mW6blRiYmZOlh4JWkDqILwUGBnE6TYEbCgevr0N1gH4At7gHiRpFaLNrrq8HNgAJA70AWxQIH1%2BvsYMDAzZQPC9VCNkDWUhGkuE5PxJNwiUK4UfLzOlD4WvzAHaoG9nxPi5d%2BjYUqfAhhykOFwJWiAAAIfkECQoAAAAsAAAAACAAIAAABPAQyElpUqnqzaciSoVkXVUMFaFSwlpOCcMYlErAavhOMnNLNo8KsZsMZItJEIDIFSkLGQoQTNhIsFehRww2CQLKF0tYGKYSg%2BygsZIuNqJksKgbfgIGepNo2cIUB3V1B3IvNiBYNQaDSTtfhhx0CwVPI0UJe0%2Bbm4g5VgcGoqOcnjmjqDSdnhgEoamcsZuXO1aWQy8KAwOAuTYYGwi7w5h%2BKr0SJ8MFihpNbx%2B4Erq7BYBuzsdiH1jCAzoSfl0rVirNbRXlBBlLX%2BBP0XJLAPGzTkAuAOqb0WT5AH7OcdCm5B8TgRwSRKIHQtaLCwg1RAAAOwAAAAAAAAAAAA%3D%3D);
visibility: visible;
opacity: 0.6;
transition: all 0.3s ease;
}
.reveal .overlay header {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 40px;
z-index: 2;
border-bottom: 1px solid #222;
}
.reveal .overlay header a {
display: inline-block;
width: 40px;
height: 40px;
line-height: 36px;
padding: 0 10px;
float: right;
opacity: 0.6;
box-sizing: border-box;
}
.reveal .overlay header a:hover {
opacity: 1;
}
.reveal .overlay header a .icon {
display: inline-block;
width: 20px;
height: 20px;
background-position: 50% 50%;
background-size: 100%;
background-repeat: no-repeat;
}
.reveal .overlay header a.close .icon {
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAABkklEQVRYR8WX4VHDMAxG6wnoJrABZQPYBCaBTWAD2g1gE5gg6OOsXuxIlr40d81dfrSJ9V4c2VLK7spHuTJ/5wpM07QXuXc5X0opX2tEJcadjHuV80li/FgxTIEK/5QBCICBD6xEhSMGHgQPgBgLiYVAB1dpSqKDawxTohFw4JSEA3clzgIBPCURwE2JucBR7rhPJJv5OpJwDX+SfDjgx1wACQeJG1aChP9K/IMmdZ8DtESV1WyP3Bt4MwM6sj4NMxMYiqUWHQu4KYA/SYkIjOsm3BXYWMKFDwU2khjCQ4ELJUJ4SmClRArOCmSXGuKma0fYD5CbzHxFpCSGAhfAVSSUGDUk2BWZaff2g6GE15BsBQ9nwmpIGDiyHQddwNTMKkbZaf9fajXQca1EX44puJZUsnY0ObGmITE3GVLCbEhQUjGVt146j6oasWN+49Vph2w1pZ5EansNZqKBm1txbU57iRRcZ86RWMDdWtBJUHBHwoQPi1GV+JCbntmvok7iTX4/Up9mgyTc/FJYDTcndgH/AA5A/CHsyEkVAAAAAElFTkSuQmCC);
}
.reveal .overlay header a.external .icon {
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAcElEQVRYR+2WSQoAIQwEzf8f7XiOMkUQxUPlGkM3hVmiQfQR9GYnH1SsAQlI4DiBqkCMoNb9y2e90IAEJPAcgdznU9+engMaeJ7Azh5Y1U67gAho4DqBqmB1buAf0MB1AlVBek83ZPkmJMGc1wAR+AAqod/B97TRpQAAAABJRU5ErkJggg==);
}
.reveal .overlay .viewport {
position: absolute;
display: flex;
top: 40px;
right: 0;
bottom: 0;
left: 0;
}
.reveal .overlay.overlay-preview .viewport iframe {
width: 100%;
height: 100%;
max-width: 100%;
max-height: 100%;
border: 0;
opacity: 0;
visibility: hidden;
transition: all 0.3s ease;
}
.reveal .overlay.overlay-preview.loaded .viewport iframe {
opacity: 1;
visibility: visible;
}
.reveal .overlay.overlay-preview.loaded .viewport-inner {
position: absolute;
z-index: -1;
left: 0;
top: 45%;
width: 100%;
text-align: center;
letter-spacing: normal;
}
.reveal .overlay.overlay-preview .x-frame-error {
opacity: 0;
transition: opacity 0.3s ease 0.3s;
}
.reveal .overlay.overlay-preview.loaded .x-frame-error {
opacity: 1;
}
.reveal .overlay.overlay-preview.loaded .spinner {
opacity: 0;
visibility: hidden;
transform: scale(0.2);
}
.reveal .overlay.overlay-help .viewport {
overflow: auto;
color: #fff;
}
.reveal .overlay.overlay-help .viewport .viewport-inner {
width: 600px;
margin: auto;
padding: 20px 20px 80px 20px;
text-align: center;
letter-spacing: normal;
}
.reveal .overlay.overlay-help .viewport .viewport-inner .title {
font-size: 20px;
}
.reveal .overlay.overlay-help .viewport .viewport-inner table {
border: 1px solid #fff;
border-collapse: collapse;
font-size: 16px;
}
.reveal .overlay.overlay-help .viewport .viewport-inner table th,
.reveal .overlay.overlay-help .viewport .viewport-inner table td {
width: 200px;
padding: 14px;
border: 1px solid #fff;
vertical-align: middle;
}
.reveal .overlay.overlay-help .viewport .viewport-inner table th {
padding-top: 20px;
padding-bottom: 20px;
}
/*********************************************
* PLAYBACK COMPONENT
*********************************************/
.reveal .playback {
position: absolute;
left: 15px;
bottom: 20px;
z-index: 30;
cursor: pointer;
transition: all 400ms ease;
-webkit-tap-highlight-color: rgba( 0, 0, 0, 0 );
}
.reveal.overview .playback {
opacity: 0;
visibility: hidden;
}
/*********************************************
* ROLLING LINKS
*********************************************/
.reveal .roll {
display: inline-block;
line-height: 1.2;
overflow: hidden;
vertical-align: top;
perspective: 400px;
perspective-origin: 50% 50%;
}
.reveal .roll:hover {
background: none;
text-shadow: none;
}
.reveal .roll span {
display: block;
position: relative;
padding: 0 2px;
pointer-events: none;
transition: all 400ms ease;
transform-origin: 50% 0%;
transform-style: preserve-3d;
backface-visibility: hidden;
}
.reveal .roll:hover span {
background: rgba(0,0,0,0.5);
transform: translate3d( 0px, 0px, -45px ) rotateX( 90deg );
}
.reveal .roll span:after {
content: attr(data-title);
display: block;
position: absolute;
left: 0;
top: 0;
padding: 0 2px;
backface-visibility: hidden;
transform-origin: 50% 0%;
transform: translate3d( 0px, 110%, 0px ) rotateX( -90deg );
}
/*********************************************
* SPEAKER NOTES
*********************************************/
// Hide on-page notes
.reveal aside.notes {
display: none;
}
// An interface element that can optionally be used to show the
// speaker notes to all viewers, on top of the presentation
.reveal .speaker-notes {
display: none;
position: absolute;
width: 25vw;
height: 100%;
top: 0;
left: 100%;
padding: 14px 18px 14px 18px;
z-index: 1;
font-size: 18px;
line-height: 1.4;
border: 1px solid rgba( 0, 0, 0, 0.05 );
color: #222;
background-color: #f5f5f5;
overflow: auto;
box-sizing: border-box;
text-align: left;
font-family: Helvetica, sans-serif;
-webkit-overflow-scrolling: touch;
.notes-placeholder {
color: #ccc;
font-style: italic;
}
&:focus {
outline: none;
}
&:before {
content: 'Speaker notes';
display: block;
margin-bottom: 10px;
opacity: 0.5;
}
}
.reveal.show-notes {
max-width: 75vw;
overflow: visible;
}
.reveal.show-notes .speaker-notes {
display: block;
}
@media screen and (min-width: 1600px) {
.reveal .speaker-notes {
font-size: 20px;
}
}
@media screen and (max-width: 1024px) {
.reveal.show-notes {
border-left: 0;
max-width: none;
max-height: 70%;
overflow: visible;
}
.reveal.show-notes .speaker-notes {
top: 100%;
left: 0;
width: 100%;
height: (30/0.7)*1%;
}
}
@media screen and (max-width: 600px) {
.reveal.show-notes {
max-height: 60%;
}
.reveal.show-notes .speaker-notes {
top: 100%;
height: (40/0.6)*1%;
}
.reveal .speaker-notes {
font-size: 14px;
}
}
/*********************************************
* ZOOM PLUGIN
*********************************************/
.zoomed .reveal *,
.zoomed .reveal *:before,
.zoomed .reveal *:after {
backface-visibility: visible !important;
}
.zoomed .reveal .progress,
.zoomed .reveal .controls {
opacity: 0;
}
.zoomed .reveal .roll span {
background: none;
}
.zoomed .reveal .roll span:after {
visibility: hidden;
}
| 0 | 0.717567 | 1 | 0.717567 | game-dev | MEDIA | 0.533764 | game-dev | 0.542633 | 1 | 0.542633 |
lightningdevkit/ldk-garbagecollected | 2,679 | src/main/java/org/ldk/structs/MonitorName.java | package org.ldk.structs;
import org.ldk.impl.bindings;
import org.ldk.enums.*;
import org.ldk.util.*;
import java.util.Arrays;
import java.lang.ref.Reference;
import javax.annotation.Nullable;
/**
* A struct representing a name for a channel monitor.
*
* `MonitorName` is primarily used within the [`MonitorUpdatingPersister`]
* in functions that store or retrieve channel monitor snapshots.
* It provides a consistent way to generate a unique key for channel
* monitors based on their funding outpoints.
*
* While users of the Lightning Dev Kit library generally won't need
* to interact with [`MonitorName`] directly, it can be useful for:
* - Custom persistence implementations
* - Debugging or logging channel monitor operations
* - Extending the functionality of the `MonitorUpdatingPersister`
* # Examples
*
* ```
* use std::str::FromStr;
*
* use bitcoin::Txid;
*
* use lightning::util::persist::MonitorName;
* use lightning::chain::transaction::OutPoint;
*
* let outpoint = OutPoint {
* \t txid: Txid::from_str(\"deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef\").unwrap(),
* \t index: 1,
* };
* let monitor_name = MonitorName::from(outpoint);
* assert_eq!(monitor_name.as_str(), \"deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef_1\");
*
* Using MonitorName to generate a storage key
* let storage_key = format!(\"channel_monitors/{}\", monitor_name.as_str());
* ```
*/
@SuppressWarnings("unchecked") // We correctly assign various generic arrays
public class MonitorName extends CommonBase {
MonitorName(Object _dummy, long ptr) { super(ptr); }
@Override @SuppressWarnings("deprecation")
protected void finalize() throws Throwable {
super.finalize();
if (ptr != 0) { bindings.MonitorName_free(ptr); }
}
/**
* Constructs a [`MonitorName`], after verifying that an [`OutPoint`] can
* be formed from the given `name`.
* This method is useful if you have a String and you want to verify that
* it's a valid storage key for a channel monitor.
*/
public static Result_MonitorNameIOErrorZ of(java.lang.String name) {
long ret = bindings.MonitorName_new(name);
Reference.reachabilityFence(name);
if (ret >= 0 && ret <= 4096) { return null; }
Result_MonitorNameIOErrorZ ret_hu_conv = Result_MonitorNameIOErrorZ.constr_from_ptr(ret);
return ret_hu_conv;
}
/**
* Convert this monitor name to a str.
* This method is particularly useful when you need to use the monitor name
* as a key in a key-value store or when logging.
*/
public String as_str() {
String ret = bindings.MonitorName_as_str(this.ptr);
Reference.reachabilityFence(this);
return ret;
}
}
| 0 | 0.955931 | 1 | 0.955931 | game-dev | MEDIA | 0.363729 | game-dev | 0.962261 | 1 | 0.962261 |
mikejsavage/cocainediesel | 19,696 | source/game/g_local.h | /*
Copyright (C) 1997-2001 Id Software, Inc.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#pragma once
#include "qcommon/qcommon.h"
#include "qcommon/hash.h"
#include "gameshared/gs_public.h"
#include "gameshared/gs_weapons.h"
#include "gameshared/collision.h"
#include "game/g_public.h"
#include "game/g_gametypes.h"
#include "game/g_ai.h"
#include "game/g_maps.h"
#include "server/server.h"
//==================================================================
// FIXME: Medar: Remove the spectator test and just make sure they always have health
#define G_IsDead( ent ) ( ( !( ent )->r.client || ( ent )->s.team != Team_None ) && HEALTH_TO_INT( ( ent )->health ) <= 0 )
#define FRAMETIME ( (float)game.frametime * 0.001f )
#define MAX_FLOOD_MESSAGES 32
// deadflag
#define DEAD_NO 0
#define DEAD_DEAD 1
// edict->movetype values
enum movetype_t {
MOVETYPE_NONE, // never moves
MOVETYPE_PLAYER, // never moves (but is moved by pmove)
MOVETYPE_NOCLIP, // like MOVETYPE_PLAYER, but not clipped
MOVETYPE_PUSH, // no clip to world, push on box contact
MOVETYPE_STOP, // no clip to world, stops on box contact
MOVETYPE_TOSS, // gravity
MOVETYPE_LINEARPROJECTILE, // extra size to monsters
MOVETYPE_BOUNCE,
MOVETYPE_BOUNCEGRENADE,
};
#define TIMEOUT_TIME 180000
#define TIMEIN_TIME 5000
struct timeout_t {
int64_t time;
int64_t endtime;
Team caller;
int used[Team_Count];
};
//
// this structure is cleared as each map is entered
//
struct level_locals_t {
int64_t time; // time in milliseconds
Time spawnedTimeStamp; // time when map was restarted
int64_t finalMatchDuration;
char callvote_map[128];
bool canSpawnEntities; // security check to prevent entities being spawned before map entities
bool exitNow;
GametypeDef gametype;
bool ready[MAX_CLIENTS];
edict_t * current_entity; // entity running from G_RunFrame
timeout_t timeout;
};
// spawn_temp_t is only used to hold entity field values that
// can be set from the editor, but aren't actualy present
// in edict_t during gameplay
struct spawn_temp_t {
Span< const char > classname;
int lip;
int distance;
int height;
StringHash noise;
StringHash noise_start;
StringHash noise_stop;
float pausetime;
int gameteam;
int size;
float spawn_probability;
float power;
StringHash weapon;
};
struct score_stats_t {
int kills;
int deaths;
int suicides;
int score;
bool ready;
int total_damage_given;
};
extern gs_state_t server_gs;
extern level_locals_t level;
extern Vec3 knockbackOfDeath;
extern int damageFlagsOfDeath;
extern Cvar *sv_password;
extern Cvar *g_maxvelocity;
extern Cvar *sv_cheats;
extern Cvar *g_floodprotection_messages;
extern Cvar *g_floodprotection_team;
extern Cvar *g_floodprotection_seconds;
extern Cvar *g_floodprotection_penalty;
extern Cvar *g_inactivity_maxtime;
extern Cvar *g_projectile_prestep;
extern Cvar *g_numbots;
extern Cvar *g_maxtimeouts;
extern Cvar *g_antilag_timenudge;
extern Cvar *g_antilag_maxtimedelta;
extern Cvar *g_teams_maxplayers;
extern Cvar *g_teams_allow_uneven;
extern Cvar *g_autorecord;
extern Cvar *g_autorecord_maxdemos;
extern Cvar *g_allow_spectator_voting;
void G_Match_Ready( edict_t * ent );
void G_Match_NotReady( edict_t * ent );
void G_Match_ToggleReady( edict_t * ent );
void G_Match_CheckReadys();
void G_EndMatch();
//
// g_spawnpoints.c
//
void DropSpawnToFloor( edict_t * ent );
const edict_t * SelectSpawnPoint( const edict_t * ent );
void SP_post_match_camera( edict_t * ent, const spawn_temp_t * st );
// g_teams
void G_Teams_Join_Cmd( edict_t * ent, msg_t args );
bool G_Teams_JoinTeam( edict_t * ent, Team team );
void G_Teams_UpdateMembersList();
bool G_Teams_JoinAnyTeam( edict_t * ent, bool silent );
void G_Teams_SetTeam( edict_t * ent, Team team );
u8 PlayersAliveOnTeam( Team team );
void GhostEveryone();
struct RespawnQueues {
struct Queue {
int players[ MAX_CLIENTS ];
size_t n;
};
Queue teams[ Team_Count ];
};
void InitRespawnQueues( RespawnQueues * queues );
void RemovePlayerFromRespawnQueues( RespawnQueues * queues, int player );
void RemoveDisconnectedPlayersFromRespawnQueues( RespawnQueues * queues );
void EnqueueRespawn( RespawnQueues * queues, Team team, int player );
void SpawnTeams( RespawnQueues * queues );
//
// g_func.c
//
void SP_func_rotating( edict_t * ent, const spawn_temp_t * st );
void SP_func_door( edict_t * ent, const spawn_temp_t * st );
void SP_func_train( edict_t * ent, const spawn_temp_t * st );
//
// g_spikes
//
void SP_spike( edict_t * ent, const spawn_temp_t * st );
void SP_spikes( edict_t * ent, const spawn_temp_t * st );
//
// g_shooter
//
void SP_shooter( edict_t * ent, const spawn_temp_t * st );
//
// g_speakers
//
void SP_speaker_wall( edict_t * ent, const spawn_temp_t * st );
//
// g_jumppad
//
void SP_jumppad( edict_t * ent, const spawn_temp_t * st );
//
// g_cinematic
//
void SP_cinematic_mapname( edict_t * ent, const spawn_temp_t * st );
//
// g_cmds.c
//
typedef void ( *gamecommandfunc_t )( edict_t * ent, msg_t args );
bool CheckFlood( edict_t * ent, bool teamonly );
void G_InitGameCommands();
void G_AddCommand( ClientCommandType command, gamecommandfunc_t cmdfunc );
//
// g_utils.c
//
EntityID NewEntity();
void ResetEntityIDSequence();
edict_t * GetEntity( EntityID id );
void KillBox( edict_t * ent, DamageType damage_type, Vec3 knockback );
float LookAtKillerYAW( edict_t * self, edict_t * inflictor, edict_t * attacker );
edict_t * G_Find( edict_t * cursor, const StringHash edict_t::* field, StringHash value );
edict_t * G_PickRandomEnt( const StringHash edict_t::* field, StringHash value );
edict_t * G_PickTarget( StringHash name );
void G_UseTargets( edict_t * ent, edict_t * activator );
void G_SetMovedir( EulerDegrees3 * angles, Vec3 * movedir );
void G_InitMover( edict_t * ent );
void G_InitEdict( edict_t * e );
edict_t * G_Spawn();
void G_FreeEdict( edict_t * e );
void G_AddEvent( edict_t * ent, int event, u64 parm, bool highPriority );
edict_t * G_SpawnEvent( int event, u64 parm, Optional< Vec3 > origin );
void G_CallThink( edict_t * ent );
void G_CallTouch( edict_t * self, edict_t * other, Vec3 normal, SolidBits solid_mask );
void G_CallUse( edict_t * self, edict_t * other, edict_t * activator );
void G_CallStop( edict_t * self );
void G_CallPain( edict_t * ent, edict_t * attacker, float kick, float damage );
void G_CallDie( edict_t * ent, edict_t * inflictor, edict_t * attacker, int assistorNo, DamageType damage_type, int damage );
[[gnu::format( printf, 2, 3 )]] void G_PrintMsg( edict_t * ent, const char * format, ... );
void G_ChatMsg( edict_t * ent, const edict_t * who, bool teamonly, Span< const char > msg );
[[gnu::format( printf, 2, 3 )]] void G_CenterPrintMsg( edict_t * ent, const char * format, ... );
void G_ClearCenterPrint( edict_t * ent );
void G_DebugPrint( const char * format, ... );
edict_t * G_Sound( edict_t * owner, StringHash sound );
edict_t * G_PositionedSound( Vec3 origin, StringHash sound );
void G_GlobalSound( StringHash sound );
void G_LocalSound( edict_t * owner, StringHash sound );
void G_TeleportEffect( edict_t * ent, bool in );
void G_RespawnEffect( edict_t * ent );
void G_CheckGround( edict_t * ent );
void G_ReleaseClientPSEvent( gclient_t *client );
void G_AddPlayerStateEvent( gclient_t *client, int event, u64 parm );
void G_ClearPlayerStateEvents( gclient_t *client );
// announcer events
void G_AnnouncerSound( edict_t * targ, StringHash sound, Team team, bool queued, edict_t * ignore );
edict_t * G_PlayerForText( Span< const char > text );
void G_SunCycle( Time duration );
//
// g_callvotes.c
//
void G_CallVotes_Init();
void G_FreeCallvotes();
void G_CallVotes_ResetClient( int n );
void G_CallVotes_Think();
bool G_Callvotes_HasVoted( edict_t * ent );
void G_CallVote_Cmd( edict_t * ent, msg_t args );
void G_CallVotes_VoteYes( edict_t * ent );
void G_CallVotes_VoteNo( edict_t * ent );
//
// g_trigger.c
//
void SP_trigger_teleport( edict_t * ent, const spawn_temp_t * st );
void SP_trigger_push( edict_t * ent, const spawn_temp_t * st );
void SP_trigger_hurt( edict_t * ent, const spawn_temp_t * st );
void InitTrigger( edict_t * self );
bool G_TriggerWait( edict_t * ent );
//
// g_clip.c
//
trace_t G_Trace( Vec3 start, MinMax3 bounds, Vec3 end, const edict_t * passedict, SolidBits solid_mask );
trace_t G_Trace4D( Vec3 start, MinMax3 bounds, Vec3 end, const edict_t * passedict, SolidBits solid_mask, int timeDelta );
void GClip_BackUpCollisionFrame();
int GClip_FindInRadius4D( Vec3 org, float rad, int * list, size_t maxcount, int timeDelta );
void G_SplashFrac4D( const edict_t * ent, Vec3 hitpoint, float maxradius, Vec3 * pushdir, float *frac, int timeDelta );
void GClip_ClearWorld();
void GClip_LinkEntity( const edict_t * ent );
void GClip_UnlinkEntity( const edict_t * ent );
void GClip_TouchTriggers( edict_t * ent );
void G_PMoveTouchTriggers( const pmove_t * pm, Vec3 previous_origin );
int GClip_FindInRadius( Vec3 org, float rad, int * list, size_t maxcount );
bool IsHeadshot( int entNum, Vec3 hit, int timeDelta );
//
// g_combat.c
//
bool G_IsTeamDamage( const SyncEntityState * targ, const SyncEntityState * attacker );
void G_Killed( edict_t * targ, edict_t * inflictor, edict_t * attacker, int topAssistorNo, DamageType damage_type, int damage );
void G_SplashFrac( const SyncEntityState * s, const entity_shared_t * r, Vec3 point, float maxradius, Vec3 * pushdir, float * frac );
void G_Damage( edict_t * targ, edict_t * inflictor, edict_t * attacker, Vec3 pushdir, Vec3 dmgdir, Vec3 point, float damage, float knockback, int dflags, DamageType damage_type );
void SpawnDamageEvents( const edict_t * attacker, edict_t * victim, float damage, bool headshot, Vec3 pos, Vec3 dir, bool showNumbers );
void G_RadiusKnockback( float maxknockback, float minknockback, float radius, edict_t * attacker, Vec3 pos, Optional< Vec3 > normal, int timeDelta );
void G_RadiusDamage( edict_t * inflictor, edict_t * attacker, Optional< Vec3 > normal, edict_t * ignore, DamageType damage_type );
// damage flags
#define DAMAGE_RADIUS ( 1 << 0 ) // damage was indirect
#define DAMAGE_HEADSHOT ( 1 << 1 )
#define DAMAGE_WALLBANG ( 1 << 2 )
//
// g_misc.c
//
void ThrowSmallPileOfGibs( edict_t * self, Vec3 knockback, int damage );
void SP_path_corner( edict_t * ent, const spawn_temp_t * st );
void SP_model( edict_t * ent, const spawn_temp_t * st );
void SP_decal( edict_t * ent, const spawn_temp_t * st );
//
// g_weapon.c
//
void G_FireWeapon( edict_t * ent, u64 parm );
void G_AltFireWeapon( edict_t * ent, u64 parm );
void G_UseGadget( edict_t * ent, GadgetType gadget, u64 parm, bool dead );
//
// g_chasecam
//
void G_ChasePlayer( edict_t * ent );
void G_ChaseStep( edict_t * ent, int step );
void Cmd_ToggleFreeFly( edict_t * ent, msg_t args );
void Cmd_Spectate( edict_t * ent );
void G_EndServerFrames_UpdateChaseCam();
//
// g_client.c
//
void ClientUserinfoChanged( edict_t * ent, const char * userinfo );
void G_Client_UpdateActivity( gclient_t *client );
void G_Client_InactivityRemove( gclient_t *client );
void G_ClientRespawn( edict_t * self, bool ghost );
score_stats_t * G_ClientGetStats( edict_t * ent );
void G_ClientClearStats( edict_t * ent );
void ClientThink( edict_t * ent, UserCommand *cmd, int timeDelta );
void G_ClientThink( edict_t * ent );
void G_CheckClientRespawnClick( edict_t * ent );
bool ClientConnect( edict_t * ent, char *userinfo, const NetAddress & address, bool fakeClient );
void ClientDisconnect( edict_t * ent, const char *reason );
void ClientBegin( edict_t * ent );
void ClientCommand( edict_t * ent, ClientCommandType command, msg_t args );
void G_PredictedEvent( int entNum, int ev, u64 parm );
void G_PredictedFireWeapon( int entNum, u64 parm );
void G_PredictedAltFireWeapon( int entNum, u64 parm );
void G_PredictedUseGadget( int entNum, GadgetType gadget, u64 parm, bool dead );
void G_SelectWeapon( edict_t * ent, int index );
void G_GiveWeapon( edict_t * ent, WeaponType weapon );
void G_GivePerk( edict_t * ent, PerkType perk );
void G_TeleportPlayer( edict_t * player, edict_t * dest );
bool G_PlayerCanTeleport( edict_t * player );
//
// g_player.c
//
void player_pain( edict_t * self, edict_t * other, float kick, int damage );
void player_die( edict_t * self, edict_t * inflictor, edict_t * attacker, int topAssistorEntNo, DamageType damage_type, int damage );
void player_think( edict_t * self );
//
// g_target.c
//
void SP_target_laser( edict_t * ent, const spawn_temp_t * st );
void SP_target_position( edict_t * ent, const spawn_temp_t * st );
//
// g_svcmds.c
//
void G_AddServerCommands();
void G_RemoveCommands();
//
// p_view.c
//
void G_ClientSetStats( edict_t * ent );
void G_ClientEndSnapFrame( edict_t * ent );
void G_ClientAddDamageIndicatorImpact( gclient_t * client, int damage, Vec3 dir );
void G_ClientDamageFeedback( edict_t * ent );
//
// g_phys.c
//
void SV_Impact( edict_t * e1, const trace_t & trace );
void G_RunEntity( edict_t * ent );
//
// g_main.c
//
void G_Init( unsigned int framemsec );
void G_Shutdown();
void G_ExitLevel();
void G_Timeout_Reset();
//
// g_frame.c
//
void G_CheckCvars();
void G_RunFrame( unsigned int msec );
void G_SnapClients();
void G_ClearSnap();
void G_SnapFrame();
//
// g_spawn.c
//
void G_RespawnLevel();
void G_ResetLevel();
void G_InitLevel( Span< const char > mapname, int64_t levelTime );
//
// window
//
void SP_window( edict_t * ent, const spawn_temp_t * st );
//============================================================================
struct projectileinfo_t {
int radius;
float minDamage;
float maxDamage;
float minKnockback;
float maxKnockback;
DamageType damage_type;
StringHash explosion_vfx;
StringHash explosion_sfx;
};
struct chasecam_t {
bool active;
int target;
int mode; //3rd or 1st person
Time timeout; //delay after loosing target
};
struct assistinfo_t {
int entno;
int cumDamage;
int64_t lastTime;
};
struct moveinfo_t {
// fixed data
Vec3 start_origin;
EulerDegrees3 start_angles;
Vec3 end_origin;
EulerDegrees3 end_angles;
StringHash sound_start;
StringHash sound_middle;
StringHash sound_end;
Vec3 movedir; // direction defined in the map
float speed;
float distance; // used by binary movers
s64 wait;
// state data
int state;
void ( *endfunc )( edict_t * );
void ( *blocked )( edict_t * self, edict_t * other );
Vec3 dest;
};
#define MAX_CLIENT_EVENTS 16
#define G_MAX_TIME_DELTAS 8
struct client_snapreset_t {
int buttons;
uint8_t plrkeys; // used for displaying key icons
int damageTaken;
Vec3 damageTakenDir;
bool kill;
float damage_given;
};
struct client_respawnreset_t {
chasecam_t chase;
int64_t timeStamp; // last time it was reset
SyncEvent events[MAX_CLIENT_EVENTS];
unsigned int eventsCurrent;
unsigned int eventsHead;
};
struct client_levelreset_t {
int64_t timeStamp; // last time it was reset
Time last_vsay;
int64_t last_activity;
Time last_spray;
score_stats_t stats;
// flood protection
Time flood_locktill; // locked from talking
Time flood_when[MAX_FLOOD_MESSAGES]; // when messages were said
int flood_whenhead; // head pointer for when said
// team only
Time flood_team_when[MAX_FLOOD_MESSAGES]; // when messages were said
int flood_team_whenhead; // head pointer for when said
Time callvote_when;
};
struct client_teamreset_t {
int64_t timeStamp; // last time it was reset
// for position command
bool position_saved;
Vec3 position_origin;
EulerDegrees3 position_angles;
Time position_lastcmd;
};
struct gclient_t {
SyncPlayerState ps;
int frags;
client_snapreset_t snap;
client_respawnreset_t resp;
client_levelreset_t level;
client_teamreset_t teamstate;
char userinfo[ MAX_INFO_STRING ];
char name[ MAX_NAME_CHARS + 1 ];
bool connecting;
Team team;
UserCommand ucmd;
int timeDelta; // time offset to adjust for shots collision (antilag)
int timeDeltas[G_MAX_TIME_DELTAS];
int timeDeltasHead;
pmove_state_t old_pmove; // for detecting out-of-pmove changes
};
using EdictTouchCallback = void ( * )( edict_t * self, edict_t * other, Vec3 normal, SolidBits solid_mask );
struct edict_t {
SyncEntityState s;
entity_shared_t r;
// DO NOT MODIFY ANYTHING ABOVE THIS, THE SERVER
// EXPECTS THE FIELDS IN THAT ORDER!
//================================
int movetype;
Time freetime;
int numEvents;
bool eventPriority[2];
//
// only used locally in game, not by server
//
StringHash classname;
int spawnflags;
int64_t nextThink;
void ( *think )( edict_t * self );
EdictTouchCallback touch;
void ( *use )( edict_t * self, edict_t * other, edict_t * activator );
void ( *pain )( edict_t * self, edict_t * other, float kick, int damage );
void ( *die )( edict_t * self, edict_t * inflictor, edict_t * attacker, int assistorNo, DamageType damage_type, int damage );
void ( *stop )( edict_t * self );
StringHash name;
StringHash target;
StringHash killtarget;
StringHash pathtarget;
StringHash deadcam;
edict_t * target_ent;
Vec3 velocity;
EulerDegrees3 avelocity;
float speed;
int64_t timeStamp;
int64_t deathTimeStamp;
int timeDelta; // SVF_PROJECTILE only. Used for 4D collision detection
projectileinfo_t projectileInfo; // specific for projectiles
int dmg;
const char * message;
int mass;
float gravity_scale;
float restitution;
edict_t * movetarget;
int64_t pain_debounce_time;
float health;
float max_health;
int deadflag;
int viewheight; // height above origin where eyesight is determined
bool takedamage;
int count;
int64_t timeout; // for SW and fat PG
edict_t * enemy;
edict_t * activator;
edict_t * groundentity;
StringHash sound;
// timing variables
s64 wait;
s64 delay; // before firing targets
s64 wait_randomness;
// common data blocks
moveinfo_t moveinfo; // func movers movement
assistinfo_t recent_attackers[ 4 ];
u32 num_bounces;
};
struct game_locals_t {
edict_t edicts[ MAX_EDICTS ];
gclient_t clients[ MAX_CLIENTS ];
// store latched cvars here that we want to get at often
int numentities;
// cross level triggers
int serverflags;
unsigned int frametime; // in milliseconds
int snapFrameTime; // in milliseconds
int64_t prevServerTime; // last frame's server time
int numBots;
};
extern game_locals_t game;
constexpr edict_t * world = &game.edicts[ 0 ];
constexpr int ENTNUM( const edict_t * x ) { return x - game.edicts; }
constexpr int ENTNUM( const gclient_t * x ) { return x - game.clients + 1; }
constexpr int PLAYERNUM( const edict_t * x ) { return x - game.edicts - 1; }
constexpr int PLAYERNUM( const gclient_t * x ) { return x - game.clients; }
constexpr edict_t * PLAYERENT( int x ) { return game.edicts + x + 1; }
static inline bool G_ISGHOSTING( const edict_t * ent ) { return EntitySolidity( ServerCollisionModelStorage(), &ent->s ) == Solid_NotSolid; }
| 0 | 0.852664 | 1 | 0.852664 | game-dev | MEDIA | 0.969644 | game-dev | 0.655033 | 1 | 0.655033 |
amethyst/rustrogueliketutorial | 2,510 | chapter-33-wfc/src/visibility_system.rs | use specs::prelude::*;
use super::{Viewshed, Position, Map, Player, Hidden, gamelog::GameLog, Name};
use rltk::{field_of_view, Point};
pub struct VisibilitySystem {}
impl<'a> System<'a> for VisibilitySystem {
#[allow(clippy::type_complexity)]
type SystemData = ( WriteExpect<'a, Map>,
Entities<'a>,
WriteStorage<'a, Viewshed>,
ReadStorage<'a, Position>,
ReadStorage<'a, Player>,
WriteStorage<'a, Hidden>,
WriteExpect<'a, rltk::RandomNumberGenerator>,
WriteExpect<'a, GameLog>,
ReadStorage<'a, Name>,);
fn run(&mut self, data : Self::SystemData) {
let (mut map, entities, mut viewshed, pos, player,
mut hidden, mut rng, mut log, names) = data;
for (ent,viewshed,pos) in (&entities, &mut viewshed, &pos).join() {
if viewshed.dirty {
viewshed.dirty = false;
viewshed.visible_tiles = field_of_view(Point::new(pos.x, pos.y), viewshed.range, &*map);
viewshed.visible_tiles.retain(|p| p.x >= 0 && p.x < map.width && p.y >= 0 && p.y < map.height );
// If this is the player, reveal what they can see
let _p : Option<&Player> = player.get(ent);
if let Some(_p) = _p {
for t in map.visible_tiles.iter_mut() { *t = false };
for vis in viewshed.visible_tiles.iter() {
let idx = map.xy_idx(vis.x, vis.y);
map.revealed_tiles[idx] = true;
map.visible_tiles[idx] = true;
// Chance to reveal hidden things
for e in map.tile_content[idx].iter() {
let maybe_hidden = hidden.get(*e);
if let Some(_maybe_hidden) = maybe_hidden {
if rng.roll_dice(1,24)==1 {
let name = names.get(*e);
if let Some(name) = name {
log.entries.push(format!("You spotted a {}.", &name.name));
}
hidden.remove(*e);
}
}
}
}
}
}
}
}
}
| 0 | 0.848345 | 1 | 0.848345 | game-dev | MEDIA | 0.947324 | game-dev | 0.922294 | 1 | 0.922294 |
Jermesa-Studio/JRS_Vehicle_Physics_Controller | 15,530 | Library/PackageCache/com.unity.ugui@1.0.0/Runtime/UI/Core/CanvasUpdateRegistry.cs | using System;
using System.Collections.Generic;
using UnityEngine.UI.Collections;
namespace UnityEngine.UI
{
/// <summary>
/// Values of 'update' called on a Canvas update.
/// </summary>
/// <remarks> If modifying also modify m_CanvasUpdateProfilerStrings to match.</remarks>
public enum CanvasUpdate
{
/// <summary>
/// Called before layout.
/// </summary>
Prelayout = 0,
/// <summary>
/// Called for layout.
/// </summary>
Layout = 1,
/// <summary>
/// Called after layout.
/// </summary>
PostLayout = 2,
/// <summary>
/// Called before rendering.
/// </summary>
PreRender = 3,
/// <summary>
/// Called late, before render.
/// </summary>
LatePreRender = 4,
/// <summary>
/// Max enum value. Always last.
/// </summary>
MaxUpdateValue = 5
}
/// <summary>
/// This is an element that can live on a Canvas.
/// </summary>
public interface ICanvasElement
{
/// <summary>
/// Rebuild the element for the given stage.
/// </summary>
/// <param name="executing">The current CanvasUpdate stage being rebuild.</param>
void Rebuild(CanvasUpdate executing);
/// <summary>
/// Get the transform associated with the ICanvasElement.
/// </summary>
Transform transform { get; }
/// <summary>
/// Callback sent when this ICanvasElement has completed layout.
/// </summary>
void LayoutComplete();
/// <summary>
/// Callback sent when this ICanvasElement has completed Graphic rebuild.
/// </summary>
void GraphicUpdateComplete();
/// <summary>
/// Used if the native representation has been destroyed.
/// </summary>
/// <returns>Return true if the element is considered destroyed.</returns>
bool IsDestroyed();
}
/// <summary>
/// A place where CanvasElements can register themselves for rebuilding.
/// </summary>
public class CanvasUpdateRegistry
{
private static CanvasUpdateRegistry s_Instance;
private bool m_PerformingLayoutUpdate;
private bool m_PerformingGraphicUpdate;
// This list matches the CanvasUpdate enum above. Keep in sync
private string[] m_CanvasUpdateProfilerStrings = new string[] { "CanvasUpdate.Prelayout", "CanvasUpdate.Layout", "CanvasUpdate.PostLayout", "CanvasUpdate.PreRender", "CanvasUpdate.LatePreRender" };
private const string m_CullingUpdateProfilerString = "ClipperRegistry.Cull";
private readonly IndexedSet<ICanvasElement> m_LayoutRebuildQueue = new IndexedSet<ICanvasElement>();
private readonly IndexedSet<ICanvasElement> m_GraphicRebuildQueue = new IndexedSet<ICanvasElement>();
protected CanvasUpdateRegistry()
{
Canvas.willRenderCanvases += PerformUpdate;
}
/// <summary>
/// Get the singleton registry instance.
/// </summary>
public static CanvasUpdateRegistry instance
{
get
{
if (s_Instance == null)
s_Instance = new CanvasUpdateRegistry();
return s_Instance;
}
}
private bool ObjectValidForUpdate(ICanvasElement element)
{
var valid = element != null;
var isUnityObject = element is Object;
if (isUnityObject)
valid = (element as Object) != null; //Here we make use of the overloaded UnityEngine.Object == null, that checks if the native object is alive.
return valid;
}
private void CleanInvalidItems()
{
// So MB's override the == operator for null equality, which checks
// if they are destroyed. This is fine if you are looking at a concrete
// mb, but in this case we are looking at a list of ICanvasElement
// this won't forward the == operator to the MB, but just check if the
// interface is null. IsDestroyed will return if the backend is destroyed.
var layoutRebuildQueueCount = m_LayoutRebuildQueue.Count;
for (int i = layoutRebuildQueueCount - 1; i >= 0; --i)
{
var item = m_LayoutRebuildQueue[i];
if (item == null)
{
m_LayoutRebuildQueue.RemoveAt(i);
continue;
}
if (item.IsDestroyed())
{
m_LayoutRebuildQueue.RemoveAt(i);
item.LayoutComplete();
}
}
var graphicRebuildQueueCount = m_GraphicRebuildQueue.Count;
for (int i = graphicRebuildQueueCount - 1; i >= 0; --i)
{
var item = m_GraphicRebuildQueue[i];
if (item == null)
{
m_GraphicRebuildQueue.RemoveAt(i);
continue;
}
if (item.IsDestroyed())
{
m_GraphicRebuildQueue.RemoveAt(i);
item.GraphicUpdateComplete();
}
}
}
private static readonly Comparison<ICanvasElement> s_SortLayoutFunction = SortLayoutList;
private void PerformUpdate()
{
UISystemProfilerApi.BeginSample(UISystemProfilerApi.SampleType.Layout);
CleanInvalidItems();
m_PerformingLayoutUpdate = true;
m_LayoutRebuildQueue.Sort(s_SortLayoutFunction);
for (int i = 0; i <= (int)CanvasUpdate.PostLayout; i++)
{
UnityEngine.Profiling.Profiler.BeginSample(m_CanvasUpdateProfilerStrings[i]);
for (int j = 0; j < m_LayoutRebuildQueue.Count; j++)
{
var rebuild = m_LayoutRebuildQueue[j];
try
{
if (ObjectValidForUpdate(rebuild))
rebuild.Rebuild((CanvasUpdate)i);
}
catch (Exception e)
{
Debug.LogException(e, rebuild.transform);
}
}
UnityEngine.Profiling.Profiler.EndSample();
}
for (int i = 0; i < m_LayoutRebuildQueue.Count; ++i)
m_LayoutRebuildQueue[i].LayoutComplete();
m_LayoutRebuildQueue.Clear();
m_PerformingLayoutUpdate = false;
UISystemProfilerApi.EndSample(UISystemProfilerApi.SampleType.Layout);
UISystemProfilerApi.BeginSample(UISystemProfilerApi.SampleType.Render);
// now layout is complete do culling...
UnityEngine.Profiling.Profiler.BeginSample(m_CullingUpdateProfilerString);
ClipperRegistry.instance.Cull();
UnityEngine.Profiling.Profiler.EndSample();
m_PerformingGraphicUpdate = true;
for (var i = (int)CanvasUpdate.PreRender; i < (int)CanvasUpdate.MaxUpdateValue; i++)
{
UnityEngine.Profiling.Profiler.BeginSample(m_CanvasUpdateProfilerStrings[i]);
for (var k = 0; k < m_GraphicRebuildQueue.Count; k++)
{
try
{
var element = m_GraphicRebuildQueue[k];
if (ObjectValidForUpdate(element))
element.Rebuild((CanvasUpdate)i);
}
catch (Exception e)
{
Debug.LogException(e, m_GraphicRebuildQueue[k].transform);
}
}
UnityEngine.Profiling.Profiler.EndSample();
}
for (int i = 0; i < m_GraphicRebuildQueue.Count; ++i)
m_GraphicRebuildQueue[i].GraphicUpdateComplete();
m_GraphicRebuildQueue.Clear();
m_PerformingGraphicUpdate = false;
UISystemProfilerApi.EndSample(UISystemProfilerApi.SampleType.Render);
}
private static int ParentCount(Transform child)
{
if (child == null)
return 0;
var parent = child.parent;
int count = 0;
while (parent != null)
{
count++;
parent = parent.parent;
}
return count;
}
private static int SortLayoutList(ICanvasElement x, ICanvasElement y)
{
Transform t1 = x.transform;
Transform t2 = y.transform;
return ParentCount(t1) - ParentCount(t2);
}
/// <summary>
/// Try and add the given element to the layout rebuild list.
/// Will not return if successfully added.
/// </summary>
/// <param name="element">The element that is needing rebuilt.</param>
public static void RegisterCanvasElementForLayoutRebuild(ICanvasElement element)
{
instance.InternalRegisterCanvasElementForLayoutRebuild(element);
}
/// <summary>
/// Try and add the given element to the layout rebuild list.
/// </summary>
/// <param name="element">The element that is needing rebuilt.</param>
/// <returns>
/// True if the element was successfully added to the rebuilt list.
/// False if either already inside a Graphic Update loop OR has already been added to the list.
/// </returns>
public static bool TryRegisterCanvasElementForLayoutRebuild(ICanvasElement element)
{
return instance.InternalRegisterCanvasElementForLayoutRebuild(element);
}
private bool InternalRegisterCanvasElementForLayoutRebuild(ICanvasElement element)
{
if (m_LayoutRebuildQueue.Contains(element))
return false;
/* TODO: this likely should be here but causes the error to show just resizing the game view (case 739376)
if (m_PerformingLayoutUpdate)
{
Debug.LogError(string.Format("Trying to add {0} for layout rebuild while we are already inside a layout rebuild loop. This is not supported.", element));
return false;
}*/
return m_LayoutRebuildQueue.AddUnique(element);
}
/// <summary>
/// Try and add the given element to the rebuild list.
/// Will not return if successfully added.
/// </summary>
/// <param name="element">The element that is needing rebuilt.</param>
public static void RegisterCanvasElementForGraphicRebuild(ICanvasElement element)
{
instance.InternalRegisterCanvasElementForGraphicRebuild(element);
}
/// <summary>
/// Try and add the given element to the rebuild list.
/// </summary>
/// <param name="element">The element that is needing rebuilt.</param>
/// <returns>
/// True if the element was successfully added to the rebuilt list.
/// False if either already inside a Graphic Update loop OR has already been added to the list.
/// </returns>
public static bool TryRegisterCanvasElementForGraphicRebuild(ICanvasElement element)
{
return instance.InternalRegisterCanvasElementForGraphicRebuild(element);
}
private bool InternalRegisterCanvasElementForGraphicRebuild(ICanvasElement element)
{
if (m_PerformingGraphicUpdate)
{
Debug.LogError(string.Format("Trying to add {0} for graphic rebuild while we are already inside a graphic rebuild loop. This is not supported.", element));
return false;
}
return m_GraphicRebuildQueue.AddUnique(element);
}
/// <summary>
/// Remove the given element from both the graphic and the layout rebuild lists.
/// </summary>
/// <param name="element"></param>
public static void UnRegisterCanvasElementForRebuild(ICanvasElement element)
{
instance.InternalUnRegisterCanvasElementForLayoutRebuild(element);
instance.InternalUnRegisterCanvasElementForGraphicRebuild(element);
}
/// <summary>
/// Disable the given element from both the graphic and the layout rebuild lists.
/// </summary>
/// <param name="element"></param>
public static void DisableCanvasElementForRebuild(ICanvasElement element)
{
instance.InternalDisableCanvasElementForLayoutRebuild(element);
instance.InternalDisableCanvasElementForGraphicRebuild(element);
}
private void InternalUnRegisterCanvasElementForLayoutRebuild(ICanvasElement element)
{
if (m_PerformingLayoutUpdate)
{
Debug.LogError(string.Format("Trying to remove {0} from rebuild list while we are already inside a rebuild loop. This is not supported.", element));
return;
}
element.LayoutComplete();
instance.m_LayoutRebuildQueue.Remove(element);
}
private void InternalUnRegisterCanvasElementForGraphicRebuild(ICanvasElement element)
{
if (m_PerformingGraphicUpdate)
{
Debug.LogError(string.Format("Trying to remove {0} from rebuild list while we are already inside a rebuild loop. This is not supported.", element));
return;
}
element.GraphicUpdateComplete();
instance.m_GraphicRebuildQueue.Remove(element);
}
private void InternalDisableCanvasElementForLayoutRebuild(ICanvasElement element)
{
if (m_PerformingLayoutUpdate)
{
Debug.LogError(string.Format("Trying to remove {0} from rebuild list while we are already inside a rebuild loop. This is not supported.", element));
return;
}
element.LayoutComplete();
instance.m_LayoutRebuildQueue.DisableItem(element);
}
private void InternalDisableCanvasElementForGraphicRebuild(ICanvasElement element)
{
if (m_PerformingGraphicUpdate)
{
Debug.LogError(string.Format("Trying to remove {0} from rebuild list while we are already inside a rebuild loop. This is not supported.", element));
return;
}
element.GraphicUpdateComplete();
instance.m_GraphicRebuildQueue.DisableItem(element);
}
/// <summary>
/// Are graphics layouts currently being calculated..
/// </summary>
/// <returns>True if the rebuild loop is CanvasUpdate.Prelayout, CanvasUpdate.Layout or CanvasUpdate.Postlayout</returns>
public static bool IsRebuildingLayout()
{
return instance.m_PerformingLayoutUpdate;
}
/// <summary>
/// Are graphics currently being rebuild.
/// </summary>
/// <returns>True if the rebuild loop is CanvasUpdate.PreRender or CanvasUpdate.Render</returns>
public static bool IsRebuildingGraphics()
{
return instance.m_PerformingGraphicUpdate;
}
}
}
| 0 | 0.815271 | 1 | 0.815271 | game-dev | MEDIA | 0.454746 | game-dev | 0.951132 | 1 | 0.951132 |
Placidina/MikScrollingBattleText | 12,861 | MSBTOptions/MSBTOptionsMain.lua | -------------------------------------------------------------------------------
-- Title: MSBT Options Main
-- Author: Mikord
-------------------------------------------------------------------------------
-- Create module and set its name.
local module = {}
local moduleName = "Main"
MSBTOptions[moduleName] = module
local IsClassic = WOW_PROJECT_ID >= WOW_PROJECT_CLASSIC
-------------------------------------------------------------------------------
-- Imports.
-------------------------------------------------------------------------------
-- Local references to various modules for faster access.
local MSBTControls = MSBTOptions.Controls
local L = MikSBT.translations
-------------------------------------------------------------------------------
-- Constants.
-------------------------------------------------------------------------------
local WINDOW_TITLE = "Mik's Scrolling Battle Text " .. MikSBT.VERSION_STRING
-------------------------------------------------------------------------------
-- Private variables.
-------------------------------------------------------------------------------
-- Prevent tainting global _.
local _
-- The main options frame.
local mainFrame
-- Holds all registered popup frames.
local popupFrames = {}
-- Tab info.
local tabData = {}
local tabListbox
-- Scheduling variables.
local waitTable = {}
local waitFrame = nil
-------------------------------------------------------------------------------
-- Tab functions.
-------------------------------------------------------------------------------
-- ****************************************************************************
-- Initializes the frame that is shown when the tab is clicked.
-- ****************************************************************************
local function InitTab(tabInfo)
local frame = tabInfo.frame
frame:SetParent(mainFrame)
frame:SetPoint("TOPLEFT", mainFrame, "TOPLEFT", 190, -78)
frame:SetWidth(400)
frame:SetHeight(350)
end
-- ****************************************************************************
-- Adds a new tab to the main options frame that will show the passed frame
-- when selected.
-- ****************************************************************************
local function AddTab(frame, text, tooltip)
local tabInfo = {}
tabInfo.text = text
tabInfo.frame = frame
tabInfo.tooltip = tooltip
tabData[#tabData+1] = tabInfo
if (tabListbox) then
InitTab(tabInfo)
tabListbox:AddItem(#tabData)
end
end
-- ****************************************************************************
-- Called by listbox to create a line for the tabs on the left.
-- ****************************************************************************
local function CreateTabLine(this)
local frame = CreateFrame("Button", nil, this)
local fontString = frame:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
fontString:SetPoint("LEFT", frame, "LEFT")
fontString:SetPoint("RIGHT", frame, "RIGHT")
frame.fontString = fontString
frame.tooltipAnchor = "ANCHOR_LEFT"
return frame
end
-- ****************************************************************************
-- Called by listbox to display a line for the tabs on the left.
-- ****************************************************************************
local function DisplayTabLine(this, line, key, isSelected)
line.fontString:SetText(tabData[key].text)
line.tooltip = tabData[key].tooltip
local color = isSelected and HIGHLIGHT_FONT_COLOR or NORMAL_FONT_COLOR
line.fontString:SetTextColor(color.r, color.g, color.b)
end
-- ****************************************************************************
-- Called when a tab line is clicked.
-- ****************************************************************************
local function OnClickTabLine(this, line, value)
-- Hide all the tab frames.
for _, info in ipairs(tabData) do
info.frame:Hide()
end
-- Hide the registered popup frames.
for frame in pairs(popupFrames) do
frame:Hide()
end
-- Show the tab's associated frame.
local frame = tabData[value].frame
if (frame) then frame:Show() end
-- Force a refresh to the listbox to update the highlight font color.
tabListbox:Refresh()
end
-------------------------------------------------------------------------------
-- Main options frame functions.
-------------------------------------------------------------------------------
-- ****************************************************************************
-- Called when the main options frame is hidden.
-- ****************************************************************************
local function OnHideMainFrame(this)
PlaySound(799)
-- Hide the registered popup frames.
for frame in pairs(popupFrames) do
frame:Hide()
end
end
-- ****************************************************************************
-- Creates the main options frame.
-- ****************************************************************************
local function CreateMainFrame()
-- Main frame.
mainFrame = CreateFrame("Frame", "MSBTMainOptionsFrame", UIParent)
mainFrame:EnableMouse(true)
mainFrame:SetMovable(true)
mainFrame:RegisterForDrag("LeftButton")
--mainFrame:SetToplevel(true)
mainFrame:SetClampedToScreen(true)
mainFrame:SetWidth(608)
mainFrame:SetHeight(440)
mainFrame:SetPoint("CENTER")
mainFrame:SetHitRectInsets(0, 0, 0, 0)
mainFrame:SetScript("OnHide", OnHideMainFrame)
mainFrame:SetScript("OnShow", function(self)
PlaySound(SOUNDKIT.IG_MAINMENU_OPTION)
end)
mainFrame:SetScript("OnDragStart", function(self)
self:StartMoving()
end)
mainFrame:SetScript("OnDragStop", function(self)
self:StopMovingOrSizing()
end)
-- Title region.
--[[local titleRegion = mainFrame:CreateTitleRegion()
titleRegion:SetWidth(525)
titleRegion:SetHeight(20)
titleRegion:SetPoint("TOPLEFT", mainFrame, "TOPLEFT", 50, -10)]]
-- Scroll Icon.
local texture = mainFrame:CreateTexture(nil, "BACKGROUND")
texture:SetTexture("Interface\\FriendsFrame\\FriendsFrameScrollIcon")
texture:SetWidth(64)
texture:SetHeight(64)
texture:SetPoint("TOPLEFT", mainFrame, "TOPLEFT", 8, 1)
-- Top left.
texture = mainFrame:CreateTexture(nil, "ARTWORK")
texture:SetTexture("Interface\\PaperDollInfoFrame\\UI-Character-General-TopLeft")
texture:SetWidth(256)
texture:SetHeight(256)
texture:SetPoint("TOPLEFT")
-- Top center left.
texture = mainFrame:CreateTexture(nil, "ARTWORK")
texture:SetTexture("Interface\\PaperDollInfoFrame\\UI-Character-General-TopLeft")
texture:SetWidth(128)
texture:SetHeight(256)
texture:SetPoint("TOPLEFT", mainFrame, "TOPLEFT", 256, 0)
texture:SetTexCoord(0.38, 0.88, 0, 1)
-- Top center right.
texture = mainFrame:CreateTexture(nil, "ARTWORK")
texture:SetTexture("Interface\\PaperDollInfoFrame\\UI-Character-General-TopLeft")
texture:SetWidth(128)
texture:SetHeight(256)
texture:SetPoint("TOPLEFT", mainFrame, "TOPLEFT", 384, 0)
texture:SetTexCoord(0.45, 0.95, 0, 1)
-- Top right.
texture = mainFrame:CreateTexture(nil, "ARTWORK")
texture:SetTexture("Interface\\PaperDollInfoFrame\\UI-Character-General-TopRight")
texture:SetWidth(100)
texture:SetHeight(256)
texture:SetPoint("TOPRIGHT")
texture:SetTexCoord(0, 0.78125, 0, 1)
-- Bottom left.
texture = mainFrame:CreateTexture(nil, "ARTWORK")
texture:SetTexture("Interface\\PaperDollInfoFrame\\UI-Character-General-BottomLeft")
texture:SetWidth(256)
texture:SetHeight(184)
texture:SetPoint("BOTTOMLEFT")
texture:SetTexCoord(0, 1, 0, 0.71875)
-- Bottom center left.
texture = mainFrame:CreateTexture(nil, "ARTWORK")
texture:SetTexture("Interface\\PaperDollInfoFrame\\UI-Character-General-BottomLeft")
texture:SetWidth(128)
texture:SetHeight(184)
texture:SetPoint("BOTTOMLEFT", mainFrame, "BOTTOMLEFT", 256, 0)
texture:SetTexCoord(0.5, 1, 0, 0.71875)
-- Bottom center right.
texture = mainFrame:CreateTexture(nil, "ARTWORK")
texture:SetTexture("Interface\\PaperDollInfoFrame\\UI-Character-General-BottomLeft")
texture:SetWidth(128)
texture:SetHeight(184)
texture:SetPoint("BOTTOMLEFT", mainFrame, "BOTTOMLEFT", 384, 0)
texture:SetTexCoord(0.5, 1, 0, 0.71875)
-- Bottom right.
texture = mainFrame:CreateTexture(nil, "ARTWORK")
texture:SetTexture("Interface\\PaperDollInfoFrame\\UI-Character-General-BottomRight")
texture:SetWidth(100)
texture:SetHeight(184)
texture:SetPoint("BOTTOMRIGHT")
texture:SetTexCoord(0, 0.78125, 0, 0.71875)
-- Top vertical.
texture = mainFrame:CreateTexture(nil, "OVERLAY")
texture:SetTexture("Interface\\PaperDollInfoFrame\\UI-Character-General-TopRight")
texture:SetWidth(8)
texture:SetHeight(184)
texture:SetPoint("TOPLEFT", mainFrame, "TOPLEFT", 180, -72)
texture:SetTexCoord(0.648437, 0.7109375, 0.28125, 1.0)
-- Bottom vertical.
texture = mainFrame:CreateTexture(nil, "OVERLAY")
texture:SetTexture("Interface\\PaperDollInfoFrame\\UI-Character-General-TopRight")
texture:SetWidth(8)
texture:SetHeight(174)
texture:SetPoint("TOPLEFT", mainFrame, "TOPLEFT", 180, -256)
texture:SetTexCoord(0.648437, 0.7109375, 0.3203125, 1.0)
-- Window title.
local fontString = mainFrame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
fontString:SetText(WINDOW_TITLE)
fontString:SetPoint("TOP", mainFrame, "TOP", 0, -18)
-- Close Button.
local frame = CreateFrame("Button", nil, mainFrame, "UIPanelCloseButton")
if IsClassic then
frame:SetPoint("TOPRIGHT", mainFrame, "TOPRIGHT", -3, -8)
else
frame:SetPoint("TOPRIGHT", mainFrame, "TOPRIGHT", -7, -12)
end
-- Setup the tabs listbox.
tabListbox = MSBTControls.CreateListbox(mainFrame)
tabListbox:Configure(150, 350, 20)
tabListbox:SetPoint("TOPLEFT", mainFrame, "TOPLEFT", 30, -78)
tabListbox:SetCreateLineHandler(CreateTabLine)
tabListbox:SetDisplayHandler(DisplayTabLine)
tabListbox:SetClickHandler(OnClickTabLine)
-- Add registered tabs.
for k, tabInfo in ipairs(tabData) do
InitTab(tabInfo)
tabListbox:AddItem(k)
end
-- Select the general tab.
tabListbox:SetSelectedItem(2)
tabListbox:Refresh()
tabData[2].frame:Show()
-- Insert the frame name into the UISpecialFrames array so it closes when
-- the escape key is pressed.
--table.insert(UISpecialFrames, mainFrame:GetName())
end
-- ****************************************************************************
-- Shows the main options frame after creating it (if it hasn't already been).
-- ****************************************************************************
local function ShowMainFrame()
if (not mainFrame) then CreateMainFrame() end
if (not MSBTScrollAreasConfigFrame or not MSBTScrollAreasConfigFrame:IsShown()) then
mainFrame:Show()
end
end
-- ****************************************************************************
-- Hides the main options frame.
-- ****************************************************************************
local function HideMainFrame()
mainFrame:Hide()
end
-- ****************************************************************************
-- Registers frames that float above the main options window.
-- These frames will be hidden when a tab is selected or the main options
-- window is hidden.
-- ****************************************************************************
local function RegisterPopupFrame(frame)
if (not popupFrames[frame]) then popupFrames[frame] = true end
end
-------------------------------------------------------------------------------
-- Scheduling functions.
-------------------------------------------------------------------------------
-- ****************************************************************************
-- Registers frames that float above the main options window.
-- These frames will be hidden when a tab is selected or the main options
-- window is hidden.
-- ****************************************************************************
local function ScheduleCallback(delay, func, ...)
if (waitFrame == nil) then
waitFrame = CreateFrame("Frame", nil, UIParent)
waitFrame:SetScript("OnUpdate",function (self, elapsed)
local count = #waitTable
local i = 1
while (i <= count) do
local waitRecord = tremove(waitTable, i)
local duration = tremove(waitRecord, 1)
local func = tremove(waitRecord, 1)
local params = tremove(waitRecord, 1)
if (duration > elapsed) then
tinsert(waitTable, i, {duration - elapsed, func, params})
i = i + 1
else
count = count - 1
func(unpack(params))
end
end
end)
end
tinsert(waitTable, {delay, func, {...}})
return true
end
-------------------------------------------------------------------------------
-- Module interface.
-------------------------------------------------------------------------------
-- Protected Functions.
module.ShowMainFrame = ShowMainFrame
module.HideMainFrame = HideMainFrame
module.RegisterPopupFrame = RegisterPopupFrame
module.AddTab = AddTab
module.ScheduleCallback = ScheduleCallback
| 0 | 0.790657 | 1 | 0.790657 | game-dev | MEDIA | 0.525013 | game-dev,graphics-rendering,desktop-app | 0.740588 | 1 | 0.740588 |
semyon422/soundsphere | 1,599 | sphere/models/RhythmModel/ScoreEngine/scores/MiscScore.lua | local ScoreSystem = require("sphere.models.RhythmModel.ScoreEngine.ScoreSystem")
---@class sphere.MiscScore: sphere.ScoreSystem
---@operator call: sphere.MiscScore
local MiscScore = ScoreSystem + {}
function MiscScore:new()
self.maxDeltaTime = 0
self.deltaTime = 0
self.earlyLate = {
early = 0,
late = 0,
}
end
---@return string
function MiscScore:getKey()
return "misc"
end
---@param event table
function MiscScore:hit(event)
---@type number
local deltaTime = event.deltaTime
self.deltaTime = deltaTime
if math.abs(deltaTime) > math.abs(self.maxDeltaTime) then
self.maxDeltaTime = deltaTime
end
if deltaTime < 0 then
self.earlyLate.early = self.earlyLate.early + 1
else
self.earlyLate.late = self.earlyLate.late + 1
end
end
---@param event any
function MiscScore:miss(event)
self.deltaTime = event.deltaTime
end
---@param event any
function MiscScore:early(event)
self.deltaTime = -math.huge
end
function MiscScore:getSlice()
return {
maxDeltaTime = self.maxDeltaTime,
deltaTime = self.deltaTime,
}
end
MiscScore.events = {
ShortNote = {
clear = {
passed = "hit",
missed = "miss",
clear = "early",
},
},
LongNote = {
clear = {
startPassedPressed = "hit",
startMissed = "miss",
startMissedPressed = "miss",
clear = "early",
},
startPassedPressed = {
startMissed = nil,
endMissed = "miss",
endPassed = "hit",
},
startMissedPressed = {
endMissedPassed = "hit",
startMissed = nil,
endMissed = "miss",
},
startMissed = {
startMissedPressed = nil,
endMissed = "miss",
},
},
}
return MiscScore
| 0 | 0.718991 | 1 | 0.718991 | game-dev | MEDIA | 0.648506 | game-dev | 0.819982 | 1 | 0.819982 |
MockBukkit/MockBukkit | 8,086 | src/main/java/org/mockbukkit/mockbukkit/inventory/ItemFactoryMock.java | package org.mockbukkit.mockbukkit.inventory;
import com.google.common.base.Preconditions;
import io.papermc.paper.registry.set.RegistryKeySet;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.event.HoverEvent;
import net.kyori.adventure.text.event.HoverEventSource;
import net.kyori.adventure.text.format.Style;
import net.kyori.adventure.text.format.TextDecoration;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.hover.content.Content;
import org.bukkit.Color;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.inventory.ItemFactory;
import org.bukkit.inventory.ItemRarity;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.Range;
import org.mockbukkit.mockbukkit.exception.ItemMetaInitException;
import org.mockbukkit.mockbukkit.exception.UnimplementedOperationException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Objects;
import java.util.Random;
import java.util.function.UnaryOperator;
/**
* Mock implementation of an {@link ItemFactory}.
*/
public class ItemFactoryMock implements ItemFactory
{
private final Color defaultLeatherColor = Color.fromRGB(10511680);
private @NotNull Class<? extends ItemMeta> getItemMetaClass(@NotNull Material material)
{
if (material.isAir() || !material.isItem())
{
return ItemMeta.class;
}
return material.asItemType().getItemMetaClass();
}
@Override
public @NotNull ItemMeta getItemMeta(@NotNull Material material)
{
Preconditions.checkNotNull(material, "Material cannot be null");
Class<? extends ItemMeta> clazz = null;
try
{
clazz = getItemMetaClass(material);
for (var ctor : clazz.getDeclaredConstructors())
{
if (ctor.getParameterCount() == 1 && ctor.getParameters()[0].getType() == Material.class)
{
return (ItemMeta) ctor.newInstance(material);
}
}
return clazz.getDeclaredConstructor().newInstance();
}
catch (ReflectiveOperationException e)
{
throw new UnsupportedOperationException("Can't instantiate class '" + clazz + "'", e);
}
}
@Override
public boolean isApplicable(ItemMeta meta, @NotNull ItemStack stack)
{
return isApplicable(meta, stack.getType());
}
@Override
public boolean isApplicable(ItemMeta meta, @NotNull Material material)
{
Class<? extends ItemMeta> target = getItemMetaClass(material);
return target.isInstance(meta);
}
@Override
public boolean equals(ItemMeta meta1, ItemMeta meta2)
{
// Returns true if both metas are null or equal.
return Objects.equals(meta1, meta2);
}
@Override
public ItemMeta asMetaFor(@NotNull ItemMeta meta, @NotNull ItemStack stack)
{
return asMetaFor(meta, stack.getType());
}
@Override
public ItemMeta asMetaFor(@NotNull ItemMeta meta, @NotNull Material material)
{
Class<? extends ItemMeta> target = getItemMetaClass(material);
try
{
for (Constructor<?> constructor : target.getDeclaredConstructors())
{
// This will make sure we find the most suitable constructor for this
if (constructor.getParameterCount() == 1
&& constructor.getParameterTypes()[0].isAssignableFrom(meta.getClass()))
{
return (ItemMeta) constructor.newInstance(meta);
}
}
throw new NoSuchMethodException(
"Cannot find an ItemMeta constructor for the class \"" + meta.getClass().getName() + "\"");
}
catch (SecurityException | InstantiationException | IllegalAccessException | InvocationTargetException
| NoSuchMethodException e)
{
throw new ItemMetaInitException(String.format("Meta %s and material %s", meta.getClass().getName(), material.name()), e);
}
}
@Override
public @NotNull Color getDefaultLeatherColor()
{
return defaultLeatherColor;
}
@NotNull
@Override
public ItemStack createItemStack(@NotNull String input) throws IllegalArgumentException
{
// TODO Auto-generated method stub
throw new UnimplementedOperationException();
}
@Override
public @NotNull ItemStack enchantWithLevels(@NotNull ItemStack itemStack, @Range(from = 1L, to = 30L) int levels, boolean allowTreasure, @NotNull Random random)
{
// TODO Auto-generated method stub
throw new UnimplementedOperationException();
}
@Override
public @NotNull ItemStack enchantWithLevels(@NotNull ItemStack itemStack, @Range(from = 1L, to = 30L) int levels, @NotNull RegistryKeySet<@NotNull Enchantment> registryKeySet, @NotNull Random random)
{
// TODO Auto-generated method stub
throw new UnimplementedOperationException();
}
@Override
public @NotNull HoverEvent<HoverEvent.ShowItem> asHoverEvent(@NotNull ItemStack item, @NotNull UnaryOperator<HoverEvent.ShowItem> op)
{
// TODO Auto-generated method stub
throw new UnimplementedOperationException();
}
@Override
public @NotNull Component displayName(@NotNull ItemStack itemStack)
{
Component component;
ItemMeta itemMeta = itemStack.getItemMeta();
if (itemMeta != null && itemMeta.customName() != null)
{
component = Component.empty().append(itemMeta.customName()).style(Style.style(TextDecoration.ITALIC));
}
else
{
component = Component.translatable(itemStack.getType().asItemType().translationKey());
}
component = Component.translatable("chat.square_brackets", component);
if (!itemStack.isEmpty() && itemMeta != null)
{
ItemRarity rarity = itemMeta.hasRarity() ? itemMeta.getRarity() : ItemRarity.COMMON;
component = component.style(Style.style(rarity.color()))
.hoverEvent(HoverEventSource.unbox(HoverEvent.showItem(itemStack.getType().asItemType(), itemStack.getAmount())));
}
return component;
}
@Override
@Deprecated(since = "1.18")
public @Nullable String getI18NDisplayName(@Nullable ItemStack item)
{
// TODO Auto-generated method stub
throw new UnimplementedOperationException();
}
@Override
public @NotNull ItemStack ensureServerConversions(@NotNull ItemStack item)
{
return item;
}
@Override
@Deprecated(since = "1.19")
public @NotNull Content hoverContentOf(@NotNull ItemStack itemStack)
{
// TODO Auto-generated method stub
throw new UnimplementedOperationException();
}
@Override
@Deprecated(since = "1.16")
public @NotNull Content hoverContentOf(@NotNull Entity entity)
{
// TODO Auto-generated method stub
throw new UnimplementedOperationException();
}
@Override
@Deprecated(since = "1.16")
public @NotNull Content hoverContentOf(@NotNull Entity entity, @Nullable String customName)
{
// TODO Auto-generated method stub
throw new UnimplementedOperationException();
}
@Override
@Deprecated(since = "1.16")
public @NotNull Content hoverContentOf(@NotNull Entity entity, @Nullable BaseComponent customName)
{
// TODO Auto-generated method stub
throw new UnimplementedOperationException();
}
@Override
@Deprecated(since = "1.16")
public @NotNull Content hoverContentOf(@NotNull Entity entity, @NotNull BaseComponent[] customName)
{
// TODO Auto-generated method stub
throw new UnimplementedOperationException();
}
@Override
public @Nullable Material getSpawnEgg(@Nullable EntityType type)
{
// TODO Auto-generated method stub
throw new UnimplementedOperationException();
}
@Override
public @NotNull ItemStack enchantItem(@NotNull Entity entity, @NotNull ItemStack item, int level, boolean allowTreasures)
{
// TODO Auto-generated method stub
throw new UnimplementedOperationException();
}
@Override
public @NotNull ItemStack enchantItem(@NotNull World world, @NotNull ItemStack item, int level, boolean allowTreasures)
{
// TODO Auto-generated method stub
throw new UnimplementedOperationException();
}
@Override
public @NotNull ItemStack enchantItem(@NotNull ItemStack item, int level, boolean allowTreasures)
{
// TODO Auto-generated method stub
throw new UnimplementedOperationException();
}
}
| 0 | 0.844906 | 1 | 0.844906 | game-dev | MEDIA | 0.984217 | game-dev | 0.865804 | 1 | 0.865804 |
followingthefasciaplane/source-engine-diff-check | 30,382 | misc/game/server/cstrike15/Effects/chicken.cpp | // chicken.cpp
// An interactive, shootable chicken
#include "cbase.h"
#include "chicken.h"
#include "cs_player.h"
#include "cs_gamerules.h"
#include "particle_parse.h"
#include "engine/IEngineSound.h"
#include "cs_simple_hostage.h"
#include "cs_player_resource.h"
// NOTE: This has to be the last file included!
#include "tier0/memdbgon.h"
BEGIN_DATADESC( CChicken )
DEFINE_ENTITYFUNC( ChickenTouch ),
DEFINE_THINKFUNC( ChickenThink ),
DEFINE_USEFUNC( ChickenUse ),
END_DATADESC()
IMPLEMENT_SERVERCLASS_ST( CChicken, DT_CChicken )
SendPropBool( SENDINFO( m_jumpedThisFrame ) ),
SendPropEHandle( SENDINFO( m_leader ) ),
END_SEND_TABLE()
LINK_ENTITY_TO_CLASS( chicken, CChicken );
PRECACHE_REGISTER( chicken );
class HostagePathCost;
extern ConVar hostage_debug;
#define CHICKEN_ZOMBIE_SPAWN_DURATION 3.5f
#define CHICKEN_DISTANCE_RUN 200.0f
#define CHICKEN_DISTANCE_WALK 100.0f
//-----------------------------------------------------------------------
CChicken::CChicken()
{
}
//-----------------------------------------------------------------------
CChicken::~CChicken()
{
}
//-----------------------------------------------------------------------
void CChicken::Precache( void )
{
SetModelName( MAKE_STRING( "models/chicken/chicken.mdl" ) ); // prop precache wants this
BaseClass::Precache();
PrecacheModel( "models/chicken/chicken.mdl" );
PrecacheModel( "models/chicken/chicken_zombie.mdl" );
PrecacheModel( "models/chicken/chicken_gone.mdl" );
PrecacheModel( "models/antlers/antlers.mdl" );
PrecacheScriptSound( "Chicken.Idle" );
PrecacheScriptSound( "Chicken.Panic" );
PrecacheScriptSound( "Chicken.Fly" );
PrecacheScriptSound( "Chicken.FlapWings" );
PrecacheScriptSound( "Chicken.Death" );
PrecacheScriptSound( "Chicken.ZombieRez" );
PrecacheParticleSystem( "weapon_confetti_omni" );
PrecacheParticleSystem( "chicken_rez" );
PrecacheParticleSystem( "chicken_gone_crumble_halloween" );
PrecacheParticleSystem( "chicken_gone_zombie" );
PrecacheParticleSystem( "impact_helmet_headshot" );
}
//-----------------------------------------------------------------------
void CChicken::Spawn( void )
{
SetModel( "models/chicken/chicken.mdl" );
BaseClass::Spawn();
SetNextThink( gpGlobals->curtime );
SetThink( &CChicken::ChickenThink );
SetTouch( &CChicken::ChickenTouch );
SetUse( &CChicken::ChickenUse );
SetSolid( SOLID_BBOX );
SetMoveType( MOVETYPE_FLYGRAVITY );
SetCollisionGroup( COLLISION_GROUP_INTERACTIVE_DEBRIS );
const model_t *pModel = modelinfo->GetModel( GetModelIndex() );
if ( pModel )
{
Vector mins, maxs;
modelinfo->GetModelBounds( pModel, mins, maxs );
mins.z = 0.0f;
SetCollisionBounds( mins, maxs );
}
SetGravity( 1.0 );
SetHealth( 1 );
SetMaxHealth( 1 );
m_takedamage = DAMAGE_YES;
Idle();
m_fleeFrom = NULL;
m_updateTimer.Invalidate();
m_reuseTimer.Invalidate( );
m_moveRateThrottleTimer.Invalidate( );
m_stuckAnchor = GetAbsOrigin();
m_stuckTimer.Start( 1.0f );
m_isOnGround = false;
m_startleTimer.Invalidate();
ListenForGameEvent( "weapon_fire" );
//ListenForGameEvent( "bullet_impact" );
if ( CSGameRules() && CSGameRules()->IsCSGOBirthday() )
{
SetBodygroup( 1, 1 ); // birthday hat
}
m_leader = INVALID_EHANDLE;
m_reuseTimer.Invalidate( );
m_hasBeenUsed = false;
m_jumpedThisFrame = false;
m_path.Invalidate( );
m_repathTimer.Invalidate( );
m_pathFollower.Reset( );
m_pathFollower.SetPath( &m_path );
m_pathFollower.SetImprov( this );
m_lastKnownArea = NULL;
// Need to make sure the hostages are on the ground when they spawn
// Vector GroundPos = DropToGround( this, GetAbsOrigin( ), HOSTAGE_BBOX_VEC_MIN, HOSTAGE_BBOX_VEC_MAX );
// SetAbsOrigin( GroundPos );
m_bInJump = false;
m_flLastJumpTime = 0;
m_inhibitObstacleAvoidanceTimer.Invalidate( );
m_isWaitingForLeader = false;
m_lastLeaderID = 0;
m_flActiveFollowStartTime = 0;
}
//-----------------------------------------------------------------------
void CChicken::ChickenTouch( CBaseEntity *pOther )
{
if ( !CSGameRules() || CSGameRules()->IsPlayingAnyCompetitiveStrictRuleset() )
{
Flee( pOther, RandomFloat( 2.0f, 3.0f ) );
}
}
bool CChicken::IsFollowingSomeone( void )
{
return ( m_leader.m_Value != NULL );
}
//-----------------------------------------------------------------------------------------------------
bool CChicken::IsFollowing( const CBaseEntity *entity )
{
return ( m_leader.m_Value == entity );
}
//-----------------------------------------------------------------------------------------------------
bool CChicken::IsOnGround( void ) const
{
return ( GetFlags( ) & FL_ONGROUND );
}
//-----------------------------------------------------------------------------------------------------
/**
* Begin following "leader"
*/
void CChicken::Follow( CCSPlayer *leader )
{
m_lastLeaderID = 0;
if ( leader )
{
leader->IncrementNumFollowers( );
m_lastLeaderID = leader->GetUserID( );
m_leader = leader;
}
else
{
m_leader = INVALID_EHANDLE;
}
m_leader = leader;
m_isWaitingForLeader = false;
m_flActiveFollowStartTime = gpGlobals->curtime;
m_moveRateThrottleTimer.Start( 1.0f);
}
//-----------------------------------------------------------------------------------------------------
/**
* Return our leader, or NULL
*/
CCSPlayer *CChicken::GetLeader( void ) const
{
return ToCSPlayer( m_leader.m_Value );
}
//-----------------------------------------------------------------------------------------------------
/**
* Invoked when a chicken is "used" by a player
*/
void CChicken::ChickenUse( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value )
{
CCSPlayer *pPlayer = ToCSPlayer( pActivator );
if ( !pPlayer )
return;
// limit use range
float useRange = 1000.0f;
Vector to = pActivator->GetAbsOrigin( ) - GetAbsOrigin( );
if ( to.IsLengthGreaterThan( useRange ) )
{
return;
}
SetChickenStartFollowingPlayer( pPlayer );
}
void CChicken::SetChickenStartFollowingPlayer( CCSPlayer *pPlayer )
{
// throttle how often leader can change
if ( !m_reuseTimer.IsElapsed( ) )
{
return;
}
// if we are already following the player who used us, stop following
if ( IsFollowing( pPlayer ) )
{
Follow( NULL );
Idle( );
EmitSound( "Chicken.Idle" );
}
else
{
// if we're already following a CT, ignore new uses
if ( IsFollowingSomeone( ) )
{
return;
}
// start following
Follow( pPlayer );
EmitSound( "Chicken.FlapWings" );
Jump( 50.0f );
}
m_reuseTimer.Start( 1.0f );
}
//--------------------------------------------------------------------------------------------------------------
/**
* Rotate body to face towards "target"
*/
void CChicken::FaceTowards( const Vector &target, float deltaT )
{
Vector to = target - GetFeet( );
to.z = 0.0f;
QAngle desiredAngles;
VectorAngles( to, desiredAngles );
QAngle angles = GetAbsAngles( );
// The animstate system for hostages will smooth out the transition to this direction, so no need to double smooth it here.
angles.y = desiredAngles.y;
SetAbsAngles( angles );
}
int CChicken::OnTakeDamage( const CTakeDamageInfo &info )
{
/*
if ( EconHolidays_IsHolidayActive( kHoliday_Halloween ) )
{
// if we recently turned into a zombie, ignore damage for CHICKEN_ZOMBIE_SPAWN_DURATION seconds.
if ( IsZombie() )
{
if ( (gpGlobals->curtime - m_flWhenZombified) > CHICKEN_ZOMBIE_SPAWN_DURATION )
{
return BaseClass::OnTakeDamage( info );
}
else
{
return 0;
}
}
else
{
if ( m_activity != ACT_GLIDE && m_isOnGround )
{
//when there's no more room in chicken-hell... turn into a chicken zombie!
Zombify();
SetModel( "models/chicken/chicken_zombie.mdl" );
m_activity = ACT_CLIMB_UP;
ResetSequence( LookupSequence( "spawn" ) );
ResetSequenceInfo();
ForceCycle( 0 );
DispatchParticleEffect( "chicken_gone_crumble_halloween", GetAbsOrigin() + Vector( 0, 0, 8 ), QAngle( 0, 0, 0 ) );
CTraceFilterNoNPCsOrPlayer traceFilter( this, COLLISION_GROUP_NONE );
trace_t tr;
UTIL_TraceLine( GetAbsOrigin(), GetAbsOrigin() + Vector( 0, 0, -16 ), MASK_PLAYERSOLID, &traceFilter, &tr );
Vector vecPos, vecVel, vecNormal;
QAngle angNormal;
vecNormal = tr.DidHit() ? tr.plane.normal : Vector( 0, 0, 0 );
//vecNormal.y *= -1;
//vecNormal.z *= -1;
VectorAngles( vecNormal, angNormal );
angNormal.x += 90;
DispatchParticleEffect( "chicken_rez", GetAbsOrigin(), angNormal );
CSoundParameters params;
if ( GetParametersForSound( "Chicken.ZombieRez", params, NULL ) )
{
EmitSound_t ep( params );
ep.m_pOrigin = &GetAbsOrigin();
CBroadcastRecipientFilter filter;
EmitSound( filter, SOUND_FROM_WORLD, ep );
}
SetSolid( SOLID_NONE );
return 0;
}
else
{
return BaseClass::OnTakeDamage( info );
}
}
}
else
*/
{
return BaseClass::OnTakeDamage( info );
}
}
//-----------------------------------------------------------------------
void CChicken::Event_Killed( const CTakeDamageInfo &info )
{
EmitSound( "Chicken.Death" );
if ( CSGameRules() && CSGameRules()->IsCSGOBirthday() )
DispatchParticleEffect( "weapon_confetti_omni", GetAbsOrigin(), QAngle( 0, 0, 0 ) );
if ( IsZombie() )
DispatchParticleEffect( "chicken_gone_zombie", GetAbsOrigin() + Vector( 0, 0, 8 ), QAngle( 0, 0, 0 ) );
if ( IsFollowingSomeone( ) )
{
CSingleUserRecipientFilter leaderfilter( ToCSPlayer( m_leader.m_Value ) );
leaderfilter.MakeReliable( );
float flFollowDuration = gpGlobals->curtime - m_flActiveFollowStartTime;
UTIL_ClientPrintFilter( leaderfilter, HUD_PRINTTALK, "#Pet_Killed", CFmtStr( "%.0f", flFollowDuration ).Get() );
}
BaseClass::Event_Killed( info );
}
//-----------------------------------------------------------------------
void CChicken::FireGameEvent( IGameEvent *event )
{
// all the events we care about scare us
if ( m_startleTimer.HasStarted() )
{
// we're already scared
return;
}
if ( event->GetBool( "silenced" ) )
{
// Silenced weapons don't scare chickens
return;
}
CBasePlayer *player = UTIL_PlayerByUserId( event->GetInt( "userid" ) );
if ( player )
{
const float fleeGunfireRange = 1000.0f;
Vector toPlayer = player->GetAbsOrigin() - GetAbsOrigin();
if ( toPlayer.IsLengthLessThan( fleeGunfireRange ) )
{
m_startleTimer.Start( RandomFloat( 0.1f, 0.5f ) );
m_fleeFrom = player;
}
}
}
//-----------------------------------------------------------------------
void CChicken::Idle()
{
// m_leader = NULL;
m_activity = ACT_IDLE;
m_activityTimer.Start( RandomFloat( 0.5, 3.0f ) );
SetSequence( SelectWeightedSequence( m_activity ) );
ResetSequenceInfo();
m_pathFollower.ResetStuck( );
}
//-----------------------------------------------------------------------
void CChicken::Walk()
{
m_activity = ACT_WALK;
m_activityTimer.Start( RandomFloat( 0.5, 3.0f ) );
m_turnRate = RandomFloat( -45.0f, 45.0f );
SetSequence( SelectWeightedSequence( m_activity ) );
ResetSequenceInfo();
}
//-----------------------------------------------------------------------
void CChicken::Flee( CBaseEntity *fleeFrom, float duration )
{
if ( m_activity != ACT_RUN || m_vocalizeTimer.IsElapsed() )
{
// throttle interval between vocalizations
m_vocalizeTimer.Start( RandomFloat( 0.5f, 1.0f ) );
EmitSound( "Chicken.Panic" );
}
m_activity = ACT_RUN;
m_activityTimer.Start( duration );
m_turnRate = 0.0f;
m_fleeFrom = fleeFrom;
SetSequence( SelectWeightedSequence( m_activity ) );
ResetSequenceInfo();
}
//-----------------------------------------------------------------------
void CChicken::Fly()
{
if ( m_activity != ACT_GLIDE || m_vocalizeTimer.IsElapsed() )
{
// throttle interval between vocalizations
m_vocalizeTimer.Start( RandomFloat( 0.5f, 1.0f ) );
EmitSound( "Chicken.Fly" );
}
m_activity = ACT_GLIDE;
m_turnRate = 0.0f;
SetSequence( SelectWeightedSequence( m_activity ) );
ResetSequenceInfo();
}
//-----------------------------------------------------------------------
void CChicken::Land()
{
if ( m_activity != ACT_LAND || m_vocalizeTimer.IsElapsed() )
{
// throttle interval between vocalizations
m_vocalizeTimer.Start( RandomFloat( 0.5f, 1.0f ) );
EmitSound( "Chicken.Idle" );
}
m_activity = ACT_LAND;
m_turnRate = 0.0f;
SetSequence( SelectWeightedSequence( m_activity ) );
ResetSequenceInfo();
}
//-----------------------------------------------------------------------
void CChicken::Update( void )
{
if ( GetLeader( ) )
return;
if ( !m_updateTimer.IsElapsed() )
return;
m_updateTimer.Start( RandomFloat( 0.5f, 1.0f ) );
// find closest visible player
CUtlVector< CBasePlayer * > playerVector;
CollectPlayers( &playerVector, TEAM_ANY, COLLECT_ONLY_LIVING_PLAYERS );
float closeRangeSq = FLT_MAX;
CBasePlayer *close = NULL;
for( int i=0; i<playerVector.Count(); ++i )
{
Vector toPlayer = playerVector[i]->GetAbsOrigin() - GetAbsOrigin();
float rangeSq = toPlayer.LengthSqr();
// Only scare chickens if we're close
if ( rangeSq < closeRangeSq )
{
// Only scare chickens if we're moving fast enough to make noise
Vector vPlayerVelocity;
playerVector[i]->GetVelocity( &vPlayerVelocity, NULL );
if ( vPlayerVelocity.Length() > 126.0f )
{
if ( playerVector[i]->IsLineOfSightClear( this ) )
{
closeRangeSq = rangeSq;
close = playerVector[i];
}
}
}
}
const float tooClose = 200.0f;
if ( close && closeRangeSq < tooClose * tooClose )
{
Flee( close, RandomFloat( 0.5, 1.0f ) );
}
}
//-----------------------------------------------------------------------
float CChicken::AvoidObstacles( void )
{
const float feelerRange = 15.0f;
const Vector &forward = Forward();
Vector left( -forward.y, forward.x, 0.0f );
Vector right( forward.y, -forward.x, 0.0f );
CTraceFilterNoNPCsOrPlayer traceFilter( this, COLLISION_GROUP_NONE );
trace_t resultLeft;
UTIL_TraceLine( WorldSpaceCenter(), WorldSpaceCenter() + feelerRange * ( forward + left ), MASK_PLAYERSOLID, &traceFilter, &resultLeft );
//NDebugOverlay::Line( WorldSpaceCenter(), WorldSpaceCenter() + feelerRange * ( forward + left ), 0, 0, 255, true, NDEBUG_PERSIST_TILL_NEXT_SERVER );
trace_t resultRight;
UTIL_TraceLine( WorldSpaceCenter(), WorldSpaceCenter() + feelerRange * ( forward + right ), MASK_PLAYERSOLID, &traceFilter, &resultRight );
//NDebugOverlay::Line( WorldSpaceCenter(), WorldSpaceCenter() + feelerRange * ( forward + right ), 255, 0, 0, true, NDEBUG_PERSIST_TILL_NEXT_SERVER );
const float maxTurnRate = 360.0f;
float turnRate = 0.0f;
if ( resultLeft.DidHit() )
{
if ( resultRight.DidHit() )
{
// both sides hit
if ( resultLeft.fraction < resultRight.fraction )
{
// left hit closer - turn right
turnRate = -maxTurnRate;
}
else
{
// right hit closer - turn left
turnRate = maxTurnRate;
}
}
else
{
// left hit - turn right
turnRate = -maxTurnRate;
}
}
else if ( resultRight.DidHit() )
{
// right hit - turn left
turnRate = maxTurnRate;
}
Vector toAnchor = m_stuckAnchor - GetAbsOrigin();
if ( toAnchor.IsLengthGreaterThan( 50.0f ) )
{
m_stuckAnchor = GetAbsOrigin();
m_stuckTimer.Reset();
}
return turnRate;
}
//-----------------------------------------------------------------------
void CChicken::ResolveCollisions( const Vector &desiredPosition, float deltaT )
{
CTraceFilterNoNPCsOrPlayer traceFilter( this, COLLISION_GROUP_NONE );
trace_t result;
const float stepHeight = WorldAlignSize().z / 2.0f;
// try to do full move
Vector testPosition = desiredPosition;
for( int slideCount=0; slideCount<3; ++slideCount )
{
UTIL_TraceHull( GetAbsOrigin(), testPosition, WorldAlignMins() + Vector( 0, 0, stepHeight ), WorldAlignMaxs(), MASK_PLAYERSOLID, &traceFilter, &result );
if ( !result.DidHit() )
{
break;
}
Vector fullMove = testPosition - GetAbsOrigin();
float blocked = DotProduct( fullMove, result.plane.normal );
testPosition = GetAbsOrigin() + fullMove - blocked * result.plane.normal;
}
Vector resolvedPosition = result.endpos;
// snap to ground (or fall)
UTIL_TraceHull( resolvedPosition + Vector( 0, 0, stepHeight ), resolvedPosition + Vector( 0, 0, -stepHeight ), WorldAlignMins(), WorldAlignMaxs(), MASK_PLAYERSOLID, &traceFilter, &result );
if ( result.DidHit( ) && !IsJumping( ) )
{
// limit slope that can be walked up
const float slopeLimit = 0.7071f;
if ( !result.plane.normal.IsZero() && result.plane.normal.z > slopeLimit )
{
SetAbsOrigin( result.endpos );
}
else
{
SetAbsOrigin( resolvedPosition );
}
if ( !m_isOnGround )
{
Land();
m_isOnGround = true;
m_bInJump = false;
}
}
else
{
SetAbsOrigin( resolvedPosition );
// fall
SetBaseVelocity( GetBaseVelocity() + Vector( 0, 0, GetGravity() * deltaT ) );
m_isOnGround = false;
Fly();
}
}
void CChicken::UpdateFollowing( float deltaT )
{
if ( !IsFollowingSomeone( ) && m_lastLeaderID != 0 )
{
m_lastLeaderID = 0;
}
// if we have a leader, follow him
CCSPlayer *leader = GetLeader( );
if ( leader )
{
// if leader is dead, stop following him
if ( !leader->IsAlive( ) )
{
Follow( NULL );
Idle( );
return;
}
// m_nHostageState = k_EHostageStates_FollowingPlayer;
// if leader has moved, repath
if ( m_path.IsValid( ) )
{
Vector pathError = leader->GetAbsOrigin( ) - m_path.GetEndpoint( );
const float repathRange = 100.0f;
if ( pathError.IsLengthGreaterThan( repathRange ) )
{
m_path.Invalidate( );
}
// m_activity = ACT_WALK;
}
// build a path to our leader
if ( !m_path.IsValid( ) && m_repathTimer.IsElapsed( ) )
{
const float repathInterval = 0.5f;
m_repathTimer.Start( repathInterval );
Vector from = GetAbsOrigin( );
Vector to = leader->GetAbsOrigin( );
HostagePathCost pathCost;
m_path.Compute( from, to, pathCost );
m_pathFollower.Reset( );
}
// if our rescuer is too far away, give up
const float giveUpRange = 2000.0f;
const float maxPathLength = 4000.0f;
Vector toLeader = leader->GetAbsOrigin( ) - GetAbsOrigin( );
if ( toLeader.IsLengthGreaterThan( giveUpRange ) || ( m_path.IsValid( ) && m_path.GetLength( ) > maxPathLength ) )
{
if ( hostage_debug.GetInt( ) < 2 )
{
Idle( );
}
return;
}
// don't crowd the leader
if ( m_isWaitingForLeader )
{
// we are close to our leader and waiting for him to move
const float waitRange = 200.0f;
if ( toLeader.IsLengthGreaterThan( waitRange ) )
{
// leader has moved away - follow him
m_isWaitingForLeader = false;
}
}
if ( !m_isWaitingForLeader )
{
// move along path towards the leader
m_pathFollower.Update( deltaT, m_inhibitObstacleAvoidanceTimer.IsElapsed( ) );
if ( hostage_debug.GetBool( ) )
{
m_pathFollower.Debug( true );
}
float flDist = GetFeet( ).DistTo( ToCSPlayer( m_leader.m_Value )->GetAbsOrigin( ) );
const float minStuckJumpTime = 1.0f;
if ( ( m_pathFollower.GetStuckDuration( ) > minStuckJumpTime ) && ( flDist > CHICKEN_DISTANCE_RUN * 2 ) )
{
Jump( );
}
if ( hostage_debug.GetBool( ) )
{
m_path.Draw( );
}
}
}
}
//-----------------------------------------------------------------------
void CChicken::ChickenThink( void )
{
float deltaT = gpGlobals->frametime;
SetNextThink( gpGlobals->curtime + deltaT );
// if we've been a zombie for less than CHICKEN_ZOMBIE_SPAWN_DURATION seconds
float flZombieDuration = (gpGlobals->curtime - m_flWhenZombified);
if ( IsZombie() && flZombieDuration < CHICKEN_ZOMBIE_SPAWN_DURATION )
{
m_activity = ACT_CLIMB_UP;
SetSequence( LookupSequence( "spawn" ) );
SetCycle( flZombieDuration / CHICKEN_ZOMBIE_SPAWN_DURATION );
m_activityTimer.Start( 0 );
SetSolid( SOLID_NONE );
}
else if ( IsZombie() && (m_flWhenZombified + 1.0f) > (gpGlobals->curtime - CHICKEN_ZOMBIE_SPAWN_DURATION) )
{
SetSolid( SOLID_BBOX );
m_activity = ACT_WALK;
}
// do leader-following behavior, if necessary
UpdateFollowing( deltaT );
Update();
if ( m_startleTimer.HasStarted() && m_startleTimer.IsElapsed() )
{
// we were startled by something and have just noticed it
m_startleTimer.Invalidate();
Flee( m_fleeFrom, RandomFloat( 2.0f, 3.0f ) );
}
if ( IsActivityFinished() && !IsFollowingSomeone() )
{
switch ( ( int ) m_activity )
{
case ACT_IDLE:
if ( RandomInt( 1, 100 ) < 30 )
{
Walk( );
}
break;
case ACT_WALK:
if ( m_activityTimer.IsElapsed( ) )
{
Idle( );
}
break;
case ACT_RUN:
if ( m_activityTimer.IsElapsed( ) )
{
Walk( );
}
break;
case ACT_GLIDE:
Fly( );
break;
case ACT_LAND:
Walk( );
break;
}
}
else// ongoing activity
{
if ( IsFollowingSomeone( ) )
{
if ( m_moveRateThrottleTimer.IsElapsed( ) )
{
float flDist = GetFeet( ).DistTo( ToCSPlayer( m_leader.m_Value )->GetAbsOrigin( ) );
if ( flDist < ( CHICKEN_DISTANCE_WALK * 0.9f ) )
{
if ( m_activity != ACT_IDLE )
Idle( );
}
else if ( flDist > ( CHICKEN_DISTANCE_WALK * 1.1f ) && flDist < ( CHICKEN_DISTANCE_RUN * 0.9f ) )
{
if ( m_activity != ACT_WALK )
Walk( );
}
if ( flDist > ( CHICKEN_DISTANCE_RUN * 1.1f ) )
{
if ( m_activity != ACT_RUN )
Run( );
}
m_moveRateThrottleTimer.Start( RandomFloat( 0.0f, 0.5f ) );
}
}
if ( m_activity == ACT_IDLE || m_activity == ACT_WALK )
{
// sound like a calm chicken
if ( m_vocalizeTimer.IsElapsed() )
{
m_vocalizeTimer.Start( RandomFloat( 1.5f, 4.5f ) );
EmitSound( "Chicken.Idle" );
}
}
// don't walk/run in a straight line - turn a bit
switch ( ( int ) m_activity )
{
case ACT_WALK:
case ACT_RUN:
QAngle angle = GetAbsAngles( );
if ( m_fleeFrom != NULL )
{
Vector fleeVector = GetAbsOrigin( ) - m_fleeFrom->GetAbsOrigin( );
fleeVector.z = 0.0f;
if ( IsZombie( ) )
fleeVector = -fleeVector; //zombie chickens flee TOWARDS players
float fleeRange = fleeVector.NormalizeInPlace( );
const float safeRange = 150.0f;
if ( fleeRange > safeRange )
{
m_fleeFrom = NULL;
}
else
{
m_activityTimer.Reset( );
if ( DotProduct( fleeVector, Forward( ) ) < 0.7071f )
{
// turn away
m_turnRate = 360.0f;
if ( CrossProduct( fleeVector, Forward( ) ).z > 0.0f )
{
m_turnRate = -m_turnRate;
}
}
else
{
m_turnRate = 0.0f;
}
}
float obstacleTurnRate = AvoidObstacles( );
float actualTurnRate = ( obstacleTurnRate == 0.0f ) ? m_turnRate : obstacleTurnRate;
angle.y += actualTurnRate * deltaT;
SetAbsAngles( angle );
}
else if ( IsFollowingSomeone( ) )
{
Vector followVector = {0,0,0};
m_activityTimer.Reset( );
CTraceFilterNoNPCsOrPlayer traceFilter( this, COLLISION_GROUP_NONE );
trace_t tr;
UTIL_TraceLine( GetEyes( ), ToCSPlayer( m_leader.m_Value )->GetAbsOrigin( ), MASK_PLAYERSOLID, &traceFilter, &tr );
if ( tr.fraction == 1.0 ) // chicken can see player so target player
{
followVector = ToCSPlayer( m_leader.m_Value )->GetAbsOrigin( ) - GetAbsOrigin( );
}
else// chicken cannot see player so target next track node
{
followVector = m_vecPathGoal - GetAbsOrigin( );
}
float followRange = followVector.NormalizeInPlace( );
// we use an softer angle threshold at greater distances. This makes the chicken seem more organic.
float flAngleTheshold = RemapValClamped( followRange, 300, 2000, 0.96, 0.707 );
if ( DotProduct( followVector, Forward( ) ) < flAngleTheshold )
{
m_turnRate = 360.0f;
if ( CrossProduct( followVector, Forward( ) ).z > 0.0f )
{
m_turnRate = -m_turnRate;
}
}
else
{
m_turnRate = 0.0f;
}
// If the path goal is above us then don't try to avoid obstacles even if one is present.
// Instead brute force into a wiggle aka jump;
//
float actualTurnRate = m_turnRate;
float obstacleTurnRate = AvoidObstacles( );
if ( DotProduct( followVector, Up( ) ) >= .9f ) // the path goal is overhead
{
Jump( );
}
if ( obstacleTurnRate != 0.0f )
{
actualTurnRate = obstacleTurnRate;
}
angle.y += actualTurnRate * deltaT;
SetAbsAngles( angle );;
}
break;
}
}
Vector desiredPosition;
Vector velocityFromAnimation = GetGroundSpeedVelocity();
desiredPosition = GetAbsOrigin() + velocityFromAnimation * deltaT;
ResolveCollisions( desiredPosition, deltaT );
SetPlaybackRate( 1.0f );
StudioFrameAdvance();
}
const Vector &CChicken::GetCentroid( void ) const
{
static Vector centroid;
centroid = GetFeet( );
centroid.z += HalfHumanHeight;
return centroid;
}
//-----------------------------------------------------------------------------------------------------
/**
* Return position of "feet" - point below centroid of improv at feet level
*/
const Vector &CChicken::GetFeet( void ) const
{
static Vector feet;
feet = GetAbsOrigin( );
return feet;
}
//-----------------------------------------------------------------------------------------------------
const Vector &CChicken::GetEyes( void ) const
{
static Vector eyes;
eyes = EyePosition( );
return eyes;
}
//-----------------------------------------------------------------------------------------------------
/**
* Return direction of movement
*/
float CChicken::GetMoveAngle( void ) const
{
return GetAbsAngles( ).y;
}
//-----------------------------------------------------------------------------------------------------
CNavArea *CChicken::GetLastKnownArea( void ) const
{
return m_lastKnownArea;
}
//-----------------------------------------------------------------------------------------------------
/**
* Find "simple" ground height, treating current nav area as part of the floo
*/
bool CChicken::GetSimpleGroundHeightWithFloor( const Vector &pos, float *height, Vector *normal )
{
if ( TheNavMesh->GetSimpleGroundHeight( pos, height, normal ) )
{
// our current nav area also serves as a ground polygon
if ( m_lastKnownArea && m_lastKnownArea->IsOverlapping( pos ) )
{
*height = MAX( ( *height ), m_lastKnownArea->GetZ( pos ) );
}
return true;
}
return false;
}
//-----------------------------------------------------------------------------------------------------
void CChicken::Crouch( void )
{
// m_isCrouching = true;
}
//-----------------------------------------------------------------------------------------------------
/**
* un-crouch
*/
void CChicken::StandUp( void )
{
// m_isCrouching = false;
}
//-----------------------------------------------------------------------------------------------------
bool CChicken::IsCrouching( void ) const
{
return false;
}
//-----------------------------------------------------------------------------------------------------
/**
* Initiate a jump
*/
void CChicken::Jump( void )
{
float flJumpPower = 250.0f; /*RandomFloat( 10.0f, 200.0f );*/ /*RemapValClamped( flTimeSinceLastJump, 3.0, 20.0, 200.0f, 30.0f );*/
Jump( flJumpPower );
}
void CChicken::Jump( float flVelocity )
{
// don't jump if the nav disallows it
CNavArea *myArea = GetLastKnownArea( );
if ( myArea && myArea->HasAttributes( NAV_MESH_NO_JUMP ) )
return;
if ( CanJump( ) && IsOnGround( ) )
{
const float minJumpInterval = 0.1f;
m_jumpTimer.Start( minJumpInterval );
m_bInJump = true;
//
// Vector dir;
// AngleVectors( GetAbsAngles( ), &dir, NULL, NULL );
//
// vel += dir * 10;
Vector vel = GetAbsVelocity( );
vel.z += flVelocity;
SetAbsVelocity( vel );
SetSequence( SelectWeightedSequence( ACT_RUN ) );
ResetSequenceInfo( );
m_jumpedThisFrame = true;
m_flLastJumpTime = gpGlobals->curtime;
}
}
//-----------------------------------------------------------------------------------------------------
bool CChicken::IsJumping( void ) const
{
//return m_bInJump;
return !m_jumpTimer.IsElapsed( );
}
bool CChicken::CanJump( void ) const
{
return !IsJumping( ) && ( gpGlobals->curtime - m_flLastJumpTime > 3.0f );
}
//-----------------------------------------------------------------------------------------------------
/**
* Set movement speed to running
*/
void CChicken::Run( void )
{
// m_isRunning = true;
m_activity = ACT_RUN;
m_activityTimer.Start( RandomFloat( 0.5, 3.0f ) );
m_turnRate = RandomFloat( -45.0f, 45.0f );
SetSequence( SelectWeightedSequence( m_activity ) );
ResetSequenceInfo( );
}
// -----------------------------------------------------------------------------------------------------
// /**
// * Set movement speed to walking
// */
// void CChicken::Walk( void )
// {
// m_isRunning = false;
// }
//-----------------------------------------------------------------------------------------------------
bool CChicken::IsRunning( void ) const
{
return false;
}
//-----------------------------------------------------------------------------------------------------
/**
* Invoked when a ladder is encountered while following a path
*/
void CChicken::StartLadder( const CNavLadder *ladder, NavTraverseType how, const Vector &approachPos, const Vector &departPos )
{
}
//-----------------------------------------------------------------------------------------------------
/**
* Traverse given ladder
*/
bool CChicken::TraverseLadder( const CNavLadder *ladder, NavTraverseType how, const Vector &approachPos, const Vector &departPos, float deltaT )
{
return false;
}
//-----------------------------------------------------------------------------------------------------
bool CChicken::IsUsingLadder( void ) const
{
return false;
}
//-----------------------------------------------------------------------------------------------------
void CChicken::TrackPath( const Vector &pathGoal, float deltaT )
{
m_vecPathGoal = pathGoal;
}
//-----------------------------------------------------------------------------------------------------
/**
* Invoked when an improv reaches its MoveTo goal
*/
void CChicken::OnMoveToSuccess( const Vector &goal )
{
}
//-----------------------------------------------------------------------------------------------------
/**
* Invoked when an improv fails to reach a MoveTo goal
*/
void CChicken::OnMoveToFailure( const Vector &goal, MoveToFailureType reason )
{
}
| 0 | 0.857549 | 1 | 0.857549 | game-dev | MEDIA | 0.984069 | game-dev | 0.905884 | 1 | 0.905884 |
kirodotdev/spirit-of-kiro | 13,892 | client/src/utils/physics.ts | export enum PhysicsType {
Static = "static",
Field = "field",
Dynamic = "dynamic"
}
export interface PhysicsProperties {
angle: number; // Angle in degrees
velocity: number; // Velocity in tiles per second
friction: number; // Friction coefficient between 0 and 1
active: boolean;
event?: string; // Event to emit when this item collides with another item
height: number; // Current height above ground in tile units
verticalVelocity: number; // Vertical velocity in tile units per second
bounceStrength: number; // How much velocity is retained on bounce (0-1)
mass: number; // Mass of object for collision calculations
physicsType?: PhysicsType; // Type of physics object (static, field, or dynamic), defaults to dynamic
}
export interface Vector2D {
x: number;
y: number;
}
export interface CollisionResult {
collided: boolean;
newVelocity?: Vector2D;
newPosition?: Vector2D;
}
// Convert angle in degrees and magnitude to a vector
export function angleToVector(angle: number, magnitude: number): Vector2D {
const radians = angle * (Math.PI / 180);
return {
x: Math.cos(radians) * magnitude,
y: Math.sin(radians) * magnitude
};
}
// Convert a vector to angle in degrees and magnitude
export function vectorToAngle(vector: Vector2D): { angle: number, magnitude: number } {
const magnitude = Math.sqrt(vector.x * vector.x + vector.y * vector.y);
let angle = Math.atan2(vector.y, vector.x) * (180 / Math.PI);
if (angle < 0) angle += 360;
return { angle, magnitude };
}
// Apply physics update to an object's position based on its physics properties
export function updatePhysicsPosition(
row: number,
col: number,
physics: PhysicsProperties,
deltaTime: number
): { row: number, col: number, physics: PhysicsProperties } {
if (!physics.active) {
return { row, col, physics };
}
// Convert angle and velocity to vector
const velocityVector = angleToVector(physics.angle, physics.velocity);
// Update position based on velocity
const newCol = col + (velocityVector.x * deltaTime);
const newRow = row + (velocityVector.y * deltaTime);
// Apply friction to slow down the object
let newVelocity = physics.velocity * (1 - physics.friction * deltaTime);
// Update vertical position based on vertical velocity
let newHeight = physics.height + (physics.verticalVelocity * deltaTime);
let newVerticalVelocity = physics.verticalVelocity;
// Apply gravity if object is above ground
const gravity = 9.8; // Gravity constant in tile units per second squared
newVerticalVelocity -= gravity * deltaTime;
// Check for ground collision
if (newHeight <= 0) {
newHeight = 0;
// Bounce with reduced velocity based on bounce strength
if (newVerticalVelocity < 0) {
newVerticalVelocity = -newVerticalVelocity * physics.bounceStrength;
// Apply some horizontal bounce effect too
const horizontalBounceEffect = 0.8; // How much of the bounce affects horizontal movement
newVelocity = newVelocity * (1 + (Math.abs(newVerticalVelocity) * horizontalBounceEffect * 0.1));
// Stop very small bounces to prevent endless tiny bounces
if (Math.abs(newVerticalVelocity) < 0.1) {
newVerticalVelocity = 0;
}
}
}
// Stop physics if velocity is very low
if (newVelocity < .1) {
newVelocity = 0;
}
if (newHeight < .05 && Math.abs(newVerticalVelocity) < .05) {
newHeight = 0;
newVerticalVelocity = 0;
}
// Update physics properties
const updatedPhysics = {
...physics,
velocity: newVelocity,
height: newHeight,
verticalVelocity: newVerticalVelocity,
active: newVelocity > 0 || newHeight > 0 || Math.abs(newVerticalVelocity) > 0
};
return { row: newRow, col: newCol, physics: updatedPhysics };
}
// Check for collision between two objects
export function checkCollision(
obj1: { row: number, col: number, width: number, depth: number, physics: PhysicsProperties },
obj2: { row: number, col: number, width: number, depth: number, physics: PhysicsProperties }
): boolean {
// Improved height-based collision check
// Calculate the effective height range for each object
const obj1MinHeight = obj1.physics.height;
const obj1MaxHeight = obj1.physics.height + Math.max(obj1.width, obj1.depth);
const obj2MinHeight = obj2.physics.height;
const obj2MaxHeight = obj2.physics.height + Math.max(obj2.width, obj2.depth);
// Check if height ranges overlap
if (obj1MaxHeight < obj2MinHeight || obj1MinHeight > obj2MaxHeight) {
return false;
}
// Check for rectangle overlap
return (
obj1.col < obj2.col + obj2.width &&
obj1.col + obj1.width > obj2.col &&
obj1.row < obj2.row + obj2.depth &&
obj1.row + obj1.depth > obj2.row
);
}
// Handle collision between two objects with momentum transfer
export function handleCollision(
obj1: { row: number, col: number, width: number, depth: number, physics: PhysicsProperties },
obj2: { row: number, col: number, width: number, depth: number, physics: PhysicsProperties }
): { obj1Physics: PhysicsProperties, obj2Physics: PhysicsProperties } {
// Convert angles and velocities to vectors
const v1 = angleToVector(obj1.physics.angle, obj1.physics.velocity);
const v2 = angleToVector(obj2.physics.angle, obj2.physics.velocity);
// Calculate centers of objects
const center1 = { x: obj1.col + obj1.width / 2, y: obj1.row + obj1.depth / 2 };
const center2 = { x: obj2.col + obj2.width / 2, y: obj2.row + obj2.depth / 2 };
// Calculate collision normal (direction from obj1 to obj2)
const collisionNormal = {
x: center2.x - center1.x,
y: center2.y - center1.y
};
// Normalize the collision normal
const distance = Math.sqrt(collisionNormal.x * collisionNormal.x + collisionNormal.y * collisionNormal.y);
if (distance === 0) {
// Objects are exactly at the same position, push in random direction
const randomAngle = Math.random() * 360;
collisionNormal.x = Math.cos(randomAngle * (Math.PI / 180));
collisionNormal.y = Math.sin(randomAngle * (Math.PI / 180));
} else {
collisionNormal.x /= distance;
collisionNormal.y /= distance;
}
// Calculate relative velocity
const relativeVelocity = {
x: v2.x - v1.x,
y: v2.y - v1.y
};
// Calculate relative velocity in terms of the collision normal
const velocityAlongNormal = relativeVelocity.x * collisionNormal.x + relativeVelocity.y * collisionNormal.y;
// Do not resolve if objects are moving away from each other
if (velocityAlongNormal > 0) {
return { obj1Physics: obj1.physics, obj2Physics: obj2.physics };
}
// Calculate restitution (bounciness)
const restitution = Math.min(obj1.physics.bounceStrength, obj2.physics.bounceStrength);
// Calculate impulse scalar
const impulseScalar = -(1 + restitution) * velocityAlongNormal /
(1 / obj1.physics.mass + 1 / obj2.physics.mass);
// Apply impulse
const impulse = {
x: impulseScalar * collisionNormal.x,
y: impulseScalar * collisionNormal.y
};
// Update velocities
const newV1 = {
x: v1.x - (impulse.x / obj1.physics.mass),
y: v1.y - (impulse.y / obj1.physics.mass)
};
const newV2 = {
x: v2.x + (impulse.x / obj2.physics.mass),
y: v2.y + (impulse.y / obj2.physics.mass)
};
// Convert back to angle and magnitude
const newObj1 = vectorToAngle(newV1);
const newObj2 = vectorToAngle(newV2);
// Calculate height difference and adjust vertical velocities to separate objects vertically
const heightDifference = obj1.physics.height - obj2.physics.height;
let obj1VerticalVelocity = obj1.physics.verticalVelocity;
let obj2VerticalVelocity = obj2.physics.verticalVelocity;
// If objects are at similar heights, give them opposing vertical velocities to separate
if (Math.abs(heightDifference) < 0.5) {
const verticalSeparationImpulse = 2.0; // Strength of vertical separation
if (heightDifference > 0) {
// obj1 is higher, push it up more
obj1VerticalVelocity = Math.max(obj1VerticalVelocity, verticalSeparationImpulse);
obj2VerticalVelocity = Math.min(obj2VerticalVelocity, -verticalSeparationImpulse * 0.5);
} else {
// obj2 is higher, push it up more
obj2VerticalVelocity = Math.max(obj2VerticalVelocity, verticalSeparationImpulse);
obj1VerticalVelocity = Math.min(obj1VerticalVelocity, -verticalSeparationImpulse * 0.5);
}
} else {
// Add a small random vertical bounce on collision
obj1VerticalVelocity += Math.random() * 0.8 - 0.2; // -0.2 to 0.6 range
obj2VerticalVelocity += Math.random() * 0.8 - 0.2;
}
// Create new physics objects with updated values
const obj1Physics: PhysicsProperties = {
...obj1.physics,
active: true,
angle: newObj1.angle,
velocity: newObj1.magnitude,
verticalVelocity: obj1VerticalVelocity
};
const obj2Physics: PhysicsProperties = {
...obj2.physics,
active: true,
angle: newObj2.angle,
velocity: newObj2.magnitude,
verticalVelocity: obj2VerticalVelocity
};
return { obj1Physics, obj2Physics };
}
// Check for wall collisions and update physics accordingly
export function handleWallCollision(
row: number,
col: number,
width: number,
depth: number,
physics: PhysicsProperties,
walls: Array<{ row: number, col: number, width: number, depth: number, height?: number }>
): { row: number, col: number, physics: PhysicsProperties } {
let newRow = row;
let newCol = col;
let newPhysics = { ...physics };
// Check collision with each wall
for (const wall of walls) {
// Get wall height (default to 1 if not specified)
const wallHeight = wall.height !== undefined ? wall.height : 1;
// Skip collision check if object's height is greater than wall's height
if (physics.height > wallHeight) {
continue;
}
// Check if object overlaps with wall
if (
col < wall.col + wall.width &&
col + width > wall.col &&
row < wall.row + wall.depth &&
row + depth > wall.row
) {
// Calculate overlap on each axis
const overlapLeft = (wall.col + wall.width) - col;
const overlapRight = (col + width) - wall.col;
const overlapTop = (wall.row + wall.depth) - row;
const overlapBottom = (row + depth) - wall.row;
// Find the smallest overlap
const minOverlap = Math.min(overlapLeft, overlapRight, overlapTop, overlapBottom);
// Determine which side of the wall was hit
if (minOverlap === overlapLeft) {
// Hit left side of wall
newCol = wall.col + wall.width;
// Reflect angle
const velocity = angleToVector(physics.angle, physics.velocity);
velocity.x = -velocity.x * physics.bounceStrength;
const newAngleData = vectorToAngle(velocity);
newPhysics.angle = newAngleData.angle;
newPhysics.velocity = newAngleData.magnitude;
} else if (minOverlap === overlapRight) {
// Hit right side of wall
newCol = wall.col - width;
// Reflect angle
const velocity = angleToVector(physics.angle, physics.velocity);
velocity.x = -velocity.x * physics.bounceStrength;
const newAngleData = vectorToAngle(velocity);
newPhysics.angle = newAngleData.angle;
newPhysics.velocity = newAngleData.magnitude;
} else if (minOverlap === overlapTop) {
// Hit top side of wall
newRow = wall.row + wall.depth;
// Reflect angle
const velocity = angleToVector(physics.angle, physics.velocity);
velocity.y = -velocity.y * physics.bounceStrength;
const newAngleData = vectorToAngle(velocity);
newPhysics.angle = newAngleData.angle;
newPhysics.velocity = newAngleData.magnitude;
} else if (minOverlap === overlapBottom) {
// Hit bottom side of wall
newRow = wall.row - depth;
// Reflect angle
const velocity = angleToVector(physics.angle, physics.velocity);
velocity.y = -velocity.y * physics.bounceStrength;
const newAngleData = vectorToAngle(velocity);
newPhysics.angle = newAngleData.angle;
newPhysics.velocity = newAngleData.magnitude;
}
newPhysics.active = true;
}
}
return { row: newRow, col: newCol, physics: newPhysics };
}
// Function to detect and fix objects that are stuck in the air
export function detectAndFixStuckObjects(
obj: { row: number, col: number, width: number, depth: number, physics: PhysicsProperties }
): PhysicsProperties {
const physics = obj.physics;
// Check if object is potentially stuck (above ground but not moving much)
if (
physics.height > 0.1 && // Object is above ground
Math.abs(physics.verticalVelocity) < 0.2 && // Very little vertical movement
physics.velocity < 0.2 // Very little horizontal movement
) {
// Object appears to be stuck, apply a small downward force to help it fall
return {
...physics,
active: true,
verticalVelocity: -1.0, // Apply downward velocity
// Add a tiny random horizontal impulse to help break free from overlaps
angle: Math.random() * 360,
velocity: 0.5 + Math.random() * 0.5
};
}
// Check for objects that have been above ground with minimal movement for too long
// This is a more aggressive unstuck mechanism that should rarely be needed
if (
physics.height > 3 && // Significantly above ground
Math.abs(physics.verticalVelocity) < 0.1 && // Almost no vertical movement
physics.velocity < 0.1 // Almost no horizontal movement
) {
// Force object to ground level with a reset
return {
...physics,
active: true,
height: 0,
verticalVelocity: 0,
velocity: 0
};
}
return physics;
} | 0 | 0.891486 | 1 | 0.891486 | game-dev | MEDIA | 0.971149 | game-dev | 0.74841 | 1 | 0.74841 |
emoose/Arise-SDK | 1,207 | src/SDK/BP_ASTR_BTL_Landing_functions.cpp |
#include "../SDK.h"
// Name: Arise, Version: 1.0.0
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
// Function BP_ASTR_BTL_Landing.BP_ASTR_BTL_Landing_C.ReceiveCanEnter
// (Event, Protected, HasOutParms, HasDefaults, BlueprintCallable, BlueprintEvent, Const)
// Parameters:
// class UAnimInstance* AnimInstance (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
bool UBP_ASTR_BTL_Landing_C::ReceiveCanEnter(class UAnimInstance* AnimInstance)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_ASTR_BTL_Landing.BP_ASTR_BTL_Landing_C.ReceiveCanEnter");
UBP_ASTR_BTL_Landing_C_ReceiveCanEnter_Params params;
params.AnimInstance = AnimInstance;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 0 | 0.746808 | 1 | 0.746808 | game-dev | MEDIA | 0.856509 | game-dev | 0.541113 | 1 | 0.541113 |
Viagi/StateSync | 16,316 | Unity/Assets/Model/Module/Pathfinding/AstarPathfindingProject/Generators/Utilities/Voxels/VoxelClasses.cs | using UnityEngine;
using System.Collections.Generic;
using PF;
using Matrix4x4 = UnityEngine.Matrix4x4;
using Vector3 = UnityEngine.Vector3;
#if NETFX_CORE && !UNITY_EDITOR
//using MarkerMetro.Unity.WinLegacy.IO;
#endif
namespace Pathfinding.Voxels {
/** Stores a voxel field. \astarpro */
public class VoxelArea {
public const uint MaxHeight = 65536;
public const int MaxHeightInt = 65536;
/** Constant for default LinkedVoxelSpan top and bottom values.
* It is important with the U since ~0 != ~0U
* This can be used to check if a LinkedVoxelSpan is valid and not just the default span
*/
public const uint InvalidSpanValue = ~0U;
/** Initial estimate on the average number of spans (layers) in the voxel representation. Should be greater or equal to 1 */
public const float AvgSpanLayerCountEstimate = 8;
/** The width of the field along the x-axis. [Limit: >= 0] [Units: vx] */
public readonly int width = 0;
/** The depth of the field along the z-axis. [Limit: >= 0] [Units: vx] */
public readonly int depth = 0;
#if ASTAR_RECAST_CLASS_BASED_LINKED_LIST
public VoxelCell[] cells;
#endif
public CompactVoxelSpan[] compactSpans;
public CompactVoxelCell[] compactCells;
public int compactSpanCount;
public ushort[] tmpUShortArr;
public int[] areaTypes;
public ushort[] dist;
public ushort maxDistance;
public int maxRegions = 0;
public int[] DirectionX;
public int[] DirectionZ;
public Vector3[] VectorDirection;
public void Reset () {
#if !ASTAR_RECAST_CLASS_BASED_LINKED_LIST
ResetLinkedVoxelSpans();
#else
for (int i = 0; i < cells.Length; i++) cells[i].firstSpan = null;
#endif
for (int i = 0; i < compactCells.Length; i++) {
compactCells[i].count = 0;
compactCells[i].index = 0;
}
}
#if !ASTAR_RECAST_CLASS_BASED_LINKED_LIST
private void ResetLinkedVoxelSpans () {
int len = linkedSpans.Length;
linkedSpanCount = width*depth;
LinkedVoxelSpan df = new LinkedVoxelSpan(InvalidSpanValue, InvalidSpanValue, -1, -1);
for (int i = 0; i < len; ) {
// 16x unrolling, actually improves performance
linkedSpans[i] = df; i++;
linkedSpans[i] = df; i++;
linkedSpans[i] = df; i++;
linkedSpans[i] = df; i++;
linkedSpans[i] = df; i++;
linkedSpans[i] = df; i++;
linkedSpans[i] = df; i++;
linkedSpans[i] = df; i++;
linkedSpans[i] = df; i++;
linkedSpans[i] = df; i++;
linkedSpans[i] = df; i++;
linkedSpans[i] = df; i++;
linkedSpans[i] = df; i++;
linkedSpans[i] = df; i++;
linkedSpans[i] = df; i++;
linkedSpans[i] = df; i++;
}
removedStackCount = 0;
}
#endif
public VoxelArea (int width, int depth) {
this.width = width;
this.depth = depth;
int wd = width*depth;
compactCells = new CompactVoxelCell[wd];
#if !ASTAR_RECAST_CLASS_BASED_LINKED_LIST
// & ~0xF ensures it is a multiple of 16. Required for unrolling
linkedSpans = new LinkedVoxelSpan[((int)(wd*AvgSpanLayerCountEstimate) + 15)& ~0xF];
ResetLinkedVoxelSpans();
#else
cells = new VoxelCell[wd];
#endif
DirectionX = new int[4] { -1, 0, 1, 0 };
DirectionZ = new int[4] { 0, width, 0, -width };
VectorDirection = new Vector3[4] { Vector3.left, Vector3.forward, Vector3.right, Vector3.back };
}
public int GetSpanCountAll () {
int count = 0;
int wd = width*depth;
for (int x = 0; x < wd; x++) {
#if !ASTAR_RECAST_CLASS_BASED_LINKED_LIST
for (int s = x; s != -1 && linkedSpans[s].bottom != InvalidSpanValue; s = linkedSpans[s].next) {
count++;
}
#else
for (VoxelSpan s = cells[x].firstSpan; s != null; s = s.next) {
count++;
}
#endif
}
return count;
}
public int GetSpanCount () {
int count = 0;
int wd = width*depth;
for (int x = 0; x < wd; x++) {
#if !ASTAR_RECAST_CLASS_BASED_LINKED_LIST
for (int s = x; s != -1 && linkedSpans[s].bottom != InvalidSpanValue; s = linkedSpans[s].next) {
if (linkedSpans[s].area != 0) {
count++;
}
}
#else
for (VoxelSpan s = cells[x].firstSpan; s != null; s = s.next) {
if (s.area != 0) {
count++;
}
}
#endif
}
return count;
}
#if !ASTAR_RECAST_CLASS_BASED_LINKED_LIST
private int linkedSpanCount;
public LinkedVoxelSpan[] linkedSpans;
private int[] removedStack = new int[128];
private int removedStackCount = 0;
void PushToSpanRemovedStack (int index) {
// Make sure we don't overflow the list
if (removedStackCount == removedStack.Length) {
// Create a new list to hold recycled values
int[] st2 = new int[removedStackCount*4];
System.Buffer.BlockCopy(removedStack, 0, st2, 0, removedStackCount*sizeof(int));
removedStack = st2;
}
removedStack[removedStackCount] = index;
removedStackCount++;
}
#endif
public void AddLinkedSpan (int index, uint bottom, uint top, int area, int voxelWalkableClimb) {
#if ASTAR_RECAST_CLASS_BASED_LINKED_LIST
cells[index].AddSpan(bottom, top, area, voxelWalkableClimb);
#else
// linkedSpans[index] is the span with the lowest y-coordinate at the position x,z such that index=x+z*width
// i.e linkedSpans is a 2D array laid out in a 1D array (for performance and simplicity)
// Check if there is a root span, otherwise we can just add a new (valid) span and exit
if (linkedSpans[index].bottom == InvalidSpanValue) {
linkedSpans[index] = new LinkedVoxelSpan(bottom, top, area);
return;
}
int prev = -1;
// Original index, the first span we visited
int oindex = index;
while (index != -1) {
if (linkedSpans[index].bottom > top) {
// If the current span's bottom higher up than the span we want to insert's top, then they do not intersect
// and we should just insert a new span here
break;
} else if (linkedSpans[index].top < bottom) {
// The current span and the span we want to insert do not intersect
// so just skip to the next span (it might intersect)
prev = index;
index = linkedSpans[index].next;
} else {
// Intersection! Merge the spans
// Find the new bottom and top for the merged span
bottom = System.Math.Min(linkedSpans[index].bottom, bottom);
top = System.Math.Max(linkedSpans[index].top, top);
// voxelWalkableClimb is flagMergeDistance, when a walkable flag is favored before an unwalkable one
// So if a walkable span intersects an unwalkable span, the walkable span can be up to voxelWalkableClimb
// below the unwalkable span and the merged span will still be walkable
if (System.Math.Abs((int)top - (int)linkedSpans[index].top) <= voxelWalkableClimb) {
// linkedSpans[index] is the lowest span, but we might use that span's area anyway if it is walkable
area = System.Math.Max(area, linkedSpans[index].area);
}
// Find the next span in the linked list
int next = linkedSpans[index].next;
if (prev != -1) {
// There is a previous span
// Remove this span from the linked list
linkedSpans[prev].next = next;
// Add this span index to a list for recycling
PushToSpanRemovedStack(index);
// Move to the next span in the list
index = next;
} else if (next != -1) {
// This was the root span and there is a span left in the linked list
// Remove this span from the linked list by assigning the next span as the root span
linkedSpans[oindex] = linkedSpans[next];
// Recycle the old span index
PushToSpanRemovedStack(next);
// Move to the next span in the list
// NOP since we just removed the current span, the next span
// we want to visit will have the same index as we are on now (i.e oindex)
} else {
// This was the root span and there are no other spans in the linked list
// Just replace the root span with the merged span and exit
linkedSpans[oindex] = new LinkedVoxelSpan(bottom, top, area);
return;
}
}
}
// We now have a merged span that needs to be inserted
// and connected with the existing spans
// The new merged span will be inserted right after 'prev' (if it exists, otherwise before index)
// Make sure that we have enough room in our array
if (linkedSpanCount >= linkedSpans.Length) {
LinkedVoxelSpan[] tmp = linkedSpans;
int count = linkedSpanCount;
int popped = removedStackCount;
linkedSpans = new LinkedVoxelSpan[linkedSpans.Length*2];
ResetLinkedVoxelSpans();
linkedSpanCount = count;
removedStackCount = popped;
for (int i = 0; i < linkedSpanCount; i++) {
linkedSpans[i] = tmp[i];
}
Debug.Log("Layer estimate too low, doubling size of buffer.\nThis message is harmless.");
}
// Take a node from the recycling stack if possible
// Otherwise create a new node (well, just a new index really)
int nextIndex;
if (removedStackCount > 0) {
removedStackCount--;
nextIndex = removedStack[removedStackCount];
} else {
nextIndex = linkedSpanCount;
linkedSpanCount++;
}
if (prev != -1) {
//span.next = prev.next;
//prev.next = span;
linkedSpans[nextIndex] = new LinkedVoxelSpan(bottom, top, area, linkedSpans[prev].next);
linkedSpans[prev].next = nextIndex;
} else {
//span.next = firstSpan;
//firstSpan = span;
linkedSpans[nextIndex] = linkedSpans[oindex];
linkedSpans[oindex] = new LinkedVoxelSpan(bottom, top, area, nextIndex);
}
#endif
}
}
public struct LinkedVoxelSpan {
public uint bottom;
public uint top;
public int next;
/*Area
* 0 is an unwalkable span (triangle face down)
* 1 is a walkable span (triangle face up)
*/
public int area;
public LinkedVoxelSpan (uint bottom, uint top, int area) {
this.bottom = bottom; this.top = top; this.area = area; this.next = -1;
}
public LinkedVoxelSpan (uint bottom, uint top, int area, int next) {
this.bottom = bottom; this.top = top; this.area = area; this.next = next;
}
}
/** Represents a mesh. \deprecated Use RasterizationMesh instead */
[System.Obsolete("Use RasterizationMesh instead")]
public class ExtraMesh : RasterizationMesh {
public ExtraMesh (Vector3[] vertices, int[] triangles, Bounds bounds) : base(vertices, triangles, bounds) {}
public ExtraMesh (Vector3[] vertices, int[] triangles, Bounds bounds, Matrix4x4 matrix) : base(vertices, triangles, bounds, matrix) {}
}
/** Represents a mesh which will be rasterized.
* The vertices will be multiplied with the matrix when rasterizing it to voxels.
* The vertices and triangles array may be used in multiple instances, it is not changed when voxelizing.
*
* \see SceneMesh
*
* \astarpro
*/
public class RasterizationMesh {
/** Source of the mesh.
* May be null if the source was not a mesh filter
*/
public MeshFilter original;
public int area;
public Vector3[] vertices;
public int[] triangles;
/** Number of vertices in the #vertices array.
* The vertices array is often pooled and then it sometimes makes sense to use a larger array than is actually necessary.
*/
public int numVertices;
/** Number of triangles in the #triangles array.
* The triangles array is often pooled and then it sometimes makes sense to use a larger array than is actually necessary.
*/
public int numTriangles;
/** World bounds of the mesh. Assumed to already be multiplied with the matrix */
public Bounds bounds;
public Matrix4x4 matrix;
/** If true, the vertex and triangle arrays will be pooled after they have been used.
* Should be used only if the vertex and triangle arrays were originally taken from a pool.
*/
public bool pool;
public RasterizationMesh () {
}
public RasterizationMesh (Vector3[] vertices, int[] triangles, Bounds bounds) {
matrix = Matrix4x4.identity;
this.vertices = vertices;
this.numVertices = vertices.Length;
this.triangles = triangles;
this.numTriangles = triangles.Length;
this.bounds = bounds;
original = null;
area = 0;
}
public RasterizationMesh (Vector3[] vertices, int[] triangles, Bounds bounds, Matrix4x4 matrix) {
this.matrix = matrix;
this.vertices = vertices;
this.numVertices = vertices.Length;
this.triangles = triangles;
this.numTriangles = triangles.Length;
this.bounds = bounds;
original = null;
area = 0;
}
/** Recalculate the bounds based on #vertices and #matrix */
public void RecalculateBounds () {
Bounds b = new Bounds(matrix.MultiplyPoint3x4(vertices[0]), Vector3.zero);
for (int i = 1; i < numVertices; i++) {
b.Encapsulate(matrix.MultiplyPoint3x4(vertices[i]));
}
// Assigned here to avoid changing bounds if vertices would happen to be null
bounds = b;
}
/** Pool the #vertices and #triangles arrays if the #pool field is true */
public void Pool () {
if (pool) {
ArrayPool<int>.Release(ref triangles);
ArrayPool<Vector3>.Release(ref vertices);
}
}
}
/** VoxelContourSet used for recast graphs.
* \astarpro
*/
public class VoxelContourSet {
public List<VoxelContour> conts; // Pointer to all contours.
public Bounds bounds; // Bounding box of the heightfield.
}
/** VoxelContour used for recast graphs.
* \astarpro
*/
public struct VoxelContour {
public int nverts;
public int[] verts; // Vertex coordinates, each vertex contains 4 components.
public int[] rverts; // Raw vertex coordinates, each vertex contains 4 components.
public int reg; // Region ID of the contour.
public int area; // Area ID of the contour.
}
/** VoxelMesh used for recast graphs.
* \astarpro
*/
public struct VoxelMesh {
/** Vertices of the mesh */
public Int3[] verts;
/** Triangles of the mesh.
* Each element points to a vertex in the #verts array
*/
public int[] tris;
/** Area index for each triangle */
public int[] areas;
}
/** VoxelCell used for recast graphs.
* \astarpro
*/
public struct VoxelCell {
public VoxelSpan firstSpan;
//public System.Object lockObject;
public void AddSpan (uint bottom, uint top, int area, int voxelWalkableClimb) {
VoxelSpan span = new VoxelSpan(bottom, top, area);
if (firstSpan == null) {
firstSpan = span;
return;
}
VoxelSpan prev = null;
VoxelSpan cSpan = firstSpan;
while (cSpan != null) {
if (cSpan.bottom > span.top) {
break;
} else if (cSpan.top < span.bottom) {
prev = cSpan;
cSpan = cSpan.next;
} else {
if (cSpan.bottom < bottom) {
span.bottom = cSpan.bottom;
}
if (cSpan.top > top) {
span.top = cSpan.top;
}
//1 is flagMergeDistance, when a walkable flag is favored before an unwalkable one
if (System.Math.Abs((int)span.top - (int)cSpan.top) <= voxelWalkableClimb) {
span.area = System.Math.Max(span.area, cSpan.area);
}
VoxelSpan next = cSpan.next;
if (prev != null) {
prev.next = next;
} else {
firstSpan = next;
}
cSpan = next;
}
}
if (prev != null) {
span.next = prev.next;
prev.next = span;
} else {
span.next = firstSpan;
firstSpan = span;
}
}
}
/** CompactVoxelCell used for recast graphs.
* \astarpro
*/
public struct CompactVoxelCell {
public uint index;
public uint count;
public CompactVoxelCell (uint i, uint c) {
index = i;
count = c;
}
}
/** CompactVoxelSpan used for recast graphs.
* \astarpro
*/
public struct CompactVoxelSpan {
public ushort y;
public uint con;
public uint h;
public int reg;
public CompactVoxelSpan (ushort bottom, uint height) {
con = 24;
y = bottom;
h = height;
reg = 0;
}
public void SetConnection (int dir, uint value) {
int shift = dir*6;
con = (uint)((con & ~(0x3f << shift)) | ((value & 0x3f) << shift));
}
public int GetConnection (int dir) {
return ((int)con >> dir*6) & 0x3f;
}
}
/** VoxelSpan used for recast graphs.
* \astarpro
*/
public class VoxelSpan {
public uint bottom;
public uint top;
public VoxelSpan next;
/*Area
* 0 is an unwalkable span (triangle face down)
* 1 is a walkable span (triangle face up)
*/
public int area;
public VoxelSpan (uint b, uint t, int area) {
bottom = b;
top = t;
this.area = area;
}
}
}
| 0 | 0.940141 | 1 | 0.940141 | game-dev | MEDIA | 0.372235 | game-dev | 0.971065 | 1 | 0.971065 |
magefree/mage | 1,981 | Mage.Sets/src/mage/cards/d/DranaKalastriaBloodchief.java |
package mage.cards.d;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.common.SimpleActivatedAbility;
import mage.abilities.costs.mana.ManaCostsImpl;
import mage.abilities.dynamicvalue.common.GetXValue;
import mage.abilities.dynamicvalue.common.SignInversionDynamicValue;
import mage.abilities.dynamicvalue.common.StaticValue;
import mage.abilities.effects.common.continuous.BoostSourceEffect;
import mage.abilities.effects.common.continuous.BoostTargetEffect;
import mage.abilities.keyword.FlyingAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.constants.Duration;
import mage.constants.SuperType;
import mage.constants.Zone;
import mage.target.common.TargetCreaturePermanent;
/**
*
* @author Loki
*/
public final class DranaKalastriaBloodchief extends CardImpl {
public DranaKalastriaBloodchief(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{3}{B}{B}");
this.supertype.add(SuperType.LEGENDARY);
this.subtype.add(SubType.VAMPIRE);
this.subtype.add(SubType.SHAMAN);
this.power = new MageInt(4);
this.toughness = new MageInt(4);
this.addAbility(FlyingAbility.getInstance());
Ability ability = new SimpleActivatedAbility(new BoostTargetEffect(StaticValue.get(0), new SignInversionDynamicValue(GetXValue.instance), Duration.EndOfTurn), new ManaCostsImpl<>("{X}{B}{B}"));
ability.addEffect(new BoostSourceEffect(GetXValue.instance, StaticValue.get(0), Duration.EndOfTurn).concatBy("and"));
ability.addTarget(new TargetCreaturePermanent());
this.addAbility(ability);
}
private DranaKalastriaBloodchief(final DranaKalastriaBloodchief card) {
super(card);
}
@Override
public DranaKalastriaBloodchief copy() {
return new DranaKalastriaBloodchief(this);
}
}
| 0 | 0.903747 | 1 | 0.903747 | game-dev | MEDIA | 0.963023 | game-dev | 0.987716 | 1 | 0.987716 |
TASEmulators/BizHawk | 4,647 | src/BizHawk.Client.Common/config/ConfigExtensions.cs | using System.Collections.Generic;
using System.Linq;
using BizHawk.Common.StringExtensions;
using BizHawk.Emulation.Common;
using Newtonsoft.Json.Linq;
namespace BizHawk.Client.Common
{
public static class ConfigExtensions
{
private class TypeNameEncapsulator
{
public object o;
}
private static JToken Serialize(object o)
{
var tne = new TypeNameEncapsulator { o = o };
return JToken.FromObject(tne, ConfigService.Serializer)["o"];
// Maybe todo: This code is identical to the code above, except that it does not emit the legacy "$type"
// parameter that we no longer need here. Leaving that in to make bisecting during this dev phase easier, and such.
// return JToken.FromObject(o, ConfigService.Serializer);
}
private static object Deserialize(JToken j, Type type)
{
try
{
return j?.ToObject(type, ConfigService.Serializer);
}
catch
{
// presumably some sort of config mismatch. Anywhere we can expose this usefully?
return null;
}
}
/// <summary>
/// Returns the core settings for a core
/// </summary>
/// <returns>null if no settings were saved, or there was an error deserializing</returns>
public static object GetCoreSettings(this Config config, Type coreType, Type settingsType)
{
_ = config.CoreSettings.TryGetValue(coreType.ToString(), out var j);
return Deserialize(j, settingsType);
}
/// <summary>
/// Returns the core settings for a core
/// </summary>
/// <returns>null if no settings were saved, or there was an error deserializing</returns>
public static TSetting GetCoreSettings<TCore, TSetting>(this Config config)
where TCore : IEmulator
{
return (TSetting)config.GetCoreSettings(typeof(TCore), typeof(TSetting));
}
/// <summary>
/// saves the core settings for a core
/// </summary>
/// <param name="o">null to remove settings for that core instead</param>
public static void PutCoreSettings(this Config config, object o, Type coreType)
{
if (o != null)
{
config.CoreSettings[coreType.ToString()] = Serialize(o);
}
else
{
config.CoreSettings.Remove(coreType.ToString());
}
}
/// <summary>
/// Returns the core syncsettings for a core
/// </summary>
/// <returns>null if no settings were saved, or there was an error deserializing</returns>
public static object GetCoreSyncSettings(this Config config, Type coreType, Type syncSettingsType)
{
_ = config.CoreSyncSettings.TryGetValue(coreType.ToString(), out var j);
return Deserialize(j, syncSettingsType);
}
/// <summary>
/// Returns the core syncsettings for a core
/// </summary>
/// <returns>null if no settings were saved, or there was an error deserializing</returns>
public static TSync GetCoreSyncSettings<TCore, TSync>(this Config config)
where TCore : IEmulator
{
return (TSync)config.GetCoreSyncSettings(typeof(TCore), typeof(TSync));
}
/// <summary>
/// saves the core syncsettings for a core
/// </summary>
/// <param name="o">null to remove settings for that core instead</param>
public static void PutCoreSyncSettings(this Config config, object o, Type coreType)
{
if (o != null)
{
config.CoreSyncSettings[coreType.ToString()] = Serialize(o);
}
else
{
config.CoreSyncSettings.Remove(coreType.ToString());
}
}
public static void ReplaceKeysInBindings(this Config config, IReadOnlyDictionary<string, string> replMap)
{
string ReplMulti(string multiBind)
=> multiBind.TransformFields(',', bind => bind.TransformFields('+', button => replMap.TryGetValue(button, out var repl) ? repl : button));
foreach (var k in config.HotkeyBindings.Keys.ToList()) config.HotkeyBindings[k] = ReplMulti(config.HotkeyBindings[k]);
foreach (var bindCollection in new[] { config.AllTrollers, config.AllTrollersAutoFire }) // analog and feedback binds can only be bound to (host) gamepads, not keyboard
{
foreach (var k in bindCollection.Keys.ToArray()) bindCollection[k] = bindCollection[k].ToDictionary(static kvp => kvp.Key, kvp => ReplMulti(kvp.Value));
}
}
/// <param name="fileExt">file extension, including the leading period and in lowercase</param>
/// <remarks><paramref name="systemID"/> will be <see langword="null"/> if returned value is <see langword="false"/></remarks>
public static bool TryGetChosenSystemForFileExt(this Config config, string fileExt, out string systemID)
{
var b = config.PreferredPlatformsForExtensions.TryGetValue(fileExt, out var v);
if (b && !string.IsNullOrEmpty(v))
{
systemID = v;
return true;
}
systemID = null;
return false;
}
}
}
| 0 | 0.850193 | 1 | 0.850193 | game-dev | MEDIA | 0.261467 | game-dev | 0.774591 | 1 | 0.774591 |
openhumanoids/oh-distro | 8,145 | software/control/src/RobotStateCoder.java | package drc.control;
import java.io.*;
import java.lang.*;
import java.util.Arrays;
import lcm.lcm.*;
public class RobotStateCoder implements drake.util.LCMCoder
{
short m_num_joints;
int m_num_floating_joints;
java.util.TreeMap<String,Integer> m_joint_map;
java.util.TreeMap<String,Integer> m_floating_joint_map;
bot_core.robot_state_t msg;
boolean include_torques;
public RobotStateCoder(String[] joint_name, boolean incl_torques) {
this(joint_name);
include_torques = incl_torques;
}
public RobotStateCoder(String[] joint_name) {
m_joint_map = new java.util.TreeMap<String,Integer>();
m_floating_joint_map = new java.util.TreeMap<String,Integer>();
include_torques = false;
m_num_joints = 0;
m_num_floating_joints = 0;
for (int i=0; i<joint_name.length; i++) {
if (joint_name[i].startsWith("base_")) {
m_floating_joint_map.put(joint_name[i],i);
m_num_floating_joints+=1;
}
else {
m_joint_map.put(joint_name[i],i);
m_num_joints+=1;
}
}
msg = new bot_core.robot_state_t();
msg.pose = new bot_core.position_3d_t();
msg.pose.translation = new bot_core.vector_3d_t();
msg.pose.rotation = new bot_core.quaternion_t();
if (m_num_floating_joints == 0) {
msg.pose.rotation.w = 1.0;
msg.pose.translation.z = 0.927;
}
msg.twist = new bot_core.twist_t();
msg.twist.linear_velocity = new bot_core.vector_3d_t();
msg.twist.angular_velocity = new bot_core.vector_3d_t();
msg.num_joints = m_num_joints;
msg.joint_name = new String[m_num_joints];
int j=0;
for (int i=0; i<joint_name.length; i++) {
if (!(joint_name[i].startsWith("base_")))
msg.joint_name[j++] = joint_name[i];
}
msg.joint_position = new float[m_num_joints];
msg.joint_velocity = new float[m_num_joints];
msg.joint_effort = new float[m_num_joints];
}
public int dim()
{
if (include_torques)
return 3*(m_num_joints+m_num_floating_joints);
else
return 2*(m_num_joints+m_num_floating_joints);
}
public drake.util.CoordinateFrameData decode(byte[] data)
{
try {
bot_core.robot_state_t msg = new bot_core.robot_state_t(data);
return decode(msg);
} catch (IOException ex) {
System.out.println("Exception: " + ex);
}
return null;
}
public drake.util.CoordinateFrameData decode(bot_core.robot_state_t msg)
{
Integer j;
int index;
drake.util.CoordinateFrameData fdata = new drake.util.CoordinateFrameData();
fdata.val = new double[dim()];
fdata.t = (double)msg.utime / 1000000.0;
for (int i=0; i<msg.num_joints; i++) {
j = m_joint_map.get(msg.joint_name[i]);
if (j!=null) {
index = j.intValue();
fdata.val[index] = msg.joint_position[i];
fdata.val[index+m_num_joints+m_num_floating_joints] = msg.joint_velocity[i];
if (include_torques)
fdata.val[index+2*(m_num_joints+m_num_floating_joints)] = msg.joint_effort[i];
}
}
// get floating joint body position and orientation
// TODO: should be generalized eventually
j = m_floating_joint_map.get("base_x");
if (j!=null) {
index = j.intValue();
fdata.val[index] = msg.pose.translation.x;
fdata.val[index+m_num_joints+m_num_floating_joints] = msg.twist.linear_velocity.x;
}
j = m_floating_joint_map.get("base_y");
if (j!=null) {
index = j.intValue();
fdata.val[index] = msg.pose.translation.y;
fdata.val[index+m_num_joints+m_num_floating_joints] = msg.twist.linear_velocity.y;
}
j = m_floating_joint_map.get("base_z");
if (j!=null) {
index = j.intValue();
fdata.val[index] = msg.pose.translation.z;
fdata.val[index+m_num_joints+m_num_floating_joints] = msg.twist.linear_velocity.z;
}
double[] q = new double[4];
q[0] = msg.pose.rotation.w;
q[1] = msg.pose.rotation.x;
q[2] = msg.pose.rotation.y;
q[3] = msg.pose.rotation.z;
double[] rpy = drake.util.Transform.quat2rpy(q);
double[] omega = new double[3];
omega[0] = msg.twist.angular_velocity.x;
omega[1] = msg.twist.angular_velocity.y;
omega[2] = msg.twist.angular_velocity.z;
double[] rpydot = drake.util.Transform.angularvel2rpydot(rpy,omega);
j = m_floating_joint_map.get("base_roll");
if (j!=null) {
index = j.intValue();
fdata.val[index] = rpy[0];
fdata.val[index+m_num_joints+m_num_floating_joints] = rpydot[0];
}
j = m_floating_joint_map.get("base_pitch");
if (j!=null) {
index = j.intValue();
fdata.val[index] = rpy[1];
fdata.val[index+m_num_joints+m_num_floating_joints] = rpydot[1];
}
j = m_floating_joint_map.get("base_yaw");
if (j!=null) {
index = j.intValue();
fdata.val[index] = rpy[2];
fdata.val[index+m_num_joints+m_num_floating_joints] = rpydot[2];
}
return fdata;
}
public LCMEncodable encode(drake.util.CoordinateFrameData d)
{
msg.utime = (long)(d.t*1000000);
Integer j;
int index;
for (int i=0; i<m_num_joints; i++) {
j = m_joint_map.get(msg.joint_name[i]);
if (j!=null) {
index = j.intValue();
msg.joint_position[i] = (float) d.val[index];
msg.joint_velocity[i] = (float) d.val[index+m_num_joints+m_num_floating_joints];
if (include_torques)
msg.joint_effort[i] = (float) d.val[index+2*(m_num_joints+m_num_floating_joints)];
}
}
if (m_num_floating_joints != 0) {
// TODO: should be generalized eventually
j = m_floating_joint_map.get("base_x");
if (j!=null) {
index = j.intValue();
msg.pose.translation.x = (float) d.val[index];
msg.twist.linear_velocity.x = (float) d.val[index+m_num_joints+m_num_floating_joints];
}
j = m_floating_joint_map.get("base_y");
if (j!=null) {
index = j.intValue();
msg.pose.translation.y = (float) d.val[index];
msg.twist.linear_velocity.y = (float) d.val[index+m_num_joints+m_num_floating_joints];
}
j = m_floating_joint_map.get("base_z");
if (j!=null) {
index = j.intValue();
msg.pose.translation.z = (float) d.val[index];
msg.twist.linear_velocity.z = (float) d.val[index+m_num_joints+m_num_floating_joints];
}
double[] rpy = new double[3];
double[] rpydot = new double[3];
index = m_floating_joint_map.get("base_roll").intValue();
rpy[0] = d.val[index];
rpydot[0] = d.val[index+m_num_joints+m_num_floating_joints];
index = m_floating_joint_map.get("base_pitch").intValue();
rpy[1] = d.val[index];
rpydot[1] = d.val[index+m_num_joints+m_num_floating_joints];
index = m_floating_joint_map.get("base_yaw").intValue();
rpy[2] = d.val[index];
rpydot[2] = d.val[index+m_num_joints+m_num_floating_joints];
// convert rpy to quaternion
double[] q = drake.util.Transform.rpy2quat(rpy);
msg.pose.rotation.w = (float) q[0];
msg.pose.rotation.x = (float) q[1];
msg.pose.rotation.y = (float) q[2];
msg.pose.rotation.z = (float) q[3];
double[] omega = drake.util.Transform.rpydot2angularvel(rpy,rpydot);
msg.twist.angular_velocity.x = (float) omega[0];
msg.twist.angular_velocity.y = (float) omega[1];
msg.twist.angular_velocity.z = (float) omega[2];
}
msg.force_torque = new bot_core.force_torque_t();
return msg;
}
public String timestampName()
{
return "utime";
}
public String[] coordinateNames() {
String[] coords = new String[dim()];
Arrays.fill(coords, "");
return coords;
}
}
| 0 | 0.789995 | 1 | 0.789995 | game-dev | MEDIA | 0.563344 | game-dev | 0.932296 | 1 | 0.932296 |
electronicarts/CnC_Renegade | 20,561 | Code/Combat/directinput.cpp | /*
** Command & Conquer Renegade(tm)
** Copyright 2025 Electronic Arts Inc.
**
** 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/>.
*/
/***********************************************************************************************
*** Confidential - Westwood Studios ***
***********************************************************************************************
* *
* Project Name : Commando *
* *
* $Archive:: /Commando/Code/Combat/directinput.cpp $*
* *
* $Author:: Patrick $*
* *
* $Modtime:: 1/15/02 5:32p $*
* *
* $Revision:: 25 $*
* *
*---------------------------------------------------------------------------------------------*
* Functions: *
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
#include "directinput.h"
#include "win.h"
#include "debug.h"
#include "timemgr.h"
#define DIRECTINPUT_VERSION 0x0800
#include <dinput.h>
/*
**
*/
LPDIRECTINPUT DIObject = NULL;
LPDIRECTINPUTDEVICE DIKeyboardDevice = NULL;
LPDIRECTINPUTDEVICE DIMouseDevice = NULL;
LPDIRECTINPUTDEVICE2 DIJoystickDevice = NULL;
DIJOYSTATE DIJoystickState;
int PASCAL InitJoystick(LPCDIDEVICEINSTANCE pdinst, LPVOID pvRef);
char DirectInput::DIKeyboardButtons[NUM_KEYBOARD_BUTTONS];
char DirectInput::DIMouseButtons[NUM_MOUSE_BUTTONS];
long DirectInput::DIMouseAxis[NUM_MOUSE_AXIS];
char DirectInput::DIJoystickButtons[NUM_MOUSE_BUTTONS];
float DirectInput::ButtonLastHitTime[NUM_KEYBOARD_BUTTONS];
Vector3 DirectInput::CursorPos (0, 0, 0);
bool DirectInput::EatMouseHeld = false;
bool DirectInput::Captured = false;
void * DirectInput::DirectInputLibrary = NULL;
int DirectInput::LastKeyPressed = 0;
// Temp State Table (only for joystick currently)
char Button_State_Table[4] = { 0,
DirectInput::DI_BUTTON_HIT | DirectInput::DI_BUTTON_HELD,
DirectInput::DI_BUTTON_RELEASED,
DirectInput::DI_BUTTON_HELD };
// Buffered input
#define DI_KEYBOARD_BUFFER_SIZE 20
#define DI_MOUSE_BUFFER_SIZE 20
int PASCAL DirectInputInitJoystick(LPCDIDEVICEINSTANCE pdinst, LPVOID pvRef);
#define MINIMUM_DIRECTINPUT_VERSION 0x300
// Button bits
#define BUTTON_BIT_DOUBLE 8
#define BUTTON_DOUBLE_THRESHHOLD 0.25f
typedef HRESULT (WINAPI *DirectInput8CreateType) (HINSTANCE hinst, DWORD dwVersion, REFIID riidltf, LPVOID* ppvOut, LPUNKNOWN punkOuter);
DirectInput8CreateType DirectInput8CreatePtr = NULL;
/*
**
*/
void DirectInput::Init( void )
{
WWDEBUG_SAY(("DirectInput: Init\n"));
HRESULT hr;
WWASSERT(DirectInputLibrary == NULL);
DirectInputLibrary = LoadLibrary("DINPUT8.DLL");
if (DirectInputLibrary != NULL) {
DirectInput8CreatePtr = (DirectInput8CreateType) GetProcAddress((HINSTANCE)DirectInputLibrary, "DirectInput8Create");
if (DirectInput8CreatePtr) {
// Create the DirectInput Object
hr = DirectInput8CreatePtr( ProgramInstance, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&DIObject, NULL);
if FAILED(hr)
{
Debug_Say(( "DirectInput %x not available, trying version %x\n", DIRECTINPUT_VERSION/0x100, MINIMUM_DIRECTINPUT_VERSION/0x100 ));
hr = DirectInput8CreatePtr( ProgramInstance, MINIMUM_DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&DIObject, NULL);
if FAILED(hr)
{
Debug_Say(( "DirectInput %x not available\n", MINIMUM_DIRECTINPUT_VERSION ));
FreeLibrary((HINSTANCE)DirectInputLibrary);
DirectInputLibrary = NULL;
return;
}
}
}
}
// Debug_Say(( "DirectInput object Created\n" ));
// Create the Keyboard Object
hr = DIObject->CreateDevice( GUID_SysKeyboard , &DIKeyboardDevice, NULL);
WWASSERT( !FAILED(hr) );
if ( DIKeyboardDevice != NULL ) {
// Set the keyboard's data format
hr = DIKeyboardDevice->SetDataFormat(&c_dfDIKeyboard);
WWASSERT( !FAILED(hr) );
// Set the keyboard's cooperative level
// First we try for "exclusive" access (mainly so debugging works well) if that fails
// then we'll take non-exclusive access.
#if 0
hr = DIKeyboardDevice->SetCooperativeLevel( MainWindow,DISCL_FOREGROUND | DISCL_EXCLUSIVE);
if (FAILED(hr)) {
DIKeyboardDevice->SetCooperativeLevel( MainWindow, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
}
#else
DIKeyboardDevice->SetCooperativeLevel( MainWindow, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
#endif
// Set Keyboard Buffer Size
DIPROPDWORD dipdw;
dipdw.diph.dwSize = sizeof(dipdw);
dipdw.diph.dwHeaderSize = sizeof(dipdw.diph);
dipdw.diph.dwObj = 0;
dipdw.diph.dwHow = DIPH_DEVICE;
dipdw.dwData = DI_KEYBOARD_BUFFER_SIZE;
hr = DIKeyboardDevice->SetProperty(DIPROP_BUFFERSIZE, &dipdw.diph);
WWASSERT( !FAILED(hr) );
// Aquire the keyboard
hr = DIKeyboardDevice->Acquire();
if ( FAILED(hr) ) {
Debug_Say(( "DirectInput Keyboard Failed to Aquire\n" ));
if (hr == DIERR_INVALIDPARAM) WWDEBUG_SAY(("DIERR_INVALIDPARAM\n"));
if (hr == DIERR_NOTINITIALIZED) WWDEBUG_SAY(("DIERR_NOTINITIALIZED\n"));
if (hr == DIERR_OTHERAPPHASPRIO) WWDEBUG_SAY(("DIERR_OTHERAPPHASPRIO\n"));
}
// Debug_Say(( "DirectInput Keyboard Ready\n" ));
}
// Create the Mouse Object
hr = DIObject->CreateDevice( GUID_SysMouse, &DIMouseDevice, NULL );
WWASSERT( !FAILED(hr) );
if ( DIMouseDevice != NULL ) {
// Set the mouse's data format
hr = DIMouseDevice->SetDataFormat(&c_dfDIMouse);
WWASSERT( !FAILED(hr) );
/**/
// Set the mouse's cooperative level
hr = DIMouseDevice->SetCooperativeLevel( MainWindow,
DISCL_EXCLUSIVE | DISCL_FOREGROUND);
WWASSERT( !FAILED(hr) );
/**/
// Set Mouse Buffer Size
DIPROPDWORD dipdw;
dipdw.diph.dwSize = sizeof(dipdw);
dipdw.diph.dwHeaderSize = sizeof(dipdw.diph);
dipdw.diph.dwObj = 0;
dipdw.diph.dwHow = DIPH_DEVICE;
dipdw.dwData = DI_MOUSE_BUFFER_SIZE;
hr = DIMouseDevice->SetProperty(DIPROP_BUFFERSIZE, &dipdw.diph);
WWASSERT( !FAILED(hr) );
// Aquire the mouse
hr = DIMouseDevice->Acquire();
if ( FAILED(hr) ) {
Debug_Say(( "DirectInput Mouse Failed to Aquire\n" ));
if (hr == DIERR_INVALIDPARAM) WWDEBUG_SAY(("DIERR_INVALIDPARAM\n"));
if (hr == DIERR_NOTINITIALIZED) WWDEBUG_SAY(("DIERR_NOTINITIALIZED\n"));
if (hr == DIERR_OTHERAPPHASPRIO) WWDEBUG_SAY(("DIERR_OTHERAPPHASPRIO\n"));
}
// Debug_Say(( "DirectInput Mouse Ready\n" ));
}
// Enumerate the Joysticks
DIObject->EnumDevices(DI8DEVCLASS_GAMECTRL, InitJoystick, DIObject, DIEDFL_ATTACHEDONLY );
if ( DIJoystickDevice != NULL ) {
// Set the joystick's data format
hr = DIJoystickDevice->SetDataFormat( &c_dfDIJoystick );
WWASSERT( !FAILED(hr) );
// Set the joystick's cooperative level
hr = DIJoystickDevice->SetCooperativeLevel( MainWindow, DISCL_NONEXCLUSIVE | DISCL_FOREGROUND);
WWASSERT( !FAILED(hr) );
DIPROPRANGE diprg;
diprg.diph.dwSize = sizeof(diprg);
diprg.diph.dwHeaderSize = sizeof(diprg.diph);
// Set X Range
diprg.diph.dwObj = DIJOFS_X;
diprg.diph.dwHow = DIPH_BYOFFSET;
diprg.lMin = -1000;
diprg.lMax = +1000;
hr = DIJoystickDevice->SetProperty(DIPROP_RANGE, &diprg.diph);
WWASSERT( !FAILED(hr) );
// Set Y Range
diprg.diph.dwObj = DIJOFS_Y;
hr = DIJoystickDevice->SetProperty(DIPROP_RANGE, &diprg.diph);
WWASSERT( !FAILED(hr) );
DIPROPDWORD dipdw;
dipdw.diph.dwSize = sizeof(dipdw);
dipdw.diph.dwHeaderSize = sizeof(dipdw.diph);
// set X axis dead zone to 20% (to avoid accidental turning)
dipdw.diph.dwObj = DIJOFS_X;
dipdw.diph.dwHow = DIPH_BYOFFSET;
dipdw.dwData = 200;
hr = DIJoystickDevice->SetProperty(DIPROP_DEADZONE, &dipdw.diph);
WWASSERT( !FAILED(hr) );
// set Y axis dead zone to 20% (to avoid accidental turning)
dipdw.diph.dwObj = DIJOFS_Y;
hr = DIJoystickDevice->SetProperty(DIPROP_DEADZONE, &dipdw.diph);
WWASSERT( !FAILED(hr) );
// Aquire the mouse
hr = DIJoystickDevice->Acquire();
if ( FAILED(hr) ) {
Debug_Say(( "DirectInput Joystick Failed to Aquire\n" ));
}
}
Captured = true;
Flush();
//
// Reset the double-click array entries
//
for ( int index = 0; index < NUM_KEYBOARD_BUTTONS; index++ ) {
ButtonLastHitTime[index] = 1000;
}
return ;
}
/*
**
*/
void DirectInput::Shutdown( void )
{
WWDEBUG_SAY(("DirectInput: Shutdown\n"));
if ( DIKeyboardDevice ) {
DIKeyboardDevice->Unacquire();
DIKeyboardDevice->Release();
DIKeyboardDevice = NULL;
}
if ( DIMouseDevice ) {
DIMouseDevice->Unacquire();
DIMouseDevice->Release();
DIMouseDevice = NULL;
}
if ( DIJoystickDevice ) {
DIJoystickDevice->Unacquire();
DIJoystickDevice->Release();
DIJoystickDevice = NULL;
}
if ( DIObject ) {
DIObject->Release();
DIObject = NULL;
if (DirectInputLibrary) {
FreeLibrary((HINSTANCE)DirectInputLibrary);
}
}
}
/*
**
*/
void DirectInput::Flush( void )
{
memset( DIKeyboardButtons, 0, sizeof(DIKeyboardButtons) );
memset( DIMouseButtons, 0, sizeof(DIMouseButtons) );
memset( DIMouseAxis, 0, sizeof(DIMouseAxis) );
memset( DIJoystickButtons, 0, sizeof(DIJoystickButtons) );
}
/*
** Acquire access to input devices
*/
void DirectInput::Acquire(void)
{
// WWDEBUG_SAY(("DirectInput: Acquire\n"));
if (Captured == false) {
Flush();
if (DIKeyboardDevice) {
DIKeyboardDevice->Acquire();
}
POINT cursorPos;
GetCursorPos(&cursorPos);
ScreenToClient(MainWindow, &cursorPos);
CursorPos.X = (float)cursorPos.x;
CursorPos.Y = (float)cursorPos.y;
if (DIMouseDevice) {
DIMouseDevice->Acquire();
}
Captured = true;
}
}
/*
** Release accesss to input devices.
*/
void DirectInput::Unacquire(void)
{
// WWDEBUG_SAY(("DirectInput: Unacquire\n"));
if (Captured) {
if (DIMouseDevice) {
DIMouseDevice->Unacquire();
}
if (DIKeyboardDevice) {
DIKeyboardDevice->Unacquire();
}
POINT cursorPos;
cursorPos.x = (LONG)CursorPos.X;
cursorPos.y = (LONG)CursorPos.Y;
ClientToScreen(MainWindow, &cursorPos);
SetCursorPos(cursorPos.x, cursorPos.y);
Captured = false;
}
}
/*
**
*/
int PASCAL InitJoystick(LPCDIDEVICEINSTANCE pdinst, LPVOID pvRef)
{
LPDIRECTINPUT pdi = (LPDIRECTINPUT)pvRef;
if ( DIJoystickDevice == NULL ) {
LPDIRECTINPUTDEVICE temp;
HRESULT hr;
hr = pdi->CreateDevice(pdinst->guidInstance, &temp, NULL);
if ( !FAILED(hr)) {
hr = temp->QueryInterface(IID_IDirectInputDevice2,
(LPVOID *)&DIJoystickDevice);
IDirectInputDevice_Release(temp);
}
if ( FAILED(hr) ) {
Debug_Say(( "Failed to Create Joystick\n" ));
} else {
return DIENUM_STOP; // we got one
}
}
return DIENUM_CONTINUE;
}
/*
**
*/
void DirectInput::ReadKeyboard( void )
{
if ( DIKeyboardDevice == NULL ) return;
for (int i = 0; i < sizeof( DIKeyboardButtons ); i++ ) {
DIKeyboardButtons[i] &= DI_BUTTON_HELD; // make off all but the STATE
}
DWORD buffer_size = 1;
DIDEVICEOBJECTDATA input_buffer;
bool done = false;
while( !done ) {
// Jani: Try to acquire first (Acquire doesn't increase ref count).
HRESULT hr = DIKeyboardDevice->Acquire();
if ( FAILED( hr) ) {
return;
}
hr = DIKeyboardDevice->GetDeviceData(
sizeof(DIDEVICEOBJECTDATA), &input_buffer, &buffer_size, 0 );
if FAILED(hr) {
if ( (hr == DIERR_INPUTLOST) || (hr == DIERR_NOTACQUIRED) ) {
if (hr == DIERR_INPUTLOST) {
Debug_Say(( "DirectInput keyboard lost\n" ));
}
// Try to re-aquire
hr = DIKeyboardDevice->Acquire();
if ( FAILED( hr) ) {
// Debug_Say(( "DirectInput keyboard not re-aquired\n" ));
return;
}
Debug_Say(( "DirectInput keyboard re-aquired\n" ));
continue;
} else {
Debug_Say(( "DirectInput GetDeviceState FAILED %x\n", hr ));
return;
}
}
if ( buffer_size == 0 ) {
done = true;
} else {
WWASSERT( !(input_buffer.dwOfs & 0x0FF00) );
if ( input_buffer.dwData & 0x80 ) {
DIKeyboardButtons[ input_buffer.dwOfs ] |= DI_BUTTON_HIT;
DIKeyboardButtons[ input_buffer.dwOfs ] |= DI_BUTTON_HELD;
LastKeyPressed = input_buffer.dwOfs;
} else {
DIKeyboardButtons[ input_buffer.dwOfs ] |= DI_BUTTON_RELEASED;
DIKeyboardButtons[ input_buffer.dwOfs ] &= ~DI_BUTTON_HELD;
}
}
}
// Set Dupe Keys
DIKeyboardButtons[ DIK_CONTROL ] = DIKeyboardButtons[ DIK_LCONTROL ] | DIKeyboardButtons[ DIK_RCONTROL ] ;
DIKeyboardButtons[ DIK_SHIFT ] = DIKeyboardButtons[ DIK_LSHIFT ] | DIKeyboardButtons[ DIK_RSHIFT ] ;
DIKeyboardButtons[ DIK_ALT ] = DIKeyboardButtons[ DIK_LALT ] | DIKeyboardButtons[ DIK_RALT ];
DIKeyboardButtons[ DIK_WIN ] = DIKeyboardButtons[ DIK_LWIN ] | DIKeyboardButtons[ DIK_RWIN ];
#if 0
retry_keyboard:
HRESULT hr = DIKeyboardDevice->GetDeviceState(sizeof(DIKeyboardState),(LPVOID)&DIKeyboardState);
if FAILED(hr) {
if ( (hr == DIERR_INPUTLOST) || (hr == DIERR_NOTACQUIRED) ) {
if (hr == DIERR_INPUTLOST) {
Debug_Say(( "DirectInput keyboard lost\n" ));
}
// Try to re-aquire
hr = DIKeyboardDevice->Acquire();
if ( FAILED( hr) ) {
// Debug_Say(( "DirectInput keyboard not re-aquired\n" ));
return;
}
Debug_Say(( "DirectInput keyboard re-aquired\n" ));
goto retry_keyboard;
} else {
Debug_Say(( "DirectInput GetDeviceState FAILED %x\n", hr ));
return;
}
}
// Set Dupe Keys
DIKeyboardState[ DIK_CONTROL ] = DIKeyboardState[ DIK_LCONTROL ] | DIKeyboardState[ DIK_RCONTROL ] ;
DIKeyboardState[ DIK_SHIFT ] = DIKeyboardState[ DIK_LSHIFT ] | DIKeyboardState[ DIK_RSHIFT ] ;
DIKeyboardState[ DIK_ALT ] = DIKeyboardState[ DIK_LALT ] | DIKeyboardState[ DIK_RALT ];
DIKeyboardState[ DIK_WIN ] = DIKeyboardState[ DIK_LWIN ] | DIKeyboardState[ DIK_RWIN ];
#endif
}
/*
**
*/
void DirectInput::ReadMouse( void )
{
if ( DIMouseDevice == NULL ) return;
for (int i = 0; i < sizeof( DIMouseButtons ); i++ ) {
DIMouseButtons[i] &= DI_BUTTON_HELD; // make off all but the STATE
}
for (i = 0; i < (sizeof( DIMouseAxis )/sizeof( DIMouseAxis[0] ) ); i++ ) {
DIMouseAxis[i] = 0;
}
DWORD buffer_size = 1;
DIDEVICEOBJECTDATA input_buffer;
bool done = false;
while( !done ) {
// Try to aquire first
HRESULT hr = DIMouseDevice->Acquire();
if ( FAILED( hr) ) {
return;
}
hr = DIMouseDevice->GetDeviceData(
sizeof(DIDEVICEOBJECTDATA), &input_buffer, &buffer_size, 0 );
if FAILED(hr) {
if ( (hr == DIERR_INPUTLOST) || (hr == DIERR_NOTACQUIRED) ) {
if (hr == DIERR_INPUTLOST) {
Debug_Say(( "DirectInput mouse lost\n" ));
}
// Try to re-aquire
hr = DIMouseDevice->Acquire();
if ( FAILED( hr) ) {
// Debug_Say(( "DirectInput mouse not re-aquired\n" ));
return;
}
Debug_Say(( "DirectInput mouse re-aquired\n" ));
continue;
} else {
Debug_Say(( "DirectInput mouse GetDeviceState FAILED %x\n", hr ));
return;
}
}
if ( buffer_size == 0 ) {
done = true;
} else {
int index = 0;
switch( input_buffer.dwOfs ) {
case DIMOFS_Z: index++;
case DIMOFS_Y: index++;
case DIMOFS_X:
DIMouseAxis[index] += input_buffer.dwData;
CursorPos[index] += ((int)input_buffer.dwData) * 2;
break;
case DIMOFS_BUTTON2: index++;
case DIMOFS_BUTTON1: index++;
case DIMOFS_BUTTON0:
if ( input_buffer.dwData & 0x80 ) {
DIMouseButtons[ index ] |= DI_BUTTON_HIT;
DIMouseButtons[ index ] |= DI_BUTTON_HELD;
} else {
DIMouseButtons[ index ] |= DI_BUTTON_RELEASED;
DIMouseButtons[ index ] &= ~DI_BUTTON_HELD;
EatMouseHeld = false;
}
break;
}
}
}
//
// "Eat" the left mouse button as necessary
//
if ( EatMouseHeld ) {
DIMouseButtons[ BUTTON_MOUSE_LEFT & 0xFF ] &= ~DI_BUTTON_HELD;
DIMouseButtons[ BUTTON_MOUSE_LEFT & 0xFF ] &= ~DI_BUTTON_HIT;
DIMouseButtons[ BUTTON_MOUSE_LEFT & 0xFF ] |= DI_BUTTON_RELEASED;
}
#if 0
retry_mouse:
HRESULT hr = DIMouseDevice->GetDeviceState( sizeof(DIMouseState), (LPVOID)&DIMouseState );
if FAILED(hr) {
if ( (hr == DIERR_INPUTLOST) || (hr == DIERR_NOTACQUIRED) ) {
if (hr == DIERR_INPUTLOST) {
Debug_Say(( "DirectInput mouse lost\n" ));
}
// Try to re-aquire
hr = DIMouseDevice->Acquire();
if ( FAILED( hr) ) {
// Debug_Say(( "DirectInput mouse not re-aquired\n" ));
return;
}
Debug_Say(( "DirectInput mouse re-aquired\n" ));
goto retry_mouse;
} else {
Debug_Say(( "DirectInput GetDeviceState FAILED %x\n", hr ));
return;
}
}
DIMouseButtons[ 0 ] = Button_State_Table[ ((DIMouseButtons[ 0 ]&1) << 1) + ((DIMouseState.rgbButtons[ 0 ] & 0x80 )?1:0) ];
DIMouseButtons[ 1 ] = Button_State_Table[ ((DIMouseButtons[ 1 ]&1) << 1) + ((DIMouseState.rgbButtons[ 1 ] & 0x80 )?1:0) ];
DIMouseButtons[ 2 ] = Button_State_Table[ ((DIMouseButtons[ 2 ]&1) << 1) + ((DIMouseState.rgbButtons[ 2 ] & 0x80 )?1:0) ];
#endif
}
/*
**
*/
void DirectInput::ReadJoystick( void )
{
if ( DIJoystickDevice == NULL ) return;
// poll the joystick to read the current state
retry_joystick:
HRESULT hr = DIJoystickDevice->Poll();
if (FAILED(hr)) {
if ( (hr == DIERR_INPUTLOST) || (hr == DIERR_NOTACQUIRED) ) {
if (hr == DIERR_INPUTLOST) {
Debug_Say(( "DirectInput Joystick lost\n" ));
}
// Try to re-aquire
hr = DIJoystickDevice->Acquire();
if ( FAILED( hr) ) {
// Debug_Say(( "DirectInput joystick not re-aquired\n" ));
return;
}
Debug_Say(( "DirectInput Joystick re-aquired\n" ));
goto retry_joystick;
}
}
hr = DIJoystickDevice->GetDeviceState( sizeof(DIJoystickState), (LPVOID)&DIJoystickState );
if FAILED(hr) {
Debug_Say(( "DirectInput GetDeviceState FAILED %x\n", hr ));
return;
}
DIJoystickButtons[ 0 ] = Button_State_Table[ ((DIJoystickButtons[ 0 ]&1) << 1) + ((DIJoystickState.rgbButtons[ 0 ] & 0x80 )?1:0) ];
DIJoystickButtons[ 1 ] = Button_State_Table[ ((DIJoystickButtons[ 1 ]&1) << 1) + ((DIJoystickState.rgbButtons[ 1 ] & 0x80 )?1:0) ];
}
/*
**
*/
void DirectInput::Read( void )
{
if (Captured) {
ReadKeyboard();
ReadMouse();
ReadJoystick();
Update_Double_Clicks();
}
return ;
}
/*
**
*/
void DirectInput::Eat_Mouse_Held_States (void)
{
if ( (DIMouseButtons[BUTTON_MOUSE_LEFT & 0xFF] & DI_BUTTON_HELD) ||
(DIMouseButtons[BUTTON_MOUSE_LEFT & 0xFF] & DI_BUTTON_HIT))
{
EatMouseHeld = true;
}
return ;
}
/*
**
*/
long DirectInput::Get_Joystick_Axis_State( JoystickAxis axis )
{
return ((long*)&DIJoystickState.lX)[axis];
}
/*
**
*/
void DirectInput::Update_Double_Clicks (void)
{
float time_delta = TimeManager::Get_Frame_Real_Seconds();
for ( int index = 0; index < NUM_KEYBOARD_BUTTONS; index++ ) {
//
// Bump time since last
//
ButtonLastHitTime[index] += time_delta;
//
// If the button is hit, check for double and reset time
//
if ( DIKeyboardButtons[index] & DI_BUTTON_HIT ) {
if ( ButtonLastHitTime[index] <= BUTTON_DOUBLE_THRESHHOLD ) {
DIKeyboardButtons[index] |= BUTTON_BIT_DOUBLE;
}
ButtonLastHitTime[index] = 0;
}
}
return ;
} | 0 | 0.918762 | 1 | 0.918762 | game-dev | MEDIA | 0.249808 | game-dev | 0.631156 | 1 | 0.631156 |
rustyscreeps/screeps-game-api | 10,982 | src/game/map.rs | //! Game map related functionality.
//!
//! [Screeps documentation](https://docs.screeps.com/api/#Game-map)
use enum_iterator::Sequence;
use js_sys::{Array, JsString, Object};
use num_traits::*;
use serde::{Deserialize, Serialize};
use wasm_bindgen::prelude::*;
use crate::{
constants::{Direction, ExitDirection},
enums::action_error_codes::game::map::*,
local::RoomName,
objects::RoomTerrain,
prelude::*,
};
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_name = "map")]
type Map;
#[wasm_bindgen(js_namespace = ["Game"], js_class = "map", static_method_of = Map, js_name = describeExits)]
fn describe_exits(room_name: &JsString) -> Object;
#[wasm_bindgen(js_namespace = ["Game"], js_class = "map", static_method_of = Map, js_name = findExit)]
fn find_exit(from_room: &JsString, to_room: &JsString, options: &JsValue) -> i8;
#[wasm_bindgen(js_namespace = ["Game"], js_class = "map", static_method_of = Map, js_name = findRoute)]
fn find_route(from_room: &JsString, to_room: &JsString, options: &JsValue) -> JsValue;
#[wasm_bindgen(js_namespace = ["Game"], js_class = "map", static_method_of = Map, js_name = getRoomLinearDistance)]
fn get_room_linear_distance(room_1: &JsString, room_2: &JsString, continuous: bool) -> u32;
#[wasm_bindgen(js_namespace = ["Game"], js_class = "map", static_method_of = Map, js_name = getRoomTerrain, catch)]
fn get_room_terrain(room_name: &JsString) -> Result<RoomTerrain, JsValue>;
#[wasm_bindgen(js_namespace = ["Game"], js_class = "map", static_method_of = Map, js_name = getWorldSize)]
fn get_world_size() -> u32;
#[wasm_bindgen(js_namespace = ["Game"], js_class = "map", static_method_of = Map, js_name = getRoomStatus, catch)]
fn get_room_status(room_name: &JsString) -> Result<JsRoomStatusResult, JsValue>;
}
/// Get an object with information about the exits from a given room, with
/// [`JsString`] versions of direction integers as keys and [`JsString`]
/// room names as values.
///
/// [Screeps documentation](https://docs.screeps.com/api/#Game.map.describeExits)
pub fn describe_exits(room_name: RoomName) -> JsHashMap<Direction, RoomName> {
let room_name = room_name.into();
Map::describe_exits(&room_name).into()
}
/// Get the distance used for range calculations between two rooms,
/// optionally setting `continuous` to true to consider the world borders to
/// wrap around, which is used for terminal calculations.
///
/// [Screeps documentation](https://docs.screeps.com/api/#Game.map.getRoomLinearDistance)
pub fn get_room_linear_distance(from_room: RoomName, to_room: RoomName, continuous: bool) -> u32 {
let from_room = from_room.into();
let to_room = to_room.into();
Map::get_room_linear_distance(&from_room, &to_room, continuous)
}
/// Get the [`RoomTerrain`] object for any room, even one you don't have
/// vision in.
///
/// [Screeps documentation](https://docs.screeps.com/api/#Game.map.getRoomTerrain)
pub fn get_room_terrain(room_name: RoomName) -> Option<RoomTerrain> {
let name = room_name.into();
Map::get_room_terrain(&name).ok()
}
/// Get the size of the world map.
///
/// [Screeps documentation](https://docs.screeps.com/api/#Game.map.getWorldSize)
pub fn get_world_size() -> u32 {
Map::get_world_size()
}
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen]
pub type JsRoomStatusResult;
#[wasm_bindgen(method, getter = status)]
pub fn status(this: &JsRoomStatusResult) -> RoomStatus;
#[wasm_bindgen(method, getter = timestamp)]
pub fn timestamp(this: &JsRoomStatusResult) -> Option<f64>;
}
#[derive(Clone, Debug)]
pub struct RoomStatusResult {
status: RoomStatus,
timestamp: Option<f64>,
}
impl RoomStatusResult {
pub fn status(&self) -> RoomStatus {
self.status
}
pub fn timestamp(&self) -> Option<f64> {
self.timestamp
}
}
impl From<JsRoomStatusResult> for RoomStatusResult {
fn from(val: JsRoomStatusResult) -> Self {
RoomStatusResult {
status: val.status(),
timestamp: val.timestamp(),
}
}
}
#[wasm_bindgen]
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Sequence, Deserialize, Serialize)]
pub enum RoomStatus {
Normal = "normal",
Closed = "closed",
Novice = "novice",
Respawn = "respawn",
}
/// Get the status of a given room, determining whether it's in a special
/// area or currently inaccessible.
///
/// [Screeps documentation](https://docs.screeps.com/api/#Game.map.getRoomStatus)
pub fn get_room_status(room_name: RoomName) -> Option<RoomStatusResult> {
let name = room_name.into();
Map::get_room_status(&name).ok().map(RoomStatusResult::from)
}
#[wasm_bindgen]
extern "C" {
/// Object that represents a set of options for a call to [`find_route`].
#[wasm_bindgen]
pub type JsFindRouteOptions;
/// Route callback, which determines the cost of entering a given room (the
/// first parameter) from a given neighbor room (the second parameter), or
/// [`f64::INFINITY`] to block entry into the room.
#[wasm_bindgen(method, setter = routeCallback)]
pub fn route_callback(
this: &JsFindRouteOptions,
callback: &Closure<dyn FnMut(JsString, JsString) -> f64>,
);
}
impl JsFindRouteOptions {
pub fn new() -> JsFindRouteOptions {
Object::new().unchecked_into()
}
}
impl Default for JsFindRouteOptions {
fn default() -> Self {
Self::new()
}
}
pub struct FindRouteOptions<F>
where
F: FnMut(RoomName, RoomName) -> f64,
{
route_callback: F,
}
impl<F> FindRouteOptions<F>
where
F: FnMut(RoomName, RoomName) -> f64,
{
pub(crate) fn into_js_options<R>(self, callback: impl Fn(&JsFindRouteOptions) -> R) -> R {
let mut raw_callback = self.route_callback;
let mut owned_callback = move |to_room: RoomName, from_room: RoomName| -> f64 {
raw_callback(to_room, from_room)
};
//
// Type erased and boxed callback: no longer a type specific to the closure
// passed in, now unified as &Fn
//
let callback_type_erased: &mut dyn FnMut(RoomName, RoomName) -> f64 = &mut owned_callback;
// Overwrite lifetime of reference so it can be passed to javascript.
// It's now pretending to be static data. This should be entirely safe
// because we control the only use of it and it remains valid during the
// pathfinder callback. This transmute is necessary because "some lifetime
// above the current scope but otherwise unknown" is not a valid lifetime.
//
let callback_lifetime_erased: &'static mut dyn FnMut(RoomName, RoomName) -> f64 =
unsafe { std::mem::transmute(callback_type_erased) };
let boxed_callback = Box::new(move |to_room: JsString, from_room: JsString| -> f64 {
let to_room = to_room
.try_into()
.expect("expected 'to' room name in route callback");
let from_room = from_room
.try_into()
.expect("expected 'rom' room name in route callback");
callback_lifetime_erased(to_room, from_room)
}) as Box<dyn FnMut(JsString, JsString) -> f64>;
let closure = Closure::wrap(boxed_callback);
//
// Create JS object and set properties.
//
let js_options = JsFindRouteOptions::new();
js_options.route_callback(&closure);
callback(&js_options)
}
}
impl Default for FindRouteOptions<fn(RoomName, RoomName) -> f64> {
fn default() -> Self {
const fn room_cost(_to_room: RoomName, _from_room: RoomName) -> f64 {
1.0
}
FindRouteOptions {
route_callback: room_cost,
}
}
}
impl FindRouteOptions<fn(RoomName, RoomName) -> f64> {
#[inline]
pub fn new() -> Self {
Self::default()
}
}
impl<F> FindRouteOptions<F>
where
F: FnMut(RoomName, RoomName) -> f64,
{
pub fn room_callback<F2>(self, route_callback: F2) -> FindRouteOptions<F2>
where
F2: FnMut(RoomName, RoomName) -> f64,
{
let FindRouteOptions { route_callback: _ } = self;
FindRouteOptions { route_callback }
}
}
#[derive(Debug, Deserialize)]
pub struct RouteStep {
pub exit: ExitDirection,
pub room: RoomName,
}
/// Get the route from a given room leading toward a destination room, with
/// an optional [`FindRouteOptions`] parameter allowing control over the
/// costs to enter rooms.
///
/// Returns an [`Array`] with an object per room in the route, with keys
/// `exit` containing an [`ExitDirection`] and `room` containing room name
/// as a [`JsString`].
///
/// [Screeps documentation](https://docs.screeps.com/api/#Game.map.findRoute)
pub fn find_route<F>(
from: RoomName,
to: RoomName,
options: Option<FindRouteOptions<F>>,
) -> Result<Vec<RouteStep>, FindRouteErrorCode>
where
F: FnMut(RoomName, RoomName) -> f64,
{
let from: JsString = from.into();
let to: JsString = to.into();
let result = if let Some(options) = options {
options.into_js_options(|js_options| Map::find_route(&from, &to, js_options))
} else {
Map::find_route(&from, &to, &JsValue::UNDEFINED)
};
if result.is_object() {
let result: &Array = result.unchecked_ref();
let steps: Vec<RouteStep> = result
.iter()
.map(|step| serde_wasm_bindgen::from_value(step).expect("expected route step"))
.collect();
Ok(steps)
} else {
// SAFETY: can never be a 0 return from the find_route API function
Err(unsafe {
FindRouteErrorCode::try_result_from_jsvalue(&result)
.expect("expected return code for pathing failure")
.unwrap_err_unchecked()
})
}
}
/// Get the exit direction from a given room leading toward a destination
/// room, with an optional [`FindRouteOptions`] parameter allowing control
/// over the costs to enter rooms.
///
/// [Screeps documentation](https://docs.screeps.com/api/#Game.map.findExit)
pub fn find_exit<F>(
from: RoomName,
to: RoomName,
options: Option<FindRouteOptions<F>>,
) -> Result<ExitDirection, FindExitErrorCode>
where
F: FnMut(RoomName, RoomName) -> f64,
{
let from: JsString = from.into();
let to: JsString = to.into();
let result = if let Some(options) = options {
options.into_js_options(|js_options| Map::find_exit(&from, &to, js_options))
} else {
Map::find_exit(&from, &to, &JsValue::UNDEFINED)
};
if result >= 0 {
Ok(ExitDirection::from_i8(result).expect("expected exit direction for pathing"))
} else {
// SAFETY: can never be an `Ok()` return from `result_from_i8` because
// non-negative values are handled by the first branch above
Err(unsafe { FindExitErrorCode::result_from_i8(result).unwrap_err_unchecked() })
}
}
| 0 | 0.893515 | 1 | 0.893515 | game-dev | MEDIA | 0.461258 | game-dev,web-frontend | 0.864635 | 1 | 0.864635 |
PotRooms/AzurPromiliaData | 3,620 | Lua/config/chs/photo_pose.lua | local photo_pose = {
[1] = {
[-1] = -1,
[-2] = {
[-3] = -2,
[-4] = -3
},
[-5] = -1,
[-6] = -4,
[-7] = {},
[-8] = -5,
[-9] = -6
},
[2] = {
[-1] = -7,
[-2] = {
[-3] = -2,
[-4] = -8
},
[-5] = -1,
[-6] = -4,
[-7] = {},
[-8] = -9,
[-9] = -10
},
[3] = {
[-1] = -11,
[-2] = {
[-3] = -2,
[-4] = -12
},
[-5] = -1,
[-6] = -4,
[-7] = {},
[-8] = -13,
[-9] = -14
},
[4] = {
[-1] = -15,
[-2] = {
[-3] = -2,
[-4] = -16
},
[-5] = -11,
[-6] = -1,
[-7] = {
{
-1,
-4,
-17
}
},
[-8] = -18,
[-9] = -19
},
[5] = {
[-1] = -20,
[-2] = {
[-3] = -2,
[-4] = -21
},
[-5] = -11,
[-6] = -1,
[-7] = {
{
-7,
-22,
-23
},
{
-7,
-24,
-25
}
},
[-8] = -18,
[-9] = -19
}
}
local key_to_index_map = {
id = -1,
name = -2,
group = -3,
langKey = -4,
type = -5,
moreType = -6,
multiaction = -7,
animname = -8,
texture = -9
}
local index_to_key_map = {}
for k, v in pairs(key_to_index_map) do
index_to_key_map[v] = k
end
local value_to_index_map = {
[1] = -1,
lang_photo_pose = -2,
["1_1_0"] = -3,
[0] = -4,
Idle = -5,
["UI/Atlas/BSPhoto/tex_photo_icon_stand.png"] = -6,
[2] = -7,
["2_1_0"] = -8,
Walk = -9,
["UI/Atlas/BSPhoto/tex_photo_icon_walk.png"] = -10,
[3] = -11,
["3_1_0"] = -12,
Run = -13,
["UI/Atlas/BSPhoto/tex_photo_icon_run.png"] = -14,
[4] = -15,
["4_1_0"] = -16,
[180] = -17,
Action = -18,
[""] = -19,
[5] = -20,
["5_1_0"] = -21,
[60] = -22,
[210] = -23,
[300] = -24,
[150] = -25
}
local index_to_value_map = {}
for k, v in pairs(value_to_index_map) do
index_to_value_map[v] = k
end
local function SetReadonlyTable(t)
for k, v in pairs(t) do
if type(v) == "table" then
t[k] = SetReadonlyTable(v)
end
end
local mt = {
__data = t,
__index_to_key_map = index_to_key_map,
__key_to_index_map = key_to_index_map,
__index_to_value_map = index_to_value_map,
__index = function(t, k)
local tmt = getmetatable(t)
local data = tmt.__data
local value_index
if tmt.__key_to_index_map[k] ~= nil then
value_index = data[tmt.__key_to_index_map[k]]
else
value_index = data[k]
end
if type(value_index) == "table" then
return value_index
else
return tmt.__index_to_value_map[value_index]
end
end,
__newindex = function(t, k, v)
errorf("attempt to modify a read-only talbe!", 2)
end,
__pairs = function(t, k)
return function(t, k)
local tmt = getmetatable(t)
local data = tmt.__data
local nk, nv
if tmt.__key_to_index_map[k] ~= nil then
local iter_key = tmt.__key_to_index_map[k]
nk, nv = next(data, iter_key)
else
nk, nv = next(data, k)
end
local key, value
if tmt.__index_to_key_map[nk] ~= nil then
key = tmt.__index_to_key_map[nk]
else
key = nk
end
if type(nv) == "table" then
value = nv
else
value = tmt.__index_to_value_map[nv]
end
return key, value
end, t, nil
end,
__len = function(t)
local tmt = getmetatable(t)
local data = tmt.__data
return #data
end
}
t = setmetatable({}, mt)
return t
end
photo_pose = SetReadonlyTable(photo_pose)
return photo_pose
| 0 | 0.604818 | 1 | 0.604818 | game-dev | MEDIA | 0.935252 | game-dev | 0.832396 | 1 | 0.832396 |
Real-Serious-Games/Unity-Weld-Examples | 3,364 | Assets/Unity-Weld/UnityWeld/Binding/ToggleActiveBinding.cs | using System;
using System.Linq;
using UnityEngine;
using UnityEngine.Assertions;
using UnityWeld.Binding.Internal;
namespace UnityWeld.Binding
{
/// <summary>
/// Bind to a boolean property on the view model and turn all child objects on
/// or off based on its value.
/// </summary>
[HelpURL("https://github.com/Real-Serious-Games/Unity-Weld")]
public class ToggleActiveBinding : AbstractMemberBinding
{
/// <summary>
/// Type of the adapter we're using to adapt between the view model property
/// and view property.
/// </summary>
public string ViewAdapterTypeName
{
get { return viewAdapterTypeName; }
set { viewAdapterTypeName = value; }
}
[SerializeField]
private string viewAdapterTypeName;
/// <summary>
/// Options for adapting from the view model to the view property.
/// </summary>
public AdapterOptions ViewAdapterOptions
{
get { return viewAdapterOptions; }
set { viewAdapterOptions = value; }
}
[SerializeField]
private AdapterOptions viewAdapterOptions;
/// <summary>
/// Name of the property in the view model to bind.
/// </summary>
public string ViewModelPropertyName
{
get { return viewModelPropertyName; }
set { viewModelPropertyName = value; }
}
[SerializeField]
private string viewModelPropertyName;
/// <summary>
/// Watcher the view-model for changes that must be propagated to the view.
/// </summary>
private PropertyWatcher viewModelWatcher;
/// <summary>
/// Preoprty for the propertySync to set in order to activate and deactivate all children
/// </summary>
public bool ChildrenActive
{
set
{
SetAllChildrenActive(value);
}
}
public override void Connect()
{
var viewModelEndPoint = MakeViewModelEndPoint(viewModelPropertyName, null, null);
var propertySync = new PropertySync(
// Source
viewModelEndPoint,
// Dest
new PropertyEndPoint(
this,
"ChildrenActive",
CreateAdapter(viewAdapterTypeName),
viewAdapterOptions,
"view",
this
),
// Errors, exceptions and validation.
null, // Validation not needed
this
);
viewModelWatcher = viewModelEndPoint.Watch(
() => propertySync.SyncFromSource()
);
// Copy the initial value over from the view-model.
propertySync.SyncFromSource();
}
public override void Disconnect()
{
if (viewModelWatcher != null)
{
viewModelWatcher.Dispose();
viewModelWatcher = null;
}
}
private void SetAllChildrenActive(bool active)
{
foreach (Transform child in transform)
{
child.gameObject.SetActive(active);
}
}
}
}
| 0 | 0.830688 | 1 | 0.830688 | game-dev | MEDIA | 0.748834 | game-dev | 0.88858 | 1 | 0.88858 |
Alex-Rachel/TEngine | 4,469 | UnityProject/Assets/TEngine/Runtime/Module/LocalizationModule/Core/Targets/LocalizeTarget_TextMeshPro_UGUI.cs | using System;
using TMPro;
using UnityEditor;
using UnityEngine;
#if TextMeshPro
namespace TEngine.Localization
{
#if UNITY_EDITOR
[InitializeOnLoad]
#endif
public class LocalizeTarget_TextMeshPro_UGUI : LocalizeTarget<TextMeshProUGUI>
{
static LocalizeTarget_TextMeshPro_UGUI() { AutoRegister(); }
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] static void AutoRegister() { LocalizationManager.RegisterTarget(new LocalizeTargetDesc_Type<TextMeshProUGUI, LocalizeTarget_TextMeshPro_UGUI> { Name = "TextMeshPro UGUI", Priority = 100 }); }
public TextAlignmentOptions mAlignment_RTL = TextAlignmentOptions.Right;
public TextAlignmentOptions mAlignment_LTR = TextAlignmentOptions.Left;
public bool mAlignmentWasRTL;
public bool mInitializeAlignment = true;
public override eTermType GetPrimaryTermType(Localize cmp) { return eTermType.Text; }
public override eTermType GetSecondaryTermType(Localize cmp) { return eTermType.TextMeshPFont; }
public override bool CanUseSecondaryTerm() { return true; }
public override bool AllowMainTermToBeRTL() { return true; }
public override bool AllowSecondTermToBeRTL() { return false; }
public override void GetFinalTerms ( Localize cmp, string Main, string Secondary, out string primaryTerm, out string secondaryTerm)
{
primaryTerm = mTarget ? mTarget.text : null;
secondaryTerm = mTarget.font != null ? mTarget.font.name : string.Empty;
}
public override void DoLocalize(Localize cmp, string mainTranslation, string secondaryTranslation)
{
{
//--[ Localize Font Object ]----------
TMP_FontAsset newFont = cmp.GetSecondaryTranslatedObj<TMP_FontAsset>(ref mainTranslation, ref secondaryTranslation);
if (newFont != null)
{
LocalizeTarget_TextMeshPro_Label.SetFont(mTarget, newFont);
}
else
{
//--[ Localize Font Material ]----------
Material newMat = cmp.GetSecondaryTranslatedObj<Material>(ref mainTranslation, ref secondaryTranslation);
if (newMat != null && mTarget.fontMaterial != newMat)
{
if (!newMat.name.StartsWith(mTarget.font.name, StringComparison.Ordinal))
{
newFont = LocalizeTarget_TextMeshPro_Label.GetTMPFontFromMaterial(cmp, secondaryTranslation.EndsWith(newMat.name, StringComparison.Ordinal) ? secondaryTranslation : newMat.name);
if (newFont != null)
LocalizeTarget_TextMeshPro_Label.SetFont(mTarget, newFont);
}
LocalizeTarget_TextMeshPro_Label.SetMaterial( mTarget, newMat );
}
}
}
if (mInitializeAlignment)
{
mInitializeAlignment = false;
mAlignmentWasRTL = LocalizationManager.IsRight2Left;
LocalizeTarget_TextMeshPro_Label.InitAlignment_TMPro(mAlignmentWasRTL, mTarget.alignment, out mAlignment_LTR, out mAlignment_RTL);
}
else
{
TextAlignmentOptions alignRTL, alignLTR;
LocalizeTarget_TextMeshPro_Label.InitAlignment_TMPro(mAlignmentWasRTL, mTarget.alignment, out alignLTR, out alignRTL);
if (mAlignmentWasRTL && mAlignment_RTL != alignRTL ||
!mAlignmentWasRTL && mAlignment_LTR != alignLTR)
{
mAlignment_LTR = alignLTR;
mAlignment_RTL = alignRTL;
}
mAlignmentWasRTL = LocalizationManager.IsRight2Left;
}
if (mainTranslation != null && mTarget.text != mainTranslation)
{
if (cmp.CorrectAlignmentForRTL)
{
mTarget.alignment = LocalizationManager.IsRight2Left ? mAlignment_RTL : mAlignment_LTR;
}
if (LocalizationManager.IsRight2Left) mainTranslation = I2Utils.ReverseText(mainTranslation);
mTarget.isRightToLeftText = LocalizationManager.IsRight2Left;
mTarget.text = mainTranslation;
}
}
}
}
#endif | 0 | 0.834453 | 1 | 0.834453 | game-dev | MEDIA | 0.881215 | game-dev | 0.945522 | 1 | 0.945522 |
PrismStudioMC/PrismArea | 1,340 | src/PrismArea/libs/muqsit/invmenu/type/util/builder/DoublePairableBlockActorFixedInvMenuTypeBuilder.php | <?php
declare(strict_types=1);
namespace PrismArea\libs\muqsit\invmenu\type\util\builder;
use LogicException;
use PrismArea\libs\muqsit\invmenu\type\DoublePairableBlockActorFixedInvMenuType;
use PrismArea\libs\muqsit\invmenu\type\graphic\network\BlockInvMenuGraphicNetworkTranslator;
final class DoublePairableBlockActorFixedInvMenuTypeBuilder implements InvMenuTypeBuilder
{
use BlockInvMenuTypeBuilderTrait;
use FixedInvMenuTypeBuilderTrait;
use GraphicNetworkTranslatableInvMenuTypeBuilderTrait;
use AnimationDurationInvMenuTypeBuilderTrait;
private ?string $block_actor_id = null;
public function __construct()
{
$this->addGraphicNetworkTranslator(BlockInvMenuGraphicNetworkTranslator::instance());
}
public function setBlockActorId(string $block_actor_id): self
{
$this->block_actor_id = $block_actor_id;
return $this;
}
private function getBlockActorId(): string
{
return $this->block_actor_id ?? throw new LogicException("No block actor ID was specified");
}
public function build(): DoublePairableBlockActorFixedInvMenuType
{
return new DoublePairableBlockActorFixedInvMenuType($this->getBlock(), $this->getSize(), $this->getBlockActorId(), $this->getGraphicNetworkTranslator(), $this->getAnimationDuration());
}
}
| 0 | 0.530352 | 1 | 0.530352 | game-dev | MEDIA | 0.693814 | game-dev | 0.701011 | 1 | 0.701011 |
h4lfheart/FortnitePorting | 1,578 | FortnitePorting/Services/BlackHoleService.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia.Input;
using CommunityToolkit.Mvvm.ComponentModel;
using FortnitePorting.Views;
namespace FortnitePorting.Services;
public partial class BlackHoleService : ObservableObject, IService
{
[ObservableProperty, NotifyPropertyChangedFor(nameof(IsActive))] private TimeWasterView? _content;
public bool IsActive => Content is not null;
private readonly List<Key> _konamiKeyPresses = [];
private readonly List<Key> _konamiSequence = [Key.Up, Key.Up, Key.Down, Key.Down, Key.Left, Key.Right, Key.Left, Key.Right, Key.B, Key.A];
public void HandleKey(Key key)
{
if (IsActive)
{
if (key == Key.Escape)
{
Close();
_konamiKeyPresses.Clear();
return;
}
return;
}
if (!_konamiSequence.Contains(key)) return; // im not keylogging you smh
_konamiKeyPresses.Add(key);
if (_konamiKeyPresses[^Math.Min(_konamiKeyPresses.Count, _konamiSequence.Count)..].SequenceEqual(_konamiSequence))
{
Open(isMinigame: true);
_konamiKeyPresses.Clear();
}
}
public void Open(bool isMinigame)
{
TaskService.RunDispatcher(() =>
{
Content = new TimeWasterView(isMinigame);
});
}
public void Close()
{
TimeWasterVM.CleanupResources();
Content = null; // TODO check that this disposes properly
}
} | 0 | 0.8158 | 1 | 0.8158 | game-dev | MEDIA | 0.679382 | game-dev | 0.746516 | 1 | 0.746516 |
PocketMine/PocketMine-MP | 1,651 | src/pocketmine/item/FlintSteel.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\item;
use pocketmine\block\Block;
use pocketmine\block\Fire;
use pocketmine\block\Solid;
use pocketmine\level\Level;
use pocketmine\Player;
class FlintSteel extends Tool{
public function __construct($meta = 0, $count = 1){
parent::__construct(self::FLINT_STEEL, $meta, $count, "Flint and Steel");
}
public function canBeActivated(){
return true;
}
public function onActivate(Level $level, Player $player, Block $block, Block $target, $face, $fx, $fy, $fz){
if($block->getId() === self::AIR and ($target instanceof Solid)){
$level->setBlock($block, new Fire(), true);
if(($player->gamemode & 0x01) === 0 and $this->useOn($block)){
if($this->getDamage() >= $this->getMaxDurability()){
$player->getInventory()->setItemInHand(new Item(Item::AIR, 0, 0));
}else{
$this->meta++;
$player->getInventory()->setItemInHand($this);
}
}
return true;
}
return false;
}
} | 0 | 0.953512 | 1 | 0.953512 | game-dev | MEDIA | 0.984928 | game-dev | 0.973198 | 1 | 0.973198 |
catbobyman/Unity-Mediapipe-Avatar-3DMotionCaptureDriven | 4,544 | AvartarMocap/Assets/Plugins/MagicaCloth/Scripts/Core/Physics/ParticleComponent/ColliderComponent.cs | // Magica Cloth.
// Copyright (c) MagicaSoft, 2020-2022.
// https://magicasoft.jp
using System.Collections.Generic;
using UnityEngine;
namespace MagicaCloth
{
/// <summary>
/// コライダーパーティクルオブジェクト基底クラス
/// </summary>
public abstract class ColliderComponent : ParticleComponent
{
/// <summary>
/// グローバルフラグ
/// </summary>
[SerializeField]
protected bool isGlobal;
[SerializeField]
private Vector3 center;
//=========================================================================================
public Vector3 Center
{
get
{
return center;
}
set
{
center = value;
ReserveDataUpdate();
}
}
//=========================================================================================
/// <summary>
/// 初期化
/// </summary>
protected override void OnInit()
{
base.OnInit();
// パーティクル初期化
if (isGlobal)
{
CreateColliderParticle(0);
}
}
/// <summary>
/// 破棄
/// </summary>
protected override void OnDispose()
{
// チームからコライダーを解除する
List<int> teamList = new List<int>();
foreach (var teamId in particleDict.Keys)
{
teamList.Add(teamId);
}
foreach (var teamId in teamList)
{
RemoveColliderParticle(teamId);
}
base.OnDispose();
}
//=========================================================================================
/// <summary>
/// データハッシュ計算
/// </summary>
/// <returns></returns>
public override int GetDataHash()
{
return isGlobal.GetDataHash();
}
/// <summary>
/// 指定座標に最も近い衝突点pと、中心軸からのpへの方向dirを返す。
/// ※エディタ計算用
/// </summary>
/// <param name="pos"></param>
/// <param name="p">衝突点</param>
/// <param name="dir">中心軸位置から衝突点へのベクトル</param>
/// <param name="d">最も近い中心軸位置</param>
public abstract bool CalcNearPoint(Vector3 pos, out Vector3 p, out Vector3 dir, out Vector3 d, bool skinning);
/// <summary>
/// 指定座標のローカル位置を返す
/// ※エディタ計算用
/// </summary>
/// <param name="pos"></param>
/// <returns></returns>
public Vector3 CalcLocalPos(Vector3 pos)
{
// スケールは含めない
var rot = transform.rotation;
var v = pos - transform.position;
return Quaternion.Inverse(rot) * v;
}
/// <summary>
/// 指定方向のローカル方向を返す
/// ※エディタ計算用
/// </summary>
/// <param name="dir"></param>
/// <returns></returns>
public Vector3 CalcLocalDir(Vector3 dir)
{
return transform.InverseTransformDirection(dir);
}
/// <summary>
/// 指定チーム用のコライダーパーティクルを作成
/// </summary>
/// <param name="teamId"></param>
/// <returns></returns>
public ChunkData CreateColliderParticle(int teamId)
{
var c = CreateColliderParticleReal(teamId);
// すでにアクティブならばパーティクル有効化
if (c.IsValid() && Status.IsActive)
EnableTeamParticle(teamId);
return c;
}
/// <summary>
/// 指定チームのコライダーパーティクルを削除
/// </summary>
/// <param name="teamId"></param>
public void RemoveColliderParticle(int teamId)
{
if (MagicaPhysicsManager.IsInstance() == false)
return;
if (particleDict.ContainsKey(teamId))
{
var c = particleDict[teamId];
for (int i = 0; i < c.dataLength; i++)
{
int pindex = c.startIndex + i;
MagicaPhysicsManager.Instance.Team.RemoveColliderParticle(teamId, pindex);
}
RemoveTeamParticle(teamId);
}
}
//=========================================================================================
/// <summary>
/// 指定チーム用のコライダーパーティクル作成
/// </summary>
/// <param name="teamId"></param>
/// <returns></returns>
protected abstract ChunkData CreateColliderParticleReal(int teamId);
}
}
| 0 | 0.876924 | 1 | 0.876924 | game-dev | MEDIA | 0.737068 | game-dev | 0.857443 | 1 | 0.857443 |
leggedrobotics/art_planner | 37,945 | ode/ode/src/collision_cylinder_trimesh.cpp | /*************************************************************************
* *
* Open Dynamics Engine, Copyright (C) 2001-2003 Russell L. Smith. *
* All rights reserved. Email: russ@q12.org Web: www.q12.org *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of EITHER: *
* (1) The GNU Lesser General Public License as published by the Free *
* Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. The text of the GNU Lesser *
* General Public License is included with this library in the *
* file LICENSE.TXT. *
* (2) The BSD-style license that is included with this library in *
* the file LICENSE-BSD.TXT. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files *
* LICENSE.TXT and LICENSE-BSD.TXT for more details. *
* *
*************************************************************************/
/*
* Cylinder-trimesh collider by Alen Ladavac
* Ported to ODE by Nguyen Binh
*/
#include <ode/collision.h>
#include <ode/rotation.h>
#include "config.h"
#include "matrix.h"
#include "odemath.h"
#include "collision_util.h"
#include "collision_trimesh_internal.h"
#include "util.h"
#if dTRIMESH_ENABLED
#define MAX_REAL dInfinity
static const int nCYLINDER_AXIS = 2;
static const int nCYLINDER_CIRCLE_SEGMENTS = 8;
static const int nMAX_CYLINDER_TRIANGLE_CLIP_POINTS = 12;
#define OPTIMIZE_CONTACTS 1
// Local contacts data
typedef struct _sLocalContactData
{
dVector3 vPos;
dVector3 vNormal;
dReal fDepth;
int triIndex;
int nFlags; // 0 = filtered out, 1 = OK
}sLocalContactData;
struct sCylinderTrimeshColliderData
{
sCylinderTrimeshColliderData(int flags, int skip): m_iFlags(flags), m_iSkip(skip), m_nContacts(0), m_gLocalContacts(NULL) {}
#ifdef OPTIMIZE_CONTACTS
void _OptimizeLocalContacts();
#endif
void _InitCylinderTrimeshData(dxGeom *Cylinder, dxTriMesh *Trimesh);
int _ProcessLocalContacts(dContactGeom *contact, dxGeom *Cylinder, dxTriMesh *Trimesh);
bool _cldTestAxis(const dVector3 &v0, const dVector3 &v1, const dVector3 &v2,
dVector3& vAxis, int iAxis, bool bNoFlip = false);
bool _cldTestCircleToEdgeAxis(
const dVector3 &v0, const dVector3 &v1, const dVector3 &v2,
const dVector3 &vCenterPoint, const dVector3 &vCylinderAxis1,
const dVector3 &vVx0, const dVector3 &vVx1, int iAxis);
bool _cldTestSeparatingAxes(const dVector3 &v0, const dVector3 &v1, const dVector3 &v2);
bool _cldClipCylinderEdgeToTriangle(const dVector3 &v0, const dVector3 &v1, const dVector3 &v2);
void _cldClipCylinderToTriangle(const dVector3 &v0, const dVector3 &v1, const dVector3 &v2);
void TestOneTriangleVsCylinder(const dVector3 &v0, const dVector3 &v1, const dVector3 &v2,
const bool bDoubleSided);
int TestCollisionForSingleTriangle(int ctContacts0, int Triint, dVector3 dv[3],
bool &bOutFinishSearching);
// cylinder data
dMatrix3 m_mCylinderRot;
dQuaternion m_qCylinderRot;
dQuaternion m_qInvCylinderRot;
dVector3 m_vCylinderPos;
dVector3 m_vCylinderAxis;
dReal m_fCylinderRadius;
dReal m_fCylinderSize;
dVector3 m_avCylinderNormals[nCYLINDER_CIRCLE_SEGMENTS];
// mesh data
dQuaternion m_qTrimeshRot;
dQuaternion m_qInvTrimeshRot;
dMatrix3 m_mTrimeshRot;
dVector3 m_vTrimeshPos;
// global collider data
dVector3 m_vBestPoint;
dReal m_fBestDepth;
dReal m_fBestCenter;
dReal m_fBestrt;
int m_iBestAxis;
dVector3 m_vContactNormal;
dVector3 m_vNormal;
dVector3 m_vE0;
dVector3 m_vE1;
dVector3 m_vE2;
// ODE stuff
int m_iFlags;
int m_iSkip;
int m_nContacts;// = 0;
sLocalContactData* m_gLocalContacts;
};
#ifdef OPTIMIZE_CONTACTS
// Use to classify contacts to be "near" in position
static const dReal fSameContactPositionEpsilon = REAL(0.0001); // 1e-4
// Use to classify contacts to be "near" in normal direction
static const dReal fSameContactNormalEpsilon = REAL(0.0001); // 1e-4
// If this two contact can be classified as "near"
inline int _IsNearContacts(sLocalContactData& c1,sLocalContactData& c2)
{
int bPosNear = 0;
int bSameDir = 0;
dVector3 vDiff;
// First check if they are "near" in position
dVector3Subtract(c1.vPos,c2.vPos,vDiff);
if ( (dFabs(vDiff[0]) < fSameContactPositionEpsilon)
&&(dFabs(vDiff[1]) < fSameContactPositionEpsilon)
&&(dFabs(vDiff[2]) < fSameContactPositionEpsilon))
{
bPosNear = 1;
}
// Second check if they are "near" in normal direction
dVector3Subtract(c1.vNormal,c2.vNormal,vDiff);
if ( (dFabs(vDiff[0]) < fSameContactNormalEpsilon)
&&(dFabs(vDiff[1]) < fSameContactNormalEpsilon)
&&(dFabs(vDiff[2]) < fSameContactNormalEpsilon) )
{
bSameDir = 1;
}
// Will be "near" if position and normal direction are "near"
return (bPosNear && bSameDir);
}
inline int _IsBetter(sLocalContactData& c1,sLocalContactData& c2)
{
// The not better will be throw away
// You can change the selection criteria here
return (c1.fDepth > c2.fDepth);
}
// iterate through gLocalContacts and filtered out "near contact"
void sCylinderTrimeshColliderData::_OptimizeLocalContacts()
{
int nContacts = m_nContacts;
for (int i = 0; i < nContacts-1; i++)
{
for (int j = i+1; j < nContacts; j++)
{
if (_IsNearContacts(m_gLocalContacts[i],m_gLocalContacts[j]))
{
// If they are seem to be the same then filtered
// out the least penetrate one
if (_IsBetter(m_gLocalContacts[j],m_gLocalContacts[i]))
{
m_gLocalContacts[i].nFlags = 0; // filtered 1st contact
}
else
{
m_gLocalContacts[j].nFlags = 0; // filtered 2nd contact
}
// NOTE
// There is other way is to add two depth together but
// it not work so well. Why???
}
}
}
}
#endif // OPTIMIZE_CONTACTS
int sCylinderTrimeshColliderData::_ProcessLocalContacts(dContactGeom *contact,
dxGeom *Cylinder, dxTriMesh *Trimesh)
{
#ifdef OPTIMIZE_CONTACTS
if (m_nContacts > 1 && !(m_iFlags & CONTACTS_UNIMPORTANT))
{
// Can be optimized...
_OptimizeLocalContacts();
}
#endif
int iContact = 0;
dContactGeom* Contact = 0;
int nFinalContact = 0;
for (iContact = 0; iContact < m_nContacts; iContact ++)
{
if (1 == m_gLocalContacts[iContact].nFlags)
{
Contact = SAFECONTACT(m_iFlags, contact, nFinalContact, m_iSkip);
Contact->depth = m_gLocalContacts[iContact].fDepth;
dVector3Copy(m_gLocalContacts[iContact].vNormal,Contact->normal);
dVector3Copy(m_gLocalContacts[iContact].vPos,Contact->pos);
Contact->g1 = Cylinder;
Contact->g2 = Trimesh;
Contact->side1 = -1;
Contact->side2 = m_gLocalContacts[iContact].triIndex;
dVector3Inv(Contact->normal);
nFinalContact++;
}
}
// debug
//if (nFinalContact != m_nContacts)
//{
// printf("[Info] %d contacts generated,%d filtered.\n",m_nContacts,m_nContacts-nFinalContact);
//}
return nFinalContact;
}
bool sCylinderTrimeshColliderData::_cldTestAxis(
const dVector3 &v0,
const dVector3 &v1,
const dVector3 &v2,
dVector3& vAxis,
int iAxis,
bool bNoFlip/* = false*/)
{
// calculate length of separating axis vector
dReal fL = dVector3Length(vAxis);
// if not long enough
if ( fL < REAL(1e-5) )
{
// do nothing
return true;
}
// otherwise normalize it
vAxis[0] /= fL;
vAxis[1] /= fL;
vAxis[2] /= fL;
dReal fdot1 = dVector3Dot(m_vCylinderAxis,vAxis);
// project capsule on vAxis
dReal frc;
if (dFabs(fdot1) > REAL(1.0) )
{
// fdot1 = REAL(1.0);
frc = dFabs(m_fCylinderSize* REAL(0.5));
}
else
{
frc = dFabs((m_fCylinderSize* REAL(0.5)) * fdot1)
+ m_fCylinderRadius * dSqrt(REAL(1.0)-(fdot1*fdot1));
}
dVector3 vV0;
dVector3Subtract(v0,m_vCylinderPos,vV0);
dVector3 vV1;
dVector3Subtract(v1,m_vCylinderPos,vV1);
dVector3 vV2;
dVector3Subtract(v2,m_vCylinderPos,vV2);
// project triangle on vAxis
dReal afv[3];
afv[0] = dVector3Dot( vV0 , vAxis );
afv[1] = dVector3Dot( vV1 , vAxis );
afv[2] = dVector3Dot( vV2 , vAxis );
dReal fMin = MAX_REAL;
dReal fMax = -MAX_REAL;
// for each vertex
for(int i = 0; i < 3; i++)
{
// find minimum
if (afv[i]<fMin)
{
fMin = afv[i];
}
// find maximum
if (afv[i]>fMax)
{
fMax = afv[i];
}
}
// find capsule's center of interval on axis
dReal fCenter = (fMin+fMax)* REAL(0.5);
// calculate triangles halfinterval
dReal fTriangleRadius = (fMax-fMin)*REAL(0.5);
// if they do not overlap,
if( dFabs(fCenter) > (frc+fTriangleRadius) )
{
// exit, we have no intersection
return false;
}
// calculate depth
dReal fDepth = -(dFabs(fCenter) - (frc + fTriangleRadius ) );
// if greater then best found so far
if ( fDepth < m_fBestDepth )
{
// remember depth
m_fBestDepth = fDepth;
m_fBestCenter = fCenter;
m_fBestrt = frc;
dVector3Copy(vAxis,m_vContactNormal);
m_iBestAxis = iAxis;
// flip normal if interval is wrong faced
if ( fCenter< REAL(0.0) && !bNoFlip)
{
dVector3Inv(m_vContactNormal);
m_fBestCenter = -fCenter;
}
}
return true;
}
// intersection test between edge and circle
bool sCylinderTrimeshColliderData::_cldTestCircleToEdgeAxis(
const dVector3 &v0, const dVector3 &v1, const dVector3 &v2,
const dVector3 &vCenterPoint, const dVector3 &vCylinderAxis1,
const dVector3 &vVx0, const dVector3 &vVx1, int iAxis)
{
// calculate direction of edge
dVector3 vkl;
dVector3Subtract( vVx1 , vVx0 , vkl);
dNormalize3(vkl);
// starting point of edge
dVector3 vol;
dVector3Copy(vVx0,vol);
// calculate angle cosine between cylinder axis and edge
dReal fdot2 = dVector3Dot(vkl , vCylinderAxis1);
// if edge is perpendicular to cylinder axis
if(dFabs(fdot2)<REAL(1e-5))
{
// this can't be separating axis, because edge is parallel to circle plane
return true;
}
// find point of intersection between edge line and circle plane
dVector3 vTemp;
dVector3Subtract(vCenterPoint,vol,vTemp);
dReal fdot1 = dVector3Dot(vTemp,vCylinderAxis1);
dVector3 vpnt;// = vol + vkl * (fdot1/fdot2);
vpnt[0] = vol[0] + vkl[0] * fdot1/fdot2;
vpnt[1] = vol[1] + vkl[1] * fdot1/fdot2;
vpnt[2] = vol[2] + vkl[2] * fdot1/fdot2;
// find tangent vector on circle with same center (vCenterPoint) that touches point of intersection (vpnt)
dVector3 vTangent;
dVector3Subtract(vCenterPoint,vpnt,vTemp);
dVector3Cross(vTemp,vCylinderAxis1,vTangent);
// find vector orthogonal both to tangent and edge direction
dVector3 vAxis;
dVector3Cross(vTangent,vkl,vAxis);
// use that vector as separating axis
return _cldTestAxis( v0, v1, v2, vAxis, iAxis );
}
// helper for less key strokes
// r = ( (v1 - v2) cross v3 ) cross v3
inline void _CalculateAxis(const dVector3& v1,
const dVector3& v2,
const dVector3& v3,
dVector3& r)
{
dVector3 t1;
dVector3 t2;
dVector3Subtract(v1,v2,t1);
dVector3Cross(t1,v3,t2);
dVector3Cross(t2,v3,r);
}
bool sCylinderTrimeshColliderData::_cldTestSeparatingAxes(
const dVector3 &v0,
const dVector3 &v1,
const dVector3 &v2)
{
// calculate edge vectors
dVector3Subtract(v1 ,v0 , m_vE0);
// m_vE1 has been calculated before -> so save some cycles here
dVector3Subtract(v0 ,v2 , m_vE2);
// calculate caps centers in absolute space
dVector3 vCp0;
vCp0[0] = m_vCylinderPos[0] + m_vCylinderAxis[0]*(m_fCylinderSize* REAL(0.5));
vCp0[1] = m_vCylinderPos[1] + m_vCylinderAxis[1]*(m_fCylinderSize* REAL(0.5));
vCp0[2] = m_vCylinderPos[2] + m_vCylinderAxis[2]*(m_fCylinderSize* REAL(0.5));
#if 0
dVector3 vCp1;
vCp1[0] = m_vCylinderPos[0] - m_vCylinderAxis[0]*(m_fCylinderSize* REAL(0.5));
vCp1[1] = m_vCylinderPos[1] - m_vCylinderAxis[1]*(m_fCylinderSize* REAL(0.5));
vCp1[2] = m_vCylinderPos[2] - m_vCylinderAxis[2]*(m_fCylinderSize* REAL(0.5));
#endif
// reset best axis
m_iBestAxis = 0;
dVector3 vAxis;
// axis m_vNormal
//vAxis = -m_vNormal;
vAxis[0] = -m_vNormal[0];
vAxis[1] = -m_vNormal[1];
vAxis[2] = -m_vNormal[2];
if (!_cldTestAxis(v0, v1, v2, vAxis, 1, true))
{
return false;
}
// axis CxE0
// vAxis = ( m_vCylinderAxis cross m_vE0 );
dVector3Cross(m_vCylinderAxis, m_vE0,vAxis);
if (!_cldTestAxis(v0, v1, v2, vAxis, 2))
{
return false;
}
// axis CxE1
// vAxis = ( m_vCylinderAxis cross m_vE1 );
dVector3Cross(m_vCylinderAxis, m_vE1,vAxis);
if (!_cldTestAxis(v0, v1, v2, vAxis, 3))
{
return false;
}
// axis CxE2
// vAxis = ( m_vCylinderAxis cross m_vE2 );
dVector3Cross(m_vCylinderAxis, m_vE2,vAxis);
if (!_cldTestAxis(v0, v1, v2, vAxis, 4))
{
return false;
}
// first vertex on triangle
// axis ((V0-Cp0) x C) x C
//vAxis = ( ( v0-vCp0 ) cross m_vCylinderAxis ) cross m_vCylinderAxis;
_CalculateAxis(v0 , vCp0 , m_vCylinderAxis , vAxis);
if (!_cldTestAxis(v0, v1, v2, vAxis, 11))
{
return false;
}
// second vertex on triangle
// axis ((V1-Cp0) x C) x C
// vAxis = ( ( v1-vCp0 ) cross m_vCylinderAxis ) cross m_vCylinderAxis;
_CalculateAxis(v1 , vCp0 , m_vCylinderAxis , vAxis);
if (!_cldTestAxis(v0, v1, v2, vAxis, 12))
{
return false;
}
// third vertex on triangle
// axis ((V2-Cp0) x C) x C
//vAxis = ( ( v2-vCp0 ) cross m_vCylinderAxis ) cross m_vCylinderAxis;
_CalculateAxis(v2 , vCp0 , m_vCylinderAxis , vAxis);
if (!_cldTestAxis(v0, v1, v2, vAxis, 13))
{
return false;
}
// test cylinder axis
// vAxis = m_vCylinderAxis;
dVector3Copy(m_vCylinderAxis , vAxis);
if (!_cldTestAxis(v0, v1, v2, vAxis, 14))
{
return false;
}
// Test top and bottom circle ring of cylinder for separation
dVector3 vccATop;
vccATop[0] = m_vCylinderPos[0] + m_vCylinderAxis[0]*(m_fCylinderSize * REAL(0.5));
vccATop[1] = m_vCylinderPos[1] + m_vCylinderAxis[1]*(m_fCylinderSize * REAL(0.5));
vccATop[2] = m_vCylinderPos[2] + m_vCylinderAxis[2]*(m_fCylinderSize * REAL(0.5));
dVector3 vccABottom;
vccABottom[0] = m_vCylinderPos[0] - m_vCylinderAxis[0]*(m_fCylinderSize * REAL(0.5));
vccABottom[1] = m_vCylinderPos[1] - m_vCylinderAxis[1]*(m_fCylinderSize * REAL(0.5));
vccABottom[2] = m_vCylinderPos[2] - m_vCylinderAxis[2]*(m_fCylinderSize * REAL(0.5));
if (!_cldTestCircleToEdgeAxis(v0, v1, v2, vccATop, m_vCylinderAxis, v0, v1, 15))
{
return false;
}
if (!_cldTestCircleToEdgeAxis(v0, v1, v2, vccATop, m_vCylinderAxis, v1, v2, 16))
{
return false;
}
if (!_cldTestCircleToEdgeAxis(v0, v1, v2, vccATop, m_vCylinderAxis, v0, v2, 17))
{
return false;
}
if (!_cldTestCircleToEdgeAxis(v0, v1, v2, vccABottom, m_vCylinderAxis, v0, v1, 18))
{
return false;
}
if (!_cldTestCircleToEdgeAxis(v0, v1, v2, vccABottom, m_vCylinderAxis, v1, v2, 19))
{
return false;
}
if (!_cldTestCircleToEdgeAxis(v0, v1, v2, vccABottom, m_vCylinderAxis, v0, v2, 20))
{
return false;
}
return true;
}
bool sCylinderTrimeshColliderData::_cldClipCylinderEdgeToTriangle(
const dVector3 &v0, const dVector3 &/*v1*/, const dVector3 &/*v2*/)
{
// translate cylinder
dReal fTemp = dVector3Dot(m_vCylinderAxis , m_vContactNormal);
dVector3 vN2;
vN2[0] = m_vContactNormal[0] - m_vCylinderAxis[0]*fTemp;
vN2[1] = m_vContactNormal[1] - m_vCylinderAxis[1]*fTemp;
vN2[2] = m_vContactNormal[2] - m_vCylinderAxis[2]*fTemp;
fTemp = dVector3Length(vN2);
if (fTemp < REAL(1e-5))
{
return false;
}
// Normalize it
vN2[0] /= fTemp;
vN2[1] /= fTemp;
vN2[2] /= fTemp;
// calculate caps centers in absolute space
dVector3 vCposTrans;
vCposTrans[0] = m_vCylinderPos[0] + vN2[0]*m_fCylinderRadius;
vCposTrans[1] = m_vCylinderPos[1] + vN2[1]*m_fCylinderRadius;
vCposTrans[2] = m_vCylinderPos[2] + vN2[2]*m_fCylinderRadius;
dVector3 vCEdgePoint0;
vCEdgePoint0[0] = vCposTrans[0] + m_vCylinderAxis[0] * (m_fCylinderSize* REAL(0.5));
vCEdgePoint0[1] = vCposTrans[1] + m_vCylinderAxis[1] * (m_fCylinderSize* REAL(0.5));
vCEdgePoint0[2] = vCposTrans[2] + m_vCylinderAxis[2] * (m_fCylinderSize* REAL(0.5));
dVector3 vCEdgePoint1;
vCEdgePoint1[0] = vCposTrans[0] - m_vCylinderAxis[0] * (m_fCylinderSize* REAL(0.5));
vCEdgePoint1[1] = vCposTrans[1] - m_vCylinderAxis[1] * (m_fCylinderSize* REAL(0.5));
vCEdgePoint1[2] = vCposTrans[2] - m_vCylinderAxis[2] * (m_fCylinderSize* REAL(0.5));
// transform cylinder edge points into triangle space
vCEdgePoint0[0] -= v0[0];
vCEdgePoint0[1] -= v0[1];
vCEdgePoint0[2] -= v0[2];
vCEdgePoint1[0] -= v0[0];
vCEdgePoint1[1] -= v0[1];
vCEdgePoint1[2] -= v0[2];
dVector4 plPlane;
dVector3 vPlaneNormal;
// triangle plane
//plPlane = Plane4f( -m_vNormal, 0);
vPlaneNormal[0] = -m_vNormal[0];
vPlaneNormal[1] = -m_vNormal[1];
vPlaneNormal[2] = -m_vNormal[2];
dConstructPlane(vPlaneNormal,REAL(0.0),plPlane);
if(!dClipEdgeToPlane( vCEdgePoint0, vCEdgePoint1, plPlane ))
{
return false;
}
// plane with edge 0
//plPlane = Plane4f( ( m_vNormal cross m_vE0 ), REAL(1e-5));
dVector3Cross(m_vNormal,m_vE0,vPlaneNormal);
dConstructPlane(vPlaneNormal,REAL(1e-5),plPlane);
if(!dClipEdgeToPlane( vCEdgePoint0, vCEdgePoint1, plPlane ))
{
return false;
}
// plane with edge 1
//dVector3 vTemp = ( m_vNormal cross m_vE1 );
dVector3Cross(m_vNormal,m_vE1,vPlaneNormal);
fTemp = dVector3Dot(m_vE0 , vPlaneNormal) - REAL(1e-5);
//plPlane = Plane4f( vTemp, -(( m_vE0 dot vTemp )-REAL(1e-5)));
dConstructPlane(vPlaneNormal,-fTemp,plPlane);
if(!dClipEdgeToPlane( vCEdgePoint0, vCEdgePoint1, plPlane ))
{
return false;
}
// plane with edge 2
// plPlane = Plane4f( ( m_vNormal cross m_vE2 ), REAL(1e-5));
dVector3Cross(m_vNormal,m_vE2,vPlaneNormal);
dConstructPlane(vPlaneNormal,REAL(1e-5),plPlane);
if(!dClipEdgeToPlane( vCEdgePoint0, vCEdgePoint1, plPlane ))
{
return false;
}
// return capsule edge points into absolute space
vCEdgePoint0[0] += v0[0];
vCEdgePoint0[1] += v0[1];
vCEdgePoint0[2] += v0[2];
vCEdgePoint1[0] += v0[0];
vCEdgePoint1[1] += v0[1];
vCEdgePoint1[2] += v0[2];
// calculate depths for both contact points
dVector3 vTemp;
dVector3Subtract(vCEdgePoint0,m_vCylinderPos, vTemp);
dReal fRestDepth0 = -dVector3Dot(vTemp,m_vContactNormal) + m_fBestrt;
dVector3Subtract(vCEdgePoint1,m_vCylinderPos, vTemp);
dReal fRestDepth1 = -dVector3Dot(vTemp,m_vContactNormal) + m_fBestrt;
dReal fDepth0 = m_fBestDepth - (fRestDepth0);
dReal fDepth1 = m_fBestDepth - (fRestDepth1);
// clamp depths to zero
if(fDepth0 < REAL(0.0) )
{
fDepth0 = REAL(0.0);
}
if(fDepth1<REAL(0.0))
{
fDepth1 = REAL(0.0);
}
// Generate contact 0
{
m_gLocalContacts[m_nContacts].fDepth = fDepth0;
dVector3Copy(m_vContactNormal,m_gLocalContacts[m_nContacts].vNormal);
dVector3Copy(vCEdgePoint0,m_gLocalContacts[m_nContacts].vPos);
m_gLocalContacts[m_nContacts].nFlags = 1;
m_nContacts++;
if(m_nContacts >= (m_iFlags & NUMC_MASK))
return true;
}
// Generate contact 1
{
// generate contacts
m_gLocalContacts[m_nContacts].fDepth = fDepth1;
dVector3Copy(m_vContactNormal,m_gLocalContacts[m_nContacts].vNormal);
dVector3Copy(vCEdgePoint1,m_gLocalContacts[m_nContacts].vPos);
m_gLocalContacts[m_nContacts].nFlags = 1;
m_nContacts++;
}
return true;
}
void sCylinderTrimeshColliderData::_cldClipCylinderToTriangle(
const dVector3 &v0, const dVector3 &v1, const dVector3 &v2)
{
int i = 0;
dVector3 avPoints[3];
dVector3 avTempArray1[nMAX_CYLINDER_TRIANGLE_CLIP_POINTS];
dVector3 avTempArray2[nMAX_CYLINDER_TRIANGLE_CLIP_POINTS];
dSetZero(&avTempArray1[0][0],nMAX_CYLINDER_TRIANGLE_CLIP_POINTS * 4);
dSetZero(&avTempArray2[0][0],nMAX_CYLINDER_TRIANGLE_CLIP_POINTS * 4);
// setup array of triangle vertices
dVector3Copy(v0,avPoints[0]);
dVector3Copy(v1,avPoints[1]);
dVector3Copy(v2,avPoints[2]);
dVector3 vCylinderCirclePos, vCylinderCircleNormal_Rel;
dSetZero(vCylinderCircleNormal_Rel,4);
// check which circle from cylinder we take for clipping
if ( dVector3Dot(m_vCylinderAxis , m_vContactNormal) > REAL(0.0))
{
// get top circle
vCylinderCirclePos[0] = m_vCylinderPos[0] + m_vCylinderAxis[0]*(m_fCylinderSize*REAL(0.5));
vCylinderCirclePos[1] = m_vCylinderPos[1] + m_vCylinderAxis[1]*(m_fCylinderSize*REAL(0.5));
vCylinderCirclePos[2] = m_vCylinderPos[2] + m_vCylinderAxis[2]*(m_fCylinderSize*REAL(0.5));
vCylinderCircleNormal_Rel[nCYLINDER_AXIS] = REAL(-1.0);
}
else
{
// get bottom circle
vCylinderCirclePos[0] = m_vCylinderPos[0] - m_vCylinderAxis[0]*(m_fCylinderSize*REAL(0.5));
vCylinderCirclePos[1] = m_vCylinderPos[1] - m_vCylinderAxis[1]*(m_fCylinderSize*REAL(0.5));
vCylinderCirclePos[2] = m_vCylinderPos[2] - m_vCylinderAxis[2]*(m_fCylinderSize*REAL(0.5));
vCylinderCircleNormal_Rel[nCYLINDER_AXIS] = REAL(1.0);
}
dVector3 vTemp;
dQuatInv(m_qCylinderRot , m_qInvCylinderRot);
// transform triangle points to space of cylinder circle
for(i=0; i<3; i++)
{
dVector3Subtract(avPoints[i] , vCylinderCirclePos , vTemp);
dQuatTransform(m_qInvCylinderRot,vTemp,avPoints[i]);
}
int iTmpCounter1 = 0;
int iTmpCounter2 = 0;
dVector4 plPlane;
// plane of cylinder that contains circle for intersection
//plPlane = Plane4f( vCylinderCircleNormal_Rel, 0.0f );
dConstructPlane(vCylinderCircleNormal_Rel,REAL(0.0),plPlane);
dClipPolyToPlane(avPoints, 3, avTempArray1, iTmpCounter1, plPlane);
// Body of base circle of Cylinder
int nCircleSegment = 0;
for (nCircleSegment = 0; nCircleSegment < nCYLINDER_CIRCLE_SEGMENTS; nCircleSegment++)
{
dConstructPlane(m_avCylinderNormals[nCircleSegment],m_fCylinderRadius,plPlane);
if (0 == (nCircleSegment % 2))
{
dClipPolyToPlane( avTempArray1 , iTmpCounter1 , avTempArray2, iTmpCounter2, plPlane);
}
else
{
dClipPolyToPlane( avTempArray2, iTmpCounter2, avTempArray1 , iTmpCounter1 , plPlane );
}
dIASSERT( iTmpCounter1 >= 0 && iTmpCounter1 <= nMAX_CYLINDER_TRIANGLE_CLIP_POINTS );
dIASSERT( iTmpCounter2 >= 0 && iTmpCounter2 <= nMAX_CYLINDER_TRIANGLE_CLIP_POINTS );
}
// back transform clipped points to absolute space
dReal ftmpdot;
dReal fTempDepth;
dVector3 vPoint;
if (nCircleSegment %2)
{
for( i=0; i<iTmpCounter2; i++)
{
dQuatTransform(m_qCylinderRot,avTempArray2[i], vPoint);
vPoint[0] += vCylinderCirclePos[0];
vPoint[1] += vCylinderCirclePos[1];
vPoint[2] += vCylinderCirclePos[2];
dVector3Subtract(vPoint,m_vCylinderPos,vTemp);
ftmpdot = dFabs(dVector3Dot(vTemp, m_vContactNormal));
fTempDepth = m_fBestrt - ftmpdot;
// Depth must be positive
if (fTempDepth > REAL(0.0))
{
m_gLocalContacts[m_nContacts].fDepth = fTempDepth;
dVector3Copy(m_vContactNormal,m_gLocalContacts[m_nContacts].vNormal);
dVector3Copy(vPoint,m_gLocalContacts[m_nContacts].vPos);
m_gLocalContacts[m_nContacts].nFlags = 1;
m_nContacts++;
if(m_nContacts >= (m_iFlags & NUMC_MASK))
return;;
}
}
}
else
{
for( i=0; i<iTmpCounter1; i++)
{
dQuatTransform(m_qCylinderRot,avTempArray1[i], vPoint);
vPoint[0] += vCylinderCirclePos[0];
vPoint[1] += vCylinderCirclePos[1];
vPoint[2] += vCylinderCirclePos[2];
dVector3Subtract(vPoint,m_vCylinderPos,vTemp);
ftmpdot = dFabs(dVector3Dot(vTemp, m_vContactNormal));
fTempDepth = m_fBestrt - ftmpdot;
// Depth must be positive
if (fTempDepth > REAL(0.0))
{
m_gLocalContacts[m_nContacts].fDepth = fTempDepth;
dVector3Copy(m_vContactNormal,m_gLocalContacts[m_nContacts].vNormal);
dVector3Copy(vPoint,m_gLocalContacts[m_nContacts].vPos);
m_gLocalContacts[m_nContacts].nFlags = 1;
m_nContacts++;
if(m_nContacts >= (m_iFlags & NUMC_MASK))
return;;
}
}
}
}
void sCylinderTrimeshColliderData::TestOneTriangleVsCylinder(
const dVector3 &v0,
const dVector3 &v1,
const dVector3 &v2,
const bool bDoubleSided)
{
// calculate triangle normal
dVector3Subtract( v2 , v1 , m_vE1);
dVector3 vTemp;
dVector3Subtract( v0 , v1 ,vTemp);
dVector3Cross(m_vE1 , vTemp , m_vNormal );
// Even though all triangles might be initially valid,
// a triangle may degenerate into a segment after applying
// space transformation.
if (!dSafeNormalize3( m_vNormal))
{
return;
}
// create plane from triangle
//Plane4f plTrianglePlane = Plane4f( vPolyNormal, v0 );
dReal plDistance = -dVector3Dot(v0, m_vNormal);
dVector4 plTrianglePlane;
dConstructPlane( m_vNormal,plDistance,plTrianglePlane);
// calculate sphere distance to plane
dReal fDistanceCylinderCenterToPlane = dPointPlaneDistance(m_vCylinderPos , plTrianglePlane);
// Sphere must be over positive side of triangle
if(fDistanceCylinderCenterToPlane < 0 && !bDoubleSided)
{
// if not don't generate contacts
return;
}
dVector3 vPnt0;
dVector3 vPnt1;
dVector3 vPnt2;
if (fDistanceCylinderCenterToPlane < REAL(0.0) )
{
// flip it
dVector3Copy(v0 , vPnt0);
dVector3Copy(v1 , vPnt2);
dVector3Copy(v2 , vPnt1);
}
else
{
dVector3Copy(v0 , vPnt0);
dVector3Copy(v1 , vPnt1);
dVector3Copy(v2 , vPnt2);
}
m_fBestDepth = MAX_REAL;
// do intersection test and find best separating axis
if(!_cldTestSeparatingAxes(vPnt0, vPnt1, vPnt2) )
{
// if not found do nothing
return;
}
// if best separation axis is not found
if ( m_iBestAxis == 0 )
{
// this should not happen (the function should have already returned in this case)
dIASSERT(false);
// do nothing
return;
}
dReal fdot = dVector3Dot( m_vContactNormal , m_vCylinderAxis );
// choose which clipping method are we going to apply
if (dFabs(fdot) < REAL(0.9) )
{
if (!_cldClipCylinderEdgeToTriangle(vPnt0, vPnt1, vPnt2))
{
return;
}
}
else
{
_cldClipCylinderToTriangle(vPnt0, vPnt1, vPnt2);
}
}
void sCylinderTrimeshColliderData::_InitCylinderTrimeshData(dxGeom *Cylinder, dxTriMesh *Trimesh)
{
// get cylinder information
// Rotation
const dReal* pRotCyc = dGeomGetRotation(Cylinder);
dMatrix3Copy(pRotCyc,m_mCylinderRot);
dGeomGetQuaternion(Cylinder,m_qCylinderRot);
// Position
const dVector3* pPosCyc = (const dVector3*)dGeomGetPosition(Cylinder);
dVector3Copy(*pPosCyc,m_vCylinderPos);
// Cylinder axis
dMat3GetCol(m_mCylinderRot,nCYLINDER_AXIS,m_vCylinderAxis);
// get cylinder radius and size
dGeomCylinderGetParams(Cylinder,&m_fCylinderRadius,&m_fCylinderSize);
// get trimesh position and orientation
const dReal* pRotTris = dGeomGetRotation(Trimesh);
dMatrix3Copy(pRotTris,m_mTrimeshRot);
dGeomGetQuaternion(Trimesh,m_qTrimeshRot);
// Position
const dVector3* pPosTris = (const dVector3*)dGeomGetPosition(Trimesh);
dVector3Copy(*pPosTris,m_vTrimeshPos);
// calculate basic angle for 8-gon
dReal fAngle = (dReal) (M_PI / nCYLINDER_CIRCLE_SEGMENTS);
// calculate angle increment
dReal fAngleIncrement = fAngle*REAL(2.0);
// calculate plane normals
// axis dependant code
for(int i=0; i<nCYLINDER_CIRCLE_SEGMENTS; i++)
{
m_avCylinderNormals[i][0] = -dCos(fAngle);
m_avCylinderNormals[i][1] = -dSin(fAngle);
m_avCylinderNormals[i][2] = REAL(0.0);
fAngle += fAngleIncrement;
}
dSetZero(m_vBestPoint,4);
// reset best depth
m_fBestCenter = REAL(0.0);
}
int sCylinderTrimeshColliderData::TestCollisionForSingleTriangle(int ctContacts0,
int Triint, dVector3 dv[3], bool &bOutFinishSearching)
{
// test this triangle
TestOneTriangleVsCylinder(dv[0],dv[1],dv[2], false);
// fill-in tri index for generated contacts
for (; ctContacts0<m_nContacts; ctContacts0++)
m_gLocalContacts[ctContacts0].triIndex = Triint;
// Putting "break" at the end of loop prevents unnecessary checks on first pass and "continue"
bOutFinishSearching = (m_nContacts >= (m_iFlags & NUMC_MASK));
return ctContacts0;
}
// OPCODE version of cylinder to mesh collider
#if dTRIMESH_OPCODE
static void dQueryCTLPotentialCollisionTriangles(OBBCollider &Collider,
sCylinderTrimeshColliderData &cData, dxGeom *Cylinder, dxTriMesh *Trimesh,
OBBCache &BoxCache)
{
Matrix4x4 MeshMatrix;
const dVector3 vZeroVector3 = { REAL(0.0), };
MakeMatrix(vZeroVector3, cData.m_mTrimeshRot, MeshMatrix);
const dVector3 &vCylinderPos = cData.m_vCylinderPos;
const dMatrix3 &mCylinderRot = cData.m_mCylinderRot;
dVector3 vCylinderOffsetPos;
dSubtractVectors3(vCylinderOffsetPos, vCylinderPos, cData.m_vTrimeshPos);
const dReal fCylinderRadius = cData.m_fCylinderRadius, fCylinderHalfAxis = cData.m_fCylinderSize * REAL(0.5);
OBB obbCylinder;
obbCylinder.mCenter.Set(vCylinderOffsetPos[0], vCylinderOffsetPos[1], vCylinderOffsetPos[2]);
obbCylinder.mExtents.Set(
0 == nCYLINDER_AXIS ? fCylinderHalfAxis : fCylinderRadius,
1 == nCYLINDER_AXIS ? fCylinderHalfAxis : fCylinderRadius,
2 == nCYLINDER_AXIS ? fCylinderHalfAxis : fCylinderRadius);
obbCylinder.mRot.Set(
mCylinderRot[0], mCylinderRot[4], mCylinderRot[8],
mCylinderRot[1], mCylinderRot[5], mCylinderRot[9],
mCylinderRot[2], mCylinderRot[6], mCylinderRot[10]);
// TC results
if (Trimesh->getDoTC(dxTriMesh::TTC_BOX))
{
dxTriMesh::BoxTC* BoxTC = 0;
const int iBoxCacheSize = Trimesh->m_BoxTCCache.size();
for (int i = 0; i != iBoxCacheSize; i++)
{
if (Trimesh->m_BoxTCCache[i].Geom == Cylinder)
{
BoxTC = &Trimesh->m_BoxTCCache[i];
break;
}
}
if (!BoxTC)
{
Trimesh->m_BoxTCCache.push(dxTriMesh::BoxTC());
BoxTC = &Trimesh->m_BoxTCCache[Trimesh->m_BoxTCCache.size() - 1];
BoxTC->Geom = Cylinder;
BoxTC->FatCoeff = REAL(1.0);
}
// Intersect
Collider.SetTemporalCoherence(true);
Collider.Collide(*BoxTC, obbCylinder, Trimesh->retrieveMeshBVTreeRef(), null, &MeshMatrix);
}
else
{
Collider.SetTemporalCoherence(false);
Collider.Collide(BoxCache, obbCylinder, Trimesh->retrieveMeshBVTreeRef(), null, &MeshMatrix);
}
}
int dCollideCylinderTrimesh(dxGeom *o1, dxGeom *o2, int flags, dContactGeom *contact, int skip)
{
dIASSERT( skip >= (int)sizeof( dContactGeom ) );
dIASSERT( o1->type == dCylinderClass );
dIASSERT( o2->type == dTriMeshClass );
dIASSERT ((flags & NUMC_MASK) >= 1);
int nContactCount = 0;
dxGeom *Cylinder = o1;
dxTriMesh *Trimesh = (dxTriMesh *)o2;
// Main data holder
sCylinderTrimeshColliderData cData(flags, skip);
cData._InitCylinderTrimeshData(Cylinder, Trimesh);
const unsigned uiTLSKind = Trimesh->getParentSpaceTLSKind();
dIASSERT(uiTLSKind == Cylinder->getParentSpaceTLSKind()); // The colliding spaces must use matching cleanup method
TrimeshCollidersCache *pccColliderCache = GetTrimeshCollidersCache(uiTLSKind);
OBBCollider& Collider = pccColliderCache->m_OBBCollider;
dQueryCTLPotentialCollisionTriangles(Collider, cData, Cylinder, Trimesh, pccColliderCache->m_DefaultBoxCache);
// Retrieve data
int TriCount = Collider.GetNbTouchedPrimitives();
if (TriCount != 0)
{
const int* Triangles = (const int*)Collider.GetTouchedPrimitives();
if (Trimesh->m_ArrayCallback != NULL)
{
Trimesh->m_ArrayCallback(Trimesh, Cylinder, Triangles, TriCount);
}
// allocate buffer for local contacts on stack
cData.m_gLocalContacts = (sLocalContactData*)dALLOCA16(sizeof(sLocalContactData)*(cData.m_iFlags & NUMC_MASK));
int ctContacts0 = 0;
// loop through all intersecting triangles
for (int i = 0; i < TriCount; i++)
{
const int Triint = Triangles[i];
if (!Trimesh->invokeCallback(Cylinder, Triint)) continue;
dVector3 dv[3];
Trimesh->fetchMeshTriangle(dv, Triint, cData.m_vTrimeshPos, cData.m_mTrimeshRot);
bool bFinishSearching;
ctContacts0 = cData.TestCollisionForSingleTriangle(ctContacts0, Triint, dv, bFinishSearching);
if (bFinishSearching)
{
break;
}
}
if (cData.m_nContacts != 0)
{
nContactCount = cData._ProcessLocalContacts(contact, Cylinder, Trimesh);
}
}
return nContactCount;
}
#endif
// GIMPACT version of cylinder to mesh collider
#if dTRIMESH_GIMPACT
int dCollideCylinderTrimesh(dxGeom *o1, dxGeom *o2, int flags, dContactGeom *contact, int skip)
{
dIASSERT( skip >= (int)sizeof( dContactGeom ) );
dIASSERT( o1->type == dCylinderClass );
dIASSERT( o2->type == dTriMeshClass );
dIASSERT ((flags & NUMC_MASK) >= 1);
int nContactCount = 0;
dxGeom *Cylinder = o1;
dxTriMesh *Trimesh = (dxTriMesh *)o2;
// Main data holder
sCylinderTrimeshColliderData cData(flags, skip);
cData._InitCylinderTrimeshData(Cylinder, Trimesh);
//*****at first , collide box aabb******//
aabb3f test_aabb(o1->aabb[0], o1->aabb[1], o1->aabb[2], o1->aabb[3], o1->aabb[4], o1->aabb[5]);
GDYNAMIC_ARRAY collision_result;
GIM_CREATE_BOXQUERY_LIST(collision_result);
gim_aabbset_box_collision(&test_aabb, &Trimesh->m_collision_trimesh.m_aabbset , &collision_result);
if (collision_result.m_size != 0)
{
//*****Set globals for box collision******//
int ctContacts0 = 0;
cData.m_gLocalContacts = (sLocalContactData*)dALLOCA16(sizeof(sLocalContactData)*(cData.m_iFlags & NUMC_MASK));
GUINT32 * boxesresult = GIM_DYNARRAY_POINTER(GUINT32,collision_result);
GIM_TRIMESH * ptrimesh = &Trimesh->m_collision_trimesh;
gim_trimesh_locks_work_data(ptrimesh);
for(unsigned int i=0;i<collision_result.m_size;i++)
{
const int Triint = boxesresult[i];
dVector3 dv[3];
gim_trimesh_get_triangle_vertices(ptrimesh, Triint, dv[0], dv[1], dv[2]);
bool bFinishSearching;
ctContacts0 = cData.TestCollisionForSingleTriangle(ctContacts0, Triint, dv, bFinishSearching);
if (bFinishSearching)
{
break;
}
}
gim_trimesh_unlocks_work_data(ptrimesh);
if (cData.m_nContacts != 0)
{
nContactCount = cData._ProcessLocalContacts(contact, Cylinder, Trimesh);
}
}
GIM_DYNARRAY_DESTROY(collision_result);
return nContactCount;
}
#endif
#endif // dTRIMESH_ENABLED
| 0 | 0.966377 | 1 | 0.966377 | game-dev | MEDIA | 0.637934 | game-dev,scientific-computing | 0.985468 | 1 | 0.985468 |
SilentChaos512/Silent-Gear | 1,907 | src/main/java/net/silentchaos512/gear/api/util/PropertyProvider.java | package net.silentchaos512.gear.api.util;
import net.silentchaos512.gear.api.part.PartType;
import net.silentchaos512.gear.api.property.GearPropertyValue;
import java.util.Collection;
import java.util.function.Supplier;
/**
* Something that can provide property modifiers, such as parts and materials
*
* @param <D> An object containing more data about this object, such as
* {@link net.silentchaos512.gear.gear.part.PartInstance} or
* {@link net.silentchaos512.gear.gear.material.MaterialInstance}
*/
public interface PropertyProvider<D> {
<T, V extends GearPropertyValue<T>> Collection<V> getPropertyModifiers(D instance, PartType partType, PropertyKey<T, V> key);
default <T, V extends GearPropertyValue<T>> Collection<V> getPropertyModifiers(D instance, Supplier<PartType> partType, PropertyKey<T, V> key) {
return getPropertyModifiers(instance, partType.get(), key);
}
default <T, V extends GearPropertyValue<T>> T getProperty(D instance, PartType partType, PropertyKey<T, V> key) {
var property = key.property();
var mods = getPropertyModifiers(instance, partType, key);
return property.compute(mods);
}
default <T, V extends GearPropertyValue<T>> T getProperty(D instance, Supplier<PartType> partType, PropertyKey<T, V> key) {
return getProperty(instance, partType.get(), key);
}
default <T, V extends GearPropertyValue<T>> T getPropertyUnclamped(D instance, PartType partType, PropertyKey<T, V> key) {
var property = key.property();
var mods = getPropertyModifiers(instance, partType, key);
return property.compute(property.getBaseValue(), false, key.gearType(), mods);
}
default <T, V extends GearPropertyValue<T>> T getPropertyUnclamped(D instance, Supplier<PartType> partType, PropertyKey<T, V> key) {
return getPropertyUnclamped(instance, partType.get(), key);
}
}
| 0 | 0.790729 | 1 | 0.790729 | game-dev | MEDIA | 0.803632 | game-dev | 0.882649 | 1 | 0.882649 |
id-Software/DOOM-3-BFG | 9,379 | neo/framework/File_SaveGame.h | /*
===========================================================================
Doom 3 BFG Edition GPL Source Code
Copyright (C) 1993-2012 id Software LLC, a ZeniMax Media company.
This file is part of the Doom 3 BFG Edition GPL Source Code ("Doom 3 BFG Edition Source Code").
Doom 3 BFG Edition Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Doom 3 BFG Edition Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Doom 3 BFG Edition Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 BFG Edition Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 BFG Edition Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
#ifndef __FILE_SAVEGAME_H__
#define __FILE_SAVEGAME_H__
#include "zlib/zlib.h"
// Listing of the types of files within a savegame package
enum saveGameType_t {
SAVEGAMEFILE_NONE = 0,
SAVEGAMEFILE_TEXT = BIT( 0 ), // implies that no checksum will be used
SAVEGAMEFILE_BINARY = BIT( 1 ), // implies that a checksum will also be used
SAVEGAMEFILE_COMPRESSED = BIT( 2 ),
SAVEGAMEFILE_PIPELINED = BIT( 3 ),
SAVEGAMEFILE_THUMB = BIT( 4 ), // for special processing on certain platforms
SAVEGAMEFILE_BKGRND_IMAGE = BIT( 5 ), // for special processing on certain platforms, large background used on PS3
SAVEGAMEFILE_AUTO_DELETE = BIT( 6 ), // to be deleted automatically after completed
SAVEGAMEFILE_OPTIONAL = BIT( 7 ) // if this flag is not set and missing, there is an error
};
/*
================================================
idFile_SaveGame
================================================
*/
class idFile_SaveGame : public idFile_Memory {
public:
idFile_SaveGame() : type( SAVEGAMEFILE_NONE ), error( false ) {}
idFile_SaveGame( const char * _name ) : idFile_Memory( _name ), type( SAVEGAMEFILE_NONE ), error( false ) {}
idFile_SaveGame( const char * _name, int type_ ) : idFile_Memory( _name ), type( type_ ), error( false ) {}
virtual ~idFile_SaveGame() { }
bool operator==( const idFile_SaveGame & other ) const {
return idStr::Icmp( GetName(), other.GetName() ) == 0;
}
bool operator==( const char * _name ) const {
return idStr::Icmp( GetName(), _name ) == 0;
}
void SetNameAndType( const char *_name, int _type ) {
name = _name;
type = _type;
}
public: // TODO_KC_CR for now...
int type; // helps platform determine what to do with the file (encrypt, checksum, etc.)
bool error; // when loading, this is set if there is a problem
};
/*
================================================
idFile_SaveGamePipelined uses threads to pipeline overlap compression and IO
================================================
*/
class idSGFreadThread;
class idSGFwriteThread;
class idSGFdecompressThread;
class idSGFcompressThread;
struct blockForIO_t {
byte * data;
size_t bytes;
};
class idFile_SaveGamePipelined : public idFile {
public:
// The buffers each hold two blocks of data, so one block can be operated on by
// the next part of the generate / compress / IO pipeline. The factor of two
// size difference between the uncompressed and compressed blocks is unrelated
// to the fact that there are two blocks in each buffer.
static const int COMPRESSED_BLOCK_SIZE = 128 * 1024;
static const int UNCOMPRESSED_BLOCK_SIZE = 256 * 1024;
idFile_SaveGamePipelined();
virtual ~idFile_SaveGamePipelined();
bool OpenForReading( const char * const filename, bool useNativeFile );
bool OpenForWriting( const char * const filename, bool useNativeFile );
bool OpenForReading( idFile * file );
bool OpenForWriting( idFile * file );
// Finish any reading or writing.
void Finish();
// Abort any reading or writing.
void Abort();
// Cancel any reading or writing for app termination
static void CancelToTerminate() { cancelToTerminate = true; }
bool ReadBuildVersion();
const char * GetBuildVersion() const { return buildVersion; }
bool ReadSaveFormatVersion();
int GetSaveFormatVersion() const { return saveFormatVersion; }
int GetPointerSize() const;
//------------------------
// idFile Interface
//------------------------
virtual const char * GetName() const { return name.c_str(); }
virtual const char * GetFullPath() const { return name.c_str(); }
virtual int Read( void * buffer, int len );
virtual int Write( const void * buffer, int len );
// this file is strictly streaming, you can't seek at all
virtual int Length() const { return compressedLength; }
virtual void SetLength( size_t len ) { compressedLength = len; }
virtual int Tell() const { assert( 0 ); return 0; }
virtual int Seek( long offset, fsOrigin_t origin ) { assert( 0 ); return 0; }
virtual ID_TIME_T Timestamp() const { return 0; }
//------------------------
// These can be used by a background thread to read/write data
// when the file was opened with 'useNativeFile' set to false.
//------------------------
enum mode_t {
CLOSED,
WRITE,
READ
};
// Get the file mode: read/write.
mode_t GetMode() const { return mode; }
// Called by a background thread to get the next block to be written out.
// This may block until a block has been made available through the pipeline.
// Pass in NULL to notify the last write failed.
// Returns false if there are no more blocks.
bool NextWriteBlock( blockForIO_t * block );
// Called by a background thread to get the next block to read data into and to
// report the number of bytes written to the previous block.
// This may block until space is available to place the next block.
// Pass in NULL to notify the end of the file was reached.
// Returns false if there are no more blocks.
bool NextReadBlock( blockForIO_t * block, size_t lastReadBytes );
private:
friend class idSGFreadThread;
friend class idSGFwriteThread;
friend class idSGFdecompressThread;
friend class idSGFcompressThread;
idStr name; // Name of the file.
idStr osPath; // OS path.
mode_t mode; // Open mode.
size_t compressedLength;
static const int COMPRESSED_BUFFER_SIZE = COMPRESSED_BLOCK_SIZE * 2;
static const int UNCOMPRESSED_BUFFER_SIZE = UNCOMPRESSED_BLOCK_SIZE * 2;
byte uncompressed[UNCOMPRESSED_BUFFER_SIZE];
size_t uncompressedProducedBytes; // not masked
size_t uncompressedConsumedBytes; // not masked
byte compressed[COMPRESSED_BUFFER_SIZE];
size_t compressedProducedBytes; // not masked
size_t compressedConsumedBytes; // not masked
//------------------------
// These variables are used to pass data between threads in a thread-safe manner.
//------------------------
byte * dataZlib;
size_t bytesZlib;
byte * dataIO;
size_t bytesIO;
//------------------------
// These variables are used by CompressBlock() and DecompressBlock().
//------------------------
z_stream zStream;
int zLibFlushType; // Z_NO_FLUSH or Z_FINISH
bool zStreamEndHit;
int numChecksums;
//------------------------
// These variables are used by WriteBlock() and ReadBlock().
//------------------------
idFile * nativeFile;
bool nativeFileEndHit;
bool finished;
//------------------------
// The background threads and signals for NextWriteBlock() and NextReadBlock().
//------------------------
idSGFreadThread * readThread;
idSGFwriteThread * writeThread;
idSGFdecompressThread * decompressThread;
idSGFcompressThread * compressThread;
idSysSignal blockRequested;
idSysSignal blockAvailable;
idSysSignal blockFinished;
idStrStatic< 32 > buildVersion; // build version this file was saved with
int16 pointerSize; // the number of bytes in a pointer, because different pointer sizes mean different offsets into objects a 64 bit build cannot load games saved from a 32 bit build or vice version (a value of 0 is interpreted as 4 bytes)
int16 saveFormatVersion; // version number specific to save games (for maintaining save compatibility across builds)
//------------------------
// These variables are used when we want to abort due to the termination of the application
//------------------------
static bool cancelToTerminate;
void FlushUncompressedBlock();
void FlushCompressedBlock();
void CompressBlock();
void WriteBlock();
void PumpUncompressedBlock();
void PumpCompressedBlock();
void DecompressBlock();
void ReadBlock();
};
#endif // !__FILE_SAVEGAME_H__
| 0 | 0.880639 | 1 | 0.880639 | game-dev | MEDIA | 0.697023 | game-dev | 0.872326 | 1 | 0.872326 |
opentibiabr/otservbr-global-archived | 4,831 | data/lib/quests/their_masters_voice.lua | local config = {
quest_duration = 60, -- how long until quest is reverted, in minutes
slime_exhaust = 5, -- exhaust until you can remove another slime, in seconds
slimes_needed = 25, -- slimes needed to be removed to kill mad mage and complete quest
max_slimes = 100, -- max slimes needed to start waves
max_waves = 25 -- max waves, last one will be mad mage
}
local mage_positions = {
{x = 33328, y = 31859, z = 9},
{x = 33367, y = 31873, z = 9},
{x = 33349, y = 31899, z = 9}
}
local servant_positions = {
{x = 33313, y = 31852, z = 9},
{x = 33313, y = 31881, z = 9},
{x = 33328, y = 31860, z = 9},
{x = 33328, y = 31873, z = 9},
{x = 33328, y = 31885, z = 9},
{x = 33308, y = 31873, z = 9},
{x = 33320, y = 31873, z = 9},
{x = 33335, y = 31873, z = 9},
{x = 33360, y = 31873, z = 9},
{x = 33336, y = 31914, z = 9},
{x = 33343, y = 31914, z = 9},
{x = 33353, y = 31914, z = 9},
{x = 33361, y = 31914, z = 9},
{x = 33345, y = 31900, z = 9},
{x = 33352, y = 31900, z = 9},
{x = 33355, y = 31854, z = 9},
{x = 33355, y = 31885, z = 9},
{x = 33345, y = 31864, z = 9},
{x = 33345, y = 31881, z = 9},
{x = 33309, y = 31867, z = 9},
{x = 33317, y = 31879, z = 9},
{x = 33311, y = 31854, z = 9},
{x = 33334, y = 31889, z = 9},
{x = 33340, y = 31890, z = 9},
{x = 33347, y = 31889, z = 9}
}
local slime_ids = {13585, 13586, 13587, 13588, 13589}
local servants = {
{10, "diamond servant"},
{40, "golden servant"},
{100, "iron servant"}
}
slime_exhaust = slime_exhaust or {}
slimes_removed = slimes_removed or {}
current_servants = current_servants or {}
current_mage = current_mage or 0
current_wave = current_wave or 0
valid_participants = valid_participants or {}
function startServantWave()
current_wave = current_wave + 1
if current_wave == config.max_waves then
local mage = Game.createMonster("Mad Mage", mage_positions[math.random(#mage_positions)], true, true)
if mage then
mage:registerEvent("Mage_Death")
end
return
end
current_servants = {}
for pos_key = 1, #servant_positions do
local random = math.random(100)
for servant_key = 1, #servants do
if random <= servants[servant_key][1] then
local servant = Game.createMonster(servants[servant_key][2], servant_positions[pos_key], true, true)
if servant then
current_servants[#current_servants + 1] = servant.uid
servant:registerEvent("Servant_Death")
break
end
end
end
end
end
function revertQuest()
for i = 1, #current_servants do
local servant = Creature(current_servants[i])
if servant then
servant:remove()
end
end
current_servants = {}
local mage = Creature(current_mage)
if mage then
mage:remove()
end
current_mage = 0
for i = 1, #slimes_removed do
local ground = Tile(slimes_removed[i].pos):getGround()
if ground then
ground:transform(slimes_removed[i].id)
end
end
slimes_removed = {}
current_wave = 0
end
function Gobbler_onUse(player, item, fromPosition, target, toPosition, isHotkey)
if not target or not isInArray(slime_ids, target.itemid) then
return false
end
local time = os.time()
if slime_exhaust[player.uid] and slime_exhaust[player.uid] >= os.time() then
player:sendCancelMessage(RETURNVALUE_YOUAREEXHAUSTED)
fromPosition:sendMagicEffect(CONST_ME_POFF)
return true
end
slime_exhaust[player.uid] = time + config.slime_exhaust
player:say("The slime gobbler gobbles large chunks of the slime fungus with great satisfaction.", TALKTYPE_MONSTER_SAY)
player:addExperience(20, true, true)
slimes_removed[#slimes_removed + 1] = {cid = player.uid, id = target.itemid, pos = toPosition}
target:transform(13590)
if not isInArray(valid_participants, player.uid) then
local slime_count = 0
for i = 1, #slimes_removed do
if slimes_removed[i].cid == player.uid then
slime_count = slime_count + 1
if slime_count == 25 then
player:say("You gobbled enough slime to get a good grip on this dungeon's slippery floor.", TALKTYPE_MONSTER_SAY)
valid_participants[#valid_participants + 1] = player.uid
break
end
end
end
end
if #slimes_removed == 1 then
addEvent(revertQuest, config.quest_duration * 60 * 1000)
elseif #slimes_removed >= config.max_slimes then
player:say("COME! My servants! RISE!", TALKTYPE_MONSTER_SAY)
startServantWave()
end
return true
end
function Servant_onDeath(creature, corpse, killer, mostDamageKiller, lastHitUnjustified)
for i = 1, #current_servants do
if current_servants[i] == creature.uid then
table.remove(current_servants, i)
break
end
end
if #current_servants < 1 then
startServantWave()
end
return true
end
function Mage_onDeath(creature, corpse, killer, mostDamageKiller, lastHitUnjustified)
if killer and isInArray(valid_participants, killer.uid) then
-- add achievements if needed
end
revertQuest()
return true
end
| 0 | 0.758193 | 1 | 0.758193 | game-dev | MEDIA | 0.939413 | game-dev | 0.816117 | 1 | 0.816117 |
BobbyAnguelov/Esoterica | 1,933 | Code/Engine/Animation/AnimationEvent.h | #pragma once
#include "Engine/_Module/API.h"
#include "Base/Time/Time.h"
#include "Base/TypeSystem/ReflectedType.h"
#include "Base/Math/NumericRange.h"
//-------------------------------------------------------------------------
// Animation Event
//-------------------------------------------------------------------------
// Base class for all animation events
namespace EE
{
class StringID;
}
//-------------------------------------------------------------------------
namespace EE::Animation
{
class EE_ENGINE_API Event : public IReflectedType
{
EE_REFLECT_TYPE( Event );
friend class AnimationClipCompiler;
public:
Event() = default;
Event( Event const& ) = default;
virtual ~Event() = default;
Event& operator=( Event const& rhs ) = default;
virtual bool IsValid() const { return true; }
inline Seconds GetStartTime() const { return m_startTime; }
inline Seconds GetDuration() const { return m_duration; }
inline Seconds GetEndTime() const { EE_ASSERT( IsDurationEvent() ); return m_startTime + m_duration; }
inline bool IsImmediateEvent() const { return m_duration == 0; }
inline bool IsDurationEvent() const { return m_duration > 0; }
// Get the time range for this event (in seconds)
EE_FORCE_INLINE FloatRange GetTimeRange() const { return FloatRange( m_startTime, m_startTime + m_duration ); }
// Optional: Allow the track to return a specific sync event ID
virtual StringID GetSyncEventID() const;
#if EE_DEVELOPMENT_TOOLS
// Get a string description of the event for use when debugging
virtual InlineString GetDebugText() const { return GetStaticTypeID().c_str(); }
#endif
protected:
EE_REFLECT( ReadOnly ) Seconds m_startTime = 0.0f;
EE_REFLECT( ReadOnly ) Seconds m_duration = 0.0f;
};
} | 0 | 0.828416 | 1 | 0.828416 | game-dev | MEDIA | 0.511609 | game-dev | 0.823796 | 1 | 0.823796 |
TylerTemp/SaintsField | 5,657 | Editor/Drawers/CustomPicker/FieldTypeDrawer/FieldTypeAttributeDrawerIMGUI.cs | using System;
using System.Collections.Generic;
using System.Reflection;
using SaintsField.Editor.Utils;
using SaintsField.Interfaces;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;
namespace SaintsField.Editor.Drawers.CustomPicker.FieldTypeDrawer
{
public partial class FieldTypeAttributeDrawer
{
private string _error = "";
protected override float GetFieldHeight(SerializedProperty property, GUIContent label,
float width,
ISaintsAttribute saintsAttribute, FieldInfo info, bool hasLabelWidth, object parent) => EditorGUIUtility.singleLineHeight;
protected override void DrawField(Rect position, SerializedProperty property, GUIContent label,
ISaintsAttribute saintsAttribute, IReadOnlyList<PropertyAttribute> allAttributes, OnGUIPayload onGUIPayload,
FieldInfo info, object parent)
{
FieldTypeAttribute fieldTypeAttribute = (FieldTypeAttribute)saintsAttribute;
Type fieldType = SerializedUtils.IsArrayOrDirectlyInsideArray(property)? ReflectUtils.GetElementType(info.FieldType): info.FieldType;
Type requiredComp = fieldTypeAttribute.CompType ?? fieldType;
Object requiredValue;
try
{
requiredValue = GetValue(property, fieldType, requiredComp);
}
catch (Exception e)
{
Debug.LogException(e);
_error = e.Message;
DefaultDrawer(position, property, label, info);
return;
}
EPick editorPick = fieldTypeAttribute.EditorPick;
bool customPicker = fieldTypeAttribute.CustomPicker;
// ReSharper disable once ConvertToUsingDeclaration
using (EditorGUI.ChangeCheckScope changed = new EditorGUI.ChangeCheckScope())
{
Rect fieldRect = customPicker
? new Rect(position)
{
width = position.width - 20,
}
: position;
Object fieldResult =
EditorGUI.ObjectField(fieldRect, label, requiredValue, requiredComp, editorPick.HasFlagFast(EPick.Scene));
// ReSharper disable once InvertIf
if (changed.changed)
{
Object result = GetNewValue(fieldResult, fieldType, requiredComp);
property.objectReferenceValue = result;
if (fieldResult != null && result == null)
{
_error = $"{fieldResult} has no component {fieldType}";
}
}
}
if(customPicker)
{
Rect overrideButtonRect = new Rect(position.x + position.width - 21, position.y, 21, position.height);
if (GUI.Button(overrideButtonRect, "●"))
{
// Type[] types = requiredComp == fieldType
// ? new []{requiredComp}
// : new []{requiredComp, fieldType};
FieldTypeSelectWindow.Open(property.objectReferenceValue, editorPick, fieldType, requiredComp, fieldResult =>
{
Object result = OnSelectWindowSelected(fieldResult, fieldType);
property.objectReferenceValue = result;
property.serializedObject.ApplyModifiedProperties();
onGUIPayload.SetValue(result);
});
}
}
}
private static Object OnSelectWindowSelected(Object fieldResult, Type fieldType)
{
return Util.GetTypeFromObj(fieldResult, fieldType);
// Object result = null;
// switch (fieldResult)
// {
// case null:
// // property.objectReferenceValue = null;
// break;
// case GameObject go:
// result = fieldType == typeof(GameObject) ? (Object)go : go.GetComponent(fieldType);
// // Debug.Log($"isGo={fieldType == typeof(GameObject)}, fieldResult={fieldResult.GetType()} result={result.GetType()}");
// break;
// case Component comp:
// result = fieldType == typeof(GameObject)
// ? (Object)comp.gameObject
// : comp.GetComponent(fieldType);
// break;
// }
//
// return result;
}
protected override bool WillDrawBelow(SerializedProperty property,
IReadOnlyList<PropertyAttribute> allAttributes, ISaintsAttribute saintsAttribute,
int index,
FieldInfo info,
object parent) => _error != "";
protected override float GetBelowExtraHeight(SerializedProperty property, GUIContent label, float width,
IReadOnlyList<PropertyAttribute> allAttributes,
ISaintsAttribute saintsAttribute, int index, FieldInfo info, object parent) => _error == "" ? 0 : ImGuiHelpBox.GetHeight(_error, EditorGUIUtility.currentViewWidth, MessageType.Error);
protected override Rect DrawBelow(Rect position, SerializedProperty property, GUIContent label,
ISaintsAttribute saintsAttribute, int index, IReadOnlyList<PropertyAttribute> allAttributes,
OnGUIPayload onGuiPayload, FieldInfo info, object parent) => ImGuiHelpBox.Draw(position, _error, MessageType.Error);
}
}
| 0 | 0.945443 | 1 | 0.945443 | game-dev | MEDIA | 0.548128 | game-dev | 0.99465 | 1 | 0.99465 |
wplib/wplib-box | 2,669 | www/wp-content/plugins/query-monitor/collectors/debug_bar.php | <?php
/**
* Mock 'Debug Bar' data collector.
*
* @package query-monitor
*/
final class QM_Collector_Debug_Bar extends QM_Collector {
public $id = 'debug_bar';
private $panel = null;
public function __construct() {
parent::__construct();
}
public function name() {
$title = $this->get_panel()->title();
return sprintf(
/* translators: Debug Bar add-on name */
__( 'Debug Bar: %s', 'query-monitor' ),
$title
);
}
public function set_panel( Debug_Bar_Panel $panel ) {
$this->panel = $panel;
}
public function get_panel() {
return $this->panel;
}
public function process() {
$this->get_panel()->prerender();
}
public function is_visible() {
return $this->get_panel()->is_visible();
}
public function render() {
return $this->get_panel()->render();
}
}
function register_qm_collectors_debug_bar() {
global $debug_bar;
if ( class_exists( 'Debug_Bar' ) || qm_debug_bar_being_activated() ) {
return;
}
$collectors = QM_Collectors::init();
$qm = QueryMonitor::init();
require_once $qm->plugin_path( 'classes/debug_bar.php' );
$debug_bar = new Debug_Bar;
$redundant = array(
'debug_bar_actions_addon_panel', // Debug Bar Actions and Filters Addon
'debug_bar_remote_requests_panel', // Debug Bar Remote Requests
'debug_bar_screen_info_panel', // Debug Bar Screen Info
'ps_listdeps_debug_bar_panel', // Debug Bar List Script & Style Dependencies
);
foreach ( $debug_bar->panels as $panel ) {
$panel_id = strtolower( sanitize_html_class( get_class( $panel ) ) );
if ( in_array( $panel_id, $redundant, true ) ) {
continue;
}
$collector = new QM_Collector_Debug_Bar;
$collector->set_id( "debug_bar_{$panel_id}" );
$collector->set_panel( $panel );
$collectors->add( $collector );
}
}
function qm_debug_bar_being_activated() {
// @codingStandardsIgnoreStart
if ( ! is_admin() ) {
return false;
}
if ( ! isset( $_REQUEST['action'] ) ) {
return false;
}
if ( isset( $_GET['action'] ) ) {
if ( ! isset( $_GET['plugin'] ) || ! isset( $_GET['_wpnonce'] ) ) {
return false;
}
if ( 'activate' === $_GET['action'] && false !== strpos( wp_unslash( $_GET['plugin'] ), 'debug-bar.php' ) ) {
return true;
}
} elseif ( isset( $_POST['action'] ) ) {
if ( ! isset( $_POST['checked'] ) || ! is_array( $_POST['checked'] ) || ! isset( $_POST['_wpnonce'] ) ) {
return false;
}
if ( 'activate-selected' === wp_unslash( $_POST['action'] ) && in_array( 'debug-bar/debug-bar.php', wp_unslash( $_POST['checked'] ), true ) ) {
return true;
}
}
return false;
// @codingStandardsIgnoreEnd
}
add_action( 'init', 'register_qm_collectors_debug_bar' );
| 0 | 0.84724 | 1 | 0.84724 | game-dev | MEDIA | 0.374862 | game-dev | 0.861967 | 1 | 0.861967 |
tgstation/tgstation | 34,028 | code/modules/mob/living/living_defense.dm |
/mob/living/proc/run_armor_check(def_zone = null, attack_flag = MELEE, absorb_text = null, soften_text = null, armour_penetration, penetrated_text, silent=FALSE, weak_against_armour = FALSE)
var/our_armor = getarmor(def_zone, attack_flag)
if(our_armor <= 0)
return our_armor
if(weak_against_armour && our_armor >= 0)
our_armor *= ARMOR_WEAKENED_MULTIPLIER
if(silent)
return max(0, PENETRATE_ARMOUR(our_armor, armour_penetration))
//the if "armor" check is because this is used for everything on /living, including humans
if(armour_penetration)
our_armor = max(PENETRATE_ARMOUR(our_armor, armour_penetration), 0)
if(penetrated_text)
to_chat(src, span_userdanger("[penetrated_text]"))
else
to_chat(src, span_userdanger("Your armor was penetrated!"))
else if(our_armor >= 100)
if(absorb_text)
to_chat(src, span_notice("[absorb_text]"))
else
to_chat(src, span_notice("Your armor absorbs the blow!"))
else
if(soften_text)
to_chat(src, span_warning("[soften_text]"))
else
to_chat(src, span_warning("Your armor softens the blow!"))
return our_armor
/mob/living/proc/getarmor(def_zone, type)
return 0
//this returns the mob's protection against eye damage (number between -1 and 2) from bright lights
/mob/living/proc/get_eye_protection()
return 0
//this returns the mob's protection against ear damage (0:no protection; 1: some ear protection; 2: has no ears)
/mob/living/proc/get_ear_protection()
var/turf/current_turf = get_turf(src)
var/datum/gas_mixture/environment = current_turf.return_air()
var/pressure = environment ? environment.return_pressure() : 0
if(pressure < SOUND_MINIMUM_PRESSURE) //space is empty
return 1
return 0
/**
* Checks if our mob has their mouth covered.
*
* Note that we only care about [ITEM_SLOT_HEAD] and [ITEM_SLOT_MASK].
* (so if you check all slots, it'll return head, then mask)
*That is also the priority order
* Arguments
* * check_flags: What item slots should we check?
*
* Retuns a truthy value (a ref to what is covering mouth), or a falsy value (null)
*/
/mob/living/proc/is_mouth_covered(check_flags = ALL)
return null
/**
* Checks if our mob has their eyes covered.
*
* Note that we only care about [ITEM_SLOT_HEAD], [ITEM_SLOT_MASK], and [ITEM_SLOT_GLASSES].
* That is also the priority order (so if you check all slots, it'll return head, then mask, then glasses)
*
* Arguments
* * check_flags: What item slots should we check?
*
* Retuns a truthy value (a ref to what is covering eyes), or a falsy value (null)
*/
/mob/living/proc/is_eyes_covered(check_flags = ALL)
return null
/**
* Checks if our mob is protected from pepper spray.
*
* Note that we only care about [ITEM_SLOT_HEAD] and [ITEM_SLOT_MASK].
* That is also the priority order (so if you check all slots, it'll return head, then mask)
*
* Arguments
* * check_flags: What item slots should we check?
*
* Retuns a truthy value (a ref to what is protecting us), or a falsy value (null)
*/
/mob/living/proc/is_pepper_proof(check_flags = ALL)
return null
/// Checks if the mob's ears (BOTH EARS, BOWMANS NEED NOT APPLY) are covered by something.
/// Returns the atom covering the mob's ears, or null if their ears are uncovered.
/mob/living/proc/is_ears_covered()
return null
/mob/living/bullet_act(obj/projectile/proj, def_zone, piercing_hit = FALSE, blocked = 0)
. = ..()
if (. != BULLET_ACT_HIT)
return .
if(blocked >= 100)
if(proj.is_hostile_projectile())
apply_projectile_effects(proj, def_zone, blocked)
return .
var/hit_limb_zone = check_hit_limb_zone_name(def_zone)
var/organ_hit_text = ""
if (hit_limb_zone)
organ_hit_text = " in \the [parse_zone_with_bodypart(hit_limb_zone)]"
switch (proj.suppressed)
if (SUPPRESSED_QUIET)
to_chat(src, span_userdanger("You're shot by \a [proj][organ_hit_text]!"))
if (SUPPRESSED_NONE)
visible_message(span_danger("[src] is hit by \a [proj][organ_hit_text]!"), \
span_userdanger("You're hit by \a [proj][organ_hit_text]!"), null, COMBAT_MESSAGE_RANGE)
if(is_blind())
to_chat(src, span_userdanger("You feel something hit you[organ_hit_text]!"))
if(proj.is_hostile_projectile())
apply_projectile_effects(proj, def_zone, blocked)
/mob/living/proc/apply_projectile_effects(obj/projectile/proj, def_zone, armor_check)
apply_damage(
damage = proj.damage,
damagetype = proj.damage_type,
def_zone = def_zone,
blocked = min(ARMOR_MAX_BLOCK, armor_check), //cap damage reduction at 90%
wound_bonus = proj.wound_bonus,
exposed_wound_bonus = proj.exposed_wound_bonus,
sharpness = proj.sharpness,
attack_direction = get_dir(proj.starting, src),
attacking_item = proj,
)
apply_effects(
stun = proj.stun,
knockdown = proj.knockdown,
unconscious = proj.unconscious,
slur = (mob_biotypes & MOB_ROBOTIC) ? 0 SECONDS : proj.slur, // Don't want your cyborgs to slur from being ebow'd
stutter = (mob_biotypes & MOB_ROBOTIC) ? 0 SECONDS : proj.stutter, // Don't want your cyborgs to stutter from being tazed
eyeblur = proj.eyeblur,
drowsy = proj.drowsy,
blocked = armor_check,
stamina = proj.stamina,
jitter = (mob_biotypes & MOB_ROBOTIC) ? 0 SECONDS : proj.jitter, // Cyborgs can jitter but not from being shot
paralyze = proj.paralyze,
immobilize = proj.immobilize,
)
if(proj.dismemberment)
check_projectile_dismemberment(proj, def_zone)
if (proj.damage && armor_check < 100)
create_projectile_hit_effects(proj, def_zone, armor_check)
/mob/living/proc/create_projectile_hit_effects(obj/projectile/proj, def_zone, blocked)
if (proj.damage_type != BRUTE)
return
var/obj/item/bodypart/hit_bodypart = get_bodypart(check_hit_limb_zone_name(def_zone))
if (blood_volume && (isnull(hit_bodypart) || hit_bodypart.can_bleed()))
create_splatter(angle2dir(proj.angle))
if(prob(33))
add_splatter_floor(get_turf(src))
return
if (hit_bodypart?.biological_state & (BIO_METAL|BIO_WIRED))
var/random_damage_mult = RANDOM_DECIMAL(0.85, 1.15) // SOMETIMES you can get more or less sparks
var/damage_dealt = ((proj.damage / (1 - (blocked / 100))) * random_damage_mult)
var/spark_amount = round((damage_dealt / PROJECTILE_DAMAGE_PER_ROBOTIC_SPARK))
if (spark_amount > 0)
do_sparks(spark_amount, FALSE, src)
/mob/living/check_projectile_armor(def_zone, obj/projectile/impacting_projectile, is_silent)
return run_armor_check(def_zone, impacting_projectile.armor_flag, "","",impacting_projectile.armour_penetration, "", is_silent, impacting_projectile.weak_against_armour)
/mob/living/proc/check_projectile_dismemberment(obj/projectile/proj, def_zone)
return
/obj/item/proc/get_volume_by_throwforce_and_or_w_class()
if(throwforce && w_class)
return clamp((throwforce + w_class) * 5, 30, 100)// Add the item's throwforce to its weight class and multiply by 5, then clamp the value between 30 and 100
if(w_class)
return clamp(w_class * 8, 20, 100) // Multiply the item's weight class by 8, then clamp the value between 20 and 100
return 0 // plays no sound
/mob/living/proc/set_combat_mode(new_mode, silent = TRUE)
if(HAS_TRAIT(src, TRAIT_COMBAT_MODE_LOCK))
return
if(combat_mode == new_mode)
return
. = combat_mode
combat_mode = new_mode
SEND_SIGNAL(src, COMSIG_COMBAT_MODE_TOGGLED)
if(hud_used?.action_intent)
hud_used.action_intent.update_appearance()
if(silent || !client?.prefs.read_preference(/datum/preference/toggle/sound_combatmode))
return
if(combat_mode)
SEND_SOUND(src, sound('sound/misc/ui_togglecombat.ogg', volume = 25)) //Sound from interbay!
else
SEND_SOUND(src, sound('sound/misc/ui_toggleoffcombat.ogg', volume = 25)) //Slightly modified version of the above
/mob/living/hitby(atom/movable/AM, skipcatch, hitpush = TRUE, blocked = FALSE, datum/thrownthing/throwingdatum)
if(!isitem(AM))
// Filled with made up numbers for non-items.
if(check_block(AM, 30, "\the [AM.name]", THROWN_PROJECTILE_ATTACK, 0, BRUTE) & SUCCESSFUL_BLOCK)
hitpush = FALSE
skipcatch = TRUE
blocked = TRUE
return SUCCESSFUL_BLOCK
else
playsound(loc, 'sound/items/weapons/genhit.ogg', 50, TRUE, -1) //Item sounds are handled in the item itself
if(!isvendor(AM) && !iscarbon(AM)) //Vendors have special interactions, while carbon mobs already generate visible messages!
visible_message(span_danger("[src] is hit by [AM]!"), \
span_userdanger("You're hit by [AM]!"))
log_combat(AM, src, "hit ")
return ..()
var/obj/item/thrown_item = AM
if(throwingdatum?.get_thrower() != src) //No throwing stuff at yourself to trigger hit reactions
if(check_block(AM, thrown_item.throwforce, "\the [thrown_item.name]", THROWN_PROJECTILE_ATTACK, 0, thrown_item.damtype))
hitpush = FALSE
skipcatch = TRUE
blocked = TRUE
var/zone = get_random_valid_zone(BODY_ZONE_CHEST, 65)//Hits a random part of the body, geared towards the chest
var/nosell_hit = (SEND_SIGNAL(thrown_item, COMSIG_MOVABLE_IMPACT_ZONE, src, zone, blocked, throwingdatum) & MOVABLE_IMPACT_ZONE_OVERRIDE) // TODO: find a better way to handle hitpush and skipcatch for humans
if(nosell_hit)
skipcatch = TRUE
hitpush = FALSE
if(blocked)
return SUCCESSFUL_BLOCK
if(nosell_hit)
log_hit_combat(throwingdatum?.get_thrower(), thrown_item)
return ..()
visible_message(span_danger("[src] is hit by [thrown_item]!"),
span_userdanger("You're hit by [thrown_item]!"))
if(!thrown_item.throwforce)
log_hit_combat(throwingdatum?.get_thrower(), thrown_item)
return
var/armor = run_armor_check(
zone,
MELEE,
"Your armor has protected your [parse_zone_with_bodypart(zone)].",
"Your armor has softened hit to your [parse_zone_with_bodypart(zone)].",
thrown_item.armour_penetration,
"",
FALSE,
thrown_item.weak_against_armour,
)
apply_damage(thrown_item.throwforce, thrown_item.damtype, zone, armor, sharpness = thrown_item.get_sharpness(), wound_bonus = (nosell_hit * CANT_WOUND), attacking_item = thrown_item)
log_hit_combat(throwingdatum?.get_thrower(), thrown_item)
if(QDELETED(src)) //Damage can delete the mob.
return
if(body_position == LYING_DOWN) // physics says it's significantly harder to push someone by constantly chucking random furniture at them if they are down on the floor.
hitpush = FALSE
return ..()
/mob/living/proc/log_hit_combat(mob/thrown_by, obj/item/thrown_item)
if(thrown_by)
return log_combat(thrown_by, src, "threw and hit", thrown_item)
return log_combat(thrown_item, src, "hit ")
///The core of catching thrown items, which non-carbons cannot without the help of items or abilities yet, as they've no throw mode.
/mob/living/proc/try_catch_item(obj/item/item, skip_throw_mode_check = FALSE, try_offhand = FALSE)
if(!can_catch_item(skip_throw_mode_check, try_offhand) || !isitem(item) || HAS_TRAIT(item, TRAIT_UNCATCHABLE) || !isturf(item.loc))
return FALSE
if(!can_hold_items(item))
return FALSE
INVOKE_ASYNC(item, TYPE_PROC_REF(/obj/item, attempt_pickup), src, TRUE)
if(get_active_held_item() == item) //if our attack_hand() picks up the item...
visible_message(span_warning("[src] catches [item]!"), \
span_userdanger("You catch [item] in mid-air!"))
return TRUE
///Checks the requites for catching a throw item.
/mob/living/proc/can_catch_item(skip_throw_mode_check = FALSE, try_offhand = FALSE)
if(HAS_TRAIT(src, TRAIT_HANDS_BLOCKED))
return FALSE
if(get_active_held_item() && (!try_offhand || get_inactive_held_item() || !swap_hand()))
return FALSE
return TRUE
/mob/living/fire_act()
. = ..()
adjust_fire_stacks(3)
ignite_mob()
/**
* Called when a mob is grabbing another mob.
*/
/mob/living/proc/grab(mob/living/target)
if(!istype(target))
return FALSE
if(SEND_SIGNAL(src, COMSIG_LIVING_GRAB, target) & (COMPONENT_CANCEL_ATTACK_CHAIN|COMPONENT_SKIP_ATTACK))
return FALSE
if(target.check_block(src, 0, "[src]'s grab", UNARMED_ATTACK))
return FALSE
target.grabbedby(src)
return TRUE
/**
* Called when this mob is grabbed by another mob.
*/
/mob/living/proc/grabbedby(mob/living/user, supress_message = FALSE)
if(user == src || anchored || !isturf(user.loc))
return FALSE
if(!user.pulling || user.pulling != src)
user.start_pulling(src, supress_message = supress_message)
return
if(!(status_flags & CANPUSH) || HAS_TRAIT(src, TRAIT_PUSHIMMUNE))
to_chat(user, span_warning("[src] can't be grabbed more aggressively!"))
return FALSE
if(user.grab_state >= GRAB_AGGRESSIVE && HAS_TRAIT(user, TRAIT_PACIFISM))
to_chat(user, span_warning("You don't want to risk hurting [src]!"))
return FALSE
grippedby(user)
update_incapacitated()
//proc to upgrade a simple pull into a more aggressive grab.
/mob/living/proc/grippedby(mob/living/user, instant = FALSE)
if(user.grab_state >= user.max_grab)
return
user.changeNext_move(CLICK_CD_GRABBING)
var/sound_to_play = 'sound/items/weapons/thudswoosh.ogg'
if(ishuman(user))
var/mob/living/carbon/human/H = user
if(H.dna.species.grab_sound)
sound_to_play = H.dna.species.grab_sound
playsound(src.loc, sound_to_play, 50, TRUE, -1)
if(user.grab_state) //only the first upgrade is instantaneous
var/old_grab_state = user.grab_state
var/grab_upgrade_time = instant ? 0 : 30
visible_message(span_danger("[user] starts to tighten [user.p_their()] grip on [src]!"), \
span_userdanger("[user] starts to tighten [user.p_their()] grip on you!"), span_hear("You hear aggressive shuffling!"), null, user)
to_chat(user, span_danger("You start to tighten your grip on [src]!"))
switch(user.grab_state)
if(GRAB_AGGRESSIVE)
log_combat(user, src, "attempted to neck grab", addition="neck grab")
if(GRAB_NECK)
log_combat(user, src, "attempted to strangle", addition="kill grab")
if(!do_after(user, grab_upgrade_time, src))
return FALSE
if(!user.pulling || user.pulling != src || user.grab_state != old_grab_state)
return FALSE
user.setGrabState(user.grab_state + 1)
switch(user.grab_state)
if(GRAB_AGGRESSIVE)
var/add_log = ""
if(HAS_TRAIT(user, TRAIT_PACIFISM))
visible_message(span_danger("[user] firmly grips [src]!"),
span_danger("[user] firmly grips you!"), span_hear("You hear aggressive shuffling!"), null, user)
to_chat(user, span_danger("You firmly grip [src]!"))
add_log = " (pacifist)"
else
visible_message(span_danger("[user] grabs [src] aggressively!"), \
span_userdanger("[user] grabs you aggressively!"), span_hear("You hear aggressive shuffling!"), null, user)
to_chat(user, span_danger("You grab [src] aggressively!"))
stop_pulling()
log_combat(user, src, "grabbed", addition="aggressive grab[add_log]")
if(GRAB_NECK)
log_combat(user, src, "grabbed", addition="neck grab")
visible_message(span_danger("[user] grabs [src] by the neck!"),\
span_userdanger("[user] grabs you by the neck!"), span_hear("You hear aggressive shuffling!"), null, user)
to_chat(user, span_danger("You grab [src] by the neck!"))
if(!buckled && !density)
Move(user.loc)
if(GRAB_KILL)
log_combat(user, src, "strangled", addition="kill grab")
visible_message(span_danger("[user] is strangling [src]!"), \
span_userdanger("[user] is strangling you!"), span_hear("You hear aggressive shuffling!"), null, user)
to_chat(user, span_danger("You're strangling [src]!"))
if(!buckled && !density)
Move(user.loc)
user.set_pull_offsets(src, user.grab_state)
return TRUE
/mob/living/attack_animal(mob/living/simple_animal/user, list/modifiers)
. = ..()
if(.)
return FALSE // looks wrong, but if the attack chain was cancelled we don't propogate it up to children calls. Yeah it's cringe.
if(user.melee_damage_upper == 0)
if(user != src)
visible_message(
span_notice("[user] [user.friendly_verb_continuous] [src]!"),
span_notice("[user] [user.friendly_verb_continuous] you!"),
vision_distance = COMBAT_MESSAGE_RANGE,
ignored_mobs = user,
)
to_chat(user, span_notice("You [user.friendly_verb_simple] [src]!"))
return FALSE
if(HAS_TRAIT(user, TRAIT_PACIFISM))
to_chat(user, span_warning("You don't want to hurt anyone!"))
return FALSE
var/damage = rand(user.melee_damage_lower, user.melee_damage_upper)
if(check_block(user, damage, "[user]'s [user.attack_verb_simple]", UNARMED_ATTACK, user.armour_penetration, user.melee_damage_type))
return FALSE
if(user.attack_sound)
playsound(src, user.attack_sound, 50, TRUE, TRUE)
user.do_attack_animation(src)
visible_message(
span_danger("[user] [user.attack_verb_continuous] [src]!"),
span_userdanger("[user] [user.attack_verb_continuous] you!"),
null,
COMBAT_MESSAGE_RANGE,
user,
)
var/dam_zone = dismembering_strike(user, pick(BODY_ZONE_CHEST, BODY_ZONE_PRECISE_L_HAND, BODY_ZONE_PRECISE_R_HAND, BODY_ZONE_L_LEG, BODY_ZONE_R_LEG))
if(!dam_zone) //Dismemberment successful
return FALSE
var/armor_block = run_armor_check(user.zone_selected, MELEE, armour_penetration = user.armour_penetration)
to_chat(user, span_danger("You [user.attack_verb_simple] [src]!"))
var/damage_done = apply_damage(
damage = damage,
damagetype = user.melee_damage_type,
def_zone = user.zone_selected,
blocked = armor_block,
wound_bonus = user.wound_bonus,
exposed_wound_bonus = user.exposed_wound_bonus,
sharpness = user.sharpness,
attack_direction = get_dir(user, src),
)
log_combat(user, src, "attacked")
return damage_done
/mob/living/attack_hand(mob/living/carbon/human/user, list/modifiers)
. = ..()
if(.)
return TRUE
for(var/datum/surgery/operations as anything in surgeries)
if(user.combat_mode)
break
if(IS_IN_INVALID_SURGICAL_POSITION(src, operations))
continue
if(operations.next_step(user, modifiers))
return TRUE
return FALSE
/mob/living/attack_paw(mob/living/carbon/human/user, list/modifiers)
if(LAZYACCESS(modifiers, RIGHT_CLICK))
user.disarm(src)
return TRUE
if (!user.combat_mode)
return FALSE
if(HAS_TRAIT(user, TRAIT_PACIFISM))
to_chat(user, span_warning("You don't want to hurt anyone!"))
return FALSE
if(!user.get_bodypart(BODY_ZONE_HEAD))
return FALSE
if(user.is_mouth_covered(ITEM_SLOT_MASK))
to_chat(user, span_warning("You can't bite with your mouth covered!"))
return FALSE
if(check_block(user, 1, "[user]'s bite", UNARMED_ATTACK, 0, BRUTE))
return FALSE
user.do_attack_animation(src, ATTACK_EFFECT_BITE)
if (HAS_TRAIT(user, TRAIT_PERFECT_ATTACKER) || prob(75))
log_combat(user, src, "attacked")
playsound(loc, 'sound/items/weapons/bite.ogg', 50, TRUE, -1)
visible_message(span_danger("[user.name] bites [src]!"), \
span_userdanger("[user.name] bites you!"), span_hear("You hear a chomp!"), COMBAT_MESSAGE_RANGE, user)
to_chat(user, span_danger("You bite [src]!"))
return TRUE
else
visible_message(span_danger("[user.name]'s bite misses [src]!"), \
span_danger("You avoid [user.name]'s bite!"), span_hear("You hear the sound of jaws snapping shut!"), COMBAT_MESSAGE_RANGE, user)
to_chat(user, span_warning("Your bite misses [src]!"))
return FALSE
/mob/living/attack_larva(mob/living/carbon/alien/larva/L, list/modifiers)
if(L.combat_mode)
if(HAS_TRAIT(L, TRAIT_PACIFISM))
to_chat(L, span_warning("You don't want to hurt anyone!"))
return FALSE
if(check_block(L, 1, "[L]'s bite", UNARMED_ATTACK, 0, BRUTE))
return FALSE
L.do_attack_animation(src)
if(prob(90))
log_combat(L, src, "attacked")
visible_message(span_danger("[L.name] bites [src]!"), \
span_userdanger("[L.name] bites you!"), span_hear("You hear a chomp!"), COMBAT_MESSAGE_RANGE, L)
to_chat(L, span_danger("You bite [src]!"))
playsound(loc, 'sound/items/weapons/bite.ogg', 50, TRUE, -1)
return TRUE
else
visible_message(span_danger("[L.name]'s bite misses [src]!"), \
span_danger("You avoid [L.name]'s bite!"), span_hear("You hear the sound of jaws snapping shut!"), COMBAT_MESSAGE_RANGE, L)
to_chat(L, span_warning("Your bite misses [src]!"))
return FALSE
visible_message(span_notice("[L.name] rubs its head against [src]."), \
span_notice("[L.name] rubs its head against you."), null, null, L)
to_chat(L, span_notice("You rub your head against [src]."))
return FALSE
/mob/living/attack_alien(mob/living/carbon/alien/adult/user, list/modifiers)
SEND_SIGNAL(src, COMSIG_MOB_ATTACK_ALIEN, user, modifiers)
if(LAZYACCESS(modifiers, RIGHT_CLICK))
if(check_block(user, 0, "[user]'s tackle", UNARMED_ATTACK, 0, BRUTE))
return FALSE
user.do_attack_animation(src, ATTACK_EFFECT_DISARM)
return TRUE
if(user.combat_mode)
if(HAS_TRAIT(user, TRAIT_PACIFISM))
to_chat(user, span_warning("You don't want to hurt anyone!"))
return FALSE
if(check_block(user, user.melee_damage_upper, "[user]'s slash", UNARMED_ATTACK, 0, BRUTE))
return FALSE
user.do_attack_animation(src)
return TRUE
visible_message(span_notice("[user] caresses [src] with its scythe-like arm."), \
span_notice("[user] caresses you with its scythe-like arm."), null, null, user)
to_chat(user, span_notice("You caress [src] with your scythe-like arm."))
return FALSE
/mob/living/attack_hulk(mob/living/carbon/human/user)
..()
if(HAS_TRAIT(user, TRAIT_PACIFISM))
to_chat(user, span_warning("You don't want to hurt [src]!"))
return FALSE
return TRUE
/mob/living/ex_act(severity, target, origin)
if(origin && istype(origin, /datum/spacevine_mutation) && isvineimmune(src))
return FALSE
return ..()
/mob/living/acid_act(acidpwr, acid_volume)
take_bodypart_damage(acidpwr * min(1, acid_volume * 0.1))
return TRUE
///As the name suggests, this should be called to apply electric shocks.
/mob/living/proc/electrocute_act(shock_damage, source, siemens_coeff = 1, flags = NONE)
if(SEND_SIGNAL(src, COMSIG_LIVING_ELECTROCUTE_ACT, shock_damage, source, siemens_coeff, flags) & COMPONENT_LIVING_BLOCK_SHOCK)
return FALSE
shock_damage *= siemens_coeff
if((flags & SHOCK_TESLA) && HAS_TRAIT(src, TRAIT_TESLA_SHOCKIMMUNE))
return FALSE
if(HAS_TRAIT(src, TRAIT_SHOCKIMMUNE))
return FALSE
if(shock_damage < 1)
return FALSE
if(!(flags & SHOCK_ILLUSION))
adjustFireLoss(shock_damage)
if(getFireLoss() > 100)
add_shared_particles(/particles/smoke/burning)
addtimer(CALLBACK(src, TYPE_PROC_REF(/atom/movable, remove_shared_particles), /particles/smoke/burning), 10 SECONDS)
else
adjustStaminaLoss(shock_damage)
if(!(flags & SHOCK_SUPPRESS_MESSAGE))
visible_message(
span_danger("[src] was shocked by \the [source]!"), \
span_userdanger("You feel a powerful shock coursing through your body!"), \
span_hear("You hear a heavy electrical crack.") \
)
return shock_damage
/mob/living/emp_act(severity)
. = ..()
if(. & EMP_PROTECT_CONTENTS)
return
for(var/obj/inside in contents)
inside.emp_act(severity)
///Logs, gibs and returns point values of whatever mob is unfortunate enough to get eaten.
/mob/living/singularity_act()
investigate_log("has been consumed by the singularity.", INVESTIGATE_ENGINE) //Oh that's where the clown ended up!
investigate_log("has been gibbed by the singularity.", INVESTIGATE_DEATHS)
gib()
return 20
/mob/living/narsie_act()
if(HAS_TRAIT(src, TRAIT_GODMODE) || QDELETED(src))
return
if(GLOB.cult_narsie && GLOB.cult_narsie.souls_needed[src])
GLOB.cult_narsie.souls_needed -= src
GLOB.cult_narsie.souls += 1
if((GLOB.cult_narsie.souls == GLOB.cult_narsie.soul_goal) && (GLOB.cult_narsie.resolved == FALSE))
GLOB.cult_narsie.resolved = TRUE
sound_to_playing_players('sound/announcer/alarm/nuke_alarm.ogg', 70)
addtimer(CALLBACK(GLOBAL_PROC, GLOBAL_PROC_REF(cult_ending_helper), CULT_VICTORY_MASS_CONVERSION), 12 SECONDS)
addtimer(CALLBACK(GLOBAL_PROC, GLOBAL_PROC_REF(ending_helper)), 27 SECONDS)
if(client)
make_new_construct(/mob/living/basic/construct/harvester, src, cultoverride = TRUE)
else
switch(rand(1, 4))
if(1)
new /mob/living/basic/construct/juggernaut/hostile(get_turf(src))
if(2)
new /mob/living/basic/construct/wraith/hostile(get_turf(src))
if(3)
new /mob/living/basic/construct/artificer/hostile(get_turf(src))
if(4)
new /mob/living/basic/construct/proteon/hostile(get_turf(src))
spawn_dust()
investigate_log("has been gibbed by Nar'Sie.", INVESTIGATE_DEATHS)
gib()
return TRUE
//called when the mob receives a bright flash
/mob/living/proc/flash_act(intensity = 1, override_blindness_check = 0, affect_silicon = 0, visual = 0, type = /atom/movable/screen/fullscreen/flash, length = 2.5 SECONDS)
if(HAS_TRAIT(src, TRAIT_NOFLASH))
return FALSE
if(get_eye_protection() >= intensity)
return FALSE
if(is_blind() && !(override_blindness_check || affect_silicon))
return FALSE
// this forces any kind of flash (namely normal and static) to use a black screen for photosensitive players
// it absolutely isn't an ideal solution since sudden flashes to black can apparently still trigger epilepsy, but byond apparently doesn't let you freeze screens
// and this is apparently at least less likely to trigger issues than a full white/static flash
if(client?.prefs?.read_preference(/datum/preference/toggle/darkened_flash))
type = /atom/movable/screen/fullscreen/flash/black
overlay_fullscreen("flash", type)
addtimer(CALLBACK(src, PROC_REF(clear_fullscreen), "flash", length), length)
SEND_SIGNAL(src, COMSIG_MOB_FLASHED, intensity, override_blindness_check, affect_silicon, visual, type, length)
return TRUE
//called when the mob receives a loud bang
/mob/living/proc/soundbang_act()
return FALSE
//to damage the clothes worn by a mob
/mob/living/proc/damage_clothes(damage_amount, damage_type = BRUTE, damage_flag = 0, def_zone)
return
/mob/living/do_attack_animation(atom/A, visual_effect_icon, obj/item/used_item, no_effect)
if(!used_item)
used_item = get_active_held_item()
..()
/**
* Does a slap animation on an atom
*
* Uses do_attack_animation to animate the attacker attacking
* then draws a hand moving across the top half of the target(where a mobs head would usually be) to look like a slap
* Arguments:
* * atom/A - atom being slapped
*/
/mob/living/proc/do_slap_animation(atom/slapped)
do_attack_animation(slapped, no_effect=TRUE)
var/mutable_appearance/glove_appearance = mutable_appearance('icons/effects/effects.dmi', "slapglove")
glove_appearance.pixel_z = 10 // should line up with head
glove_appearance.pixel_w = 10
var/atom/movable/flick_visual/glove = slapped.flick_overlay_view(glove_appearance, 1 SECONDS)
// And animate the attack!
animate(glove, alpha = 175, transform = matrix() * 0.75, pixel_x = 0, pixel_y = 10, pixel_z = 0, time = 3)
animate(time = 1)
animate(alpha = 0, time = 3, easing = CIRCULAR_EASING|EASE_OUT)
/** Handles exposing a mob to reagents.
*
* If the methods include INGEST or INHALE, the mob tastes the reagents.
* If the methods include VAPOR or TOUCH it incorporates permiability protection.
*/
/mob/living/expose_reagents(list/reagents, datum/reagents/source, methods=TOUCH, volume_modifier=1, show_message=TRUE)
. = ..()
if(. & COMPONENT_NO_EXPOSE_REAGENTS)
return
if(show_message && (methods & (INGEST | INHALE)))
taste_list(reagents)
var/touch_protection = (methods & (VAPOR | TOUCH)) ? getarmor(null, BIO) * 0.01 : 0
SEND_SIGNAL(source, COMSIG_REAGENTS_EXPOSE_MOB, src, reagents, methods, volume_modifier, show_message, touch_protection)
for(var/datum/reagent/reagent as anything in reagents)
var/reac_volume = reagents[reagent]
. |= reagent.expose_mob(src, methods, reac_volume, show_message, touch_protection)
/// Simplified ricochet angle calculation for mobs (also the base version doesn't work on mobs)
/mob/living/handle_ricochet(obj/projectile/ricocheting_projectile)
var/face_angle = get_angle_raw(ricocheting_projectile.x, ricocheting_projectile.pixel_x, ricocheting_projectile.pixel_y, ricocheting_projectile.p_y, x, y, pixel_x, pixel_y)
var/new_angle_s = SIMPLIFY_DEGREES(face_angle + GET_ANGLE_OF_INCIDENCE(face_angle, (ricocheting_projectile.angle + 180)))
ricocheting_projectile.set_angle(new_angle_s)
return TRUE
/**
* Attempt to disarm the target mob. Some items might let you do it, also carbon can do it with right click.
* Will shove the target mob back, and drop them if they're in front of something dense
* or another carbon.
*/
/mob/living/proc/disarm(mob/living/target, obj/item/weapon)
if(!can_disarm(target))
return
var/shove_flags = target.get_shove_flags(src, weapon)
if(weapon)
do_attack_animation(target, used_item = weapon)
playsound(target, 'sound/effects/glass/glassbash.ogg', 50, TRUE, -1)
else
do_attack_animation(target, ATTACK_EFFECT_DISARM)
playsound(target, 'sound/items/weapons/shove.ogg', 50, TRUE, -1)
if (ishuman(target) && isnull(weapon))
var/mob/living/carbon/human/human_target = target
human_target.w_uniform?.add_fingerprint(src)
SEND_SIGNAL(target, COMSIG_LIVING_DISARM_HIT, src, zone_selected, weapon)
var/shove_dir = get_dir(loc, target.loc)
var/turf/target_shove_turf = get_step(target.loc, shove_dir)
var/turf/target_old_turf = target.loc
//Are we hitting anything? or
if(shove_flags & SHOVE_CAN_MOVE)
if(SEND_SIGNAL(target_shove_turf, COMSIG_LIVING_DISARM_PRESHOVE, src, target, weapon) & COMSIG_LIVING_ACT_SOLID)
shove_flags |= SHOVE_BLOCKED
else
target.Move(target_shove_turf, shove_dir)
if(get_turf(target) == target_old_turf)
shove_flags |= SHOVE_BLOCKED
if(!(shove_flags & SHOVE_BLOCKED))
target.setGrabState(GRAB_PASSIVE)
//Directional checks to make sure that we're not shoving through a windoor or something like that
if((shove_flags & SHOVE_BLOCKED) && (shove_dir in GLOB.cardinals))
var/target_turf = get_turf(target)
for(var/obj/obj_content in target_turf)
if(obj_content.flags_1 & ON_BORDER_1 && obj_content.dir == shove_dir && obj_content.density)
shove_flags |= SHOVE_DIRECTIONAL_BLOCKED
break
if(target_turf != target_shove_turf && !(shove_flags && SHOVE_DIRECTIONAL_BLOCKED)) //Make sure that we don't run the exact same check twice on the same tile
for(var/obj/obj_content in target_shove_turf)
if(obj_content.flags_1 & ON_BORDER_1 && obj_content.dir == REVERSE_DIR(shove_dir) && obj_content.density)
shove_flags |= SHOVE_DIRECTIONAL_BLOCKED
break
if(shove_flags & SHOVE_CAN_HIT_SOMETHING)
//Don't hit people through windows, ok?
if(!(shove_flags & SHOVE_DIRECTIONAL_BLOCKED) && (SEND_SIGNAL(target_shove_turf, COMSIG_LIVING_DISARM_COLLIDE, src, target, shove_flags, weapon) & COMSIG_LIVING_SHOVE_HANDLED))
return
if((shove_flags & SHOVE_BLOCKED) && !(shove_flags & (SHOVE_KNOCKDOWN_BLOCKED|SHOVE_CAN_KICK_SIDE)))
target.Knockdown(SHOVE_KNOCKDOWN_SOLID, daze_amount = 3 SECONDS)
target.visible_message(span_danger("[name] shoves [target.name], knocking [target.p_them()] down!"),
span_userdanger("You're knocked down from a shove by [name]!"), span_hear("You hear aggressive shuffling followed by a loud thud!"), COMBAT_MESSAGE_RANGE, src)
to_chat(src, span_danger("You shove [target.name], knocking [target.p_them()] down!"))
log_combat(src, target, "shoved", "knocking them down[weapon ? " with [weapon]" : ""]")
return
if(shove_flags & SHOVE_CAN_KICK_SIDE) //KICK HIM IN THE NUTS
target.Paralyze(SHOVE_CHAIN_PARALYZE)
target.apply_status_effect(/datum/status_effect/no_side_kick)
target.visible_message(span_danger("[name] kicks [target.name] onto [target.p_their()] side!"),
span_userdanger("You're kicked onto your side by [name]!"), span_hear("You hear aggressive shuffling followed by a loud thud!"), COMBAT_MESSAGE_RANGE, src)
to_chat(src, span_danger("You kick [target.name] onto [target.p_their()] side!"))
addtimer(CALLBACK(target, TYPE_PROC_REF(/mob/living, SetKnockdown), 0), SHOVE_CHAIN_PARALYZE)
log_combat(src, target, "kicks", "onto their side (paralyzing)")
return
target.get_shoving_message(src, weapon, shove_flags)
//Take their lunch money
var/target_held_item = target.get_active_held_item()
var/append_message = weapon ? " with [weapon]" : ""
// If it's in our typecache, they're staggered and it exists, disarm. If they're knocked down, disarm too.
if(target_held_item && target.get_timed_status_effect_duration(/datum/status_effect/staggered) && is_type_in_typecache(target_held_item, GLOB.shove_disarming_types) || target_held_item && target.body_position == LYING_DOWN)
target.dropItemToGround(target_held_item)
append_message = "causing [target.p_them()] to drop [target_held_item]"
target.visible_message(span_danger("[target.name] drops \the [target_held_item]!"),
span_warning("You drop \the [target_held_item]!"), null, COMBAT_MESSAGE_RANGE)
if(shove_flags & SHOVE_CAN_STAGGER)
target.adjust_staggered_up_to(STAGGERED_SLOWDOWN_LENGTH, 10 SECONDS)
log_combat(src, target, "shoved", append_message)
///Check if the universal conditions for disarming/shoving are met.
/mob/living/proc/can_disarm(mob/living/target)
if(body_position != STANDING_UP || src == target || loc == target.loc)
return FALSE
return TRUE
///Check if there's anything that could stop the knockdown from being shoved into something or someone.
/mob/living/proc/get_shove_flags(mob/living/shover, obj/item/weapon)
if(shover.move_force >= move_resist)
. |= SHOVE_CAN_MOVE
if(!buckled)
. |= SHOVE_CAN_HIT_SOMETHING
if(HAS_TRAIT(src, TRAIT_BRAWLING_KNOCKDOWN_BLOCKED))
. |= SHOVE_KNOCKDOWN_BLOCKED
///Send the chat feedback message for shoving
/mob/living/proc/get_shoving_message(mob/living/shover, obj/item/weapon, shove_flags)
visible_message(span_danger("[shover] shoves [name][weapon ? " with [weapon]" : ""]!"),
span_userdanger("You're shoved by [shover][weapon ? " with [weapon]" : ""]!"), span_hear("You hear aggressive shuffling!"), COMBAT_MESSAGE_RANGE, shover)
to_chat(shover, span_danger("You shove [name][weapon ? " with [weapon]" : ""]!"))
/mob/living/proc/check_block(atom/hit_by, damage, attack_text = "the attack", attack_type = MELEE_ATTACK, armour_penetration = 0, damage_type = BRUTE)
if(SEND_SIGNAL(src, COMSIG_LIVING_CHECK_BLOCK, hit_by, damage, attack_text, attack_type, armour_penetration, damage_type) & SUCCESSFUL_BLOCK)
return SUCCESSFUL_BLOCK
return FAILED_BLOCK
| 0 | 0.989519 | 1 | 0.989519 | game-dev | MEDIA | 0.997808 | game-dev | 0.934959 | 1 | 0.934959 |
baileyholl/Ars-Nouveau | 5,438 | src/main/java/com/hollingsworth/arsnouveau/common/datagen/EnchantmentProvider.java | package com.hollingsworth.arsnouveau.common.datagen;
import com.hollingsworth.arsnouveau.ArsNouveau;
import com.hollingsworth.arsnouveau.api.perk.PerkAttributes;
import com.hollingsworth.arsnouveau.setup.registry.EnchantmentRegistry;
import net.minecraft.core.HolderGetter;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.RegistryAccess;
import net.minecraft.core.RegistrySetBuilder;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.core.registries.Registries;
import net.minecraft.data.PackOutput;
import net.minecraft.data.worldgen.BootstrapContext;
import net.minecraft.resources.ResourceKey;
import net.minecraft.tags.EnchantmentTags;
import net.minecraft.tags.ItemTags;
import net.minecraft.world.entity.EquipmentSlotGroup;
import net.minecraft.world.entity.ai.attributes.AttributeModifier;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.enchantment.Enchantment;
import net.minecraft.world.item.enchantment.EnchantmentEffectComponents;
import net.minecraft.world.item.enchantment.LevelBasedValue;
import net.minecraft.world.item.enchantment.effects.EnchantmentAttributeEffect;
import net.neoforged.neoforge.common.data.DatapackBuiltinEntriesProvider;
import net.neoforged.neoforge.common.data.ExistingFileHelper;
import net.neoforged.neoforge.registries.holdersets.AnyHolderSet;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
public class EnchantmentProvider extends DatapackBuiltinEntriesProvider {
private static final RegistrySetBuilder BUILDER = new RegistrySetBuilder()
.add(Registries.ENCHANTMENT, EnchantmentProvider::bootstrap);
public static void bootstrap(BootstrapContext<Enchantment> ctx) {
HolderGetter<Item> holdergetter2 = ctx.lookup(Registries.ITEM);
register(ctx, EnchantmentRegistry.MANA_BOOST_ENCHANTMENT, Enchantment.enchantment(Enchantment.definition(
holdergetter2.getOrThrow(ItemTags.ARMOR_ENCHANTABLE),
5,
3,
Enchantment.dynamicCost(1, 11),
Enchantment.dynamicCost(12, 11),
1,
EquipmentSlotGroup.ARMOR
)).withEffect(EnchantmentEffectComponents.ATTRIBUTES,
new EnchantmentAttributeEffect(
ArsNouveau.prefix("enchantment.max_mana"),
PerkAttributes.MAX_MANA,
LevelBasedValue.perLevel(25F),
AttributeModifier.Operation.ADD_VALUE
)));
register(ctx, EnchantmentRegistry.MANA_REGEN_ENCHANTMENT, Enchantment.enchantment(Enchantment.definition(
holdergetter2.getOrThrow(ItemTags.ARMOR_ENCHANTABLE),
5,
3,
Enchantment.dynamicCost(1, 11),
Enchantment.dynamicCost(12, 11),
1,
EquipmentSlotGroup.ARMOR
)).withEffect(EnchantmentEffectComponents.ATTRIBUTES,
new EnchantmentAttributeEffect(
ArsNouveau.prefix("enchantment.mana_regen"),
PerkAttributes.MANA_REGEN_BONUS,
LevelBasedValue.perLevel(2.0F),
AttributeModifier.Operation.ADD_VALUE
)));
register(ctx, EnchantmentRegistry.REACTIVE_ENCHANTMENT, Enchantment.enchantment(Enchantment.definition(
new AnyHolderSet<>(BuiltInRegistries.ITEM.asLookup()),
1,
4,
Enchantment.dynamicCost(1, 11),
Enchantment.dynamicCost(12, 11),
1,
EquipmentSlotGroup.ANY
)));
}
protected static void register(BootstrapContext<Enchantment> ctx, ResourceKey<Enchantment> enchantment, Enchantment.Builder builder) {
ctx.register(enchantment, builder.build(enchantment.location()));
}
public EnchantmentProvider(PackOutput output, CompletableFuture<HolderLookup.Provider> registries) {
super(output, registries, BUILDER, Set.of(ArsNouveau.MODID));
}
@Override
@NotNull
public String getName() {
return "Ars Nouveau's Enchantment Data";
}
public static HolderLookup.Provider createLookup() {
RegistryAccess.Frozen frozen = RegistryAccess.fromRegistryOfRegistries(BuiltInRegistries.REGISTRY);
return BUILDER.build(frozen);
}
public static class EnchantmentTagsProvider extends net.minecraft.data.tags.EnchantmentTagsProvider {
public EnchantmentTagsProvider(PackOutput pPackOutput, CompletableFuture<HolderLookup.Provider> provider, @Nullable ExistingFileHelper existingFileHelper) {
super(pPackOutput, provider, ArsNouveau.MODID, existingFileHelper);
}
@Override
protected void addTags(HolderLookup.@NotNull Provider pProvider) {
this.tag(EnchantmentTags.NON_TREASURE).addOptional(
EnchantmentRegistry.MANA_BOOST_ENCHANTMENT.location())
.addOptional(EnchantmentRegistry.MANA_REGEN_ENCHANTMENT.location());
this.tag(EnchantmentTags.TRADEABLE).addOptional(
EnchantmentRegistry.MANA_BOOST_ENCHANTMENT.location()).addOptional(
EnchantmentRegistry.MANA_REGEN_ENCHANTMENT.location());
}
}
}
| 0 | 0.831501 | 1 | 0.831501 | game-dev | MEDIA | 0.97964 | game-dev | 0.761873 | 1 | 0.761873 |
KittyPBoxx/pokeemerald-net-demo | 22,407 | pokeemerald/src/battle_anim_ground.c | #include "global.h"
#include "battle_anim.h"
#include "random.h"
#include "scanline_effect.h"
#include "task.h"
#include "trig.h"
#include "constants/rgb.h"
static void AnimBonemerangProjectile(struct Sprite *);
static void AnimBoneHitProjectile(struct Sprite *);
static void AnimDirtScatter(struct Sprite *);
static void AnimMudSportDirt(struct Sprite *);
static void AnimDirtPlumeParticle(struct Sprite *);
static void AnimDirtPlumeParticle_Step(struct Sprite *);
static void AnimDigDirtMound(struct Sprite *);
static void AnimBonemerangProjectile_Step(struct Sprite *);
static void AnimBonemerangProjectile_End(struct Sprite *);
static void AnimMudSportDirtRising(struct Sprite *);
static void AnimMudSportDirtFalling(struct Sprite *);
static void AnimTask_DigBounceMovement(u8);
static void AnimTask_DigEndBounceMovementSetInvisible(u8);
static void AnimTask_DigSetVisibleUnderground(u8);
static void AnimTask_DigRiseUpFromHole(u8);
static void SetDigScanlineEffect(u8, s16, s16);
static void AnimTask_ShakeTerrain(u8);
static void AnimTask_ShakeBattlers(u8);
static void SetBattlersXOffsetForShake(struct Task *);
static void WaitForFissureCompletion(u8);
static const union AffineAnimCmd sAffineAnim_Bonemerang[] =
{
AFFINEANIMCMD_FRAME(0x0, 0x0, 15, 1),
AFFINEANIMCMD_JUMP(0),
};
static const union AffineAnimCmd sAffineAnim_SpinningBone[] =
{
AFFINEANIMCMD_FRAME(0x0, 0x0, 20, 1),
AFFINEANIMCMD_JUMP(0),
};
static const union AffineAnimCmd *const sAffineAnims_Bonemerang[] =
{
sAffineAnim_Bonemerang,
};
static const union AffineAnimCmd *const sAffineAnims_SpinningBone[] =
{
sAffineAnim_SpinningBone,
};
const struct SpriteTemplate gBonemerangSpriteTemplate =
{
.tileTag = ANIM_TAG_BONE,
.paletteTag = ANIM_TAG_BONE,
.oam = &gOamData_AffineNormal_ObjNormal_32x32,
.anims = gDummySpriteAnimTable,
.images = NULL,
.affineAnims = sAffineAnims_Bonemerang,
.callback = AnimBonemerangProjectile,
};
const struct SpriteTemplate gSpinningBoneSpriteTemplate =
{
.tileTag = ANIM_TAG_BONE,
.paletteTag = ANIM_TAG_BONE,
.oam = &gOamData_AffineNormal_ObjNormal_32x32,
.anims = gDummySpriteAnimTable,
.images = NULL,
.affineAnims = sAffineAnims_SpinningBone,
.callback = AnimBoneHitProjectile,
};
const struct SpriteTemplate gSandAttackDirtSpriteTemplate =
{
.tileTag = ANIM_TAG_MUD_SAND,
.paletteTag = ANIM_TAG_MUD_SAND,
.oam = &gOamData_AffineOff_ObjNormal_8x8,
.anims = gDummySpriteAnimTable,
.images = NULL,
.affineAnims = gDummySpriteAffineAnimTable,
.callback = AnimDirtScatter,
};
static const union AnimCmd sAnim_MudSlapMud[] =
{
ANIMCMD_FRAME(1, 1),
ANIMCMD_END,
};
static const union AnimCmd *const sAnims_MudSlapMud[] =
{
sAnim_MudSlapMud,
};
const struct SpriteTemplate gMudSlapMudSpriteTemplate =
{
.tileTag = ANIM_TAG_MUD_SAND,
.paletteTag = ANIM_TAG_MUD_SAND,
.oam = &gOamData_AffineOff_ObjNormal_16x16,
.anims = sAnims_MudSlapMud,
.images = NULL,
.affineAnims = gDummySpriteAffineAnimTable,
.callback = AnimDirtScatter,
};
const struct SpriteTemplate gMudsportMudSpriteTemplate =
{
.tileTag = ANIM_TAG_MUD_SAND,
.paletteTag = ANIM_TAG_MUD_SAND,
.oam = &gOamData_AffineOff_ObjNormal_16x16,
.anims = gDummySpriteAnimTable,
.images = NULL,
.affineAnims = gDummySpriteAffineAnimTable,
.callback = AnimMudSportDirt,
};
const struct SpriteTemplate gDirtPlumeSpriteTemplate =
{
.tileTag = ANIM_TAG_MUD_SAND,
.paletteTag = ANIM_TAG_MUD_SAND,
.oam = &gOamData_AffineOff_ObjNormal_8x8,
.anims = gDummySpriteAnimTable,
.images = NULL,
.affineAnims = gDummySpriteAffineAnimTable,
.callback = AnimDirtPlumeParticle,
};
const struct SpriteTemplate gDirtMoundSpriteTemplate =
{
.tileTag = ANIM_TAG_DIRT_MOUND,
.paletteTag = ANIM_TAG_DIRT_MOUND,
.oam = &gOamData_AffineOff_ObjNormal_32x16,
.anims = gDummySpriteAnimTable,
.images = NULL,
.affineAnims = gDummySpriteAffineAnimTable,
.callback = AnimDigDirtMound,
};
// Moves a bone projectile towards the target mon, which moves like
// a boomerang. After hitting the target mon, it comes back to the user.
static void AnimBonemerangProjectile(struct Sprite *sprite)
{
sprite->x = GetBattlerSpriteCoord(gBattleAnimAttacker, BATTLER_COORD_X_2);
sprite->y = GetBattlerSpriteCoord(gBattleAnimAttacker, BATTLER_COORD_Y_PIC_OFFSET);
sprite->data[0] = 20;
sprite->data[2] = GetBattlerSpriteCoord(gBattleAnimTarget, BATTLER_COORD_X_2);
sprite->data[4] = GetBattlerSpriteCoord(gBattleAnimTarget, BATTLER_COORD_Y_PIC_OFFSET);
sprite->data[5] = -40;
InitAnimArcTranslation(sprite);
sprite->callback = AnimBonemerangProjectile_Step;
}
static void AnimBonemerangProjectile_Step(struct Sprite *sprite)
{
if (TranslateAnimHorizontalArc(sprite))
{
sprite->x += sprite->x2;
sprite->y += sprite->y2;
sprite->y2 = 0;
sprite->x2 = 0;
sprite->data[0] = 20;
sprite->data[2] = GetBattlerSpriteCoord(gBattleAnimAttacker, BATTLER_COORD_X_2);
sprite->data[4] = GetBattlerSpriteCoord(gBattleAnimAttacker, BATTLER_COORD_Y_PIC_OFFSET);
sprite->data[5] = 40;
InitAnimArcTranslation(sprite);
sprite->callback = AnimBonemerangProjectile_End;
}
}
static void AnimBonemerangProjectile_End(struct Sprite *sprite)
{
if (TranslateAnimHorizontalArc(sprite))
DestroyAnimSprite(sprite);
}
// Moves a bone projectile towards the target mon, starting right next to
// the target mon.
// arg 0: initial x pixel offset
// arg 1: initial y pixel offset
// arg 2: target x pixel offset
// arg 3: target y pixel offset
// arg 4: duration
static void AnimBoneHitProjectile(struct Sprite *sprite)
{
InitSpritePosToAnimTarget(sprite, TRUE);
if (GetBattlerSide(gBattleAnimAttacker) != B_SIDE_PLAYER)
gBattleAnimArgs[2] = -gBattleAnimArgs[2];
sprite->data[0] = gBattleAnimArgs[4];
sprite->data[2] = GetBattlerSpriteCoord(gBattleAnimTarget, BATTLER_COORD_X_2) + gBattleAnimArgs[2];
sprite->data[4] = GetBattlerSpriteCoord(gBattleAnimTarget, BATTLER_COORD_Y_PIC_OFFSET) + gBattleAnimArgs[3];
sprite->callback = StartAnimLinearTranslation;
StoreSpriteCallbackInData6(sprite, DestroyAnimSprite);
}
// Moves a small dirt projectile towards the target mon.
// arg 0: initial x pixel offset
// arg 1: initial y pixel offset
// arg 2: duration
// arg 3: target x pixel offset
// arg 4: target y pixel offset
static void AnimDirtScatter(struct Sprite *sprite)
{
u8 targetXPos, targetYPos;
s16 xOffset, yOffset;
InitSpritePosToAnimAttacker(sprite, TRUE);
targetXPos = GetBattlerSpriteCoord2(gBattleAnimTarget, BATTLER_COORD_X_2);
targetYPos = GetBattlerSpriteCoord2(gBattleAnimTarget, BATTLER_COORD_Y_PIC_OFFSET);
xOffset = Random2() & 0x1F;
yOffset = Random2() & 0x1F;
if (xOffset > 16)
xOffset = 16 - xOffset;
if (yOffset > 16)
yOffset = 16 - yOffset;
sprite->data[0] = gBattleAnimArgs[2];
sprite->data[2] = targetXPos + xOffset;
sprite->data[4] = targetYPos + yOffset;
sprite->callback = StartAnimLinearTranslation;
StoreSpriteCallbackInData6(sprite, DestroySpriteAndMatrix);
}
// Moves a particle of dirt in the Mud Sport animation.
// The dirt can either be rising upward, or falling down.
// arg 0: 0 = dirt is rising into the air, 1 = dirt is falling down
// arg 1: initial x pixel offset
// arg 2: initial y pixel offset
static void AnimMudSportDirt(struct Sprite *sprite)
{
sprite->oam.tileNum++;
if (gBattleAnimArgs[0] == 0)
{
sprite->x = GetBattlerSpriteCoord(gBattleAnimAttacker, BATTLER_COORD_X_2) + gBattleAnimArgs[1];
sprite->y = GetBattlerSpriteCoord(gBattleAnimAttacker, BATTLER_COORD_Y_PIC_OFFSET) + gBattleAnimArgs[2];
sprite->data[0] = gBattleAnimArgs[1] > 0 ? 1 : -1;
sprite->callback = AnimMudSportDirtRising;
}
else
{
sprite->x = gBattleAnimArgs[1];
sprite->y = gBattleAnimArgs[2];
sprite->y2 = -gBattleAnimArgs[2];
sprite->callback = AnimMudSportDirtFalling;
}
}
static void AnimMudSportDirtRising(struct Sprite *sprite)
{
if (++sprite->data[1] > 1)
{
sprite->data[1] = 0;
sprite->x += sprite->data[0];
}
sprite->y -= 4;
if (sprite->y < -4)
DestroyAnimSprite(sprite);
}
static void AnimMudSportDirtFalling(struct Sprite *sprite)
{
switch (sprite->data[0])
{
case 0:
sprite->y2 += 4;
if (sprite->y2 >= 0)
{
sprite->y2 = 0;
sprite->data[0]++;
}
break;
case 1:
if (++sprite->data[1] > 0)
{
sprite->data[1] = 0;
sprite->invisible ^= 1;
if (++sprite->data[2] == 10)
DestroyAnimSprite(sprite);
}
break;
}
}
void AnimTask_DigDownMovement(u8 taskId)
{
struct Task *task = &gTasks[taskId];
if (gBattleAnimArgs[0] == FALSE)
task->func = AnimTask_DigBounceMovement;
else
task->func = AnimTask_DigEndBounceMovementSetInvisible;
task->func(taskId);
}
static void AnimTask_DigBounceMovement(u8 taskId)
{
u8 y;
struct Task *task = &gTasks[taskId];
switch (task->data[0])
{
case 0:
task->data[10] = GetAnimBattlerSpriteId(ANIM_ATTACKER);
task->data[11] = GetBattlerSpriteBGPriorityRank(gBattleAnimAttacker);
if (task->data[11] == 1)
{
task->data[12] = gBattle_BG1_X;
task->data[13] = gBattle_BG1_Y;
}
else
{
task->data[12] = gBattle_BG2_X;
task->data[13] = gBattle_BG2_Y;
}
y = GetBattlerYCoordWithElevation(gBattleAnimAttacker);
task->data[14] = y - 32;
task->data[15] = y + 32;
if (task->data[14] < 0)
task->data[14] = 0;
gSprites[task->data[10]].invisible = TRUE;
task->data[0]++;
break;
case 1:
SetDigScanlineEffect(task->data[11], task->data[14], task->data[15]);
task->data[0]++;
break;
case 2:
task->data[2] = (task->data[2] + 6) & 0x7F;
if (++task->data[4] > 2)
{
task->data[4] = 0;
task->data[3]++;
}
task->data[5] = task->data[3] + (gSineTable[task->data[2]] >> 4);
if (task->data[11] == 1)
gBattle_BG1_Y = task->data[13] - task->data[5];
else
gBattle_BG2_Y = task->data[13] - task->data[5];
if (task->data[5] > 63)
{
task->data[5] = 120 - task->data[14];
if (task->data[11] == 1)
gBattle_BG1_Y = task->data[13] - task->data[5];
else
gBattle_BG2_Y = task->data[13] - task->data[5];
gSprites[task->data[10]].x2 = DISPLAY_WIDTH + 32 - gSprites[task->data[10]].x;
task->data[0]++;
}
break;
case 3:
gScanlineEffect.state = 3;
task->data[0]++;
break;
case 4:
DestroyAnimVisualTask(taskId);
gSprites[task->data[10]].invisible = TRUE;
break;
}
}
static void AnimTask_DigEndBounceMovementSetInvisible(u8 taskId)
{
u8 spriteId = GetAnimBattlerSpriteId(ANIM_ATTACKER);
gSprites[spriteId].invisible = TRUE;
gSprites[spriteId].x2 = 0;
gSprites[spriteId].y2 = 0;
if (GetBattlerSpriteBGPriorityRank(gBattleAnimAttacker) == 1)
gBattle_BG1_Y = 0;
else
gBattle_BG2_Y = 0;
DestroyAnimVisualTask(taskId);
}
void AnimTask_DigUpMovement(u8 taskId)
{
struct Task *task = &gTasks[taskId];
if (gBattleAnimArgs[0] == FALSE)
task->func = AnimTask_DigSetVisibleUnderground;
else
task->func = AnimTask_DigRiseUpFromHole;
task->func(taskId);
}
static void AnimTask_DigSetVisibleUnderground(u8 taskId)
{
struct Task *task = &gTasks[taskId];
switch (task->data[0])
{
case 0:
task->data[10] = GetAnimBattlerSpriteId(ANIM_ATTACKER);
gSprites[task->data[10]].invisible = FALSE;
gSprites[task->data[10]].x2 = 0;
gSprites[task->data[10]].y2 = DISPLAY_HEIGHT - gSprites[task->data[10]].y;
task->data[0]++;
break;
case 1:
DestroyAnimVisualTask(taskId);
}
}
static void AnimTask_DigRiseUpFromHole(u8 taskId)
{
u8 var0;
struct Task *task = &gTasks[taskId];
switch (task->data[0])
{
case 0:
task->data[10] = GetAnimBattlerSpriteId(ANIM_ATTACKER);
task->data[11] = GetBattlerSpriteBGPriorityRank(gBattleAnimAttacker);
if (task->data[11] == 1)
task->data[12] = gBattle_BG1_X;
else
task->data[12] = gBattle_BG2_X;
var0 = GetBattlerYCoordWithElevation(gBattleAnimAttacker);
task->data[14] = var0 - 32;
task->data[15] = var0 + 32;
task->data[0]++;
break;
case 1:
SetDigScanlineEffect(task->data[11], 0, task->data[15]);
task->data[0]++;
break;
case 2:
gSprites[task->data[10]].y2 = 96;
task->data[0]++;
break;
case 3:
gSprites[task->data[10]].y2 -= 8;
if (gSprites[task->data[10]].y2 == 0)
{
gScanlineEffect.state = 3;
task->data[0]++;
}
break;
case 4:
DestroyAnimVisualTask(taskId);
break;
}
}
static void SetDigScanlineEffect(u8 useBG1, s16 y, s16 endY)
{
s16 bgX;
struct ScanlineEffectParams scanlineParams;
if (useBG1 == 1)
{
bgX = gBattle_BG1_X;
scanlineParams.dmaDest = ®_BG1HOFS;
}
else
{
bgX = gBattle_BG2_X;
scanlineParams.dmaDest = ®_BG2HOFS;
}
if (y < 0)
y = 0;
while (y < endY)
{
gScanlineEffectRegBuffers[0][y] = bgX;
gScanlineEffectRegBuffers[1][y] = bgX;
y++;
}
while (y < DISPLAY_HEIGHT)
{
gScanlineEffectRegBuffers[0][y] = bgX + DISPLAY_WIDTH;
gScanlineEffectRegBuffers[1][y] = bgX + DISPLAY_WIDTH;
y++;
}
scanlineParams.dmaControl = SCANLINE_EFFECT_DMACNT_16BIT;
scanlineParams.initState = 1;
scanlineParams.unused9 = 0;
ScanlineEffect_SetParams(scanlineParams);
}
// Moves a particle of dirt in a plume of dirt. Used in Fissure and Dig.
// arg 0: which mon (0 = attacker, 1 = target)
// arg 1: which side of mon (0 = left, 1 = right)
// arg 2: target x offset
// arg 3: target y offset
// arg 4: wave amplitude
// arg 5: duration
void AnimDirtPlumeParticle(struct Sprite *sprite)
{
s8 battler;
s16 xOffset;
if (gBattleAnimArgs[0] == 0)
battler = gBattleAnimAttacker;
else
battler = gBattleAnimTarget;
xOffset = 24;
if (gBattleAnimArgs[1] == 1)
{
xOffset *= -1;
gBattleAnimArgs[2] *= -1;
}
sprite->x = GetBattlerSpriteCoord(battler, BATTLER_COORD_X_2) + xOffset;
sprite->y = GetBattlerYCoordWithElevation(battler) + 30;
sprite->data[0] = gBattleAnimArgs[5];
sprite->data[2] = sprite->x + gBattleAnimArgs[2];
sprite->data[4] = sprite->y + gBattleAnimArgs[3];
sprite->data[5] = gBattleAnimArgs[4];
InitAnimArcTranslation(sprite);
sprite->callback = AnimDirtPlumeParticle_Step;
}
static void AnimDirtPlumeParticle_Step(struct Sprite *sprite)
{
if (TranslateAnimHorizontalArc(sprite))
DestroyAnimSprite(sprite);
}
// Displays the dirt mound seen in the move Dig for set duration.
// The dirt mound image is too large for a single sprite, so two
// sprites are lined up next to each other.
// arg 0: which mon (0 = attacker, 1 = target)
// arg 1: oam tile num (0 = left half of image, 1 = right half of image)
// arg 2: duration
static void AnimDigDirtMound(struct Sprite *sprite)
{
s8 battler;
if (gBattleAnimArgs[0] == 0)
battler = gBattleAnimAttacker;
else
battler = gBattleAnimTarget;
sprite->x = GetBattlerSpriteCoord(battler, BATTLER_COORD_X) - 16 + (gBattleAnimArgs[1] * 32);
sprite->y = GetBattlerYCoordWithElevation(battler) + 32;
sprite->oam.tileNum += gBattleAnimArgs[1] * 8;
StoreSpriteCallbackInData6(sprite, DestroyAnimSprite);
sprite->data[0] = gBattleAnimArgs[2];
sprite->callback = WaitAnimForDuration;
}
#define tState data[0]
#define tDelay data[1]
#define tTimer data[2]
#define tMaxTime data[3]
#define tbattlerSpriteIds(i) data[9 + (i)]
#define tNumBattlers data[13] // AnimTask_ShakeBattlers
#define tInitialX data[13] // AnimTask_ShakeTerrain
#define tHorizOffset data[14]
#define tInitHorizOffset data[15]
// Shakes battler(s) or the battle terrain back and forth horizontally. Used by e.g. Earthquake, Eruption
// arg0: What to shake. 0-3 for any specific battler, MAX_BATTLERS_COUNT for all battlers, MAX_BATTLERS_COUNT + 1 for the terrain
// arg1: Shake intensity, used to calculate horizontal pixel offset (if 0, use move power instead)
// arg2: Length of time to shake for
void AnimTask_HorizontalShake(u8 taskId)
{
u16 i;
struct Task *task = &gTasks[taskId];
if (gBattleAnimArgs[1] != 0)
task->tHorizOffset = task->tInitHorizOffset = gBattleAnimArgs[1] + 3;
else
task->tHorizOffset = task->tInitHorizOffset = (gAnimMovePower / 10) + 3;
task->tMaxTime = gBattleAnimArgs[2];
switch (gBattleAnimArgs[0])
{
case MAX_BATTLERS_COUNT + 1: // Shake terrain
task->tInitialX = gBattle_BG3_X;
task->func = AnimTask_ShakeTerrain;
break;
case MAX_BATTLERS_COUNT: // Shake all battlers
task->tNumBattlers = 0;
for (i = 0; i < MAX_BATTLERS_COUNT; i++)
{
if (IsBattlerSpriteVisible(i))
{
task->tbattlerSpriteIds(task->tNumBattlers) = gBattlerSpriteIds[i];
task->tNumBattlers++;
}
}
task->func = AnimTask_ShakeBattlers;
break;
default: // Shake specific battler
task->tbattlerSpriteIds(0) = GetAnimBattlerSpriteId(gBattleAnimArgs[0]);
if (task->tbattlerSpriteIds(0) == SPRITE_NONE)
{
DestroyAnimVisualTask(taskId);
}
else
{
task->tNumBattlers = 1;
task->func = AnimTask_ShakeBattlers;
}
break;
}
}
static void AnimTask_ShakeTerrain(u8 taskId)
{
struct Task *task = &gTasks[taskId];
switch (task->tState)
{
case 0:
if (++task->tDelay > 1)
{
task->tDelay = 0;
if ((task->tTimer & 1) == 0)
gBattle_BG3_X = task->tInitialX + task->tInitHorizOffset;
else
gBattle_BG3_X = task->tInitialX - task->tInitHorizOffset;
if (++task->tTimer == task->tMaxTime)
{
task->tTimer = 0;
task->tHorizOffset--;
task->tState++;
}
}
break;
case 1:
if (++task->tDelay > 1)
{
task->tDelay = 0;
if ((task->tTimer & 1) == 0)
gBattle_BG3_X = task->tInitialX + task->tHorizOffset;
else
gBattle_BG3_X = task->tInitialX - task->tHorizOffset;
if (++task->tTimer == 4)
{
task->tTimer = 0;
if (--task->tHorizOffset == 0)
task->tState++;
}
}
break;
case 2:
gBattle_BG3_X = task->tInitialX;
DestroyAnimVisualTask(taskId);
break;
}
}
static void AnimTask_ShakeBattlers(u8 taskId)
{
u16 i;
struct Task *task = &gTasks[taskId];
switch (task->tState)
{
case 0:
if (++task->tDelay > 1)
{
task->tDelay = 0;
SetBattlersXOffsetForShake(task);
if (++task->tTimer == task->tMaxTime)
{
task->tTimer = 0;
task->tHorizOffset--;
task->tState++;
}
}
break;
case 1:
if (++task->tDelay > 1)
{
task->tDelay = 0;
SetBattlersXOffsetForShake(task);
if (++task->tTimer == 4)
{
task->tTimer = 0;
if (--task->tHorizOffset == 0)
task->tState++;
}
}
break;
case 2:
for (i = 0; i < task->tNumBattlers; i++)
gSprites[task->tbattlerSpriteIds(i)].x2 = 0;
DestroyAnimVisualTask(taskId);
break;
}
}
static void SetBattlersXOffsetForShake(struct Task *task)
{
u16 i;
u16 xOffset;
if ((task->tTimer & 1) == 0)
xOffset = (task->tHorizOffset / 2) + (task->tHorizOffset & 1);
else
xOffset = -(task->tHorizOffset / 2);
for (i = 0; i < task->tNumBattlers; i++)
{
gSprites[task->tbattlerSpriteIds(i)].x2 = xOffset;
}
}
#undef tState
#undef tDelay
#undef tTimer
#undef tMaxTime
#undef tbattlerSpriteIds
#undef tNumBattlers
#undef tInitialX
#undef tHorizOffset
#undef tInitHorizOffset
void AnimTask_IsPowerOver99(u8 taskId)
{
gBattleAnimArgs[15] = gAnimMovePower > 99;
DestroyAnimVisualTask(taskId);
}
void AnimTask_PositionFissureBgOnBattler(u8 taskId)
{
struct Task *newTask;
u8 battler = (gBattleAnimArgs[0] & ANIM_TARGET) ? gBattleAnimTarget : gBattleAnimAttacker;
if (gBattleAnimArgs[0] > ANIM_TARGET)
battler = BATTLE_PARTNER(battler);
newTask = &gTasks[CreateTask(WaitForFissureCompletion, gBattleAnimArgs[1])];
newTask->data[1] = (32 - GetBattlerSpriteCoord(battler, BATTLER_COORD_X_2)) & 0x1FF;
newTask->data[2] = (64 - GetBattlerSpriteCoord(battler, BATTLER_COORD_Y_PIC_OFFSET)) & 0xFF;
gBattle_BG3_X = newTask->data[1];
gBattle_BG3_Y = newTask->data[2];
newTask->data[3] = gBattleAnimArgs[2];
DestroyAnimVisualTask(taskId);
}
static void WaitForFissureCompletion(u8 taskId)
{
struct Task *task = &gTasks[taskId];
// Holds the BG3 offsets until gBattleAnimArgs[7]
// is set to a special terminator value.
if (gBattleAnimArgs[7] == task->data[3])
{
gBattle_BG3_X = 0;
gBattle_BG3_Y = 0;
DestroyTask(taskId);
}
else
{
gBattle_BG3_X = task->data[1];
gBattle_BG3_Y = task->data[2];
}
}
| 0 | 0.859863 | 1 | 0.859863 | game-dev | MEDIA | 0.885932 | game-dev,graphics-rendering | 0.936936 | 1 | 0.936936 |
DrewKestell/BloogBot | 4,183 | BalanceDruidBot/RestState.cs | using BloogBot;
using BloogBot.AI;
using BloogBot.AI.SharedStates;
using BloogBot.Game;
using BloogBot.Game.Objects;
using System.Collections.Generic;
using System.Linq;
namespace BalanceDruidBot
{
class RestState : IBotState
{
const int stackCount = 5;
const string Regrowth = "Regrowth";
const string Rejuvenation = "Rejuvenation";
const string MoonkinForm = "Moonkin Form";
readonly Stack<IBotState> botStates;
readonly IDependencyContainer container;
readonly LocalPlayer player;
readonly WoWItem drinkItem;
public RestState(Stack<IBotState> botStates, IDependencyContainer container)
{
this.botStates = botStates;
this.container = container;
player = ObjectManager.Player;
drinkItem = Inventory.GetAllItems()
.FirstOrDefault(i => i.Info.Name == container.BotSettings.Drink);
}
public void Update()
{
if (player.IsCasting)
return;
if (InCombat)
{
Wait.RemoveAll();
player.Stand();
botStates.Pop();
return;
}
if (HealthOk && ManaOk)
{
Wait.RemoveAll();
player.Stand();
botStates.Pop();
var drinkCount = drinkItem == null ? 0 : Inventory.GetItemCount(drinkItem.ItemId);
if (!InCombat && drinkCount == 0 && !container.RunningErrands)
{
var drinkToBuy = 28 - (drinkCount / stackCount);
var itemsToBuy = new Dictionary<string, int>
{
{ container.BotSettings.Drink, drinkToBuy }
};
var currentHotspot = container.GetCurrentHotspot();
if (currentHotspot.TravelPath != null)
{
botStates.Push(new TravelState(botStates, container, currentHotspot.TravelPath.Waypoints, 0));
botStates.Push(new MoveToPositionState(botStates, container, currentHotspot.TravelPath.Waypoints[0]));
}
botStates.Push(new BuyItemsState(botStates, currentHotspot.Innkeeper.Name, itemsToBuy));
botStates.Push(new SellItemsState(botStates, container, currentHotspot.Innkeeper.Name));
botStates.Push(new MoveToPositionState(botStates, container, currentHotspot.Innkeeper.Position));
container.CheckForTravelPath(botStates, true, false);
container.RunningErrands = true;
}
else
botStates.Push(new BuffSelfState(botStates));
}
if (player.HealthPercent < 60 && !player.HasBuff(Regrowth) && Wait.For("SelfHealDelay", 5000, true))
{
TryCastSpell(MoonkinForm, player.HasBuff(MoonkinForm));
TryCastSpell(Regrowth);
}
if (player.HealthPercent < 80 && !player.HasBuff(Rejuvenation) && !player.HasBuff(Regrowth) && Wait.For("SelfHealDelay", 5000, true))
{
TryCastSpell(MoonkinForm, player.HasBuff(MoonkinForm));
TryCastSpell(Rejuvenation);
}
if (player.Level >= 6 && drinkItem != null && !player.IsDrinking && player.ManaPercent < 60)
drinkItem.Use();
}
bool HealthOk => player.HealthPercent >= 81;
bool ManaOk => (player.Level < 6 && player.ManaPercent > 50) || player.ManaPercent >= 90 || (player.ManaPercent >= 65 && !player.IsDrinking);
bool InCombat => ObjectManager.Aggressors.Count() > 0;
void TryCastSpell(string name, bool condition = true)
{
if (player.IsSpellReady(name) && !player.IsCasting && player.Mana > player.GetManaCost(name) && !player.IsDrinking && condition)
{
player.Stand();
player.LuaCall($"CastSpellByName('{name}',1)");
}
}
}
}
| 0 | 0.950194 | 1 | 0.950194 | game-dev | MEDIA | 0.649706 | game-dev | 0.994272 | 1 | 0.994272 |
HbmMods/Hbm-s-Nuclear-Tech-GIT | 1,668 | src/main/java/com/hbm/blocks/machine/BlockHadronCoil.java | package com.hbm.blocks.machine;
import java.util.List;
import java.util.Locale;
import com.hbm.blocks.ITooltipProvider;
import com.hbm.render.block.ct.CT;
import com.hbm.render.block.ct.CTStitchReceiver;
import com.hbm.render.block.ct.IBlockCT;
import com.hbm.util.i18n.I18nUtil;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
import net.minecraft.world.IBlockAccess;
public class BlockHadronCoil extends Block implements IBlockCT, ITooltipProvider {
public int factor;
public BlockHadronCoil(Material mat, int factor) {
super(mat);
this.factor = factor;
}
@Override
public int getRenderType() {
return CT.renderID;
}
@SideOnly(Side.CLIENT)
public CTStitchReceiver rec;
@SideOnly(Side.CLIENT)
public void registerBlockIcons(IIconRegister reg) {
this.blockIcon = reg.registerIcon(this.getTextureName());
this.rec = IBlockCT.primeReceiver(reg, this.getTextureName(), this.blockIcon);
}
@Override
public IIcon[] getFragments(IBlockAccess world, int x, int y, int z) {
return rec.fragCache;
}
@Override
public boolean canConnect(IBlockAccess world, int x, int y, int z, Block block) {
return block instanceof BlockHadronCoil;
}
@Override
public void addInformation(ItemStack itemstack, EntityPlayer player, List list, boolean bool) {
list.add(I18nUtil.resolveKey("info.coil") + ": " + String.format(Locale.US, "%,d", factor));
}
}
| 0 | 0.536889 | 1 | 0.536889 | game-dev | MEDIA | 0.940753 | game-dev | 0.625146 | 1 | 0.625146 |
CesiumGS/cesium-unity | 1,235 | native~/Runtime/src/Cesium3DTileImpl.cpp | #include "Cesium3DTileImpl.h"
#include "UnityTransforms.h"
#include <Cesium3DTilesSelection/Tile.h>
#include <CesiumGeospatial/Ellipsoid.h>
#include <DotNet/Unity/Mathematics/double4x4.h>
#include <DotNet/UnityEngine/Bounds.h>
using namespace Cesium3DTilesSelection;
using namespace CesiumGeometry;
using namespace CesiumGeospatial;
namespace CesiumForUnityNative {
DotNet::UnityEngine::Bounds Cesium3DTileImpl::getBounds(
void* pTileVoid,
void* pTileEllipsoidVoid,
const DotNet::Unity::Mathematics::double4x4& ecefToLocalMatrix) {
const Tile* pTile = static_cast<const Tile*>(pTileVoid);
const Ellipsoid* pTileEllipsoid =
static_cast<const Ellipsoid*>(pTileEllipsoidVoid);
const BoundingVolume& bv = pTile->getBoundingVolume();
OrientedBoundingBox obb =
getOrientedBoundingBoxFromBoundingVolume(bv, *pTileEllipsoid);
obb = obb.transform(UnityTransforms::fromUnity(ecefToLocalMatrix));
AxisAlignedBox aabb = obb.toAxisAligned();
return DotNet::UnityEngine::Bounds::Construct(
UnityTransforms::toUnity(aabb.center),
DotNet::UnityEngine::Vector3{
float(aabb.lengthX),
float(aabb.lengthY),
float(aabb.lengthZ)});
}
} // namespace CesiumForUnityNative
| 0 | 0.791666 | 1 | 0.791666 | game-dev | MEDIA | 0.727573 | game-dev | 0.909083 | 1 | 0.909083 |
BedwarsRel/BedwarsRel | 2,409 | common/src/main/java/io/github/bedwarsrel/commands/GameTimeCommand.java | package io.github.bedwarsrel.commands;
import com.google.common.collect.ImmutableMap;
import io.github.bedwarsrel.BedwarsRel;
import io.github.bedwarsrel.game.Game;
import io.github.bedwarsrel.game.GameState;
import io.github.bedwarsrel.utils.ChatWriter;
import io.github.bedwarsrel.utils.Utils;
import java.util.ArrayList;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class GameTimeCommand extends BaseCommand implements ICommand {
public GameTimeCommand(BedwarsRel plugin) {
super(plugin);
}
@Override
public boolean execute(CommandSender sender, ArrayList<String> args) {
if (!sender.hasPermission("bw." + this.getPermission())) {
return false;
}
Player player = (Player) sender;
Game game = this.getPlugin().getGameManager().getGame(args.get(0));
String gametime = args.get(1).toString();
if (game == null) {
player.sendMessage(ChatWriter.pluginMessage(ChatColor.RED
+ BedwarsRel
._l(sender, "errors.gamenotfound", ImmutableMap.of("game", args.get(0).toString()))));
return false;
}
if (game.getState() == GameState.RUNNING) {
sender.sendMessage(
ChatWriter.pluginMessage(ChatColor.RED + BedwarsRel
._l(sender, "errors.notwhilegamerunning")));
return false;
}
if (!Utils.isNumber(gametime) && !"day".equals(gametime) && !"night".equals(gametime)) {
player.sendMessage(
ChatWriter.pluginMessage(ChatColor.RED + BedwarsRel._l(player, "errors.timeincorrect")));
return true;
}
int time = 1000;
if ("day".equals(gametime)) {
time = 6000;
} else if ("night".equals(gametime)) {
time = 18000;
} else {
time = Integer.valueOf(gametime);
}
game.setTime(time);
player.sendMessage(
ChatWriter.pluginMessage(ChatColor.GREEN + BedwarsRel._l(player, "success.gametimeset")));
return true;
}
@Override
public String[] getArguments() {
return new String[]{"game", "time"};
}
@Override
public String getCommand() {
return "gametime";
}
@Override
public String getDescription() {
return BedwarsRel._l("commands.gametime.desc");
}
@Override
public String getName() {
return BedwarsRel._l("commands.gametime.name");
}
@Override
public String getPermission() {
return "setup";
}
}
| 0 | 0.858692 | 1 | 0.858692 | game-dev | MEDIA | 0.816452 | game-dev | 0.835428 | 1 | 0.835428 |
gamekit-developers/gamekit | 1,990 | Engine/gkDebugProperty.h | /*
-------------------------------------------------------------------------------
This file is part of OgreKit.
http://gamekit.googlecode.com/
Copyright (c) 2006-2013 Charlie C.
Contributor(s): none yet.
-------------------------------------------------------------------------------
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 _gkDebugProperty_h_
#define _gkDebugProperty_h_
#include "gkVariable.h"
#include "OgreOverlay.h"
#include "OgreOverlayContainer.h"
#include "OgreOverlayElement.h"
class gkDebugPropertyPage
{
private:
bool m_isInit, m_isShown;
Ogre::Overlay* m_over;
Ogre::OverlayContainer* m_cont;
Ogre::OverlayElement* m_key, *m_val;
typedef utList<gkVariable*> VariableList;
VariableList m_props;
public:
gkDebugPropertyPage();
~gkDebugPropertyPage();
void initialize(void);
void show(bool v);
bool isShown(void) {return m_isShown;}
void addVariable(gkVariable* prop);
void removeVariable(gkVariable* prop);
bool hasVariable(gkVariable* prop);
void clearProps(void);
void draw(void);
};
#endif//_gkDebugProperty_h_
| 0 | 0.748812 | 1 | 0.748812 | game-dev | MEDIA | 0.446413 | game-dev,graphics-rendering | 0.760937 | 1 | 0.760937 |
MinecraftModdedClients/Resilience-Client-Source | 1,352 | net/minecraft/block/BlockPressurePlateWeighted.java | package net.minecraft.block;
import net.minecraft.block.material.Material;
import net.minecraft.entity.Entity;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
public class BlockPressurePlateWeighted extends BlockBasePressurePlate
{
private final int field_150068_a;
private static final String __OBFID = "CL_00000334";
protected BlockPressurePlateWeighted(String p_i45436_1_, Material p_i45436_2_, int p_i45436_3_)
{
super(p_i45436_1_, p_i45436_2_);
this.field_150068_a = p_i45436_3_;
}
protected int func_150065_e(World p_150065_1_, int p_150065_2_, int p_150065_3_, int p_150065_4_)
{
int var5 = Math.min(p_150065_1_.getEntitiesWithinAABB(Entity.class, this.func_150061_a(p_150065_2_, p_150065_3_, p_150065_4_)).size(), this.field_150068_a);
if (var5 <= 0)
{
return 0;
}
else
{
float var6 = (float)Math.min(this.field_150068_a, var5) / (float)this.field_150068_a;
return MathHelper.ceiling_float_int(var6 * 15.0F);
}
}
protected int func_150060_c(int p_150060_1_)
{
return p_150060_1_;
}
protected int func_150066_d(int p_150066_1_)
{
return p_150066_1_;
}
public int func_149738_a(World p_149738_1_)
{
return 10;
}
}
| 0 | 0.527913 | 1 | 0.527913 | game-dev | MEDIA | 0.729067 | game-dev | 0.58096 | 1 | 0.58096 |
shiversoftdev/t8-src | 11,644 | scripts/weapons/bouncingbetty.gsc | // Decompiled by Serious. Credits to Scoba for his original tool, Cerberus, which I heavily upgraded to support remaining features, other games, and other platforms.
#using scripts\weapons\weaponobjects.gsc;
#using scripts\core_common\util_shared.gsc;
#using scripts\core_common\scoreevents_shared.gsc;
#using scripts\core_common\player\player_stats.gsc;
#using scripts\core_common\clientfield_shared.gsc;
#using scripts\core_common\challenges_shared.gsc;
#namespace bouncingbetty;
/*
Name: init_shared
Namespace: bouncingbetty
Checksum: 0xA6E9EFFE
Offset: 0x150
Size: 0x374
Parameters: 0
Flags: None
*/
function init_shared()
{
level.bettydestroyedfx = #"weapon/fx_betty_exp_destroyed";
level._effect[#"fx_betty_friendly_light"] = #"hash_5f76ecd582d98e38";
level._effect[#"fx_betty_enemy_light"] = #"hash_330682ff4f12f646";
level.bettymindist = 20;
level.bettystuntime = 1;
bettyexplodeanim = "o_spider_mine_detonate";
bettydeployanim = "o_spider_mine_deploy";
level.bettyradius = getdvarint(#"betty_detect_radius", 180);
level.bettyactivationdelay = getdvarfloat(#"betty_activation_delay", 1);
level.bettygraceperiod = getdvarfloat(#"betty_grace_period", 0);
level.bettydamageradius = getdvarint(#"betty_damage_radius", 180);
level.bettydamagemax = getdvarint(#"betty_damage_max", 180);
level.bettydamagemin = getdvarint(#"betty_damage_min", 70);
level.bettydamageheight = getdvarint(#"betty_damage_cylinder_height", 200);
level.bettyjumpheight = getdvarint(#"betty_jump_height_onground", 55);
level.bettyjumpheightwall = getdvarint(#"betty_jump_height_wall", 20);
level.bettyjumpheightwallangle = getdvarint(#"betty_onground_angle_threshold", 30);
level.bettyjumpheightwallanglecos = cos(level.bettyjumpheightwallangle);
level.bettyjumptime = getdvarfloat(#"betty_jump_time", 0.7);
level.bettybombletspawndistance = 20;
level.bettybombletcount = 4;
level thread register();
/#
level thread bouncingbettydvarupdate();
#/
weaponobjects::function_e6400478(#"bouncingbetty", &createbouncingbettywatcher, 0);
}
/*
Name: register
Namespace: bouncingbetty
Checksum: 0xDF43ADC3
Offset: 0x4D0
Size: 0x64
Parameters: 0
Flags: None
*/
function register()
{
clientfield::register("missile", "bouncingbetty_state", 1, 2, "int");
clientfield::register("scriptmover", "bouncingbetty_state", 1, 2, "int");
}
/*
Name: bouncingbettydvarupdate
Namespace: bouncingbetty
Checksum: 0xD1D7279C
Offset: 0x540
Size: 0x2A0
Parameters: 0
Flags: None
*/
function bouncingbettydvarupdate()
{
/#
for(;;)
{
level.bettyradius = getdvarint(#"betty_detect_radius", level.bettyradius);
level.bettyactivationdelay = getdvarfloat(#"betty_activation_delay", level.bettyactivationdelay);
level.bettygraceperiod = getdvarfloat(#"betty_grace_period", level.bettygraceperiod);
level.bettydamageradius = getdvarint(#"betty_damage_radius", level.bettydamageradius);
level.bettydamagemax = getdvarint(#"betty_damage_max", level.bettydamagemax);
level.bettydamagemin = getdvarint(#"betty_damage_min", level.bettydamagemin);
level.bettydamageheight = getdvarint(#"betty_damage_cylinder_height", level.bettydamageheight);
level.bettyjumpheight = getdvarint(#"betty_jump_height_onground", level.bettyjumpheight);
level.bettyjumpheightwall = getdvarint(#"betty_jump_height_wall", level.bettyjumpheightwall);
level.bettyjumpheightwallangle = getdvarint(#"betty_onground_angle_threshold", level.bettyjumpheightwallangle);
level.bettyjumpheightwallanglecos = cos(level.bettyjumpheightwallangle);
level.bettyjumptime = getdvarfloat(#"betty_jump_time", level.bettyjumptime);
wait(3);
}
#/
}
/*
Name: createbouncingbettywatcher
Namespace: bouncingbetty
Checksum: 0xAB9CD39E
Offset: 0x7E8
Size: 0x176
Parameters: 1
Flags: None
*/
function createbouncingbettywatcher(watcher)
{
watcher.onspawn = &onspawnbouncingbetty;
watcher.watchforfire = 1;
watcher.ondetonatecallback = &bouncingbettydetonate;
watcher.activatesound = #"wpn_betty_alert";
watcher.hackable = 1;
watcher.hackertoolradius = level.equipmenthackertoolradius;
watcher.hackertooltimems = level.equipmenthackertooltimems;
watcher.ownergetsassist = 1;
watcher.ignoredirection = 1;
watcher.immediatedetonation = 1;
watcher.immunespecialty = "specialty_immunetriggerbetty";
watcher.detectionmindist = level.bettymindist;
watcher.detectiongraceperiod = level.bettygraceperiod;
watcher.detonateradius = level.bettyradius;
watcher.onfizzleout = &onbouncingbettyfizzleout;
watcher.stun = &weaponobjects::weaponstun;
watcher.stuntime = level.bettystuntime;
watcher.activationdelay = level.bettyactivationdelay;
}
/*
Name: onbouncingbettyfizzleout
Namespace: bouncingbetty
Checksum: 0x2DE4E08F
Offset: 0x968
Size: 0x74
Parameters: 0
Flags: None
*/
function onbouncingbettyfizzleout()
{
if(isdefined(self.minemover))
{
if(isdefined(self.minemover.killcament))
{
self.minemover.killcament delete();
}
self.minemover delete();
}
self delete();
}
/*
Name: onspawnbouncingbetty
Namespace: bouncingbetty
Checksum: 0x9296D9B4
Offset: 0x9E8
Size: 0xAC
Parameters: 2
Flags: None
*/
function onspawnbouncingbetty(watcher, owner)
{
weaponobjects::onspawnproximityweaponobject(watcher, owner);
self.originalowner = owner;
self thread spawnminemover();
self trackonowner(owner);
self thread trackusedstatondeath();
self thread donotrackusedstatonpickup();
self thread trackusedonhack();
}
/*
Name: trackusedstatondeath
Namespace: bouncingbetty
Checksum: 0x8CBBC8A7
Offset: 0xAA0
Size: 0x66
Parameters: 0
Flags: None
*/
function trackusedstatondeath()
{
self endon(#"do_not_track_used");
self waittill(#"death");
waittillframeend();
self.owner trackbouncingbettyasused();
self notify(#"end_donotrackusedonpickup");
self notify(#"end_donotrackusedonhacked");
}
/*
Name: donotrackusedstatonpickup
Namespace: bouncingbetty
Checksum: 0xCEB54864
Offset: 0xB10
Size: 0x3E
Parameters: 0
Flags: None
*/
function donotrackusedstatonpickup()
{
self endon(#"end_donotrackusedonpickup");
self waittill(#"picked_up");
self notify(#"do_not_track_used");
}
/*
Name: trackusedonhack
Namespace: bouncingbetty
Checksum: 0xC1098234
Offset: 0xB58
Size: 0x56
Parameters: 0
Flags: None
*/
function trackusedonhack()
{
self endon(#"end_donotrackusedonhacked");
self waittill(#"hacked");
self.originalowner trackbouncingbettyasused();
self notify(#"do_not_track_used");
}
/*
Name: trackbouncingbettyasused
Namespace: bouncingbetty
Checksum: 0x3F94DA74
Offset: 0xBB8
Size: 0x64
Parameters: 0
Flags: None
*/
function trackbouncingbettyasused()
{
if(isplayer(self))
{
self stats::function_e24eec31(getweapon(#"bouncingbetty"), #"used", 1);
}
}
/*
Name: trackonowner
Namespace: bouncingbetty
Checksum: 0x94708ABE
Offset: 0xC28
Size: 0x8A
Parameters: 1
Flags: None
*/
function trackonowner(owner)
{
if(level.trackbouncingbettiesonowner === 1)
{
if(!isdefined(owner))
{
return;
}
if(!isdefined(owner.activebouncingbetties))
{
owner.activebouncingbetties = [];
}
else
{
arrayremovevalue(owner.activebouncingbetties, undefined);
}
owner.activebouncingbetties[owner.activebouncingbetties.size] = self;
}
}
/*
Name: spawnminemover
Namespace: bouncingbetty
Checksum: 0x52120927
Offset: 0xCC0
Size: 0x29C
Parameters: 0
Flags: None
*/
function spawnminemover()
{
self endon(#"death");
self util::waittillnotmoving();
self clientfield::set("bouncingbetty_state", 2);
self useanimtree("generic");
self setanim(#"o_spider_mine_deploy", 1, 0, 1);
minemover = spawn("script_model", self.origin);
minemover.angles = self.angles;
minemover setmodel(#"tag_origin");
minemover.owner = self.owner;
mineup = anglestoup(minemover.angles);
z_offset = getdvarfloat(#"scr_bouncing_betty_killcam_offset", 18);
minemover enablelinkto();
minemover linkto(self);
minemover.killcamoffset = vectorscale(mineup, z_offset);
minemover.weapon = self.weapon;
minemover playsound(#"wpn_betty_arm");
killcament = spawn("script_model", minemover.origin + minemover.killcamoffset);
killcament.angles = (0, 0, 0);
killcament setmodel(#"tag_origin");
killcament setweapon(self.weapon);
minemover.killcament = killcament;
self.minemover = minemover;
self thread killminemoveronpickup();
}
/*
Name: killminemoveronpickup
Namespace: bouncingbetty
Checksum: 0xDFED91E0
Offset: 0xF68
Size: 0x54
Parameters: 0
Flags: None
*/
function killminemoveronpickup()
{
self.minemover endon(#"death");
self waittill(#"picked_up", #"hacked");
self killminemover();
}
/*
Name: killminemover
Namespace: bouncingbetty
Checksum: 0xAFCFD739
Offset: 0xFC8
Size: 0x5C
Parameters: 0
Flags: None
*/
function killminemover()
{
if(isdefined(self.minemover))
{
if(isdefined(self.minemover.killcament))
{
self.minemover.killcament delete();
}
self.minemover delete();
}
}
/*
Name: bouncingbettydetonate
Namespace: bouncingbetty
Checksum: 0xE111D62F
Offset: 0x1030
Size: 0x14C
Parameters: 3
Flags: None
*/
function bouncingbettydetonate(attacker, weapon, target)
{
if(isdefined(weapon) && weapon.isvalid)
{
self.destroyedby = attacker;
if(isdefined(attacker))
{
if(self.owner util::isenemyplayer(attacker))
{
attacker challenges::destroyedexplosive(weapon);
scoreevents::processscoreevent(#"destroyed_bouncingbetty", attacker, self.owner, weapon);
}
}
self bouncingbettydestroyed();
}
else
{
if(isdefined(self.minemover))
{
self.minemover.ignore_team_kills = 1;
self.minemover setmodel(self.model);
self.minemover thread bouncingbettyjumpandexplode();
self delete();
}
else
{
self bouncingbettydestroyed();
}
}
}
/*
Name: bouncingbettydestroyed
Namespace: bouncingbetty
Checksum: 0xB9CAD3D7
Offset: 0x1188
Size: 0xE4
Parameters: 0
Flags: None
*/
function bouncingbettydestroyed()
{
playfx(level.bettydestroyedfx, self.origin);
playsoundatposition(#"dst_equipment_destroy", self.origin);
if(isdefined(self.trigger))
{
self.trigger delete();
}
self killminemover();
self radiusdamage(self.origin, 128, 110, 10, self.owner, "MOD_EXPLOSIVE", self.weapon);
self delete();
}
/*
Name: bouncingbettyjumpandexplode
Namespace: bouncingbetty
Checksum: 0x8CB1DF24
Offset: 0x1278
Size: 0x114
Parameters: 0
Flags: None
*/
function bouncingbettyjumpandexplode()
{
jumpdir = vectornormalize(anglestoup(self.angles));
if(jumpdir[2] > level.bettyjumpheightwallanglecos)
{
jumpheight = level.bettyjumpheight;
}
else
{
jumpheight = level.bettyjumpheightwall;
}
explodepos = self.origin + (jumpdir * jumpheight);
self.killcament moveto(explodepos + self.killcamoffset, level.bettyjumptime, 0, level.bettyjumptime);
self clientfield::set("bouncingbetty_state", 1);
wait(level.bettyjumptime);
self thread mineexplode(jumpdir, explodepos);
}
/*
Name: mineexplode
Namespace: bouncingbetty
Checksum: 0x5B48408A
Offset: 0x1398
Size: 0x18C
Parameters: 2
Flags: None
*/
function mineexplode(explosiondir, explodepos)
{
if(!isdefined(self) || !isdefined(self.owner))
{
return;
}
self playsound(#"wpn_betty_explo");
self clientfield::increment("sndRattle", 1);
waitframe(1);
if(!isdefined(self) || !isdefined(self.owner))
{
return;
}
self cylinderdamage(explosiondir * level.bettydamageheight, explodepos, level.bettydamageradius, level.bettydamageradius, level.bettydamagemax, level.bettydamagemin, self.owner, "MOD_EXPLOSIVE", self.weapon);
self ghost();
wait(0.1);
if(!isdefined(self) || !isdefined(self.owner))
{
return;
}
if(isdefined(self.trigger))
{
self.trigger delete();
}
self.killcament delete();
self delete();
}
| 0 | 0.822508 | 1 | 0.822508 | game-dev | MEDIA | 0.984973 | game-dev | 0.785325 | 1 | 0.785325 |
someweirdhuman/KuiNameplates335aCustom | 23,282 | Kui_Nameplates/Libs/AceConfig-3.0/AceConfigCmd-3.0/AceConfigCmd-3.0.lua | --- AceConfigCmd-3.0 handles access to an options table through the "command line" interface via the ChatFrames.
-- @class file
-- @name AceConfigCmd-3.0
-- @release $Id: AceConfigCmd-3.0.lua 904 2009-12-13 11:56:37Z nevcairiel $
--[[
AceConfigCmd-3.0
Handles commandline optionstable access
REQUIRES: AceConsole-3.0 for command registration (loaded on demand)
]]
-- TODO: plugin args
local MAJOR, MINOR = "AceConfigCmd-3.0", 12
local AceConfigCmd = LibStub:NewLibrary(MAJOR, MINOR)
if not AceConfigCmd then return end
AceConfigCmd.commands = AceConfigCmd.commands or {}
local commands = AceConfigCmd.commands
local cfgreg = LibStub("AceConfigRegistry-3.0")
local AceConsole -- LoD
local AceConsoleName = "AceConsole-3.0"
-- Lua APIs
local strsub, strsplit, strlower, strmatch, strtrim = string.sub, string.split, string.lower, string.match, string.trim
local format, tonumber, tostring = string.format, tonumber, tostring
local tsort, tinsert = table.sort, table.insert
local select, pairs, next, type = select, pairs, next, type
local error, assert = error, assert
-- WoW APIs
local _G = _G
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
-- List them here for Mikk's FindGlobals script
-- GLOBALS: LibStub, SELECTED_CHAT_FRAME, DEFAULT_CHAT_FRAME
local L = setmetatable({}, { -- TODO: replace with proper locale
__index = function(self,k) return k end
})
local function print(msg)
(SELECTED_CHAT_FRAME or DEFAULT_CHAT_FRAME):AddMessage(msg)
end
-- constants used by getparam() calls below
local handlertypes = {["table"]=true}
local handlermsg = "expected a table"
local functypes = {["function"]=true, ["string"]=true}
local funcmsg = "expected function or member name"
-- pickfirstset() - picks the first non-nil value and returns it
local function pickfirstset(...)
for i=1,select("#",...) do
if select(i,...)~=nil then
return select(i,...)
end
end
end
-- err() - produce real error() regarding malformed options tables etc
local function err(info,inputpos,msg )
local cmdstr=" "..strsub(info.input, 1, inputpos-1)
error(MAJOR..": /" ..info[0] ..cmdstr ..": "..(msg or "malformed options table"), 2)
end
-- usererr() - produce chatframe message regarding bad slash syntax etc
local function usererr(info,inputpos,msg )
local cmdstr=strsub(info.input, 1, inputpos-1);
print("/" ..info[0] .. " "..cmdstr ..": "..(msg or "malformed options table"))
end
-- callmethod() - call a given named method (e.g. "get", "set") with given arguments
local function callmethod(info, inputpos, tab, methodtype, ...)
local method = info[methodtype]
if not method then
err(info, inputpos, "'"..methodtype.."': not set")
end
info.arg = tab.arg
info.option = tab
info.type = tab.type
if type(method)=="function" then
return method(info, ...)
elseif type(method)=="string" then
if type(info.handler[method])~="function" then
err(info, inputpos, "'"..methodtype.."': '"..method.."' is not a member function of "..tostring(info.handler))
end
return info.handler[method](info.handler, info, ...)
else
assert(false) -- type should have already been checked on read
end
end
-- callfunction() - call a given named function (e.g. "name", "desc") with given arguments
local function callfunction(info, tab, methodtype, ...)
local method = tab[methodtype]
info.arg = tab.arg
info.option = tab
info.type = tab.type
if type(method)=="function" then
return method(info, ...)
else
assert(false) -- type should have already been checked on read
end
end
-- do_final() - do the final step (set/execute) along with validation and confirmation
local function do_final(info, inputpos, tab, methodtype, ...)
if info.validate then
local res = callmethod(info,inputpos,tab,"validate",...)
if type(res)=="string" then
usererr(info, inputpos, "'"..strsub(info.input, inputpos).."' - "..res)
return
end
end
-- console ignores .confirm
callmethod(info,inputpos,tab,methodtype, ...)
end
-- getparam() - used by handle() to retreive and store "handler", "get", "set", etc
local function getparam(info, inputpos, tab, depth, paramname, types, errormsg)
local old,oldat = info[paramname], info[paramname.."_at"]
local val=tab[paramname]
if val~=nil then
if val==false then
val=nil
elseif not types[type(val)] then
err(info, inputpos, "'" .. paramname.. "' - "..errormsg)
end
info[paramname] = val
info[paramname.."_at"] = depth
end
return old,oldat
end
-- iterateargs(tab) - custom iterator that iterates both t.args and t.plugins.*
local dummytable={}
local function iterateargs(tab)
if not tab.plugins then
return pairs(tab.args)
end
local argtabkey,argtab=next(tab.plugins)
local v
return function(_, k)
while argtab do
k,v = next(argtab, k)
if k then return k,v end
if argtab==tab.args then
argtab=nil
else
argtabkey,argtab = next(tab.plugins, argtabkey)
if not argtabkey then
argtab=tab.args
end
end
end
end
end
local function checkhidden(info, inputpos, tab)
if tab.cmdHidden~=nil then
return tab.cmdHidden
end
local hidden = tab.hidden
if type(hidden) == "function" or type(hidden) == "string" then
info.hidden = hidden
hidden = callmethod(info, inputpos, tab, 'hidden')
info.hidden = nil
end
return hidden
end
local function showhelp(info, inputpos, tab, depth, noHead)
if not noHead then
print("|cff33ff99"..info.appName.."|r: Arguments to |cffffff78/"..info[0].."|r "..strsub(info.input,1,inputpos-1)..":")
end
local sortTbl = {} -- [1..n]=name
local refTbl = {} -- [name]=tableref
for k,v in iterateargs(tab) do
if not refTbl[k] then -- a plugin overriding something in .args
tinsert(sortTbl, k)
refTbl[k] = v
end
end
tsort(sortTbl, function(one, two)
local o1 = refTbl[one].order or 100
local o2 = refTbl[two].order or 100
if type(o1) == "function" or type(o1) == "string" then
info.order = o1
info[#info+1] = one
o1 = callmethod(info, inputpos, refTbl[one], "order")
info[#info] = nil
info.order = nil
end
if type(o2) == "function" or type(o1) == "string" then
info.order = o2
info[#info+1] = two
o2 = callmethod(info, inputpos, refTbl[two], "order")
info[#info] = nil
info.order = nil
end
if o1<0 and o2<0 then return o1<o2 end
if o2<0 then return true end
if o1<0 then return false end
if o1==o2 then return tostring(one)<tostring(two) end -- compare names
return o1<o2
end)
for i = 1, #sortTbl do
local k = sortTbl[i]
local v = refTbl[k]
if not checkhidden(info, inputpos, v) then
if v.type ~= "description" and v.type ~= "header" then
-- recursively show all inline groups
local name, desc = v.name, v.desc
if type(name) == "function" then
name = callfunction(info, v, 'name')
end
if type(desc) == "function" then
desc = callfunction(info, v, 'desc')
end
if v.type == "group" and pickfirstset(v.cmdInline, v.inline, false) then
print(" "..(desc or name)..":")
local oldhandler,oldhandler_at = getparam(info, inputpos, v, depth, "handler", handlertypes, handlermsg)
showhelp(info, inputpos, v, depth, true)
info.handler,info.handler_at = oldhandler,oldhandler_at
else
local key = k:gsub(" ", "_")
print(" |cffffff78"..key.."|r - "..(desc or name or ""))
end
end
end
end
end
local function keybindingValidateFunc(text)
if text == nil or text == "NONE" then
return nil
end
text = text:upper()
local shift, ctrl, alt
local modifier
while true do
if text == "-" then
break
end
modifier, text = strsplit('-', text, 2)
if text then
if modifier ~= "SHIFT" and modifier ~= "CTRL" and modifier ~= "ALT" then
return false
end
if modifier == "SHIFT" then
if shift then
return false
end
shift = true
end
if modifier == "CTRL" then
if ctrl then
return false
end
ctrl = true
end
if modifier == "ALT" then
if alt then
return false
end
alt = true
end
else
text = modifier
break
end
end
if text == "" then
return false
end
if not text:find("^F%d+$") and text ~= "CAPSLOCK" and text:len() ~= 1 and (text:byte() < 128 or text:len() > 4) and not _G["KEY_" .. text] then
return false
end
local s = text
if shift then
s = "SHIFT-" .. s
end
if ctrl then
s = "CTRL-" .. s
end
if alt then
s = "ALT-" .. s
end
return s
end
-- handle() - selfrecursing function that processes input->optiontable
-- - depth - starts at 0
-- - retfalse - return false rather than produce error if a match is not found (used by inlined groups)
local function handle(info, inputpos, tab, depth, retfalse)
if not(type(tab)=="table" and type(tab.type)=="string") then err(info,inputpos) end
-------------------------------------------------------------------
-- Grab hold of handler,set,get,func,etc if set (and remember old ones)
-- Note that we do NOT validate if method names are correct at this stage,
-- the handler may change before they're actually used!
local oldhandler,oldhandler_at = getparam(info,inputpos,tab,depth,"handler",handlertypes,handlermsg)
local oldset,oldset_at = getparam(info,inputpos,tab,depth,"set",functypes,funcmsg)
local oldget,oldget_at = getparam(info,inputpos,tab,depth,"get",functypes,funcmsg)
local oldfunc,oldfunc_at = getparam(info,inputpos,tab,depth,"func",functypes,funcmsg)
local oldvalidate,oldvalidate_at = getparam(info,inputpos,tab,depth,"validate",functypes,funcmsg)
--local oldconfirm,oldconfirm_at = getparam(info,inputpos,tab,depth,"confirm",functypes,funcmsg)
-------------------------------------------------------------------
-- Act according to .type of this table
if tab.type=="group" then
------------ group --------------------------------------------
if type(tab.args)~="table" then err(info, inputpos) end
if tab.plugins and type(tab.plugins)~="table" then err(info,inputpos) end
-- grab next arg from input
local _,nextpos,arg = (info.input):find(" *([^ ]+) *", inputpos)
if not arg then
showhelp(info, inputpos, tab, depth)
return
end
nextpos=nextpos+1
-- loop .args and try to find a key with a matching name
for k,v in iterateargs(tab) do
if not(type(k)=="string" and type(v)=="table" and type(v.type)=="string") then err(info,inputpos, "options table child '"..tostring(k).."' is malformed") end
-- is this child an inline group? if so, traverse into it
if v.type=="group" and pickfirstset(v.cmdInline, v.inline, false) then
info[depth+1] = k
if handle(info, inputpos, v, depth+1, true)==false then
info[depth+1] = nil
-- wasn't found in there, but that's ok, we just keep looking down here
else
return -- done, name was found in inline group
end
-- matching name and not a inline group
elseif strlower(arg)==strlower(k:gsub(" ", "_")) then
info[depth+1] = k
return handle(info,nextpos,v,depth+1)
end
end
-- no match
if retfalse then
-- restore old infotable members and return false to indicate failure
info.handler,info.handler_at = oldhandler,oldhandler_at
info.set,info.set_at = oldset,oldset_at
info.get,info.get_at = oldget,oldget_at
info.func,info.func_at = oldfunc,oldfunc_at
info.validate,info.validate_at = oldvalidate,oldvalidate_at
--info.confirm,info.confirm_at = oldconfirm,oldconfirm_at
return false
end
-- couldn't find the command, display error
usererr(info, inputpos, "'"..arg.."' - " .. L["unknown argument"])
return
end
local str = strsub(info.input,inputpos);
if tab.type=="execute" then
------------ execute --------------------------------------------
do_final(info, inputpos, tab, "func")
elseif tab.type=="input" then
------------ input --------------------------------------------
local res = true
if tab.pattern then
if not(type(tab.pattern)=="string") then err(info, inputpos, "'pattern' - expected a string") end
if not strmatch(str, tab.pattern) then
usererr(info, inputpos, "'"..str.."' - " .. L["invalid input"])
return
end
end
do_final(info, inputpos, tab, "set", str)
elseif tab.type=="toggle" then
------------ toggle --------------------------------------------
local b
local str = strtrim(strlower(str))
if str=="" then
b = callmethod(info, inputpos, tab, "get")
if tab.tristate then
--cycle in true, nil, false order
if b then
b = nil
elseif b == nil then
b = false
else
b = true
end
else
b = not b
end
elseif str==L["on"] then
b = true
elseif str==L["off"] then
b = false
elseif tab.tristate and str==L["default"] then
b = nil
else
if tab.tristate then
usererr(info, inputpos, format(L["'%s' - expected 'on', 'off' or 'default', or no argument to toggle."], str))
else
usererr(info, inputpos, format(L["'%s' - expected 'on' or 'off', or no argument to toggle."], str))
end
return
end
do_final(info, inputpos, tab, "set", b)
elseif tab.type=="range" then
------------ range --------------------------------------------
local val = tonumber(str)
if not val then
usererr(info, inputpos, "'"..str.."' - "..L["expected number"])
return
end
if type(info.step)=="number" then
val = val- (val % info.step)
end
if type(info.min)=="number" and val<info.min then
usererr(info, inputpos, val.." - "..format(L["must be equal to or higher than %s"], tostring(info.min)) )
return
end
if type(info.max)=="number" and val>info.max then
usererr(info, inputpos, val.." - "..format(L["must be equal to or lower than %s"], tostring(info.max)) )
return
end
do_final(info, inputpos, tab, "set", val)
elseif tab.type=="select" then
------------ select ------------------------------------
local str = strtrim(strlower(str))
local values = tab.values
if type(values) == "function" or type(values) == "string" then
info.values = values
values = callmethod(info, inputpos, tab, "values")
info.values = nil
end
if str == "" then
local b = callmethod(info, inputpos, tab, "get")
local fmt = "|cffffff78- [%s]|r %s"
local fmt_sel = "|cffffff78- [%s]|r %s |cffff0000*|r"
print(L["Options for |cffffff78"..info[#info].."|r:"])
for k, v in pairs(values) do
if b == k then
print(fmt_sel:format(k, v))
else
print(fmt:format(k, v))
end
end
return
end
local ok
for k,v in pairs(values) do
if strlower(k)==str then
str = k -- overwrite with key (in case of case mismatches)
ok = true
break
end
end
if not ok then
usererr(info, inputpos, "'"..str.."' - "..L["unknown selection"])
return
end
do_final(info, inputpos, tab, "set", str)
elseif tab.type=="multiselect" then
------------ multiselect -------------------------------------------
local str = strtrim(strlower(str))
local values = tab.values
if type(values) == "function" or type(values) == "string" then
info.values = values
values = callmethod(info, inputpos, tab, "values")
info.values = nil
end
if str == "" then
local fmt = "|cffffff78- [%s]|r %s"
local fmt_sel = "|cffffff78- [%s]|r %s |cffff0000*|r"
print(L["Options for |cffffff78"..info[#info].."|r (multiple possible):"])
for k, v in pairs(values) do
if callmethod(info, inputpos, tab, "get", k) then
print(fmt_sel:format(k, v))
else
print(fmt:format(k, v))
end
end
return
end
--build a table of the selections, checking that they exist
--parse for =on =off =default in the process
--table will be key = true for options that should toggle, key = [on|off|default] for options to be set
local sels = {}
for v in str:gmatch("[^ ]+") do
--parse option=on etc
local opt, val = v:match('(.+)=(.+)')
--get option if toggling
if not opt then
opt = v
end
--check that the opt is valid
local ok
for k,v in pairs(values) do
if strlower(k)==opt then
opt = k -- overwrite with key (in case of case mismatches)
ok = true
break
end
end
if not ok then
usererr(info, inputpos, "'"..opt.."' - "..L["unknown selection"])
return
end
--check that if val was supplied it is valid
if val then
if val == L["on"] or val == L["off"] or (tab.tristate and val == L["default"]) then
--val is valid insert it
sels[opt] = val
else
if tab.tristate then
usererr(info, inputpos, format(L["'%s' '%s' - expected 'on', 'off' or 'default', or no argument to toggle."], v, val))
else
usererr(info, inputpos, format(L["'%s' '%s' - expected 'on' or 'off', or no argument to toggle."], v, val))
end
return
end
else
-- no val supplied, toggle
sels[opt] = true
end
end
for opt, val in pairs(sels) do
local newval
if (val == true) then
--toggle the option
local b = callmethod(info, inputpos, tab, "get", opt)
if tab.tristate then
--cycle in true, nil, false order
if b then
b = nil
elseif b == nil then
b = false
else
b = true
end
else
b = not b
end
newval = b
else
--set the option as specified
if val==L["on"] then
newval = true
elseif val==L["off"] then
newval = false
elseif val==L["default"] then
newval = nil
end
end
do_final(info, inputpos, tab, "set", opt, newval)
end
elseif tab.type=="color" then
------------ color --------------------------------------------
local str = strtrim(strlower(str))
if str == "" then
--TODO: Show current value
return
end
local r, g, b, a
if tab.hasAlpha then
if str:len() == 8 and str:find("^%x*$") then
--parse a hex string
r,g,b,a = tonumber(str:sub(1, 2), 16) / 255, tonumber(str:sub(3, 4), 16) / 255, tonumber(str:sub(5, 6), 16) / 255, tonumber(str:sub(7, 8), 16) / 255
else
--parse seperate values
r,g,b,a = str:match("^([%d%.]+) ([%d%.]+) ([%d%.]+) ([%d%.]+)$")
r,g,b,a = tonumber(r), tonumber(g), tonumber(b), tonumber(a)
end
if not (r and g and b and a) then
usererr(info, inputpos, format(L["'%s' - expected 'RRGGBBAA' or 'r g b a'."], str))
return
end
if r >= 0.0 and r <= 1.0 and g >= 0.0 and g <= 1.0 and b >= 0.0 and b <= 1.0 and a >= 0.0 and a <= 1.0 then
--values are valid
elseif r >= 0 and r <= 255 and g >= 0 and g <= 255 and b >= 0 and b <= 255 and a >= 0 and a <= 255 then
--values are valid 0..255, convert to 0..1
r = r / 255
g = g / 255
b = b / 255
a = a / 255
else
--values are invalid
usererr(info, inputpos, format(L["'%s' - values must all be either in the range 0..1 or 0..255."], str))
end
else
a = 1.0
if str:len() == 6 and str:find("^%x*$") then
--parse a hex string
r,g,b = tonumber(str:sub(1, 2), 16) / 255, tonumber(str:sub(3, 4), 16) / 255, tonumber(str:sub(5, 6), 16) / 255
else
--parse seperate values
r,g,b = str:match("^([%d%.]+) ([%d%.]+) ([%d%.]+)$")
r,g,b = tonumber(r), tonumber(g), tonumber(b)
end
if not (r and g and b) then
usererr(info, inputpos, format(L["'%s' - expected 'RRGGBB' or 'r g b'."], str))
return
end
if r >= 0.0 and r <= 1.0 and g >= 0.0 and g <= 1.0 and b >= 0.0 and b <= 1.0 then
--values are valid
elseif r >= 0 and r <= 255 and g >= 0 and g <= 255 and b >= 0 and b <= 255 then
--values are valid 0..255, convert to 0..1
r = r / 255
g = g / 255
b = b / 255
else
--values are invalid
usererr(info, inputpos, format(L["'%s' - values must all be either in the range 0-1 or 0-255."], str))
end
end
do_final(info, inputpos, tab, "set", r,g,b,a)
elseif tab.type=="keybinding" then
------------ keybinding --------------------------------------------
local str = strtrim(strlower(str))
if str == "" then
--TODO: Show current value
return
end
local value = keybindingValidateFunc(str:upper())
if value == false then
usererr(info, inputpos, format(L["'%s' - Invalid Keybinding."], str))
return
end
do_final(info, inputpos, tab, "set", value)
elseif tab.type=="description" then
------------ description --------------------
-- ignore description, GUI config only
else
err(info, inputpos, "unknown options table item type '"..tostring(tab.type).."'")
end
end
--- Handle the chat command.
-- This is usually called from a chat command handler to parse the command input as operations on an aceoptions table.\\
-- AceConfigCmd uses this function internally when a slash command is registered with `:CreateChatCommand`
-- @param slashcmd The slash command WITHOUT leading slash (only used for error output)
-- @param appName The application name as given to `:RegisterOptionsTable()`
-- @param input The commandline input (as given by the WoW handler, i.e. without the command itself)
-- @usage
-- MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon", "AceConsole-3.0")
-- -- Use AceConsole-3.0 to register a Chat Command
-- MyAddon:RegisterChatCommand("mychat", "ChatCommand")
--
-- -- Show the GUI if no input is supplied, otherwise handle the chat input.
-- function MyAddon:ChatCommand(input)
-- -- Assuming "MyOptions" is the appName of a valid options table
-- if not input or input:trim() == "" then
-- LibStub("AceConfigDialog-3.0"):Open("MyOptions")
-- else
-- LibStub("AceConfigCmd-3.0").HandleCommand(MyAddon, "mychat", "MyOptions", input)
-- end
-- end
function AceConfigCmd:HandleCommand(slashcmd, appName, input)
local optgetter = cfgreg:GetOptionsTable(appName)
if not optgetter then
error([[Usage: HandleCommand("slashcmd", "appName", "input"): 'appName' - no options table "]]..tostring(appName)..[[" has been registered]], 2)
end
local options = assert( optgetter("cmd", MAJOR) )
local info = { -- Don't try to recycle this, it gets handed off to callbacks and whatnot
[0] = slashcmd,
appName = appName,
options = options,
input = input,
self = self,
handler = self,
uiType = "cmd",
uiName = MAJOR,
}
handle(info, 1, options, 0) -- (info, inputpos, table, depth)
end
--- Utility function to create a slash command handler.
-- Also registers tab completion with AceTab
-- @param slashcmd The slash command WITHOUT leading slash (only used for error output)
-- @param appName The application name as given to `:RegisterOptionsTable()`
function AceConfigCmd:CreateChatCommand(slashcmd, appName)
if not AceConsole then
AceConsole = LibStub(AceConsoleName)
end
if AceConsole.RegisterChatCommand(self, slashcmd, function(input)
AceConfigCmd.HandleCommand(self, slashcmd, appName, input) -- upgradable
end,
true) then -- succesfully registered so lets get the command -> app table in
commands[slashcmd] = appName
end
end
--- Utility function that returns the options table that belongs to a slashcommand.
-- Designed to be used for the AceTab interface.
-- @param slashcmd The slash command WITHOUT leading slash (only used for error output)
-- @return The options table associated with the slash command (or nil if the slash command was not registered)
function AceConfigCmd:GetChatCommandOptions(slashcmd)
return commands[slashcmd]
end
| 0 | 0.906246 | 1 | 0.906246 | game-dev | MEDIA | 0.575572 | game-dev | 0.974224 | 1 | 0.974224 |
Relintai/broken_seals | 3,129 | game/ui/player/vendor_window/ItemContainer.gd | extends Control
# Copyright (c) 2019-2021 Péter Magyar
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
export(NodePath) var icon_path : NodePath
export(NodePath) var name_label_path : NodePath
#export(NodePath) var description_label_path : NodePath
export(NodePath) var quantity_spinbox_path : NodePath
export(NodePath) var learn_button_path : NodePath
export(NodePath) var spell_button_path : NodePath
export(NodePath) var popup_path : NodePath
export(Color) var known_color : Color = Color.white
export(Color) var not_known_color : Color = Color.gray
export(Color) var unlearnable_color : Color = Color.gray
var _icon : TextureRect
var _name_label : Label
#var _description_label : RichTextLabel
var _item_button : Button
var _popup : Popup
var _quantity_spinbox : SpinBox
var _vendor_item_data_entry : VendorItemDataEntry
var _player : Entity
var _index : int
func _ready() -> void:
_icon = get_node(icon_path) as TextureRect
_name_label = get_node(name_label_path) as Label
# _description_label = get_node(description_label_path) as RichTextLabel
_item_button = get_node(spell_button_path) as Button
_popup = get_node(popup_path) as Popup
_quantity_spinbox = get_node(quantity_spinbox_path) as SpinBox
func set_vendor_item(p_player : Entity, p_vide: VendorItemDataEntry, index : int) -> void:
_vendor_item_data_entry = p_vide
_player = p_player
_index = index
# _icon.set_spell(_spell)
_item_button.set_item(_vendor_item_data_entry)
_popup.set_item(_vendor_item_data_entry)
if _vendor_item_data_entry != null && _vendor_item_data_entry.item != null:
_icon.texture = _vendor_item_data_entry.item.icon
_name_label.text = _vendor_item_data_entry.item.text_name
else:
_icon.texture = null
_name_label.text = "....."
update_spell_indicators()
func spell_button_pressed() -> void:
var pos : Vector2 = _item_button.rect_global_position
pos.x += _item_button.rect_size.x
_popup.popup(Rect2(pos, _popup.rect_size))
func buy():
if !_player:
return
var count : int = _quantity_spinbox.value
_player.vendor_item_sbuy(_index, count)
func update_spell_indicators():
pass
| 0 | 0.52516 | 1 | 0.52516 | game-dev | MEDIA | 0.813266 | game-dev | 0.833312 | 1 | 0.833312 |
juce-framework/JUCE | 2,371 | examples/Assets/Box2DTests/Pyramid.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 PYRAMID_H
#define PYRAMID_H
class Pyramid : public Test
{
public:
enum
{
e_count = 20
};
Pyramid()
{
{
b2BodyDef bd;
b2Body* ground = m_world->CreateBody(&bd);
b2EdgeShape shape;
shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));
ground->CreateFixture(&shape, 0.0f);
}
{
float32 a = 0.5f;
b2PolygonShape shape;
shape.SetAsBox(a, a);
b2Vec2 x(-7.0f, 0.75f);
b2Vec2 y;
b2Vec2 deltaX(0.5625f, 1.25f);
b2Vec2 deltaY(1.125f, 0.0f);
for (int32 i = 0; i < e_count; ++i)
{
y = x;
for (int32 j = i; j < e_count; ++j)
{
b2BodyDef bd;
bd.type = b2_dynamicBody;
bd.position = y;
b2Body* body = m_world->CreateBody(&bd);
body->CreateFixture(&shape, 5.0f);
y += deltaY;
}
x += deltaX;
}
}
}
void Step(Settings* settings)
{
Test::Step(settings);
//b2DynamicTree* tree = &m_world->m_contactManager.m_broadPhase.m_tree;
//if (m_stepCount == 400)
//{
// tree->RebuildBottomUp();
//}
}
static Test* Create()
{
return new Pyramid;
}
};
#endif
| 0 | 0.720508 | 1 | 0.720508 | game-dev | MEDIA | 0.783637 | game-dev | 0.904016 | 1 | 0.904016 |
ttayfunylmz/Unity_DesignPatterns | 13,626 | Assets/Plugins/Zenject/Source/Binding/Binders/SubContainerBinder.cs | using System;
using ModestTree;
namespace Zenject
{
[NoReflectionBaking]
public class SubContainerBinder
{
readonly BindInfo _bindInfo;
readonly BindStatement _bindStatement;
readonly object _subIdentifier;
readonly bool _resolveAll;
public SubContainerBinder(
BindInfo bindInfo,
BindStatement bindStatement,
object subIdentifier, bool resolveAll)
{
_bindInfo = bindInfo;
_bindStatement = bindStatement;
_subIdentifier = subIdentifier;
_resolveAll = resolveAll;
// Reset in case the user ends the binding here
bindStatement.SetFinalizer(null);
}
protected IBindingFinalizer SubFinalizer
{
set { _bindStatement.SetFinalizer(value); }
}
public ScopeConcreteIdArgConditionCopyNonLazyBinder ByInstance(DiContainer subContainer)
{
SubFinalizer = new SubContainerBindingFinalizer(
_bindInfo, _subIdentifier, _resolveAll,
(_) => new SubContainerCreatorByInstance(subContainer));
return new ScopeConcreteIdArgConditionCopyNonLazyBinder(_bindInfo);
}
public ScopeConcreteIdArgConditionCopyNonLazyBinder ByInstanceGetter(
Func<InjectContext, DiContainer> subContainerGetter)
{
SubFinalizer = new SubContainerBindingFinalizer(
_bindInfo, _subIdentifier, _resolveAll,
(_) => new SubContainerCreatorByInstanceGetter(subContainerGetter));
return new ScopeConcreteIdArgConditionCopyNonLazyBinder(_bindInfo);
}
public
#if NOT_UNITY3D
WithKernelScopeConcreteIdArgConditionCopyNonLazyBinder
#else
WithKernelDefaultParentScopeConcreteIdArgConditionCopyNonLazyBinder
#endif
ByInstaller<TInstaller>()
where TInstaller : InstallerBase
{
return ByInstaller(typeof(TInstaller));
}
public
#if NOT_UNITY3D
WithKernelScopeConcreteIdArgConditionCopyNonLazyBinder
#else
WithKernelDefaultParentScopeConcreteIdArgConditionCopyNonLazyBinder
#endif
ByInstaller(Type installerType)
{
Assert.That(installerType.DerivesFrom<InstallerBase>(),
"Invalid installer type given during bind command. Expected type '{0}' to derive from 'Installer<>'", installerType);
var subContainerBindInfo = new SubContainerCreatorBindInfo();
SubFinalizer = new SubContainerBindingFinalizer(
_bindInfo, _subIdentifier, _resolveAll,
(container) => new SubContainerCreatorByInstaller(container, subContainerBindInfo, installerType));
return new
#if NOT_UNITY3D
WithKernelScopeConcreteIdArgConditionCopyNonLazyBinder
#else
WithKernelDefaultParentScopeConcreteIdArgConditionCopyNonLazyBinder
#endif
(subContainerBindInfo, _bindInfo);
}
public
#if NOT_UNITY3D
WithKernelScopeConcreteIdArgConditionCopyNonLazyBinder
#else
WithKernelDefaultParentScopeConcreteIdArgConditionCopyNonLazyBinder
#endif
ByMethod(Action<DiContainer> installerMethod)
{
var subContainerBindInfo = new SubContainerCreatorBindInfo();
SubFinalizer = new SubContainerBindingFinalizer(
_bindInfo, _subIdentifier, _resolveAll,
(container) => new SubContainerCreatorByMethod(container, subContainerBindInfo, installerMethod));
return new
#if NOT_UNITY3D
WithKernelScopeConcreteIdArgConditionCopyNonLazyBinder
#else
WithKernelDefaultParentScopeConcreteIdArgConditionCopyNonLazyBinder
#endif
(subContainerBindInfo, _bindInfo);
}
#if !NOT_UNITY3D
public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewGameObjectMethod(
Action<DiContainer> installerMethod)
{
var gameObjectInfo = new GameObjectCreationParameters();
SubFinalizer = new SubContainerPrefabBindingFinalizer(
_bindInfo, _subIdentifier, _resolveAll,
(container) => new SubContainerCreatorByNewGameObjectMethod(
container, gameObjectInfo, installerMethod));
return new NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder(_bindInfo, gameObjectInfo);
}
public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewPrefabMethod(
Func<InjectContext, UnityEngine.Object> prefabGetter, Action<DiContainer> installerMethod)
{
var gameObjectInfo = new GameObjectCreationParameters();
SubFinalizer = new SubContainerPrefabBindingFinalizer(
_bindInfo, _subIdentifier, _resolveAll,
(container) => new SubContainerCreatorByNewPrefabMethod(
container,
new PrefabProviderCustom(prefabGetter),
gameObjectInfo, installerMethod));
return new NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder(_bindInfo, gameObjectInfo);
}
public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewPrefabMethod(
UnityEngine.Object prefab, Action<DiContainer> installerMethod)
{
BindingUtil.AssertIsValidPrefab(prefab);
var gameObjectInfo = new GameObjectCreationParameters();
SubFinalizer = new SubContainerPrefabBindingFinalizer(
_bindInfo, _subIdentifier, _resolveAll,
(container) => new SubContainerCreatorByNewPrefabMethod(
container,
new PrefabProvider(prefab),
gameObjectInfo, installerMethod));
return new NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder(_bindInfo, gameObjectInfo);
}
public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewGameObjectInstaller<TInstaller>()
where TInstaller : InstallerBase
{
return ByNewGameObjectInstaller(typeof(TInstaller));
}
public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewGameObjectInstaller(Type installerType)
{
Assert.That(installerType.DerivesFrom<InstallerBase>(),
"Invalid installer type given during bind command. Expected type '{0}' to derive from 'Installer<>'", installerType);
var gameObjectInfo = new GameObjectCreationParameters();
SubFinalizer = new SubContainerPrefabBindingFinalizer(
_bindInfo, _subIdentifier, _resolveAll,
(container) => new SubContainerCreatorByNewGameObjectInstaller(
container, gameObjectInfo, installerType, _bindInfo.Arguments));
return new NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder(_bindInfo, gameObjectInfo);
}
public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewPrefabInstaller<TInstaller>(
Func<InjectContext, UnityEngine.Object> prefabGetter)
where TInstaller : InstallerBase
{
return ByNewPrefabInstaller(prefabGetter, typeof(TInstaller));
}
public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewPrefabInstaller(
Func<InjectContext, UnityEngine.Object> prefabGetter, Type installerType)
{
Assert.That(installerType.DerivesFrom<InstallerBase>(),
"Invalid installer type given during bind command. Expected type '{0}' to derive from 'Installer<>'", installerType);
var gameObjectInfo = new GameObjectCreationParameters();
SubFinalizer = new SubContainerPrefabBindingFinalizer(
_bindInfo, _subIdentifier, _resolveAll,
(container) => new SubContainerCreatorByNewPrefabInstaller(
container,
new PrefabProviderCustom(prefabGetter),
gameObjectInfo, installerType, _bindInfo.Arguments));
return new NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder(_bindInfo, gameObjectInfo);
}
public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewPrefabInstaller<TInstaller>(
UnityEngine.Object prefab)
where TInstaller : InstallerBase
{
return ByNewPrefabInstaller(prefab, typeof(TInstaller));
}
public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewPrefabInstaller(
UnityEngine.Object prefab, Type installerType)
{
Assert.That(installerType.DerivesFrom<InstallerBase>(),
"Invalid installer type given during bind command. Expected type '{0}' to derive from 'Installer<>'", installerType);
var gameObjectInfo = new GameObjectCreationParameters();
SubFinalizer = new SubContainerPrefabBindingFinalizer(
_bindInfo, _subIdentifier, _resolveAll,
(container) => new SubContainerCreatorByNewPrefabInstaller(
container,
new PrefabProvider(prefab),
gameObjectInfo, installerType, _bindInfo.Arguments));
return new NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder(_bindInfo, gameObjectInfo);
}
public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewPrefabResourceMethod(
string resourcePath, Action<DiContainer> installerMethod)
{
BindingUtil.AssertIsValidResourcePath(resourcePath);
var gameObjectInfo = new GameObjectCreationParameters();
SubFinalizer = new SubContainerPrefabBindingFinalizer(
_bindInfo, _subIdentifier, _resolveAll,
(container) => new SubContainerCreatorByNewPrefabMethod(
container,
new PrefabProviderResource(resourcePath),
gameObjectInfo, installerMethod));
return new NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder(_bindInfo, gameObjectInfo);
}
public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewPrefabResourceInstaller<TInstaller>(
string resourcePath)
where TInstaller : InstallerBase
{
return ByNewPrefabResourceInstaller(resourcePath, typeof(TInstaller));
}
public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewPrefabResourceInstaller(
string resourcePath, Type installerType)
{
BindingUtil.AssertIsValidResourcePath(resourcePath);
Assert.That(installerType.DerivesFrom<InstallerBase>(),
"Invalid installer type given during bind command. Expected type '{0}' to derive from 'Installer<>'", installerType);
var gameObjectInfo = new GameObjectCreationParameters();
SubFinalizer = new SubContainerPrefabBindingFinalizer(
_bindInfo, _subIdentifier, _resolveAll,
(container) => new SubContainerCreatorByNewPrefabInstaller(
container,
new PrefabProviderResource(resourcePath),
gameObjectInfo, installerType, _bindInfo.Arguments));
return new NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder(_bindInfo, gameObjectInfo);
}
[System.Obsolete("ByNewPrefab has been renamed to ByNewContextPrefab to avoid confusion with ByNewPrefabInstaller and ByNewPrefabMethod")]
public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewPrefab(UnityEngine.Object prefab)
{
return ByNewContextPrefab(prefab);
}
public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewContextPrefab(UnityEngine.Object prefab)
{
BindingUtil.AssertIsValidPrefab(prefab);
var gameObjectInfo = new GameObjectCreationParameters();
SubFinalizer = new SubContainerPrefabBindingFinalizer(
_bindInfo, _subIdentifier, _resolveAll,
(container) => new SubContainerCreatorByNewPrefab(
container, new PrefabProvider(prefab), gameObjectInfo));
return new NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder(_bindInfo, gameObjectInfo);
}
[System.Obsolete("ByNewPrefabResource has been renamed to ByNewContextPrefabResource to avoid confusion with ByNewPrefabResourceInstaller and ByNewPrefabResourceMethod")]
public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewPrefabResource(string resourcePath)
{
return ByNewContextPrefabResource(resourcePath);
}
public NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder ByNewContextPrefabResource(string resourcePath)
{
BindingUtil.AssertIsValidResourcePath(resourcePath);
var gameObjectInfo = new GameObjectCreationParameters();
SubFinalizer = new SubContainerPrefabBindingFinalizer(
_bindInfo, _subIdentifier, _resolveAll,
(container) => new SubContainerCreatorByNewPrefab(
container, new PrefabProviderResource(resourcePath), gameObjectInfo));
return new NameTransformScopeConcreteIdArgConditionCopyNonLazyBinder(_bindInfo, gameObjectInfo);
}
#endif
}
}
| 0 | 0.737762 | 1 | 0.737762 | game-dev | MEDIA | 0.808976 | game-dev | 0.591249 | 1 | 0.591249 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.