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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mindreframer/love2d-games | 5,162 | sienna/AdvTiledLoader/Grid.lua | ---------------------------------------------------------------------------------------------------
-- -= Grid =-
---------------------------------------------------------------------------------------------------
local Grid = {}
Grid.__index = Grid
-- Creates and returns a new grid
function Grid:new()
local grid = {}
grid.cells = {}
grid.cells.mt = {__mode = ""}
return setmetatable(grid, Grid)
end
-- Weakens the grid's cells so the garbage collecter can delete their contents if they have no
-- other references.
function Grid:weaken()
self.cells.mt.__mode = "v"
for key,row in pairs(self.cells) do
setmetatable(row,self.cells.mt)
end
end
-- Unweakens the grid
function Grid:unweaken()
self.cells.mt.__mode = ""
for key,row in pairs(self.cells) do
setmetatable(row,self.cells.mt)
end
end
-- Gets the value of a single cell
function Grid:get(x,y)
return self.cells[x] and self.cells[x][y] or nil
end
-- Sets the value of a single cell
function Grid:set(x,y,value)
if not self.cells[x] then
self.cells[x] = setmetatable({}, self.cells.mt)
end
self.cells[x][y] = value
end
-- Sets all of the cells in an area to the same value
function Grid:setArea(startX, startY, endX, endY, value)
for x = startX,endX do
for y = startY,endY do
self:set(x,y,value)
end
end
end
-- Iterate over all values
function Grid:iterate()
local x, row = next(self.cells)
local y, val
return function()
repeat
y,val = next(row,y)
if y == nil then x,row = next(self.cells, x) end
until (val and x and y and type(x)=="number") or (not val and not x and not y)
return x,y,val
end
end
-- Iterate over a rectangle shape
function Grid:rectangle(startX, startY, endX, endY, includeNil)
local x, y = startX, startY
return function()
while y <= endY do
while x <=endX do
x = x+1
if self(x-1,y) ~= nil or includeNil then
return x-1, y, self(x-1,y)
end
end
x = startX
y = y+1
end
return nil
end
end
-- Iterate over a line. Set noDiag to true to keep from traversing diagonally.
function Grid:line(startX, startY, endX, endY, noDiag, includeNil)
local dx = math.abs(endX - startX)
local dy = math.abs(endY - startY)
local x = startX
local y = startY
local incrX = endX > startX and 1 or -1
local incrY = endY > startY and 1 or -1
local err = dx - dy
local err2 = err*2
local i = 1+dx+dy
local rx,ry,rv
local checkX = false
return function()
while i>0 do
rx,ry,rv = x,y,self(x,y)
err2 = err*2
while true do
checkX = not checkX
if checkX == true or not noDiag then
if err2 > -dy then
err = err - dy
x = x + incrX
i = i-1
if noDiag then break end
end
end
if checkX == false or not noDiag then
if err2 < dx then
err = err + dx
y = y + incrY
i = i-1
if noDiag then break end
end
end
if not noDiag then break end
end
if rx == endX and ry == endY then i = 0 end
if rv ~= nil or includeNil then return rx,ry,rv end
end
return nil
end
end
-- Iterates over a circle of cells
function Grid:circle(cx, cy, r, includeNil)
local x,y
x = x or cx-r
return function()
repeat
y = y == nil and cy or y <= cy and y-1 or y+1
while ((cx-x)*(cx-x)+(cy-y)*(cy-y)) >= r*r do
if x > cx+r then return nil end
x = x + (y < cy and 0 or 1)
y = cy + (y < cy and 1 or 0)
end
until self(x,y) ~= nil or includeNil
return x,y,self(x,y)
end
end
-- Cleans the grid of empty rows.
function Grid:clean()
for key,row in pairs(self.cells) do
if not next(row) then self.cells[key] = nil end
end
end
-- This makes calling the grid as a function act like Grid.get.
Grid.__call = Grid.get
-- Returns the grid class
return Grid
--------------------------------------------------------------------------------------
-- Copyright (c) 2011 Casey Baxter
-- 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.
-- Except as contained in this notice, the name(s) of the above copyright holders
-- shall not be used in advertising or otherwise to promote the sale, use or
-- other dealings in this Software without prior written authorization.
-- 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. | 412 | 0.819687 | 1 | 0.819687 | game-dev | MEDIA | 0.649417 | game-dev | 0.911999 | 1 | 0.911999 |
GreenComfyTea/MHW-Better-Matchmaking | 1,685 | BetterMatchmaking/Core/Quests/InGameFilterOverride/Rewards/Customization/RewardFilterCustomization_Options.cs | using ImGuiNET;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BetterMatchmaking;
internal class RewardFilterCustomization_Options : SingletonAccessor
{
private bool _noRewards = true;
public bool NoRewards { get => _noRewards; set => _noRewards = value; }
private bool _rewardsAvailable = true;
public bool RewardsAvailable { get => _rewardsAvailable; set => _rewardsAvailable = value; }
public RewardFilterCustomization_Options()
{
InstantiateSingletons();
}
private RewardFilterCustomization_Options SelectAll()
{
NoRewards = true;
RewardsAvailable = true;
return this;
}
private RewardFilterCustomization_Options DeselectAll()
{
NoRewards = false;
RewardsAvailable = false;
return this;
}
public bool RenderImGui()
{
var changed = false;
if (ImGui.TreeNode(LocalizationManager_I.ImGui.FilterOptions))
{
if (ImGui.Button(LocalizationManager_I.ImGui.SelectAll))
{
SelectAll();
changed = true;
}
ImGui.SameLine();
if (ImGui.Button(LocalizationManager_I.ImGui.DeselectAll))
{
DeselectAll();
changed = true;
}
changed = ImGui.Checkbox(LocalizationManager_I.ImGui.NoRewards, ref _noRewards) || changed;
changed = ImGui.Checkbox(LocalizationManager_I.ImGui.RewardsAvailable, ref _rewardsAvailable) || changed;
ImGui.TreePop();
}
return changed;
}
}
| 412 | 0.897314 | 1 | 0.897314 | game-dev | MEDIA | 0.452421 | game-dev,desktop-app | 0.767708 | 1 | 0.767708 |
LogicalError/realtime-CSG-for-unity | 14,629 | Plugins/Editor/Scripts/View/GUI/Utility/CSG_EditorGUIUtility.cs | using System;
using System.Linq;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using InternalRealtimeCSG;
namespace RealtimeCSG
{
internal static class CSG_EditorGUIUtility
{
public static bool PassThroughButton(bool passThrough, bool mixedValues)
{
CSG_GUIStyleUtility.InitStyles();
var rcsgSkin = CSG_GUIStyleUtility.Skin;
var oldColor = GUI.color;
GUI.color = Color.white;
bool pressed = false;
GUILayout.BeginVertical();
{
GUIContent content;
GUIStyle style;
if (!mixedValues && GUI.enabled && passThrough)
{
content = rcsgSkin.passThroughOn;
style = CSG_GUIStyleUtility.selectedIconLabelStyle;
} else
{
content = rcsgSkin.passThrough;
style = CSG_GUIStyleUtility.unselectedIconLabelStyle;
}
if (GUILayout.Button(content, style))
{
pressed = true;
}
TooltipUtility.SetToolTip(CSG_GUIStyleUtility.passThroughTooltip);
}
GUILayout.EndVertical();
GUI.color = oldColor;
return pressed;
}
public static Foundation.CSGOperationType ChooseOperation(Foundation.CSGOperationType operation, bool mixedValues)
{
CSG_GUIStyleUtility.InitStyles();
var rcsgSkin = CSG_GUIStyleUtility.Skin;
if (rcsgSkin == null)
return operation;
var oldColor = GUI.color;
GUI.color = Color.white;
GUILayout.BeginVertical();
try
{
GUIContent content;
GUIStyle style;
bool have_selection = !mixedValues && GUI.enabled;
for (int i = 0; i < CSG_GUIStyleUtility.operationTypeCount; i++)
{
if (!have_selection || (int)operation != i)
{
content = rcsgSkin.operationNames[i];
style = CSG_GUIStyleUtility.unselectedIconLabelStyle;
} else
{
content = rcsgSkin.operationNamesOn[i];
style = CSG_GUIStyleUtility.selectedIconLabelStyle;
}
if (content == null || style == null)
continue;
if (GUILayout.Button(content, style))
{
operation = (Foundation.CSGOperationType)i;
GUI.changed = true;
}
TooltipUtility.SetToolTip(CSG_GUIStyleUtility.operationTooltip[i]);
}
}
finally
{
GUILayout.EndVertical();
}
GUI.color = oldColor;
return operation;
}
static void CalcSize(ref Rect[] rects, out Rect bounds, out int xCount, GUIContent[] contents, float yOffset, float areaWidth = -1)
{
if (areaWidth <= 0)
areaWidth = EditorGUIUtility.currentViewWidth;
var position = new Rect();
if (rects == null ||
rects.Length != contents.Length)
rects = new Rect[contents.Length];
{
var skin = GUI.skin;
var buttonSkin = skin.button;
var textWidth = buttonSkin.CalcSize(contents[0]).x;
for (var i = 1; i < contents.Length; i++)
{
var width = buttonSkin.CalcSize(contents[i]).x;
if (width > textWidth)
textWidth = width;
}
var margin = buttonSkin.margin;
var padding = buttonSkin.padding;
var paddingWidth = padding.left + padding.right;
var minButtonWidth = textWidth + paddingWidth + margin.horizontal;
var screenWidth = areaWidth - margin.horizontal;
var countValue = Mathf.Clamp((screenWidth / minButtonWidth), 1, contents.Length);
xCount = Mathf.FloorToInt(countValue);
var realButtonWidth = (float)(screenWidth / xCount);
if (xCount == contents.Length)
realButtonWidth = (screenWidth / countValue);
position.x = 0;
position.y = yOffset;
position.width = realButtonWidth;
position.height = 15;
bounds = new Rect();
bounds.width = areaWidth;
xCount--;
int count = 0;
while (count < contents.Length)
{
position.y ++;
position.x = 2;
for (int x = 0; x <= xCount; x++)
{
position.x ++;
rects[count] = position;
position.x += realButtonWidth - 1;
count++;
if (count >= contents.Length)
break;
}
position.y += 16;
}
bounds.height = (position.y - yOffset);
}
}
public static int ToolbarWrapped(int selected, ref Rect[] rects, out Rect bounds, GUIContent[] contents, ToolTip[] tooltips = null, float yOffset = 0, float areaWidth = -1)
{
if (areaWidth <= 0)
areaWidth = EditorGUIUtility.currentViewWidth;
int xCount;
CalcSize(ref rects, out bounds, out xCount, contents, yOffset, areaWidth);
var leftStyle = EditorStyles.miniButtonLeft;
var middleStyle = EditorStyles.miniButtonMid;
var rightStyle = EditorStyles.miniButtonRight;
var singleStyle = EditorStyles.miniButton;
int count = 0;
while (count < contents.Length)
{
var last = Mathf.Min(xCount, contents.Length - 1 - count);
for (int x = 0; x <= xCount; x++)
{
GUIStyle style = (x > 0) ? ((x < last) ? middleStyle : rightStyle) : ((x < last) ? leftStyle : singleStyle);
if (GUI.Toggle(rects[count], selected == count, contents[count], style))//, buttonWidthLayout))
{
if (selected != count)
{
selected = count;
GUI.changed = true;
}
}
if (tooltips != null)
TooltipUtility.SetToolTip(tooltips[count], rects[count]);
count++;
if (count >= contents.Length)
break;
}
}
return selected;
}
internal const int materialSmallSize = 48;
internal const int materialLargeSize = 100;
[NonSerialized]
private static MaterialEditor materialEditor = null;
private static readonly GUILayoutOption materialSmallWidth = GUILayout.Width(materialSmallSize);
private static readonly GUILayoutOption materialSmallHeight = GUILayout.Height(materialSmallSize);
private static readonly GUILayoutOption materialLargeWidth = GUILayout.Width(materialLargeSize);
private static readonly GUILayoutOption materialLargeHeight = GUILayout.Height(materialLargeSize);
static Material GetDragMaterial()
{
if (DragAndDrop.objectReferences != null &&
DragAndDrop.objectReferences.Length > 0)
{
var dragMaterials = new List<Material>();
foreach (var obj in DragAndDrop.objectReferences)
{
var dragMaterial = obj as Material;
if (dragMaterial == null)
continue;
dragMaterials.Add(dragMaterial);
}
if (dragMaterials.Count == 1)
return dragMaterials[0];
}
return null;
}
public static Material MaterialImage(Material material, bool small = true)
{
var showMixedValue = EditorGUI.showMixedValue;
EditorGUI.showMixedValue = false;
var width = small ? materialSmallWidth : materialLargeWidth;
var height = small ? materialSmallHeight : materialLargeHeight;
GUILayout.BeginHorizontal(CSG_GUIStyleUtility.emptyMaterialStyle, width, height);
{
//if (!materialEditor || prevMaterial != material)
{
var editor = materialEditor as Editor;
Editor.CreateCachedEditor(material, typeof(MaterialEditor), ref editor);
materialEditor = editor as MaterialEditor;
//prevMaterial = material;
}
if (materialEditor)
{
var rect = GUILayoutUtility.GetRect(small ? materialSmallSize : materialLargeSize,
small ? materialSmallSize : materialLargeSize);
EditorGUI.showMixedValue = showMixedValue;
materialEditor.OnPreviewGUI(rect, GUIStyle.none);
EditorGUI.showMixedValue = false;
}
else
{
GUILayout.Box(new GUIContent(), CSG_GUIStyleUtility.emptyMaterialStyle, width, height);
}
}
GUILayout.EndHorizontal();
var currentArea = GUILayoutUtility.GetLastRect();
var currentPoint = Event.current.mousePosition;
if (currentArea.Contains(currentPoint))
{
if (Event.current.type == EventType.DragUpdated &&
GetDragMaterial() != null)
{
DragAndDrop.visualMode = DragAndDropVisualMode.Generic;
Event.current.Use();
}
if (Event.current.type == EventType.DragPerform)
{
var new_material = GetDragMaterial();
if (new_material != null)
{
material = new_material;
GUI.changed = true;
Event.current.Use();
return material;
}
}
}
return material;
}
public static void RepaintAll()
{
SceneView.RepaintAll();
}
static readonly GUIContent VectorXContent = new GUIContent("X");
static readonly GUIContent VectorYContent = new GUIContent("Y");
static readonly GUIContent VectorZContent = new GUIContent("Z");
static readonly float Width22Value = 22;
static readonly GUILayoutOption Width22 = GUILayout.Width(Width22Value);
public static float DistanceField(GUIContent label, float value, GUILayoutOption[] options = null)
{
bool modified = false;
var distanceUnit = RealtimeCSG.CSGSettings.DistanceUnit;
var nextUnit = Units.CycleToNextUnit(distanceUnit);
var unitText = Units.GetUnitGUIContent(distanceUnit);
float realValue = value;
EditorGUI.BeginChangeCheck();
{
value = Units.DistanceUnitToUnity(distanceUnit, EditorGUILayout.DoubleField(label, Units.UnityToDistanceUnit(distanceUnit, value), options));
}
if (EditorGUI.EndChangeCheck())
{
realValue = value; // don't want to introduce math errors unless we actually modify something
modified = true;
}
if (GUILayout.Button(unitText, EditorStyles.miniLabel, Width22))
{
distanceUnit = nextUnit;
RealtimeCSG.CSGSettings.DistanceUnit = distanceUnit;
RealtimeCSG.CSGSettings.UpdateSnapSettings();
RealtimeCSG.CSGSettings.Save();
RepaintAll();
}
GUI.changed = modified;
return realValue;
}
static GUIContent angleUnitLabel = new GUIContent("°");
public static Vector3 EulerDegreeField(Vector3 value, GUILayoutOption[] options = null)
{
bool modified = false;
const float vectorLabelWidth = 12;
var realValue = value;
var originalLabelWidth = EditorGUIUtility.labelWidth;
EditorGUIUtility.labelWidth = vectorLabelWidth;
GUILayout.BeginHorizontal();
{
EditorGUI.BeginChangeCheck();
{
value.x = EditorGUILayout.FloatField(VectorXContent, value.x, options);
}
if (EditorGUI.EndChangeCheck())
{
realValue.x = value.x; // don't want to introduce math errors unless we actually modify something
modified = true;
}
EditorGUI.BeginChangeCheck();
{
value.y = EditorGUILayout.FloatField(VectorYContent, value.y, options);
}
if (EditorGUI.EndChangeCheck())
{
realValue.y = value.y; // don't want to introduce math errors unless we actually modify something
modified = true;
}
EditorGUI.BeginChangeCheck();
{
value.z = EditorGUILayout.FloatField(VectorZContent, value.z, options);
}
if (EditorGUI.EndChangeCheck())
{
realValue.z = value.z; // don't want to introduce math errors unless we actually modify something
modified = true;
}
GUILayout.Label(angleUnitLabel, EditorStyles.miniLabel, Width22);
}
GUILayout.EndHorizontal();
EditorGUIUtility.labelWidth = originalLabelWidth;
GUI.changed = modified;
return realValue;
}
public static float DegreeField(GUIContent label, float value, GUILayoutOption[] options = null)
{
bool modified = false;
float realValue = value;
EditorGUI.BeginChangeCheck();
{
GUILayout.BeginHorizontal();
{
value = EditorGUILayout.FloatField(label, value, options);
GUILayout.Label(angleUnitLabel, EditorStyles.miniLabel, Width22);
}
GUILayout.EndHorizontal();
}
if (EditorGUI.EndChangeCheck())
{
realValue = value; // don't want to introduce math errors unless we actually modify something
modified = true;
}
GUI.changed = modified;
return realValue;
}
public static float DegreeField(float value, GUILayoutOption[] options = null)
{
return DegreeField(GUIContent.none, value, options);
}
public static Vector3 DistanceVector3Field(Vector3 value, bool multiLine, GUILayoutOption[] options = null)
{
var distanceUnit = RealtimeCSG.CSGSettings.DistanceUnit;
var nextUnit = Units.CycleToNextUnit(distanceUnit);
var unitText = Units.GetUnitGUIContent(distanceUnit);
bool modified = false;
bool clickedUnitButton = false;
var areaWidth = EditorGUIUtility.currentViewWidth;
const float minWidth = 65;
const float vectorLabelWidth = 12;
var allWidth = (12 * 3) + (Width22Value * 3) + (minWidth * 3);
Vector3 realValue = value;
multiLine = multiLine || (allWidth >= areaWidth);
if (multiLine)
GUILayout.BeginVertical();
var originalLabelWidth = EditorGUIUtility.labelWidth;
EditorGUIUtility.labelWidth = vectorLabelWidth;
GUILayout.BeginHorizontal();
{
EditorGUI.BeginChangeCheck();
{
value.x = Units.DistanceUnitToUnity(distanceUnit, EditorGUILayout.DoubleField(VectorXContent, Units.UnityToDistanceUnit(distanceUnit, value.x), options));
}
if (EditorGUI.EndChangeCheck())
{
realValue.x = value.x; // don't want to introduce math errors unless we actually modify something
modified = true;
}
if (multiLine)
clickedUnitButton = GUILayout.Button(unitText, EditorStyles.miniLabel, Width22) || clickedUnitButton;
if (multiLine)
{
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
}
EditorGUI.BeginChangeCheck();
{
value.y = Units.DistanceUnitToUnity(distanceUnit, EditorGUILayout.DoubleField(VectorYContent, Units.UnityToDistanceUnit(distanceUnit, value.y), options));
}
if (EditorGUI.EndChangeCheck())
{
realValue.y = value.y; // don't want to introduce math errors unless we actually modify something
modified = true;
}
if (multiLine)
clickedUnitButton = GUILayout.Button(unitText, EditorStyles.miniLabel, Width22) || clickedUnitButton;
if (multiLine)
{
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
}
EditorGUI.BeginChangeCheck();
{
value.z = Units.DistanceUnitToUnity(distanceUnit, EditorGUILayout.DoubleField(VectorZContent, Units.UnityToDistanceUnit(distanceUnit, value.z), options));
}
if (EditorGUI.EndChangeCheck())
{
realValue.z = value.z; // don't want to introduce math errors unless we actually modify something
modified = true;
}
clickedUnitButton = GUILayout.Button(unitText, EditorStyles.miniLabel, Width22) || clickedUnitButton;
}
GUILayout.EndHorizontal();
EditorGUIUtility.labelWidth = originalLabelWidth;
if (multiLine)
GUILayout.EndVertical();
if (clickedUnitButton)
{
distanceUnit = nextUnit;
RealtimeCSG.CSGSettings.DistanceUnit = distanceUnit;
RealtimeCSG.CSGSettings.UpdateSnapSettings();
RealtimeCSG.CSGSettings.Save();
RepaintAll();
}
GUI.changed = modified;
return realValue;
}
}
}
| 412 | 0.933268 | 1 | 0.933268 | game-dev | MEDIA | 0.553407 | game-dev | 0.984241 | 1 | 0.984241 |
EngineHub/WorldEdit | 2,265 | worldedit-core/src/main/java/com/sk89q/worldedit/world/chunk/PackedIntArrayReader.java | /*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.sk89q.worldedit.world.chunk;
import static com.google.common.base.Preconditions.checkElementIndex;
public class PackedIntArrayReader {
private static final int[] FACTORS = new int[64];
static {
FACTORS[0] = -1;
for (int i = 2; i <= 64; i++) {
FACTORS[i - 1] = (int) (Integer.toUnsignedLong(-1) / i);
}
}
private static final int SIZE = 4096;
private final long[] data;
private final int elementBits;
private final long maxValue;
private final int elementsPerLong;
private final int factor;
public PackedIntArrayReader(long[] data) {
this.data = data;
this.elementBits = data.length * 64 / 4096;
this.maxValue = (1L << elementBits) - 1L;
this.elementsPerLong = 64 / elementBits;
this.factor = FACTORS[elementsPerLong - 1];
int j = (SIZE + this.elementsPerLong - 1) / this.elementsPerLong;
if (j != data.length) {
throw new IllegalStateException("Invalid packed-int array provided, should be of length " + j);
}
}
public int get(int index) {
checkElementIndex(index, SIZE);
int i = this.adjustIndex(index);
long l = this.data[i];
int j = (index - i * this.elementsPerLong) * this.elementBits;
return (int) (l >> j & this.maxValue);
}
private int adjustIndex(int i) {
return (int) ((long) i * factor + factor >> 32);
}
}
| 412 | 0.908061 | 1 | 0.908061 | game-dev | MEDIA | 0.37713 | game-dev | 0.951496 | 1 | 0.951496 |
rovo89/android_art | 4,477 | test/079-phantom/src/Bitmap.java | /*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.lang.ref.ReferenceQueue;
import java.lang.ref.PhantomReference;
import java.util.ArrayList;
public class Bitmap {
String mName; /* for debugging */
int mWidth, mHeight;
Bitmap.NativeWrapper mNativeWrapper;
private static int sSerial = 100;
private static ArrayList sPhantomList = new ArrayList<PhantomWrapper>();
private static ReferenceQueue<PhantomWrapper> sPhantomQueue =
new ReferenceQueue<PhantomWrapper>();
private static BitmapWatcher sWatcher = new BitmapWatcher(sPhantomQueue);
static {
sWatcher.setDaemon(true);
sWatcher.start();
};
Bitmap(String name, int width, int height, Bitmap.NativeWrapper nativeData) {
mName = name;
mWidth = width;
mHeight = height;
mNativeWrapper = nativeData;
System.out.println("Created " + this);
}
public String toString() {
return "Bitmap " + mName + ": " + mWidth + "x" + mHeight + " (" +
mNativeWrapper.mNativeData + ")";
}
public void drawAt(int x, int y) {
System.out.println("Drawing " + this);
}
public static void shutDown() {
sWatcher.shutDown();
try {
sWatcher.join();
} catch (InterruptedException ie) {
System.out.println("join intr");
}
System.out.println("Bitmap has shut down");
}
/*
* Pretend we're allocating native storage. Just returns a unique
* serial number.
*/
static Bitmap.NativeWrapper allocNativeStorage(int width, int height) {
int nativeData;
synchronized (Bitmap.class) {
nativeData = sSerial++;
}
Bitmap.NativeWrapper wrapper = new Bitmap.NativeWrapper(nativeData);
PhantomWrapper phan = new PhantomWrapper(wrapper, sPhantomQueue,
nativeData);
sPhantomList.add(phan);
return wrapper;
}
static void freeNativeStorage(int nativeDataPtr) {
System.out.println("freeNativeStorage: " + nativeDataPtr);
}
/*
* Wraps a native data pointer in an object. When this object is no
* longer referenced, we free the native data.
*/
static class NativeWrapper {
public NativeWrapper(int nativeDataPtr) {
mNativeData = nativeDataPtr;
}
public int mNativeData;
/*
@Override
protected void finalize() throws Throwable {
System.out.println("finalized " + mNativeData);
}
*/
}
}
/*
* Keep an eye on the native data.
*
* We keep a copy of the native data pointer value, and set the wrapper
* as our referent. We need the copy because you can't get the referred-to
* object back out of a PhantomReference.
*/
class PhantomWrapper extends PhantomReference {
PhantomWrapper(Bitmap.NativeWrapper wrapper,
ReferenceQueue<PhantomWrapper> queue, int nativeDataPtr)
{
super(wrapper, queue);
mNativeData = nativeDataPtr;
}
public int mNativeData;
}
/*
* Thread that watches for un-referenced bitmap data.
*/
class BitmapWatcher extends Thread {
ReferenceQueue<PhantomWrapper> mQueue;
BitmapWatcher(ReferenceQueue<PhantomWrapper> queue) {
mQueue = queue;
setName("Bitmap Watcher");
}
public void run() {
while (true) {
try {
PhantomWrapper ref = (PhantomWrapper) mQueue.remove();
//System.out.println("dequeued ref " + ref.mNativeData +
// " - " + ref);
Bitmap.freeNativeStorage(ref.mNativeData);
//ref.clear();
} catch (InterruptedException ie) {
System.out.println("intr");
break;
}
}
}
public void shutDown() {
interrupt();
}
}
| 412 | 0.919821 | 1 | 0.919821 | game-dev | MEDIA | 0.503702 | game-dev | 0.950767 | 1 | 0.950767 |
eclipse-archived/ceylon | 4,825 | model/src/org/eclipse/ceylon/model/typechecker/model/FunctionOrValue.java | /********************************************************************************
* Copyright (c) 2011-2017 Red Hat Inc. and/or its affiliates and others
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* http://www.apache.org/licenses/LICENSE-2.0
*
* SPDX-License-Identifier: Apache-2.0
********************************************************************************/
package org.eclipse.ceylon.model.typechecker.model;
import static org.eclipse.ceylon.model.typechecker.model.DeclarationFlags.FunctionOrValueFlags.*;
import java.util.ArrayList;
import java.util.List;
public abstract class FunctionOrValue extends TypedDeclaration {
private Parameter initializerParameter;
private List<Declaration> members = new ArrayList<Declaration>(3);
private List<Annotation> annotations = new ArrayList<Annotation>(4);
private List<Declaration> overloads;
@Override
public List<Annotation> getAnnotations() {
return annotations;
}
@Override
public List<Declaration> getMembers() {
return members;
}
public void addMember(Declaration declaration) {
members.add(declaration);
}
public boolean isShortcutRefinement() {
return (flags&SHORTCUT_REFINEMENT)!=0;
}
public void setShortcutRefinement(boolean shortcutRefinement) {
if (shortcutRefinement) {
flags|=SHORTCUT_REFINEMENT;
}
else {
flags&=(~SHORTCUT_REFINEMENT);
}
}
@Override
public boolean isConstructor() {
return (flags&CONSTRUCTOR)!=0;
}
public void setConstructor(boolean constructor) {
if (constructor) {
flags|=CONSTRUCTOR;
}
else {
flags&=(~CONSTRUCTOR);
}
}
@Override
public DeclarationKind getDeclarationKind() {
return DeclarationKind.MEMBER;
}
public Parameter getInitializerParameter() {
return initializerParameter;
}
public void setInitializerParameter(Parameter d) {
initializerParameter = d;
}
@Override
public boolean isParameter() {
return initializerParameter!=null;
}
public boolean isTransient() {
return true;
}
@Override
public boolean isCaptured() {
return (flags&CAPTURED)!=0;
}
public void setCaptured(boolean captured) {
if (captured) {
flags|=CAPTURED;
}
else {
flags&=(~CAPTURED);
}
}
@Override
public boolean isJsCaptured() {
return (flags&JS_CAPTURED)!=0;
}
public void setJsCaptured(boolean captured) {
if (captured) {
flags|=JS_CAPTURED;
}
else {
flags&=(~JS_CAPTURED);
}
}
@Override
public boolean isOverloaded() {
return (flags&OVERLOADED)!=0;
}
public void setOverloaded(boolean overloaded) {
if (overloaded) {
flags|=OVERLOADED;
}
else {
flags&=(~OVERLOADED);
}
}
public void setAbstraction(boolean abstraction) {
if (abstraction) {
flags|=ABSTRACTION;
}
else {
flags&=(~ABSTRACTION);
}
}
@Override
public boolean isAbstraction() {
return (flags&ABSTRACTION)!=0;
}
@Override
public List<Declaration> getOverloads() {
return overloads;
}
public void setOverloads(List<Declaration> overloads) {
this.overloads = overloads;
}
public void initOverloads(FunctionOrValue... initial) {
overloads =
new ArrayList<Declaration>
(initial.length+1);
for (Declaration d: initial) {
overloads.add(d);
}
}
public boolean isImplemented() {
return (flags&IMPLEMENTED)!=0;
}
public void setImplemented(boolean implemented) {
if (implemented) {
flags|=IMPLEMENTED;
}
else {
flags&=(~IMPLEMENTED);
}
}
public void setSmall(boolean small) {
if (small) {
flags|=SMALL;
}
else {
flags&=(~SMALL);
}
}
public boolean isSmall() {
return (flags&SMALL)!=0;
}
public void setJavaNative(boolean b) {
if (b) {
flags|=JAVA_NATIVE;
}
else {
flags&=(~JAVA_NATIVE);
}
}
@Override
public boolean isJavaNative() {
return (flags&JAVA_NATIVE)!=0;
}
public FunctionOrValue getOriginalParameterDeclaration() {
return null;
}
}
| 412 | 0.785547 | 1 | 0.785547 | game-dev | MEDIA | 0.361629 | game-dev | 0.816018 | 1 | 0.816018 |
tccundari/HackSlashRPG-BZA | 2,619 | Hack and Slash/Assets/Standard Assets/Character Controllers/Sources/Scripts/PlatformInputController.js | // This makes the character turn to face the current movement speed per default.
var autoRotate : boolean = true;
var maxRotationSpeed : float = 360;
private var motor : CharacterMotor;
// Use this for initialization
function Awake () {
motor = GetComponent(CharacterMotor);
}
// Update is called once per frame
function Update () {
// Get the input vector from kayboard or analog stick
var directionVector = new Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"), 0);
if (directionVector != Vector3.zero) {
// Get the length of the directon vector and then normalize it
// Dividing by the length is cheaper than normalizing when we already have the length anyway
var directionLength = directionVector.magnitude;
directionVector = directionVector / directionLength;
// Make sure the length is no bigger than 1
directionLength = Mathf.Min(1, directionLength);
// Make the input vector more sensitive towards the extremes and less sensitive in the middle
// This makes it easier to control slow speeds when using analog sticks
directionLength = directionLength * directionLength;
// Multiply the normalized direction vector by the modified length
directionVector = directionVector * directionLength;
}
// Rotate the input vector into camera space so up is camera's up and right is camera's right
directionVector = Camera.main.transform.rotation * directionVector;
// Rotate input vector to be perpendicular to character's up vector
var camToCharacterSpace = Quaternion.FromToRotation(-Camera.main.transform.forward, transform.up);
directionVector = (camToCharacterSpace * directionVector);
// Apply the direction to the CharacterMotor
motor.inputMoveDirection = directionVector;
motor.inputJump = Input.GetButton("Jump");
// Set rotation to the move direction
if (autoRotate && directionVector.sqrMagnitude > 0.01) {
var newForward : Vector3 = ConstantSlerp(
transform.forward,
directionVector,
maxRotationSpeed * Time.deltaTime
);
newForward = ProjectOntoPlane(newForward, transform.up);
transform.rotation = Quaternion.LookRotation(newForward, transform.up);
}
}
function ProjectOntoPlane (v : Vector3, normal : Vector3) {
return v - Vector3.Project(v, normal);
}
function ConstantSlerp (from : Vector3, to : Vector3, angle : float) {
var value : float = Mathf.Min(1, angle / Vector3.Angle(from, to));
return Vector3.Slerp(from, to, value);
}
// Require a character controller to be attached to the same game object
@script RequireComponent (CharacterMotor)
@script AddComponentMenu ("Character/Platform Input Controller")
| 412 | 0.815823 | 1 | 0.815823 | game-dev | MEDIA | 0.87256 | game-dev | 0.986789 | 1 | 0.986789 |
GameFoundry/bsf | 5,078 | Source/Plugins/bsfPhysX/BsPhysXRigidbody.h | //************************************ bs::framework - Copyright 2018 Marko Pintera **************************************//
//*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********//
#pragma once
#include "BsPhysXPrerequisites.h"
#include "Physics/BsRigidbody.h"
#include "Math/BsVector3.h"
#include "Math/BsQuaternion.h"
#include "PxPhysics.h"
namespace bs
{
/** @addtogroup PhysX
* @{
*/
/** PhysX implementation of a Rigidbody. */
class PhysXRigidbody : public Rigidbody
{
public:
PhysXRigidbody(physx::PxPhysics* physx, physx::PxScene* scene, const HSceneObject& linkedSO);
~PhysXRigidbody();
/** @copydoc Rigidbody::move */
void move(const Vector3& position) override;
/** @copydoc Rigidbody::rotate */
void rotate(const Quaternion& rotation) override;
/** @copydoc Rigidbody::getPosition */
Vector3 getPosition() const override;
/** @copydoc Rigidbody::getRotation */
Quaternion getRotation() const override;
/** @copydoc Rigidbody::setTransform */
void setTransform(const Vector3& pos, const Quaternion& rot) override;
/** @copydoc Rigidbody::setMass */
void setMass(float mass) override;
/** @copydoc Rigidbody::getMass */
float getMass() const override;
/** @copydoc Rigidbody::setIsKinematic */
void setIsKinematic(bool kinematic) override;
/** @copydoc Rigidbody::getIsKinematic */
bool getIsKinematic() const override;
/** @copydoc Rigidbody::isSleeping */
bool isSleeping() const override;
/** @copydoc Rigidbody::sleep */
void sleep() override;
/** @copydoc Rigidbody::wakeUp */
void wakeUp() override;
/** @copydoc Rigidbody::setSleepThreshold */
void setSleepThreshold(float threshold) override;
/** @copydoc Rigidbody::getSleepThreshold */
float getSleepThreshold() const override;
/** @copydoc Rigidbody::setUseGravity */
void setUseGravity(bool gravity) override;
/** @copydoc Rigidbody::getUseGravity */
bool getUseGravity() const override;
/** @copydoc Rigidbody::setVelocity */
void setVelocity(const Vector3& velocity) override;
/** @copydoc Rigidbody::getVelocity */
Vector3 getVelocity() const override;
/** @copydoc Rigidbody::setAngularVelocity */
void setAngularVelocity(const Vector3& velocity) override;
/** @copydoc Rigidbody::getAngularVelocity */
Vector3 getAngularVelocity() const override;
/** @copydoc Rigidbody::setDrag */
void setDrag(float drag) override;
/** @copydoc Rigidbody::getDrag */
float getDrag() const override;
/** @copydoc Rigidbody::setAngularDrag */
void setAngularDrag(float drag) override;
/** @copydoc Rigidbody::getAngularDrag */
float getAngularDrag() const override;
/** @copydoc Rigidbody::setInertiaTensor */
void setInertiaTensor(const Vector3& tensor) override;
/** @copydoc Rigidbody::getInertiaTensor */
Vector3 getInertiaTensor() const override;
/** @copydoc Rigidbody::setMaxAngularVelocity */
void setMaxAngularVelocity(float maxVelocity) override;
/** @copydoc Rigidbody::getMaxAngularVelocity */
float getMaxAngularVelocity() const override;
/** @copydoc Rigidbody::setCenterOfMass */
void setCenterOfMass(const Vector3& position, const Quaternion& rotation) override;
/** @copydoc Rigidbody::getCenterOfMassPosition */
Vector3 getCenterOfMassPosition() const override;
/** @copydoc Rigidbody::getCenterOfMassRotation */
Quaternion getCenterOfMassRotation() const override;
/** @copydoc Rigidbody::setPositionSolverCount */
void setPositionSolverCount(UINT32 count) override;
/** @copydoc Rigidbody::getPositionSolverCount */
UINT32 getPositionSolverCount() const override;
/** @copydoc Rigidbody::setVelocitySolverCount */
void setVelocitySolverCount(UINT32 count) override;
/** @copydoc Rigidbody::getVelocitySolverCount */
UINT32 getVelocitySolverCount() const override;
/** @copydoc Rigidbody::setFlags */
void setFlags(RigidbodyFlag flags) override;
/** @copydoc Rigidbody::addForce */
void addForce(const Vector3& force, ForceMode mode = ForceMode::Force) override;
/** @copydoc Rigidbody::addTorque */
void addTorque(const Vector3& torque, ForceMode mode = ForceMode::Force) override;
/** @copydoc Rigidbody::addForceAtPoint */
void addForceAtPoint(const Vector3& force, const Vector3& position,
PointForceMode mode = PointForceMode::Force) override;
/** @copydoc Rigidbody::getVelocityAtPoint */
Vector3 getVelocityAtPoint(const Vector3& point) const override;
/** @copydoc Rigidbody::addCollider */
void addCollider(Collider* collider) override;
/** @copydoc Rigidbody::removeCollider */
void removeCollider(Collider* collider) override;
/** @copydoc Rigidbody::removeColliders */
void removeColliders() override;
/** @copydoc Rigidbody::updateMassDistribution */
void updateMassDistribution() override;
/** Returns the internal PhysX dynamic actor. */
physx::PxRigidDynamic* _getInternal() const { return mInternal; }
private:
physx::PxRigidDynamic* mInternal;
};
/** @} */
}
| 412 | 0.872477 | 1 | 0.872477 | game-dev | MEDIA | 0.85325 | game-dev | 0.584623 | 1 | 0.584623 |
SnowLeopardEngine/SnowLeopardEngine | 1,084 | Source/Runtime/include/SnowLeopardEngine/Core/Event/EventSystem.h | #pragma once
#include "SnowLeopardEngine/Core/Base/EngineSubSystem.h"
#include "SnowLeopardEngine/Core/Event/EventHandler.h"
namespace SnowLeopardEngine
{
using EventId = std::string;
using HandlerId = std::uint64_t;
class EventSystem final : public EngineSubSystem
{
public:
DECLARE_SUBSYSTEM(EventSystem)
void Subscribe(EventId eventId, Scope<IEventHandlerWrapper>&& handler, HandlerId handlerId);
void Unsubscribe(EventId eventId, const std::string& handlerName, HandlerId handlerId);
void TriggerEvent(const Event& e, HandlerId handlerId);
void QueueEvent(Scope<Event>&& e, HandlerId handlerId);
void DispatchEvents();
private:
std::vector<std::pair<Scope<Event>, HandlerId>> m_EventsQueue;
std::unordered_map<EventId, std::vector<Scope<IEventHandlerWrapper>>> m_Subscribers;
std::unordered_map<EventId, std::unordered_map<HandlerId, std::vector<Scope<IEventHandlerWrapper>>>>
m_SubscribersByHandlerId;
};
} // namespace SnowLeopardEngine
| 412 | 0.682474 | 1 | 0.682474 | game-dev | MEDIA | 0.284402 | game-dev | 0.575723 | 1 | 0.575723 |
davechurchill/ualbertabot | 2,070 | BOSS/source/DFBB_BuildOrderStackSearch.h | #pragma once
#include "Common.h"
#include "ActionType.h"
#include "DFBB_BuildOrderSearchResults.h"
#include "DFBB_BuildOrderSearchParameters.h"
#include "Timer.hpp"
#include "Tools.h"
#include "BuildOrder.h"
#define DFBB_TIMEOUT_EXCEPTION 1
namespace BOSS
{
class StackData
{
public:
size_t currentChildIndex;
GameState state;
ActionSet legalActions;
ActionType currentActionType;
UnitCountType repetitionValue;
UnitCountType completedRepetitions;
StackData()
: currentChildIndex(0)
, repetitionValue(1)
, completedRepetitions(0)
{
}
};
class DFBB_BuildOrderStackSearch
{
DFBB_BuildOrderSearchParameters _params; //parameters that will be used in this search
DFBB_BuildOrderSearchResults _results; //the results of the search so far
Timer _searchTimer;
BuildOrder _buildOrder;
std::vector<StackData> _stack;
size_t _depth;
bool _firstSearch;
bool _wasInterrupted;
void updateResults(const GameState & state);
bool isTimeOut();
void calculateRecursivePrerequisites(const ActionType & action, ActionSet & all);
void generateLegalActions(const GameState & state, ActionSet & legalActions);
std::vector<ActionType> getBuildOrder(GameState & state);
UnitCountType getRepetitions(const GameState & state, const ActionType & a);
ActionSet calculateRelevantActions();
public:
DFBB_BuildOrderStackSearch(const DFBB_BuildOrderSearchParameters & p);
void setTimeLimit(double ms);
void search();
const DFBB_BuildOrderSearchResults & getResults() const;
void DFBB();
};
} | 412 | 0.913919 | 1 | 0.913919 | game-dev | MEDIA | 0.948198 | game-dev | 0.710312 | 1 | 0.710312 |
SlimeKnights/TinkersConstruct | 6,991 | src/main/java/slimeknights/tconstruct/tools/modules/OverburnModule.java | package slimeknights.tconstruct.tools.modules;
import lombok.Getter;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.Tag;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraftforge.fluids.FluidStack;
import slimeknights.mantle.data.loadable.record.SingletonLoader;
import slimeknights.tconstruct.library.modifiers.Modifier;
import slimeknights.tconstruct.library.modifiers.ModifierEntry;
import slimeknights.tconstruct.library.modifiers.ModifierHooks;
import slimeknights.tconstruct.library.modifiers.hook.build.ModifierRemovalHook;
import slimeknights.tconstruct.library.modifiers.hook.interaction.InventoryTickModifierHook;
import slimeknights.tconstruct.library.modifiers.modules.ModifierModule;
import slimeknights.tconstruct.library.modifiers.modules.capacity.OverslimeModule;
import slimeknights.tconstruct.library.module.HookProvider;
import slimeknights.tconstruct.library.module.ModuleHook;
import slimeknights.tconstruct.library.recipe.fuel.MeltingFuel;
import slimeknights.tconstruct.library.recipe.fuel.MeltingFuelLookup;
import slimeknights.tconstruct.library.tools.capability.fluid.ToolTankHelper;
import slimeknights.tconstruct.library.tools.nbt.IToolStackView;
import slimeknights.tconstruct.library.tools.nbt.ModDataNBT;
import javax.annotation.Nullable;
import java.util.List;
/**
* Module implementing the overburn modifier.
* TODO 1.21: move to {@link slimeknights.tconstruct.tools.modules.durability}
*/
public enum OverburnModule implements ModifierModule, InventoryTickModifierHook, ModifierRemovalHook {
INSTANCE;
private static final List<ModuleHook<?>> DEFAULT_HOOKS = HookProvider.<OverburnModule>defaultHooks(ModifierHooks.INVENTORY_TICK, ModifierHooks.REMOVE);
@Getter
private final SingletonLoader<OverburnModule> loader = new SingletonLoader<>(this);
@Override
public List<ModuleHook<?>> getDefaultHooks() {
return DEFAULT_HOOKS;
}
@Nullable
@Override
public Component onRemoved(IToolStackView tool, Modifier modifier) {
tool.getPersistentData().remove(modifier.getId());
return null;
}
/**
* Keeps track of fuel consumed on the tool
* @param expiration Tick when this fuel info is discarded
* @param rate Fuel rate, gives more or less overslime
*/
private record FuelInfo(long expiration, int rate) {
private static final String EXPIRATION = "expiration";
private static final String RATE = "rate";
/** Reads the info from the tool */
@Nullable
public static FuelInfo read(IToolStackView tool, ResourceLocation location) {
ModDataNBT persistentData = tool.getPersistentData();
if (persistentData.contains(location, Tag.TAG_COMPOUND)) {
CompoundTag tag = persistentData.getCompound(location);
return new FuelInfo(tag.getLong(EXPIRATION), tag.getInt(RATE));
}
return null;
}
/** Writes the info to the tool */
public void write(IToolStackView tool, ResourceLocation location) {
CompoundTag tag = new CompoundTag();
tag.putLong(EXPIRATION, expiration);
tag.putInt(RATE, rate);
tool.getPersistentData().put(location, tag);
}
}
@Override
public void onInventoryTick(IToolStackView tool, ModifierEntry modifier, Level world, LivingEntity holder, int itemSlot, boolean isSelected, boolean isCorrectSlot, ItemStack stack) {
// overslime increases every 2^(4-level) seconds
// that is 1 per second at 4 levels, 1 per 8 seconds at 1 level
// we support max level 6, as that leaves us working with integers
int level = Math.min(modifier.getLevel(), 6);
int updateInterval = 5 << (6 - level);
// don't run if drawing back a bow, prevents losing animation
// does mean you may end up wasting some fuel, could be as much as 19 lost. So, don't hold your bows for 20 updates?
if (!world.isClientSide && holder.tickCount % updateInterval == 0 && holder.getUseItem() != stack) {
// must have overslime and space to fill
if (OverslimeModule.INSTANCE.getAmount(tool) < OverslimeModule.getCapacity(tool)) {
// find current fuel info
ResourceLocation key = modifier.getId();
FuelInfo info = FuelInfo.read(tool, key);
// if we have no fuel, try and find some
boolean neededFuel = info == null;
// since we will write this to NBT, use game time as that is global
long time = holder.level().getGameTime();
if (neededFuel || info.expiration < time) {
info = null;
FluidStack fluid = ToolTankHelper.TANK_HELPER.getFluid(tool);
if (!fluid.isEmpty()) {
MeltingFuel fuel = MeltingFuelLookup.findFuel(fluid.getFluid());
if (fuel != null) {
// scale amount consumed by level
int amount = fuel.getAmount(fluid.getFluid());
// scale up fuel duration so we always get the same amount of overslime per fuel bucket
// if we didn't do this, lower levels would consume way more than higher ones
// this works out to equivalent to the alloyer/melter at level 4
// note this does mean changing trait levels multiplies fuel efficiency, but the part swap costs more than just adding a slimeball so its fine
int duration = fuel.getDuration() * updateInterval / 5;
// if we don't have a full recipe, use what is left but scale down the duration
if (amount > fluid.getAmount()) {
ToolTankHelper.TANK_HELPER.setFluid(tool, FluidStack.EMPTY);
duration = duration * fluid.getAmount() / amount;
} else {
// if we have a complete recipe, just decrease fluid in the tank
fluid.shrink(amount);
ToolTankHelper.TANK_HELPER.setFluid(tool, fluid);
}
info = new FuelInfo(time + duration, fuel.getRate());
}
}
// store current fuel in NBT for next round if it will last
// no need to store if it will expire before our next update tick though
if (info != null && info.expiration >= time + updateInterval) {
info.write(tool, key);
} else if (!neededFuel) {
// no need to remove if we had nothing, saves some hash map modifications
tool.getPersistentData().remove(key);
}
}
// if we have fuel, increase overslime
if (info != null) {
// restore 1 per 10 rate. For the remainder, treat it as a chance
int restore = info.rate / 10;
int remainder = info.rate % 10;
if (remainder > 0 && Modifier.RANDOM.nextInt(10) < remainder) {
restore++;
}
OverslimeModule.INSTANCE.addAmount(tool, restore);
}
}
}
}
}
| 412 | 0.867835 | 1 | 0.867835 | game-dev | MEDIA | 0.979825 | game-dev | 0.96311 | 1 | 0.96311 |
erwincoumans/experiments | 36,250 | bullet2/BulletCollision/BroadphaseCollision/btDbvt.cpp | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
///btDbvt implementation by Nathanael Presson
#include "btDbvt.h"
//
typedef btAlignedObjectArray<btDbvtNode*> tNodeArray;
typedef btAlignedObjectArray<const btDbvtNode*> tConstNodeArray;
//
struct btDbvtNodeEnumerator : btDbvt::ICollide
{
tConstNodeArray nodes;
void Process(const btDbvtNode* n) { nodes.push_back(n); }
};
//
static DBVT_INLINE int indexof(const btDbvtNode* node)
{
return(node->parent->childs[1]==node);
}
//
static DBVT_INLINE btDbvtVolume merge( const btDbvtVolume& a,
const btDbvtVolume& b)
{
#if (DBVT_MERGE_IMPL==DBVT_IMPL_SSE)
ATTRIBUTE_ALIGNED16(char locals[sizeof(btDbvtAabbMm)]);
btDbvtVolume& res=*(btDbvtVolume*)locals;
#else
btDbvtVolume res;
#endif
Merge(a,b,res);
return(res);
}
// volume+edge lengths
static DBVT_INLINE btScalar size(const btDbvtVolume& a)
{
const btVector3 edges=a.Lengths();
return( edges.x()*edges.y()*edges.z()+
edges.x()+edges.y()+edges.z());
}
//
static void getmaxdepth(const btDbvtNode* node,int depth,int& maxdepth)
{
if(node->isinternal())
{
getmaxdepth(node->childs[0],depth+1,maxdepth);
getmaxdepth(node->childs[1],depth+1,maxdepth);
} else maxdepth=btMax(maxdepth,depth);
}
//
static DBVT_INLINE void deletenode( btDbvt* pdbvt,
btDbvtNode* node)
{
btAlignedFree(pdbvt->m_free);
pdbvt->m_free=node;
}
//
static void recursedeletenode( btDbvt* pdbvt,
btDbvtNode* node)
{
if(!node->isleaf())
{
recursedeletenode(pdbvt,node->childs[0]);
recursedeletenode(pdbvt,node->childs[1]);
}
if(node==pdbvt->m_root) pdbvt->m_root=0;
deletenode(pdbvt,node);
}
//
static DBVT_INLINE btDbvtNode* createnode( btDbvt* pdbvt,
btDbvtNode* parent,
void* data)
{
btDbvtNode* node;
if(pdbvt->m_free)
{ node=pdbvt->m_free;pdbvt->m_free=0; }
else
{ node=new(btAlignedAlloc(sizeof(btDbvtNode),16)) btDbvtNode(); }
node->parent = parent;
node->data = data;
node->childs[1] = 0;
return(node);
}
//
static DBVT_INLINE btDbvtNode* createnode( btDbvt* pdbvt,
btDbvtNode* parent,
const btDbvtVolume& volume,
void* data)
{
btDbvtNode* node=createnode(pdbvt,parent,data);
node->volume=volume;
return(node);
}
//
static DBVT_INLINE btDbvtNode* createnode( btDbvt* pdbvt,
btDbvtNode* parent,
const btDbvtVolume& volume0,
const btDbvtVolume& volume1,
void* data)
{
btDbvtNode* node=createnode(pdbvt,parent,data);
Merge(volume0,volume1,node->volume);
return(node);
}
//
static void insertleaf( btDbvt* pdbvt,
btDbvtNode* root,
btDbvtNode* leaf)
{
if(!pdbvt->m_root)
{
pdbvt->m_root = leaf;
leaf->parent = 0;
}
else
{
if(!root->isleaf())
{
do {
root=root->childs[Select( leaf->volume,
root->childs[0]->volume,
root->childs[1]->volume)];
} while(!root->isleaf());
}
btDbvtNode* prev=root->parent;
btDbvtNode* node=createnode(pdbvt,prev,leaf->volume,root->volume,0);
if(prev)
{
prev->childs[indexof(root)] = node;
node->childs[0] = root;root->parent=node;
node->childs[1] = leaf;leaf->parent=node;
do {
if(!prev->volume.Contain(node->volume))
Merge(prev->childs[0]->volume,prev->childs[1]->volume,prev->volume);
else
break;
node=prev;
} while(0!=(prev=node->parent));
}
else
{
node->childs[0] = root;root->parent=node;
node->childs[1] = leaf;leaf->parent=node;
pdbvt->m_root = node;
}
}
}
//
static btDbvtNode* removeleaf( btDbvt* pdbvt,
btDbvtNode* leaf)
{
if(leaf==pdbvt->m_root)
{
pdbvt->m_root=0;
return(0);
}
else
{
btDbvtNode* parent=leaf->parent;
btDbvtNode* prev=parent->parent;
btDbvtNode* sibling=parent->childs[1-indexof(leaf)];
if(prev)
{
prev->childs[indexof(parent)]=sibling;
sibling->parent=prev;
deletenode(pdbvt,parent);
while(prev)
{
const btDbvtVolume pb=prev->volume;
Merge(prev->childs[0]->volume,prev->childs[1]->volume,prev->volume);
if(NotEqual(pb,prev->volume))
{
prev=prev->parent;
} else break;
}
return(prev?prev:pdbvt->m_root);
}
else
{
pdbvt->m_root=sibling;
sibling->parent=0;
deletenode(pdbvt,parent);
return(pdbvt->m_root);
}
}
}
//
static void fetchleaves(btDbvt* pdbvt,
btDbvtNode* root,
tNodeArray& leaves,
int depth=-1)
{
if(root->isinternal()&&depth)
{
fetchleaves(pdbvt,root->childs[0],leaves,depth-1);
fetchleaves(pdbvt,root->childs[1],leaves,depth-1);
deletenode(pdbvt,root);
}
else
{
leaves.push_back(root);
}
}
//
static void split( const tNodeArray& leaves,
tNodeArray& left,
tNodeArray& right,
const btVector3& org,
const btVector3& axis)
{
left.resize(0);
right.resize(0);
for(int i=0,ni=leaves.size();i<ni;++i)
{
if(btDot(axis,leaves[i]->volume.Center()-org)<0)
left.push_back(leaves[i]);
else
right.push_back(leaves[i]);
}
}
//
static btDbvtVolume bounds( const tNodeArray& leaves)
{
#if DBVT_MERGE_IMPL==DBVT_IMPL_SSE
ATTRIBUTE_ALIGNED16(char locals[sizeof(btDbvtVolume)]);
btDbvtVolume& volume=*(btDbvtVolume*)locals;
volume=leaves[0]->volume;
#else
btDbvtVolume volume=leaves[0]->volume;
#endif
for(int i=1,ni=leaves.size();i<ni;++i)
{
Merge(volume,leaves[i]->volume,volume);
}
return(volume);
}
//
static void bottomup( btDbvt* pdbvt,
tNodeArray& leaves)
{
while(leaves.size()>1)
{
btScalar minsize=SIMD_INFINITY;
int minidx[2]={-1,-1};
for(int i=0;i<leaves.size();++i)
{
for(int j=i+1;j<leaves.size();++j)
{
const btScalar sz=size(merge(leaves[i]->volume,leaves[j]->volume));
if(sz<minsize)
{
minsize = sz;
minidx[0] = i;
minidx[1] = j;
}
}
}
btDbvtNode* n[] = {leaves[minidx[0]],leaves[minidx[1]]};
btDbvtNode* p = createnode(pdbvt,0,n[0]->volume,n[1]->volume,0);
p->childs[0] = n[0];
p->childs[1] = n[1];
n[0]->parent = p;
n[1]->parent = p;
leaves[minidx[0]] = p;
leaves.swap(minidx[1],leaves.size()-1);
leaves.pop_back();
}
}
//
static btDbvtNode* topdown(btDbvt* pdbvt,
tNodeArray& leaves,
int bu_treshold)
{
static const btVector3 axis[]={btVector3(1,0,0),
btVector3(0,1,0),
btVector3(0,0,1)};
if(leaves.size()>1)
{
if(leaves.size()>bu_treshold)
{
const btDbvtVolume vol=bounds(leaves);
const btVector3 org=vol.Center();
tNodeArray sets[2];
int bestaxis=-1;
int bestmidp=leaves.size();
int splitcount[3][2]={{0,0},{0,0},{0,0}};
int i;
for( i=0;i<leaves.size();++i)
{
const btVector3 x=leaves[i]->volume.Center()-org;
for(int j=0;j<3;++j)
{
++splitcount[j][btDot(x,axis[j])>0?1:0];
}
}
for( i=0;i<3;++i)
{
if((splitcount[i][0]>0)&&(splitcount[i][1]>0))
{
const int midp=(int)btFabs(btScalar(splitcount[i][0]-splitcount[i][1]));
if(midp<bestmidp)
{
bestaxis=i;
bestmidp=midp;
}
}
}
if(bestaxis>=0)
{
sets[0].reserve(splitcount[bestaxis][0]);
sets[1].reserve(splitcount[bestaxis][1]);
split(leaves,sets[0],sets[1],org,axis[bestaxis]);
}
else
{
sets[0].reserve(leaves.size()/2+1);
sets[1].reserve(leaves.size()/2);
for(int i=0,ni=leaves.size();i<ni;++i)
{
sets[i&1].push_back(leaves[i]);
}
}
btDbvtNode* node=createnode(pdbvt,0,vol,0);
node->childs[0]=topdown(pdbvt,sets[0],bu_treshold);
node->childs[1]=topdown(pdbvt,sets[1],bu_treshold);
node->childs[0]->parent=node;
node->childs[1]->parent=node;
return(node);
}
else
{
bottomup(pdbvt,leaves);
return(leaves[0]);
}
}
return(leaves[0]);
}
//
static DBVT_INLINE btDbvtNode* sort(btDbvtNode* n,btDbvtNode*& r)
{
btDbvtNode* p=n->parent;
btAssert(n->isinternal());
if(p>n)
{
const int i=indexof(n);
const int j=1-i;
btDbvtNode* s=p->childs[j];
btDbvtNode* q=p->parent;
btAssert(n==p->childs[i]);
if(q) q->childs[indexof(p)]=n; else r=n;
s->parent=n;
p->parent=n;
n->parent=q;
p->childs[0]=n->childs[0];
p->childs[1]=n->childs[1];
n->childs[0]->parent=p;
n->childs[1]->parent=p;
n->childs[i]=p;
n->childs[j]=s;
btSwap(p->volume,n->volume);
return(p);
}
return(n);
}
#if 0
static DBVT_INLINE btDbvtNode* walkup(btDbvtNode* n,int count)
{
while(n&&(count--)) n=n->parent;
return(n);
}
#endif
//
// Api
//
//
btDbvt::btDbvt()
{
m_root = 0;
m_free = 0;
m_lkhd = -1;
m_leaves = 0;
m_opath = 0;
}
//
btDbvt::~btDbvt()
{
clear();
}
//
void btDbvt::clear()
{
if(m_root)
recursedeletenode(this,m_root);
btAlignedFree(m_free);
m_free=0;
m_lkhd = -1;
m_stkStack.clear();
m_opath = 0;
}
//
void btDbvt::optimizeBottomUp()
{
if(m_root)
{
tNodeArray leaves;
leaves.reserve(m_leaves);
fetchleaves(this,m_root,leaves);
bottomup(this,leaves);
m_root=leaves[0];
}
}
//
void btDbvt::optimizeTopDown(int bu_treshold)
{
if(m_root)
{
tNodeArray leaves;
leaves.reserve(m_leaves);
fetchleaves(this,m_root,leaves);
m_root=topdown(this,leaves,bu_treshold);
}
}
//
void btDbvt::optimizeIncremental(int passes)
{
if(passes<0) passes=m_leaves;
if(m_root&&(passes>0))
{
do {
btDbvtNode* node=m_root;
unsigned bit=0;
while(node->isinternal())
{
node=sort(node,m_root)->childs[(m_opath>>bit)&1];
bit=(bit+1)&(sizeof(unsigned)*8-1);
}
update(node);
++m_opath;
} while(--passes);
}
}
//
btDbvtNode* btDbvt::insert(const btDbvtVolume& volume,void* data)
{
btDbvtNode* leaf=createnode(this,0,volume,data);
insertleaf(this,m_root,leaf);
++m_leaves;
return(leaf);
}
//
void btDbvt::update(btDbvtNode* leaf,int lookahead)
{
btDbvtNode* root=removeleaf(this,leaf);
if(root)
{
if(lookahead>=0)
{
for(int i=0;(i<lookahead)&&root->parent;++i)
{
root=root->parent;
}
} else root=m_root;
}
insertleaf(this,root,leaf);
}
//
void btDbvt::update(btDbvtNode* leaf,btDbvtVolume& volume)
{
btDbvtNode* root=removeleaf(this,leaf);
if(root)
{
if(m_lkhd>=0)
{
for(int i=0;(i<m_lkhd)&&root->parent;++i)
{
root=root->parent;
}
} else root=m_root;
}
leaf->volume=volume;
insertleaf(this,root,leaf);
}
//
bool btDbvt::update(btDbvtNode* leaf,btDbvtVolume& volume,const btVector3& velocity,btScalar margin)
{
if(leaf->volume.Contain(volume)) return(false);
volume.Expand(btVector3(margin,margin,margin));
volume.SignedExpand(velocity);
update(leaf,volume);
return(true);
}
//
bool btDbvt::update(btDbvtNode* leaf,btDbvtVolume& volume,const btVector3& velocity)
{
if(leaf->volume.Contain(volume)) return(false);
volume.SignedExpand(velocity);
update(leaf,volume);
return(true);
}
//
bool btDbvt::update(btDbvtNode* leaf,btDbvtVolume& volume,btScalar margin)
{
if(leaf->volume.Contain(volume)) return(false);
volume.Expand(btVector3(margin,margin,margin));
update(leaf,volume);
return(true);
}
//
void btDbvt::remove(btDbvtNode* leaf)
{
removeleaf(this,leaf);
deletenode(this,leaf);
--m_leaves;
}
//
void btDbvt::write(IWriter* iwriter) const
{
btDbvtNodeEnumerator nodes;
nodes.nodes.reserve(m_leaves*2);
enumNodes(m_root,nodes);
iwriter->Prepare(m_root,nodes.nodes.size());
for(int i=0;i<nodes.nodes.size();++i)
{
const btDbvtNode* n=nodes.nodes[i];
int p=-1;
if(n->parent) p=nodes.nodes.findLinearSearch(n->parent);
if(n->isinternal())
{
const int c0=nodes.nodes.findLinearSearch(n->childs[0]);
const int c1=nodes.nodes.findLinearSearch(n->childs[1]);
iwriter->WriteNode(n,i,p,c0,c1);
}
else
{
iwriter->WriteLeaf(n,i,p);
}
}
}
//
void btDbvt::clone(btDbvt& dest,IClone* iclone) const
{
dest.clear();
if(m_root!=0)
{
btAlignedObjectArray<sStkCLN> stack;
stack.reserve(m_leaves);
stack.push_back(sStkCLN(m_root,0));
do {
const int i=stack.size()-1;
const sStkCLN e=stack[i];
btDbvtNode* n=createnode(&dest,e.parent,e.node->volume,e.node->data);
stack.pop_back();
if(e.parent!=0)
e.parent->childs[i&1]=n;
else
dest.m_root=n;
if(e.node->isinternal())
{
stack.push_back(sStkCLN(e.node->childs[0],n));
stack.push_back(sStkCLN(e.node->childs[1],n));
}
else
{
iclone->CloneLeaf(n);
}
} while(stack.size()>0);
}
}
//
int btDbvt::maxdepth(const btDbvtNode* node)
{
int depth=0;
if(node) getmaxdepth(node,1,depth);
return(depth);
}
//
int btDbvt::countLeaves(const btDbvtNode* node)
{
if(node->isinternal())
return(countLeaves(node->childs[0])+countLeaves(node->childs[1]));
else
return(1);
}
//
void btDbvt::extractLeaves(const btDbvtNode* node,btAlignedObjectArray<const btDbvtNode*>& leaves)
{
if(node->isinternal())
{
extractLeaves(node->childs[0],leaves);
extractLeaves(node->childs[1],leaves);
}
else
{
leaves.push_back(node);
}
}
//
#if DBVT_ENABLE_BENCHMARK
#include <stdio.h>
#include <stdlib.h>
#include "LinearMath/btQuickProf.h"
/*
q6600,2.4ghz
/Ox /Ob2 /Oi /Ot /I "." /I "..\.." /I "..\..\src" /D "NDEBUG" /D "_LIB" /D "_WINDOWS" /D "_CRT_SECURE_NO_DEPRECATE" /D "_CRT_NONSTDC_NO_DEPRECATE" /D "WIN32"
/GF /FD /MT /GS- /Gy /arch:SSE2 /Zc:wchar_t- /Fp"..\..\out\release8\build\libbulletcollision\libbulletcollision.pch"
/Fo"..\..\out\release8\build\libbulletcollision\\"
/Fd"..\..\out\release8\build\libbulletcollision\bulletcollision.pdb"
/W3 /nologo /c /Wp64 /Zi /errorReport:prompt
Benchmarking dbvt...
World scale: 100.000000
Extents base: 1.000000
Extents range: 4.000000
Leaves: 8192
sizeof(btDbvtVolume): 32 bytes
sizeof(btDbvtNode): 44 bytes
[1] btDbvtVolume intersections: 3499 ms (-1%)
[2] btDbvtVolume merges: 1934 ms (0%)
[3] btDbvt::collideTT: 5485 ms (-21%)
[4] btDbvt::collideTT self: 2814 ms (-20%)
[5] btDbvt::collideTT xform: 7379 ms (-1%)
[6] btDbvt::collideTT xform,self: 7270 ms (-2%)
[7] btDbvt::rayTest: 6314 ms (0%),(332143 r/s)
[8] insert/remove: 2093 ms (0%),(1001983 ir/s)
[9] updates (teleport): 1879 ms (-3%),(1116100 u/s)
[10] updates (jitter): 1244 ms (-4%),(1685813 u/s)
[11] optimize (incremental): 2514 ms (0%),(1668000 o/s)
[12] btDbvtVolume notequal: 3659 ms (0%)
[13] culling(OCL+fullsort): 2218 ms (0%),(461 t/s)
[14] culling(OCL+qsort): 3688 ms (5%),(2221 t/s)
[15] culling(KDOP+qsort): 1139 ms (-1%),(7192 t/s)
[16] insert/remove batch(256): 5092 ms (0%),(823704 bir/s)
[17] btDbvtVolume select: 3419 ms (0%)
*/
struct btDbvtBenchmark
{
struct NilPolicy : btDbvt::ICollide
{
NilPolicy() : m_pcount(0),m_depth(-SIMD_INFINITY),m_checksort(true) {}
void Process(const btDbvtNode*,const btDbvtNode*) { ++m_pcount; }
void Process(const btDbvtNode*) { ++m_pcount; }
void Process(const btDbvtNode*,btScalar depth)
{
++m_pcount;
if(m_checksort)
{ if(depth>=m_depth) m_depth=depth; else printf("wrong depth: %f (should be >= %f)\r\n",depth,m_depth); }
}
int m_pcount;
btScalar m_depth;
bool m_checksort;
};
struct P14 : btDbvt::ICollide
{
struct Node
{
const btDbvtNode* leaf;
btScalar depth;
};
void Process(const btDbvtNode* leaf,btScalar depth)
{
Node n;
n.leaf = leaf;
n.depth = depth;
}
static int sortfnc(const Node& a,const Node& b)
{
if(a.depth<b.depth) return(+1);
if(a.depth>b.depth) return(-1);
return(0);
}
btAlignedObjectArray<Node> m_nodes;
};
struct P15 : btDbvt::ICollide
{
struct Node
{
const btDbvtNode* leaf;
btScalar depth;
};
void Process(const btDbvtNode* leaf)
{
Node n;
n.leaf = leaf;
n.depth = dot(leaf->volume.Center(),m_axis);
}
static int sortfnc(const Node& a,const Node& b)
{
if(a.depth<b.depth) return(+1);
if(a.depth>b.depth) return(-1);
return(0);
}
btAlignedObjectArray<Node> m_nodes;
btVector3 m_axis;
};
static btScalar RandUnit()
{
return(rand()/(btScalar)RAND_MAX);
}
static btVector3 RandVector3()
{
return(btVector3(RandUnit(),RandUnit(),RandUnit()));
}
static btVector3 RandVector3(btScalar cs)
{
return(RandVector3()*cs-btVector3(cs,cs,cs)/2);
}
static btDbvtVolume RandVolume(btScalar cs,btScalar eb,btScalar es)
{
return(btDbvtVolume::FromCE(RandVector3(cs),btVector3(eb,eb,eb)+RandVector3()*es));
}
static btTransform RandTransform(btScalar cs)
{
btTransform t;
t.setOrigin(RandVector3(cs));
t.setRotation(btQuaternion(RandUnit()*SIMD_PI*2,RandUnit()*SIMD_PI*2,RandUnit()*SIMD_PI*2).normalized());
return(t);
}
static void RandTree(btScalar cs,btScalar eb,btScalar es,int leaves,btDbvt& dbvt)
{
dbvt.clear();
for(int i=0;i<leaves;++i)
{
dbvt.insert(RandVolume(cs,eb,es),0);
}
}
};
void btDbvt::benchmark()
{
static const btScalar cfgVolumeCenterScale = 100;
static const btScalar cfgVolumeExentsBase = 1;
static const btScalar cfgVolumeExentsScale = 4;
static const int cfgLeaves = 8192;
static const bool cfgEnable = true;
//[1] btDbvtVolume intersections
bool cfgBenchmark1_Enable = cfgEnable;
static const int cfgBenchmark1_Iterations = 8;
static const int cfgBenchmark1_Reference = 3499;
//[2] btDbvtVolume merges
bool cfgBenchmark2_Enable = cfgEnable;
static const int cfgBenchmark2_Iterations = 4;
static const int cfgBenchmark2_Reference = 1945;
//[3] btDbvt::collideTT
bool cfgBenchmark3_Enable = cfgEnable;
static const int cfgBenchmark3_Iterations = 512;
static const int cfgBenchmark3_Reference = 5485;
//[4] btDbvt::collideTT self
bool cfgBenchmark4_Enable = cfgEnable;
static const int cfgBenchmark4_Iterations = 512;
static const int cfgBenchmark4_Reference = 2814;
//[5] btDbvt::collideTT xform
bool cfgBenchmark5_Enable = cfgEnable;
static const int cfgBenchmark5_Iterations = 512;
static const btScalar cfgBenchmark5_OffsetScale = 2;
static const int cfgBenchmark5_Reference = 7379;
//[6] btDbvt::collideTT xform,self
bool cfgBenchmark6_Enable = cfgEnable;
static const int cfgBenchmark6_Iterations = 512;
static const btScalar cfgBenchmark6_OffsetScale = 2;
static const int cfgBenchmark6_Reference = 7270;
//[7] btDbvt::rayTest
bool cfgBenchmark7_Enable = cfgEnable;
static const int cfgBenchmark7_Passes = 32;
static const int cfgBenchmark7_Iterations = 65536;
static const int cfgBenchmark7_Reference = 6307;
//[8] insert/remove
bool cfgBenchmark8_Enable = cfgEnable;
static const int cfgBenchmark8_Passes = 32;
static const int cfgBenchmark8_Iterations = 65536;
static const int cfgBenchmark8_Reference = 2105;
//[9] updates (teleport)
bool cfgBenchmark9_Enable = cfgEnable;
static const int cfgBenchmark9_Passes = 32;
static const int cfgBenchmark9_Iterations = 65536;
static const int cfgBenchmark9_Reference = 1879;
//[10] updates (jitter)
bool cfgBenchmark10_Enable = cfgEnable;
static const btScalar cfgBenchmark10_Scale = cfgVolumeCenterScale/10000;
static const int cfgBenchmark10_Passes = 32;
static const int cfgBenchmark10_Iterations = 65536;
static const int cfgBenchmark10_Reference = 1244;
//[11] optimize (incremental)
bool cfgBenchmark11_Enable = cfgEnable;
static const int cfgBenchmark11_Passes = 64;
static const int cfgBenchmark11_Iterations = 65536;
static const int cfgBenchmark11_Reference = 2510;
//[12] btDbvtVolume notequal
bool cfgBenchmark12_Enable = cfgEnable;
static const int cfgBenchmark12_Iterations = 32;
static const int cfgBenchmark12_Reference = 3677;
//[13] culling(OCL+fullsort)
bool cfgBenchmark13_Enable = cfgEnable;
static const int cfgBenchmark13_Iterations = 1024;
static const int cfgBenchmark13_Reference = 2231;
//[14] culling(OCL+qsort)
bool cfgBenchmark14_Enable = cfgEnable;
static const int cfgBenchmark14_Iterations = 8192;
static const int cfgBenchmark14_Reference = 3500;
//[15] culling(KDOP+qsort)
bool cfgBenchmark15_Enable = cfgEnable;
static const int cfgBenchmark15_Iterations = 8192;
static const int cfgBenchmark15_Reference = 1151;
//[16] insert/remove batch
bool cfgBenchmark16_Enable = cfgEnable;
static const int cfgBenchmark16_BatchCount = 256;
static const int cfgBenchmark16_Passes = 16384;
static const int cfgBenchmark16_Reference = 5138;
//[17] select
bool cfgBenchmark17_Enable = cfgEnable;
static const int cfgBenchmark17_Iterations = 4;
static const int cfgBenchmark17_Reference = 3390;
btClock wallclock;
printf("Benchmarking dbvt...\r\n");
printf("\tWorld scale: %f\r\n",cfgVolumeCenterScale);
printf("\tExtents base: %f\r\n",cfgVolumeExentsBase);
printf("\tExtents range: %f\r\n",cfgVolumeExentsScale);
printf("\tLeaves: %u\r\n",cfgLeaves);
printf("\tsizeof(btDbvtVolume): %u bytes\r\n",sizeof(btDbvtVolume));
printf("\tsizeof(btDbvtNode): %u bytes\r\n",sizeof(btDbvtNode));
if(cfgBenchmark1_Enable)
{// Benchmark 1
srand(380843);
btAlignedObjectArray<btDbvtVolume> volumes;
btAlignedObjectArray<bool> results;
volumes.resize(cfgLeaves);
results.resize(cfgLeaves);
for(int i=0;i<cfgLeaves;++i)
{
volumes[i]=btDbvtBenchmark::RandVolume(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale);
}
printf("[1] btDbvtVolume intersections: ");
wallclock.reset();
for(int i=0;i<cfgBenchmark1_Iterations;++i)
{
for(int j=0;j<cfgLeaves;++j)
{
for(int k=0;k<cfgLeaves;++k)
{
results[k]=Intersect(volumes[j],volumes[k]);
}
}
}
const int time=(int)wallclock.getTimeMilliseconds();
printf("%u ms (%i%%)\r\n",time,(time-cfgBenchmark1_Reference)*100/time);
}
if(cfgBenchmark2_Enable)
{// Benchmark 2
srand(380843);
btAlignedObjectArray<btDbvtVolume> volumes;
btAlignedObjectArray<btDbvtVolume> results;
volumes.resize(cfgLeaves);
results.resize(cfgLeaves);
for(int i=0;i<cfgLeaves;++i)
{
volumes[i]=btDbvtBenchmark::RandVolume(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale);
}
printf("[2] btDbvtVolume merges: ");
wallclock.reset();
for(int i=0;i<cfgBenchmark2_Iterations;++i)
{
for(int j=0;j<cfgLeaves;++j)
{
for(int k=0;k<cfgLeaves;++k)
{
Merge(volumes[j],volumes[k],results[k]);
}
}
}
const int time=(int)wallclock.getTimeMilliseconds();
printf("%u ms (%i%%)\r\n",time,(time-cfgBenchmark2_Reference)*100/time);
}
if(cfgBenchmark3_Enable)
{// Benchmark 3
srand(380843);
btDbvt dbvt[2];
btDbvtBenchmark::NilPolicy policy;
btDbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt[0]);
btDbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt[1]);
dbvt[0].optimizeTopDown();
dbvt[1].optimizeTopDown();
printf("[3] btDbvt::collideTT: ");
wallclock.reset();
for(int i=0;i<cfgBenchmark3_Iterations;++i)
{
btDbvt::collideTT(dbvt[0].m_root,dbvt[1].m_root,policy);
}
const int time=(int)wallclock.getTimeMilliseconds();
printf("%u ms (%i%%)\r\n",time,(time-cfgBenchmark3_Reference)*100/time);
}
if(cfgBenchmark4_Enable)
{// Benchmark 4
srand(380843);
btDbvt dbvt;
btDbvtBenchmark::NilPolicy policy;
btDbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt);
dbvt.optimizeTopDown();
printf("[4] btDbvt::collideTT self: ");
wallclock.reset();
for(int i=0;i<cfgBenchmark4_Iterations;++i)
{
btDbvt::collideTT(dbvt.m_root,dbvt.m_root,policy);
}
const int time=(int)wallclock.getTimeMilliseconds();
printf("%u ms (%i%%)\r\n",time,(time-cfgBenchmark4_Reference)*100/time);
}
if(cfgBenchmark5_Enable)
{// Benchmark 5
srand(380843);
btDbvt dbvt[2];
btAlignedObjectArray<btTransform> transforms;
btDbvtBenchmark::NilPolicy policy;
transforms.resize(cfgBenchmark5_Iterations);
for(int i=0;i<transforms.size();++i)
{
transforms[i]=btDbvtBenchmark::RandTransform(cfgVolumeCenterScale*cfgBenchmark5_OffsetScale);
}
btDbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt[0]);
btDbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt[1]);
dbvt[0].optimizeTopDown();
dbvt[1].optimizeTopDown();
printf("[5] btDbvt::collideTT xform: ");
wallclock.reset();
for(int i=0;i<cfgBenchmark5_Iterations;++i)
{
btDbvt::collideTT(dbvt[0].m_root,dbvt[1].m_root,transforms[i],policy);
}
const int time=(int)wallclock.getTimeMilliseconds();
printf("%u ms (%i%%)\r\n",time,(time-cfgBenchmark5_Reference)*100/time);
}
if(cfgBenchmark6_Enable)
{// Benchmark 6
srand(380843);
btDbvt dbvt;
btAlignedObjectArray<btTransform> transforms;
btDbvtBenchmark::NilPolicy policy;
transforms.resize(cfgBenchmark6_Iterations);
for(int i=0;i<transforms.size();++i)
{
transforms[i]=btDbvtBenchmark::RandTransform(cfgVolumeCenterScale*cfgBenchmark6_OffsetScale);
}
btDbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt);
dbvt.optimizeTopDown();
printf("[6] btDbvt::collideTT xform,self: ");
wallclock.reset();
for(int i=0;i<cfgBenchmark6_Iterations;++i)
{
btDbvt::collideTT(dbvt.m_root,dbvt.m_root,transforms[i],policy);
}
const int time=(int)wallclock.getTimeMilliseconds();
printf("%u ms (%i%%)\r\n",time,(time-cfgBenchmark6_Reference)*100/time);
}
if(cfgBenchmark7_Enable)
{// Benchmark 7
srand(380843);
btDbvt dbvt;
btAlignedObjectArray<btVector3> rayorg;
btAlignedObjectArray<btVector3> raydir;
btDbvtBenchmark::NilPolicy policy;
rayorg.resize(cfgBenchmark7_Iterations);
raydir.resize(cfgBenchmark7_Iterations);
for(int i=0;i<rayorg.size();++i)
{
rayorg[i]=btDbvtBenchmark::RandVector3(cfgVolumeCenterScale*2);
raydir[i]=btDbvtBenchmark::RandVector3(cfgVolumeCenterScale*2);
}
btDbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt);
dbvt.optimizeTopDown();
printf("[7] btDbvt::rayTest: ");
wallclock.reset();
for(int i=0;i<cfgBenchmark7_Passes;++i)
{
for(int j=0;j<cfgBenchmark7_Iterations;++j)
{
btDbvt::rayTest(dbvt.m_root,rayorg[j],rayorg[j]+raydir[j],policy);
}
}
const int time=(int)wallclock.getTimeMilliseconds();
unsigned rays=cfgBenchmark7_Passes*cfgBenchmark7_Iterations;
printf("%u ms (%i%%),(%u r/s)\r\n",time,(time-cfgBenchmark7_Reference)*100/time,(rays*1000)/time);
}
if(cfgBenchmark8_Enable)
{// Benchmark 8
srand(380843);
btDbvt dbvt;
btDbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt);
dbvt.optimizeTopDown();
printf("[8] insert/remove: ");
wallclock.reset();
for(int i=0;i<cfgBenchmark8_Passes;++i)
{
for(int j=0;j<cfgBenchmark8_Iterations;++j)
{
dbvt.remove(dbvt.insert(btDbvtBenchmark::RandVolume(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale),0));
}
}
const int time=(int)wallclock.getTimeMilliseconds();
const int ir=cfgBenchmark8_Passes*cfgBenchmark8_Iterations;
printf("%u ms (%i%%),(%u ir/s)\r\n",time,(time-cfgBenchmark8_Reference)*100/time,ir*1000/time);
}
if(cfgBenchmark9_Enable)
{// Benchmark 9
srand(380843);
btDbvt dbvt;
btAlignedObjectArray<const btDbvtNode*> leaves;
btDbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt);
dbvt.optimizeTopDown();
dbvt.extractLeaves(dbvt.m_root,leaves);
printf("[9] updates (teleport): ");
wallclock.reset();
for(int i=0;i<cfgBenchmark9_Passes;++i)
{
for(int j=0;j<cfgBenchmark9_Iterations;++j)
{
dbvt.update(const_cast<btDbvtNode*>(leaves[rand()%cfgLeaves]),
btDbvtBenchmark::RandVolume(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale));
}
}
const int time=(int)wallclock.getTimeMilliseconds();
const int up=cfgBenchmark9_Passes*cfgBenchmark9_Iterations;
printf("%u ms (%i%%),(%u u/s)\r\n",time,(time-cfgBenchmark9_Reference)*100/time,up*1000/time);
}
if(cfgBenchmark10_Enable)
{// Benchmark 10
srand(380843);
btDbvt dbvt;
btAlignedObjectArray<const btDbvtNode*> leaves;
btAlignedObjectArray<btVector3> vectors;
vectors.resize(cfgBenchmark10_Iterations);
for(int i=0;i<vectors.size();++i)
{
vectors[i]=(btDbvtBenchmark::RandVector3()*2-btVector3(1,1,1))*cfgBenchmark10_Scale;
}
btDbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt);
dbvt.optimizeTopDown();
dbvt.extractLeaves(dbvt.m_root,leaves);
printf("[10] updates (jitter): ");
wallclock.reset();
for(int i=0;i<cfgBenchmark10_Passes;++i)
{
for(int j=0;j<cfgBenchmark10_Iterations;++j)
{
const btVector3& d=vectors[j];
btDbvtNode* l=const_cast<btDbvtNode*>(leaves[rand()%cfgLeaves]);
btDbvtVolume v=btDbvtVolume::FromMM(l->volume.Mins()+d,l->volume.Maxs()+d);
dbvt.update(l,v);
}
}
const int time=(int)wallclock.getTimeMilliseconds();
const int up=cfgBenchmark10_Passes*cfgBenchmark10_Iterations;
printf("%u ms (%i%%),(%u u/s)\r\n",time,(time-cfgBenchmark10_Reference)*100/time,up*1000/time);
}
if(cfgBenchmark11_Enable)
{// Benchmark 11
srand(380843);
btDbvt dbvt;
btDbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt);
dbvt.optimizeTopDown();
printf("[11] optimize (incremental): ");
wallclock.reset();
for(int i=0;i<cfgBenchmark11_Passes;++i)
{
dbvt.optimizeIncremental(cfgBenchmark11_Iterations);
}
const int time=(int)wallclock.getTimeMilliseconds();
const int op=cfgBenchmark11_Passes*cfgBenchmark11_Iterations;
printf("%u ms (%i%%),(%u o/s)\r\n",time,(time-cfgBenchmark11_Reference)*100/time,op/time*1000);
}
if(cfgBenchmark12_Enable)
{// Benchmark 12
srand(380843);
btAlignedObjectArray<btDbvtVolume> volumes;
btAlignedObjectArray<bool> results;
volumes.resize(cfgLeaves);
results.resize(cfgLeaves);
for(int i=0;i<cfgLeaves;++i)
{
volumes[i]=btDbvtBenchmark::RandVolume(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale);
}
printf("[12] btDbvtVolume notequal: ");
wallclock.reset();
for(int i=0;i<cfgBenchmark12_Iterations;++i)
{
for(int j=0;j<cfgLeaves;++j)
{
for(int k=0;k<cfgLeaves;++k)
{
results[k]=NotEqual(volumes[j],volumes[k]);
}
}
}
const int time=(int)wallclock.getTimeMilliseconds();
printf("%u ms (%i%%)\r\n",time,(time-cfgBenchmark12_Reference)*100/time);
}
if(cfgBenchmark13_Enable)
{// Benchmark 13
srand(380843);
btDbvt dbvt;
btAlignedObjectArray<btVector3> vectors;
btDbvtBenchmark::NilPolicy policy;
vectors.resize(cfgBenchmark13_Iterations);
for(int i=0;i<vectors.size();++i)
{
vectors[i]=(btDbvtBenchmark::RandVector3()*2-btVector3(1,1,1)).normalized();
}
btDbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt);
dbvt.optimizeTopDown();
printf("[13] culling(OCL+fullsort): ");
wallclock.reset();
for(int i=0;i<cfgBenchmark13_Iterations;++i)
{
static const btScalar offset=0;
policy.m_depth=-SIMD_INFINITY;
dbvt.collideOCL(dbvt.m_root,&vectors[i],&offset,vectors[i],1,policy);
}
const int time=(int)wallclock.getTimeMilliseconds();
const int t=cfgBenchmark13_Iterations;
printf("%u ms (%i%%),(%u t/s)\r\n",time,(time-cfgBenchmark13_Reference)*100/time,(t*1000)/time);
}
if(cfgBenchmark14_Enable)
{// Benchmark 14
srand(380843);
btDbvt dbvt;
btAlignedObjectArray<btVector3> vectors;
btDbvtBenchmark::P14 policy;
vectors.resize(cfgBenchmark14_Iterations);
for(int i=0;i<vectors.size();++i)
{
vectors[i]=(btDbvtBenchmark::RandVector3()*2-btVector3(1,1,1)).normalized();
}
btDbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt);
dbvt.optimizeTopDown();
policy.m_nodes.reserve(cfgLeaves);
printf("[14] culling(OCL+qsort): ");
wallclock.reset();
for(int i=0;i<cfgBenchmark14_Iterations;++i)
{
static const btScalar offset=0;
policy.m_nodes.resize(0);
dbvt.collideOCL(dbvt.m_root,&vectors[i],&offset,vectors[i],1,policy,false);
policy.m_nodes.quickSort(btDbvtBenchmark::P14::sortfnc);
}
const int time=(int)wallclock.getTimeMilliseconds();
const int t=cfgBenchmark14_Iterations;
printf("%u ms (%i%%),(%u t/s)\r\n",time,(time-cfgBenchmark14_Reference)*100/time,(t*1000)/time);
}
if(cfgBenchmark15_Enable)
{// Benchmark 15
srand(380843);
btDbvt dbvt;
btAlignedObjectArray<btVector3> vectors;
btDbvtBenchmark::P15 policy;
vectors.resize(cfgBenchmark15_Iterations);
for(int i=0;i<vectors.size();++i)
{
vectors[i]=(btDbvtBenchmark::RandVector3()*2-btVector3(1,1,1)).normalized();
}
btDbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt);
dbvt.optimizeTopDown();
policy.m_nodes.reserve(cfgLeaves);
printf("[15] culling(KDOP+qsort): ");
wallclock.reset();
for(int i=0;i<cfgBenchmark15_Iterations;++i)
{
static const btScalar offset=0;
policy.m_nodes.resize(0);
policy.m_axis=vectors[i];
dbvt.collideKDOP(dbvt.m_root,&vectors[i],&offset,1,policy);
policy.m_nodes.quickSort(btDbvtBenchmark::P15::sortfnc);
}
const int time=(int)wallclock.getTimeMilliseconds();
const int t=cfgBenchmark15_Iterations;
printf("%u ms (%i%%),(%u t/s)\r\n",time,(time-cfgBenchmark15_Reference)*100/time,(t*1000)/time);
}
if(cfgBenchmark16_Enable)
{// Benchmark 16
srand(380843);
btDbvt dbvt;
btAlignedObjectArray<btDbvtNode*> batch;
btDbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt);
dbvt.optimizeTopDown();
batch.reserve(cfgBenchmark16_BatchCount);
printf("[16] insert/remove batch(%u): ",cfgBenchmark16_BatchCount);
wallclock.reset();
for(int i=0;i<cfgBenchmark16_Passes;++i)
{
for(int j=0;j<cfgBenchmark16_BatchCount;++j)
{
batch.push_back(dbvt.insert(btDbvtBenchmark::RandVolume(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale),0));
}
for(int j=0;j<cfgBenchmark16_BatchCount;++j)
{
dbvt.remove(batch[j]);
}
batch.resize(0);
}
const int time=(int)wallclock.getTimeMilliseconds();
const int ir=cfgBenchmark16_Passes*cfgBenchmark16_BatchCount;
printf("%u ms (%i%%),(%u bir/s)\r\n",time,(time-cfgBenchmark16_Reference)*100/time,int(ir*1000.0/time));
}
if(cfgBenchmark17_Enable)
{// Benchmark 17
srand(380843);
btAlignedObjectArray<btDbvtVolume> volumes;
btAlignedObjectArray<int> results;
btAlignedObjectArray<int> indices;
volumes.resize(cfgLeaves);
results.resize(cfgLeaves);
indices.resize(cfgLeaves);
for(int i=0;i<cfgLeaves;++i)
{
indices[i]=i;
volumes[i]=btDbvtBenchmark::RandVolume(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale);
}
for(int i=0;i<cfgLeaves;++i)
{
btSwap(indices[i],indices[rand()%cfgLeaves]);
}
printf("[17] btDbvtVolume select: ");
wallclock.reset();
for(int i=0;i<cfgBenchmark17_Iterations;++i)
{
for(int j=0;j<cfgLeaves;++j)
{
for(int k=0;k<cfgLeaves;++k)
{
const int idx=indices[k];
results[idx]=Select(volumes[idx],volumes[j],volumes[k]);
}
}
}
const int time=(int)wallclock.getTimeMilliseconds();
printf("%u ms (%i%%)\r\n",time,(time-cfgBenchmark17_Reference)*100/time);
}
printf("\r\n\r\n");
}
#endif
| 412 | 0.976849 | 1 | 0.976849 | game-dev | MEDIA | 0.246803 | game-dev | 0.994225 | 1 | 0.994225 |
openglobus/openglobus | 19,274 | src/utils/earcut.ts | // @ts-nocheck
/* eslint-disable no-unused-vars */
/* eslint-disable curly */
/* eslint-disable operator-linebreak */
/* eslint-disable no-mixed-operators */
/**
* @module og/utils/earcut
*/
'use strict';
// ISC License
//
// Copyright (c) 2016, Mapbox
//
// Permission to use, copy, modify, and/or distribute this software for any purpose
// with or without fee is hereby granted, provided that the above copyright notice
// and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
// OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
// TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
// THIS SOFTWARE.
//
//https://github.com/mapbox/earcut
function earcut(data, holeIndices, dim) {
dim = dim || 2;
var hasHoles = holeIndices && holeIndices.length,
outerLen = hasHoles ? holeIndices[0] * dim : data.length,
outerNode = linkedList(data, 0, outerLen, dim, true),
triangles = [];
if (!outerNode) return triangles;
var minX, minY, maxX, maxY, x, y, size;
if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
// if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
if (data.length > 80 * dim) {
minX = maxX = data[0];
minY = maxY = data[1];
for (let i = dim; i < outerLen; i += dim) {
x = data[i];
y = data[i + 1];
if (x < minX) minX = x;
if (y < minY) minY = y;
if (x > maxX) maxX = x;
if (y > maxY) maxY = y;
}
// minX, minY and size are later used to transform coords into integers for z-order calculation
size = Math.max(maxX - minX, maxY - minY);
}
earcutLinked(outerNode, triangles, dim, minX, minY, size);
return triangles;
}
// create a circular doubly linked list from polygon points in the specified winding order
function linkedList(data, start, end, dim, clockwise) {
var i, last;
if (clockwise === (signedArea(data, start, end, dim) > 0)) {
for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
} else {
for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
}
if (last && equals(last, last.next)) {
removeNode(last);
last = last.next;
}
return last;
}
// eliminate colinear or duplicate points
function filterPoints(start, end) {
if (!start) return start;
if (!end) end = start;
var p = start,
again;
do {
again = false;
if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
removeNode(p);
p = end = p.prev;
if (p === p.next) return null;
again = true;
} else {
p = p.next;
}
} while (again || p !== end);
return end;
}
// main ear slicing loop which triangulates a polygon (given as a linked list)
function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
if (!ear) return;
// interlink polygon nodes in z-order
if (!pass && size) indexCurve(ear, minX, minY, size);
var stop = ear,
prev, next;
// iterate through ears, slicing them one by one
while (ear.prev !== ear.next) {
prev = ear.prev;
next = ear.next;
if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
// cut off the triangle
triangles.push(prev.i / dim);
triangles.push(ear.i / dim);
triangles.push(next.i / dim);
removeNode(ear);
// skipping the next vertice leads to less sliver triangles
ear = next.next;
stop = next.next;
continue;
}
ear = next;
// if we looped through the whole remaining polygon and can't find any more ears
if (ear === stop) {
// try filtering points and slicing again
if (!pass) {
earcutLinked(filterPoints(ear), triangles, dim, minX, minY, size, 1);
// if this didn't work, try curing all small self-intersections locally
} else if (pass === 1) {
ear = cureLocalIntersections(ear, triangles, dim);
earcutLinked(ear, triangles, dim, minX, minY, size, 2);
// as a last resort, try splitting the remaining polygon into two
} else if (pass === 2) {
splitEarcut(ear, triangles, dim, minX, minY, size);
}
break;
}
}
}
// check whether a polygon node forms a valid ear with adjacent nodes
function isEar(ear) {
var a = ear.prev,
b = ear,
c = ear.next;
if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
// now make sure we don't have other points inside the potential ear
var p = ear.next.next;
while (p !== ear.prev) {
if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
area(p.prev, p, p.next) >= 0) return false;
p = p.next;
}
return true;
}
function isEarHashed(ear, minX, minY, size) {
var a = ear.prev,
b = ear,
c = ear.next;
if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
// triangle bbox; min & max are calculated like this for speed
var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x),
minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y),
maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x),
maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
// z-order range for the current triangle bbox;
var minZ = zOrder(minTX, minTY, minX, minY, size),
maxZ = zOrder(maxTX, maxTY, minX, minY, size);
// first look for points inside the triangle in increasing z-order
var p = ear.nextZ;
while (p && p.z <= maxZ) {
if (p !== ear.prev && p !== ear.next &&
pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
area(p.prev, p, p.next) >= 0) return false;
p = p.nextZ;
}
// then look for points in decreasing z-order
p = ear.prevZ;
while (p && p.z >= minZ) {
if (p !== ear.prev && p !== ear.next &&
pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
area(p.prev, p, p.next) >= 0) return false;
p = p.prevZ;
}
return true;
}
// go through all polygon nodes and cure small local self-intersections
function cureLocalIntersections(start, triangles, dim) {
var p = start;
do {
var a = p.prev,
b = p.next.next;
if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
triangles.push(a.i / dim);
triangles.push(p.i / dim);
triangles.push(b.i / dim);
// remove two nodes involved
removeNode(p);
removeNode(p.next);
p = start = b;
}
p = p.next;
} while (p !== start);
return p;
}
// try splitting polygon into two and triangulate them independently
function splitEarcut(start, triangles, dim, minX, minY, size) {
// look for a valid diagonal that divides the polygon into two
var a = start;
do {
var b = a.next.next;
while (b !== a.prev) {
if (a.i !== b.i && isValidDiagonal(a, b)) {
// split the polygon in two by the diagonal
var c = splitPolygon(a, b);
// filter colinear points around the cuts
a = filterPoints(a, a.next);
c = filterPoints(c, c.next);
// run earcut on each half
earcutLinked(a, triangles, dim, minX, minY, size);
earcutLinked(c, triangles, dim, minX, minY, size);
return;
}
b = b.next;
}
a = a.next;
} while (a !== start);
}
// link every hole into the outer loop, producing a single-ring polygon without holes
function eliminateHoles(data, holeIndices, outerNode, dim) {
var queue = [],
i, len, start, end, list;
for (i = 0, len = holeIndices.length; i < len; i++) {
start = holeIndices[i] * dim;
end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
list = linkedList(data, start, end, dim, false);
if (list === list.next) list.steiner = true;
queue.push(getLeftmost(list));
}
queue.sort(compareX);
// process holes from left to right
for (i = 0; i < queue.length; i++) {
eliminateHole(queue[i], outerNode);
outerNode = filterPoints(outerNode, outerNode.next);
}
return outerNode;
}
function compareX(a, b) {
return a.x - b.x;
}
// find a bridge between vertices that connects hole with an outer ring and and link it
function eliminateHole(hole, outerNode) {
outerNode = findHoleBridge(hole, outerNode);
if (outerNode) {
var b = splitPolygon(outerNode, hole);
filterPoints(b, b.next);
}
}
// David Eberly's algorithm for finding a bridge between hole and outer polygon
function findHoleBridge(hole, outerNode) {
var p = outerNode,
hx = hole.x,
hy = hole.y,
qx = -Infinity,
m;
// find a segment intersected by a ray from the hole's leftmost point to the left;
// segment's endpoint with lesser x will be potential connection point
do {
if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
if (x <= hx && x > qx) {
qx = x;
if (x === hx) {
if (hy === p.y) return p;
if (hy === p.next.y) return p.next;
}
m = p.x < p.next.x ? p : p.next;
}
}
p = p.next;
} while (p !== outerNode);
if (!m) return null;
if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint
// look for points inside the triangle of hole point, segment intersection and endpoint;
// if there are no points found, we have a valid connection;
// otherwise choose the point of the minimum angle with the ray as connection point
var stop = m,
mx = m.x,
my = m.y,
tanMin = Infinity,
tan;
p = m.next;
while (p !== stop) {
if (hx >= p.x && p.x >= mx && hx !== p.x &&
pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
m = p;
tanMin = tan;
}
}
p = p.next;
}
return m;
}
// interlink polygon nodes in z-order
function indexCurve(start, minX, minY, size) {
var p = start;
do {
if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, size);
p.prevZ = p.prev;
p.nextZ = p.next;
p = p.next;
} while (p !== start);
p.prevZ.nextZ = null;
p.prevZ = null;
sortLinked(p);
}
// Simon Tatham's linked list merge sort algorithm
// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
function sortLinked(list) {
var i, p, q, e, tail, numMerges, pSize, qSize,
inSize = 1;
do {
p = list;
list = null;
tail = null;
numMerges = 0;
while (p) {
numMerges++;
q = p;
pSize = 0;
for (i = 0; i < inSize; i++) {
pSize++;
q = q.nextZ;
if (!q) break;
}
qSize = inSize;
while (pSize > 0 || (qSize > 0 && q)) {
if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
e = p;
p = p.nextZ;
pSize--;
} else {
e = q;
q = q.nextZ;
qSize--;
}
if (tail) tail.nextZ = e;
else list = e;
e.prevZ = tail;
tail = e;
}
p = q;
}
tail.nextZ = null;
inSize *= 2;
} while (numMerges > 1);
return list;
}
// z-order of a point given coords and size of the data bounding box
function zOrder(x, y, minX, minY, size) {
// coords are transformed into non-negative 15-bit integer range
x = 32767 * (x - minX) / size;
y = 32767 * (y - minY) / size;
x = (x | (x << 8)) & 0x00FF00FF;
x = (x | (x << 4)) & 0x0F0F0F0F;
x = (x | (x << 2)) & 0x33333333;
x = (x | (x << 1)) & 0x55555555;
y = (y | (y << 8)) & 0x00FF00FF;
y = (y | (y << 4)) & 0x0F0F0F0F;
y = (y | (y << 2)) & 0x33333333;
y = (y | (y << 1)) & 0x55555555;
return x | (y << 1);
}
// find the leftmost node of a polygon ring
function getLeftmost(start) {
var p = start,
leftmost = start;
do {
if (p.x < leftmost.x) leftmost = p;
p = p.next;
} while (p !== start);
return leftmost;
}
// check if a point lies within a convex triangle
function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
(ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
(bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
}
// check if a diagonal between two polygon nodes is valid (lies in polygon interior)
function isValidDiagonal(a, b) {
return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) &&
locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b);
}
// signed area of a triangle
function area(p, q, r) {
return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
}
// check if two points are equal
function equals(p1, p2) {
return p1.x === p2.x && p1.y === p2.y;
}
// check if two segments intersect
function intersects(p1, q1, p2, q2) {
if ((equals(p1, q1) && equals(p2, q2)) ||
(equals(p1, q2) && equals(p2, q1))) return true;
return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
}
// check if a polygon diagonal intersects any polygon segments
function intersectsPolygon(a, b) {
var p = a;
do {
if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
intersects(p, p.next, a, b)) return true;
p = p.next;
} while (p !== a);
return false;
}
// check if a polygon diagonal is locally inside the polygon
function locallyInside(a, b) {
return area(a.prev, a, a.next) < 0 ?
area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
}
// check if the middle point of a polygon diagonal is inside the polygon
function middleInside(a, b) {
var p = a,
inside = false,
px = (a.x + b.x) / 2,
py = (a.y + b.y) / 2;
do {
if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
(px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
inside = !inside;
p = p.next;
} while (p !== a);
return inside;
}
// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
// if one belongs to the outer ring and another to a hole, it merges it into a single ring
function splitPolygon(a, b) {
var a2 = new Node(a.i, a.x, a.y),
b2 = new Node(b.i, b.x, b.y),
an = a.next,
bp = b.prev;
a.next = b;
b.prev = a;
a2.next = an;
an.prev = a2;
b2.next = a2;
a2.prev = b2;
bp.next = b2;
b2.prev = bp;
return b2;
}
// create a node and optionally link it with previous one (in a circular doubly linked list)
function insertNode(i, x, y, last) {
var p = new Node(i, x, y);
if (!last) {
p.prev = p;
p.next = p;
} else {
p.next = last.next;
p.prev = last;
last.next.prev = p;
last.next = p;
}
return p;
}
function removeNode(p) {
p.next.prev = p.prev;
p.prev.next = p.next;
if (p.prevZ) p.prevZ.nextZ = p.nextZ;
if (p.nextZ) p.nextZ.prevZ = p.prevZ;
}
function Node(i, x, y) {
// vertice index in coordinates array
this.i = i;
// vertex coordinates
this.x = x;
this.y = y;
// previous and next vertice nodes in a polygon ring
this.prev = null;
this.next = null;
// z-order curve value
this.z = null;
// previous and next nodes in z-order
this.prevZ = null;
this.nextZ = null;
// indicates whether this is a steiner point
this.steiner = false;
}
// return a percentage difference between the polygon area and its triangulation area;
// used to verify correctness of triangulation
function deviation(data, holeIndices, dim, triangles) {
var hasHoles = holeIndices && holeIndices.length;
var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
if (hasHoles) {
for (let i = 0, len = holeIndices.length; i < len; i++) {
var start = holeIndices[i] * dim;
var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
polygonArea -= Math.abs(signedArea(data, start, end, dim));
}
}
var trianglesArea = 0;
for (let i = 0; i < triangles.length; i += 3) {
var a = triangles[i] * dim;
var b = triangles[i + 1] * dim;
var c = triangles[i + 2] * dim;
trianglesArea += Math.abs(
(data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
(data[a] - data[b]) * (data[c + 1] - data[a + 1]));
}
return polygonArea === 0 && trianglesArea === 0 ? 0 :
Math.abs((trianglesArea - polygonArea) / polygonArea);
}
function signedArea(data, start, end, dim) {
var sum = 0;
for (let i = start, j = end - dim; i < end; i += dim) {
sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
j = i;
}
return sum;
}
// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
function flatten(data) {
var dim = data[0][0].length,
result = { vertices: [], holes: [], dimensions: dim },
holeIndex = 0;
for (let i = 0; i < data.length; i++) {
for (let j = 0; j < data[i].length; j++) {
for (let d = 0; d < dim; d++) result.vertices.push(data[i][j][d]);
}
if (i > 0) {
holeIndex += data[i - 1].length;
result.holes.push(holeIndex);
}
}
return result;
}
export { earcut, flatten };
| 412 | 0.863211 | 1 | 0.863211 | game-dev | MEDIA | 0.427493 | game-dev | 0.989325 | 1 | 0.989325 |
JHGuitarFreak/UQM-MegaMod | 12,423 | src/uqm/ships/vux/vux.c | //Copyright Paul Reiche, Fred Ford. 1992-2002
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "../ship.h"
#include "vux.h"
#include "resinst.h"
#include "../../setup.h"
#include "../../setupmenu.h"
#include "uqm/globdata.h"
#include "libs/mathlib.h"
// Core characteristics
#define MAX_CREW 20
#define MAX_ENERGY 40
#define ENERGY_REGENERATION 1
#define ENERGY_WAIT 8
#define MAX_THRUST /* DISPLAY_TO_WORLD (5) */ 21
#define THRUST_INCREMENT /* DISPLAY_TO_WORLD (2) */ 7
#define THRUST_WAIT 4
#define TURN_WAIT 6
#define SHIP_MASS 6
// Laser
#define WEAPON_ENERGY_COST 1
#define WEAPON_WAIT 0
#define VUX_OFFSET RES_BOOL (12, 38)
#define LASER_BASE RES_SCALE (150)
#define LASER_RANGE DISPLAY_TO_WORLD (LASER_BASE + VUX_OFFSET)
// Limpet
#define SPECIAL_ENERGY_COST 2
#define SPECIAL_WAIT 7
#define LIMPET_SPEED RES_SCALE (25)
#define LIMPET_OFFSET RES_SCALE (8)
#define LIMPET_LIFE 80
#define LIMPET_HITS 1
#define LIMPET_DAMAGE 0
#define MIN_THRUST_INCREMENT DISPLAY_TO_WORLD (RES_SCALE (1))
// Aggressive Entry
#define WARP_OFFSET RES_SCALE (46)
/* How far outside of the laser range can the ship warp in. */
#define MAXX_ENTRY_DIST DISPLAY_TO_WORLD ((LASER_BASE + VUX_OFFSET + WARP_OFFSET) << 1)
#define MAXY_ENTRY_DIST DISPLAY_TO_WORLD ((LASER_BASE + VUX_OFFSET + WARP_OFFSET) << 1)
/* Originally, the warp distance was:
* DISPLAY_TO_WORLD (SPACE_HEIGHT << 1)
* where SPACE_HEIGHT = SCREEN_HEIGHT
* But in reality this should be relative to the laser-range. */
static RACE_DESC vux_desc =
{
{ /* SHIP_INFO */
"intruder",
FIRES_FORE | SEEKING_SPECIAL | IMMEDIATE_WEAPON,
12, /* Super Melee cost */
MAX_CREW, MAX_CREW,
MAX_ENERGY, MAX_ENERGY,
VUX_RACE_STRINGS,
VUX_ICON_MASK_PMAP_ANIM,
VUX_MICON_MASK_PMAP_ANIM,
NULL, NULL, NULL
},
{ /* FLEET_STUFF */
900 / SPHERE_RADIUS_INCREMENT * 2, /* Initial SoI radius */
{ /* Known location (center of SoI) */
4412, 1558,
},
},
{
MAX_THRUST,
THRUST_INCREMENT,
ENERGY_REGENERATION,
WEAPON_ENERGY_COST,
SPECIAL_ENERGY_COST,
ENERGY_WAIT,
TURN_WAIT,
THRUST_WAIT,
WEAPON_WAIT,
SPECIAL_WAIT,
SHIP_MASS,
},
{
{
VUX_BIG_MASK_PMAP_ANIM,
VUX_MED_MASK_PMAP_ANIM,
VUX_SML_MASK_PMAP_ANIM,
},
{
SLIME_MASK_PMAP_ANIM,
NULL_RESOURCE,
NULL_RESOURCE,
},
{
LIMPETS_BIG_MASK_PMAP_ANIM,
LIMPETS_MED_MASK_PMAP_ANIM,
LIMPETS_SML_MASK_PMAP_ANIM,
},
{
VUX_CAPTAIN_MASK_PMAP_ANIM,
NULL, NULL, NULL, NULL, NULL,
0, 0, 0, 0, 0
},
VUX_VICTORY_SONG,
VUX_SHIP_SOUNDS,
{ NULL, NULL, NULL },
{ NULL, NULL, NULL },
{ NULL, NULL, NULL },
NULL, NULL
},
{
0,
CLOSE_RANGE_WEAPON,
NULL,
},
(UNINIT_FUNC *) NULL,
(PREPROCESS_FUNC *) NULL,
(POSTPROCESS_FUNC *) NULL,
(INIT_WEAPON_FUNC *) NULL,
0,
0, /* CodeRef */
};
static void
limpet_preprocess (ELEMENT *ElementPtr)
{
COUNT facing, orig_facing;
SIZE delta_facing;
facing = orig_facing = NORMALIZE_FACING (ANGLE_TO_FACING (
GetVelocityTravelAngle (&ElementPtr->velocity)
));
if ((delta_facing = TrackShip (ElementPtr, &facing)) > 0)
{
facing = orig_facing + delta_facing;
SetVelocityVector (&ElementPtr->velocity, LIMPET_SPEED, facing);
}
ElementPtr->next.image.frame =
IncFrameIndex (ElementPtr->next.image.frame);
ElementPtr->state_flags |= CHANGING;
}
static void
limpet_collision (ELEMENT *ElementPtr0, POINT *pPt0,
ELEMENT *ElementPtr1, POINT *pPt1)
{
if (ElementPtr1->state_flags & PLAYER_SHIP)
{
STAMP s;
STARSHIP *StarShipPtr;
RACE_DESC *RDPtr;
GetElementStarShip (ElementPtr1, &StarShipPtr);
RDPtr = StarShipPtr->RaceDescPtr;
if (!(antiCheat (ElementPtr1, FALSE, OPTVAL_INF_HEALTH)
|| antiCheat (ElementPtr1, FALSE, OPTVAL_FULL_GOD)))
{
if (++RDPtr->characteristics.turn_wait == 0)
--RDPtr->characteristics.turn_wait;
if (++RDPtr->characteristics.thrust_wait == 0)
--RDPtr->characteristics.thrust_wait;
if (RDPtr->characteristics.thrust_increment <= MIN_THRUST_INCREMENT)
{
RDPtr->characteristics.max_thrust =
RDPtr->characteristics.thrust_increment << 1;
}
else
{
COUNT num_thrusts;
num_thrusts = RDPtr->characteristics.max_thrust /
RDPtr->characteristics.thrust_increment;
RDPtr->characteristics.thrust_increment -= RES_SCALE (1);
RDPtr->characteristics.max_thrust =
RDPtr->characteristics.thrust_increment * num_thrusts;
}
RDPtr->cyborg_control.ManeuverabilityIndex = 0;
GetElementStarShip (ElementPtr0, &StarShipPtr);
ProcessSound (SetAbsSoundIndex (
/* LIMPET_AFFIXES */
StarShipPtr->RaceDescPtr->ship_data.ship_sounds, 2), ElementPtr1);
s.frame = SetAbsFrameIndex (
StarShipPtr->RaceDescPtr->ship_data.weapon[0], (COUNT)TFB_Random ()
);
ModifySilhouette (ElementPtr1, &s, MODIFY_IMAGE);
}
else
{
GetElementStarShip (ElementPtr0, &StarShipPtr);
ProcessSound (SetAbsSoundIndex (
/* LIMPET_AFFIXES */
StarShipPtr->RaceDescPtr->ship_data.ship_sounds, 2), ElementPtr1);
}
}
ElementPtr0->hit_points = 0;
ElementPtr0->life_span = 0;
ElementPtr0->state_flags |= COLLISION | DISAPPEARING;
(void) pPt0; /* Satisfying compiler (unused parameter) */
(void) pPt1; /* Satisfying compiler (unused parameter) */
}
static void
spawn_limpets (ELEMENT *ElementPtr)
{
HELEMENT Limpet;
STARSHIP *StarShipPtr;
MISSILE_BLOCK MissileBlock;
GetElementStarShip (ElementPtr, &StarShipPtr);
MissileBlock.farray = StarShipPtr->RaceDescPtr->ship_data.special;
MissileBlock.face = StarShipPtr->ShipFacing + HALF_CIRCLE;
MissileBlock.index = 0;
MissileBlock.sender = ElementPtr->playerNr;
MissileBlock.flags = IGNORE_SIMILAR;
MissileBlock.pixoffs = LIMPET_OFFSET;
MissileBlock.speed = LIMPET_SPEED;
MissileBlock.hit_points = LIMPET_HITS;
MissileBlock.damage = LIMPET_DAMAGE;
MissileBlock.life = LIMPET_LIFE;
MissileBlock.preprocess_func = limpet_preprocess;
MissileBlock.blast_offs = 0;
MissileBlock.cx = ElementPtr->next.location.x;
MissileBlock.cy = ElementPtr->next.location.y;
Limpet = initialize_missile (&MissileBlock);
if (Limpet)
{
ELEMENT *LimpetPtr;
LockElement (Limpet, &LimpetPtr);
LimpetPtr->collision_func = limpet_collision;
SetElementStarShip (LimpetPtr, StarShipPtr);
UnlockElement (Limpet);
PutElement (Limpet);
}
}
static COUNT
initialize_horrific_laser (ELEMENT *ShipPtr, HELEMENT LaserArray[])
{
STARSHIP *StarShipPtr;
LASER_BLOCK LaserBlock;
GetElementStarShip (ShipPtr, &StarShipPtr);
LaserBlock.face = StarShipPtr->ShipFacing;
LaserBlock.cx = ShipPtr->next.location.x;
LaserBlock.cy = ShipPtr->next.location.y;
LaserBlock.ex = COSINE (FACING_TO_ANGLE (LaserBlock.face), LASER_RANGE);
LaserBlock.ey = SINE (FACING_TO_ANGLE (LaserBlock.face), LASER_RANGE);
LaserBlock.sender = ShipPtr->playerNr;
LaserBlock.flags = IGNORE_SIMILAR;
LaserBlock.pixoffs = VUX_OFFSET;
LaserBlock.color = BUILD_COLOR (MAKE_RGB15 (0x0A, 0x1F, 0x0A), 0x0A);
LaserArray[0] = initialize_laser (&LaserBlock);
return (1);
}
static void
vux_intelligence (ELEMENT *ShipPtr, EVALUATE_DESC *ObjectsOfConcern,
COUNT ConcernCounter)
{
EVALUATE_DESC *lpEvalDesc;
STARSHIP *StarShipPtr;
lpEvalDesc = &ObjectsOfConcern[ENEMY_SHIP_INDEX];
lpEvalDesc->MoveState = PURSUE;
if (ObjectsOfConcern[ENEMY_WEAPON_INDEX].ObjectPtr != 0
&& ObjectsOfConcern[ENEMY_WEAPON_INDEX].MoveState == ENTICE)
{
if ((ObjectsOfConcern[ENEMY_WEAPON_INDEX].ObjectPtr->state_flags
& FINITE_LIFE)
&& !(ObjectsOfConcern[ENEMY_WEAPON_INDEX].ObjectPtr->state_flags
& CREW_OBJECT))
ObjectsOfConcern[ENEMY_WEAPON_INDEX].MoveState = AVOID;
else
ObjectsOfConcern[ENEMY_WEAPON_INDEX].MoveState = PURSUE;
}
ship_intelligence (ShipPtr,
ObjectsOfConcern, ConcernCounter);
GetElementStarShip (ShipPtr, &StarShipPtr);
if (StarShipPtr->special_counter == 0
&& lpEvalDesc->ObjectPtr != 0
&& lpEvalDesc->which_turn <= 12
&& (StarShipPtr->ship_input_state & (LEFT | RIGHT))
&& StarShipPtr->RaceDescPtr->ship_info.energy_level >=
(BYTE)(StarShipPtr->RaceDescPtr->ship_info.max_energy >> 1))
StarShipPtr->ship_input_state |= SPECIAL;
else
StarShipPtr->ship_input_state &= ~SPECIAL;
}
static void
vux_postprocess (ELEMENT *ElementPtr)
{
STARSHIP *StarShipPtr;
GetElementStarShip (ElementPtr, &StarShipPtr);
if ((StarShipPtr->cur_status_flags & SPECIAL)
&& StarShipPtr->special_counter == 0
&& DeltaEnergy (ElementPtr, -SPECIAL_ENERGY_COST))
{
ProcessSound (SetAbsSoundIndex (
/* LAUNCH_LIMPET */
StarShipPtr->RaceDescPtr->ship_data.ship_sounds, 1), ElementPtr);
spawn_limpets (ElementPtr);
StarShipPtr->special_counter =
StarShipPtr->RaceDescPtr->characteristics.special_wait;
}
}
static void
vux_preprocess (ELEMENT *ElementPtr)
{
if (ElementPtr->state_flags & APPEARING)
{
COUNT facing;
STARSHIP *StarShipPtr;
GetElementStarShip (ElementPtr, &StarShipPtr);
facing = StarShipPtr->ShipFacing;
if ((LOBYTE (GLOBAL (CurrentActivity)) != IN_ENCOUNTER
|| DIF_HARD)
&& TrackShip (ElementPtr, &facing) >= 0)
{
ELEMENT *OtherShipPtr;
SIZE SA_MATRA_EXTRA_DIST = 0;
LockElement (ElementPtr->hTarget, &OtherShipPtr);
// JMS: Not REALLY necessary as VUX can ordinarily never be played against Sa-Matra.
// But handy in debugging as a single VUX limpet incapacitates Sa-Matra completely.
if (LOBYTE (GLOBAL (CurrentActivity)) == IN_LAST_BATTLE)
SA_MATRA_EXTRA_DIST += RES_SCALE (1000);
do
{
// JMS_GFX: Circumventing overflows by using temp variables
// instead of subtracting straight from the POINT sized
// ShipImagePtr->current.location.
SDWORD dx, dy;
SDWORD temp_x =
((SDWORD)OtherShipPtr->current.location.x -
(MAXX_ENTRY_DIST >> 1)) +
((COUNT)TFB_Random () % MAXX_ENTRY_DIST);
SDWORD temp_y =
((SDWORD)OtherShipPtr->current.location.y -
(MAXY_ENTRY_DIST >> 1)) +
((COUNT)TFB_Random () % MAXY_ENTRY_DIST);
temp_x += temp_x > 0 ? SA_MATRA_EXTRA_DIST : -SA_MATRA_EXTRA_DIST;
temp_y += temp_y > 0 ? SA_MATRA_EXTRA_DIST : -SA_MATRA_EXTRA_DIST;
dx = OtherShipPtr->current.location.x - temp_x;
dy = OtherShipPtr->current.location.y - temp_y;
facing = NORMALIZE_FACING (
ANGLE_TO_FACING (ARCTAN (dx, dy))
);
ElementPtr->current.image.frame =
SetAbsFrameIndex (ElementPtr->current.image.frame,
facing);
ElementPtr->current.location.x =
WRAP_X (DISPLAY_ALIGN (temp_x));
ElementPtr->current.location.y =
WRAP_Y (DISPLAY_ALIGN (temp_y));
} while (CalculateGravity (ElementPtr)
|| TimeSpaceMatterConflict (ElementPtr));
UnlockElement (ElementPtr->hTarget);
ElementPtr->hTarget = 0;
ElementPtr->next = ElementPtr->current;
InitIntersectStartPoint (ElementPtr);
InitIntersectEndPoint (ElementPtr);
InitIntersectFrame (ElementPtr);
StarShipPtr->ShipFacing = facing;
}
StarShipPtr->RaceDescPtr->preprocess_func = 0;
}
}
RACE_DESC*
init_vux (void)
{
RACE_DESC *RaceDescPtr;
if (IS_HD)
{
vux_desc.characteristics.max_thrust = RES_SCALE (MAX_THRUST);
vux_desc.characteristics.thrust_increment = RES_SCALE (THRUST_INCREMENT);
vux_desc.cyborg_control.WeaponRange = CLOSE_RANGE_WEAPON_HD;
}
else
{
vux_desc.characteristics.max_thrust = MAX_THRUST;
vux_desc.characteristics.thrust_increment = THRUST_INCREMENT;
vux_desc.cyborg_control.WeaponRange = CLOSE_RANGE_WEAPON;
}
vux_desc.preprocess_func = vux_preprocess;
vux_desc.postprocess_func = vux_postprocess;
vux_desc.init_weapon_func = initialize_horrific_laser;
vux_desc.cyborg_control.intelligence_func = vux_intelligence;
RaceDescPtr = &vux_desc;
return (RaceDescPtr);
}
| 412 | 0.831664 | 1 | 0.831664 | game-dev | MEDIA | 0.929677 | game-dev | 0.897451 | 1 | 0.897451 |
opentibiabr/otservbr-global | 3,116 | data/npc/partos.lua | local internalNpcName = "Partos"
local npcType = Game.createNpcType(internalNpcName)
local npcConfig = {}
npcConfig.name = internalNpcName
npcConfig.description = internalNpcName
npcConfig.health = 100
npcConfig.maxHealth = npcConfig.health
npcConfig.walkInterval = 2000
npcConfig.walkRadius = 2
npcConfig.outfit = {
lookType = 128,
lookHead = 116,
lookBody = 56,
lookLegs = 95,
lookFeet = 121,
lookAddons = 0
}
npcConfig.flags = {
floorchange = false
}
local keywordHandler = KeywordHandler:new()
local npcHandler = NpcHandler:new(keywordHandler)
npcType.onThink = function(npc, interval)
npcHandler:onThink(npc, interval)
end
npcType.onAppear = function(npc, creature)
npcHandler:onAppear(npc, creature)
end
npcType.onDisappear = function(npc, creature)
npcHandler:onDisappear(npc, creature)
end
npcType.onMove = function(npc, creature, fromPosition, toPosition)
npcHandler:onMove(npc, creature, fromPosition, toPosition)
end
npcType.onSay = function(npc, creature, type, message)
npcHandler:onSay(npc, creature, type, message)
end
npcType.onCloseChannel = function(npc, creature)
npcHandler:onCloseChannel(npc, creature)
end
local function creatureSayCallback(npc, creature, type, message)
local player = Player(creature)
local playerId = player:getId()
if not npcHandler:checkInteraction(npc, creature) then
return false
end
if MsgContains(message, 'supplies') then
if player:getStorageValue(Storage.DjinnWar.EfreetFaction.Mission01) == 1 then
npcHandler:say({
'What!? I bet, Baa\'leal sent you! ...',
'I won\'t tell you anything! Shove off!'
}, npc, creature)
player:setStorageValue(Storage.DjinnWar.EfreetFaction.Mission01, 2)
else
npcHandler:say('I won\'t talk about that.', npc, creature)
end
elseif MsgContains(message, 'ankrahmun') then
npcHandler:say({
'Yes, I\'ve lived in Ankrahmun for quite some time. Ahh, good old times! ...',
'Unfortunately I had to relocate. <sigh> ...',
'Business reasons - you know.'
}, npc, creature)
end
return true
end
keywordHandler:addKeyword({'prison'}, StdModule.say, {npcHandler = npcHandler, text = 'You mean that\'s a JAIL? They told me it\'s the finest hotel in town! THAT explains the lousy roomservice!'})
keywordHandler:addKeyword({'jail'}, StdModule.say, {npcHandler = npcHandler, text = 'You mean that\'s a JAIL? They told me it\'s the finest hotel in town! THAT explains the lousy roomservice!'})
keywordHandler:addKeyword({'cell'}, StdModule.say, {npcHandler = npcHandler, text = 'You mean that\'s a JAIL? They told me it\'s the finest hotel in town! THAT explains the lousy roomservice!'})
npcHandler:setMessage(MESSAGE_GREET, 'Welcome to my little kingdom, |PLAYERNAME|.')
npcHandler:setMessage(MESSAGE_FAREWELL, 'Good bye, visit me again. I will be here, promised.')
npcHandler:setMessage(MESSAGE_WALKAWAY, 'Good bye, visit me again. I will be here, promised.')
npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback)
npcHandler:addModule(FocusModule:new(), npcConfig.name, true, true, true)
-- npcType registering the npcConfig table
npcType:register(npcConfig)
| 412 | 0.886077 | 1 | 0.886077 | game-dev | MEDIA | 0.970325 | game-dev | 0.864169 | 1 | 0.864169 |
mirrorfishmedia/EndlessRunnerUnity | 2,218 | ColorRun/Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_ResourcesLoader.cs | using UnityEditor;
using UnityEngine;
using System.Collections;
namespace TMPro.EditorUtilities
{
//[InitializeOnLoad]
class TMP_ResourcesLoader
{
/// <summary>
/// Function to pre-load the TMP Resources
/// </summary>
public static void LoadTextMeshProResources()
{
//TMP_Settings.LoadDefaultSettings();
//TMP_StyleSheet.LoadDefaultStyleSheet();
}
static TMP_ResourcesLoader()
{
//Debug.Log("Loading TMP Resources...");
// Get current targetted platform
//string Settings = PlayerSettings.GetScriptingDefineSymbolsForGroup(BuildTargetGroup.Standalone);
//TMPro.TMP_Settings.LoadDefaultSettings();
//TMPro.TMP_StyleSheet.LoadDefaultStyleSheet();
}
//[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
//static void OnBeforeSceneLoaded()
//{
//Debug.Log("Before scene is loaded.");
// //TMPro.TMP_Settings.LoadDefaultSettings();
// //TMPro.TMP_StyleSheet.LoadDefaultStyleSheet();
// //ShaderVariantCollection collection = new ShaderVariantCollection();
// //Shader s0 = Shader.Find("TextMeshPro/Mobile/Distance Field");
// //ShaderVariantCollection.ShaderVariant tmp_Variant = new ShaderVariantCollection.ShaderVariant(s0, UnityEngine.Rendering.PassType.Normal, string.Empty);
// //collection.Add(tmp_Variant);
// //collection.WarmUp();
//}
}
//static class TMP_ProjectSettings
//{
// [InitializeOnLoadMethod]
// static void SetProjectDefineSymbols()
// {
// string currentBuildSettings = PlayerSettings.GetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup);
// //Check for and inject TMP_INSTALLED
// if (!currentBuildSettings.Contains("TMP_PRESENT"))
// {
// PlayerSettings.SetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup, currentBuildSettings + ";TMP_PRESENT");
// }
// }
//}
}
| 412 | 0.601373 | 1 | 0.601373 | game-dev | MEDIA | 0.739323 | game-dev | 0.766908 | 1 | 0.766908 |
dwslab/melt | 1,986 | matching-jena-matchers/src/main/java/de/uni_mannheim/informatik/dws/melt/matching_jena_matchers/filter/extraction/MwbNode.java | package de.uni_mannheim.informatik.dws.melt.matching_jena_matchers.filter.extraction;
import java.util.HashSet;
import java.util.Set;
/**
* Helper class for {@link MaxWeightBipartiteExtractor}.
* The node of a graph.
*/
class MwbNode implements Comparable<MwbNode>{
/**
* The graph structure (modeled only as successor).
*/
private Set<MwbEdge> successor;
/**
* The potential as given in the algorithm.
*/
private int potential;
/**
* Shortest path property for distance.
*/
private int distance;
/**
* Is the node already matched.
*/
private boolean free;
/**
* Shortest path property for restoring the path.
*/
private MwbEdge predecessor;
public MwbNode() {
this.successor = new HashSet<>();
this.potential = 0;
this.distance = 0;
this.free = true;
this.predecessor = null;
}
public void addSuccesor(MwbEdge e){
this.successor.add(e);
}
public void removeSuccesor(MwbEdge e){
this.successor.remove(e);
}
public int getPotential() {
return potential;
}
public void setPotential(int potential) {
this.potential = potential;
}
public int getDistance() {
return distance;
}
public void setDistance(int distance) {
this.distance = distance;
}
public boolean isFree() {
return free;
}
public void setFree(boolean free) {
this.free = free;
}
public MwbEdge getPredecessor() {
return predecessor;
}
public void setPredecessor(MwbEdge predecessor) {
this.predecessor = predecessor;
}
public Set<MwbEdge> getSuccessor() {
return successor;
}
public void setSuccessor(Set<MwbEdge> successor) {
this.successor = successor;
}
@Override
public int compareTo(MwbNode o) {
return Integer.compare(distance, o.distance);
}
}
| 412 | 0.564177 | 1 | 0.564177 | game-dev | MEDIA | 0.581324 | game-dev | 0.766367 | 1 | 0.766367 |
Arkania/ArkCORE-NG | 2,491 | src/server/scripts/Northrend/Nexus/EyeOfEternity/eye_of_eternity.h | /*
* Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2011-2016 ArkCORE <http://www.arkania.net/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef DEF_EYE_OF_ETERNITY_H
#define DEF_EYE_OF_ETERNITY_H
enum InstanceData
{
DATA_MALYGOS_EVENT,
MAX_ENCOUNTER,
DATA_VORTEX_HANDLING,
DATA_POWER_SPARKS_HANDLING,
DATA_RESPAWN_IRIS
};
enum InstanceData64
{
DATA_TRIGGER,
DATA_MALYGOS,
DATA_PLATFORM,
DATA_ALEXSTRASZA_BUNNY_GUID,
DATA_HEART_OF_MAGIC_GUID,
DATA_FOCUSING_IRIS_GUID,
DATA_GIFT_BOX_BUNNY_GUID
};
enum InstanceNpcs
{
NPC_MALYGOS = 28859,
NPC_VORTEX_TRIGGER = 30090,
NPC_PORTAL_TRIGGER = 30118,
NPC_POWER_SPARK = 30084,
NPC_HOVER_DISK_MELEE = 30234,
NPC_HOVER_DISK_CASTER = 30248,
NPC_ARCANE_OVERLOAD = 30282,
NPC_WYRMREST_SKYTALON = 30161,
NPC_ALEXSTRASZA = 32295,
NPC_ALEXSTRASZA_BUNNY = 31253,
NPC_ALEXSTRASZAS_GIFT = 32448,
NPC_SURGE_OF_POWER = 30334
};
enum InstanceGameObjects
{
GO_NEXUS_RAID_PLATFORM = 193070,
GO_EXIT_PORTAL = 193908,
GO_FOCUSING_IRIS_10 = 193958,
GO_FOCUSING_IRIS_25 = 193960,
GO_ALEXSTRASZA_S_GIFT_10 = 193905,
GO_ALEXSTRASZA_S_GIFT_25 = 193967,
GO_HEART_OF_MAGIC_10 = 194158,
GO_HEART_OF_MAGIC_25 = 194159
};
enum InstanceEvents
{
EVENT_FOCUSING_IRIS = 20711
};
enum InstanceSpells
{
SPELL_VORTEX_4 = 55853, // damage | used to enter to the vehicle
SPELL_VORTEX_5 = 56263, // damage | used to enter to the vehicle
SPELL_PORTAL_OPENED = 61236,
SPELL_RIDE_RED_DRAGON_TRIGGERED = 56072,
SPELL_IRIS_OPENED = 61012 // visual when starting encounter
};
#endif
| 412 | 0.807142 | 1 | 0.807142 | game-dev | MEDIA | 0.883059 | game-dev | 0.50729 | 1 | 0.50729 |
openclonk/openclonk | 6,912 | planet/Objects.ocd/Items.ocd/Tools.ocd/Pickaxe.ocd/Script.c | /*
Pickaxe
A useful but tedious tool for breaking through rock without explosives.
@author: Randrian/Ringwaul
*/
#include Library_Flammable
local swingtime = 0;
local using;
static const Pickaxe_SwingTime = 40;
/*-- Engine Callbacks --*/
func Hit(x, y)
{
StonyObjectHit(x, y);
}
// Reroute callback to clonk context to ensure DigOutObject callback is done in Clonk
public func DigOutObject(object obj)
{
// TODO: it would be nice if the method of finding the clonk does not rely on it to be the container of the pickaxe
var clonk = Contained();
if (clonk)
clonk->~DigOutObject(obj);
}
/*-- Usage --*/
public func HoldingEnabled() { return true; }
public func RejectUse(object clonk)
{
var proc = clonk->GetProcedure();
return proc != "WALK" && proc != "SCALE";
}
public func ControlUseStart(object clonk, int ix, int iy)
{
using = 1;
// Create an offset, so that the hit matches with the animation
swingtime = Pickaxe_SwingTime*1/38;
clonk->SetTurnType(1);
clonk->SetHandAction(1);
clonk->UpdateAttach();
clonk->PlayAnimation("StrikePickaxe", CLONK_ANIM_SLOT_Arms, Anim_Linear(0, 0, clonk->GetAnimationLength("StrikePickaxe"), Pickaxe_SwingTime, ANIM_Loop), Anim_Const(1000));
var fx = AddEffect("IntPickaxe", clonk, 1, 1, this);
if (!fx) return false;
fx.x = ix;
fx.y = iy;
return true;
}
public func ControlUseHolding(object clonk, int new_x, int new_y)
{
// Can clonk use pickaxe?
if (clonk->GetProcedure() != "WALK")
{
clonk->PauseUse(this);
return true;
}
var fx = GetEffect("IntPickaxe", clonk);
if (!fx) return clonk->CancelUse();
fx.x = new_x; fx.y = new_y;
return true;
}
func ControlUseCancel(object clonk, int ix, int iy)
{
Reset(clonk);
return true;
}
public func ControlUseStop(object clonk, int ix, int iy)
{
Reset(clonk);
return true;
}
public func Reset(clonk)
{
using = 0;
clonk->SetTurnType(0);
clonk->SetHandAction(false);
clonk->UpdateAttach();
clonk->StopAnimation(clonk->GetRootAnimation(10));
swingtime = 0;
RemoveEffect("IntPickaxe", clonk);
}
func DoSwing(object clonk, int ix, int iy)
{
var angle = 180-Angle(0, 0, ix, iy);
//Creates an imaginary line which runs for 'MaxReach' distance (units in pixels)
//or until it hits a solid wall.
var iDist = 0;
var x2, y2;
while (!GBackSolid((x2 = Sin(angle, iDist)), (y2 = Cos(angle, iDist))) && iDist < MaxReach)
{
// Check some additional surrounding pixels in a cone to make hitting single pixels easier.
for (var da = -StrikeCone/2; da <= StrikeCone/2; da += 2)
{
if (Abs(da) < 3) continue;
var x3 = Sin(angle + da, iDist), y3 = Cos(angle + da, iDist);
if (x3 != x2 || y3 != y2)
{
x2 = x3; y2 = y3;
if (GBackSolid(x2, y2))
break;
}
}
++iDist;
}
//Point of contact, where the pick strikes the landscape
var is_solid = GBackSolid(x2, y2);
// alternatively hit certain objects
var target_obj = FindObject(Find_AtPoint(x2, y2), Find_Func("CanBeHitByPickaxe"));
// notify the object that it has been hit
if (target_obj)
target_obj->~OnHitByPickaxe(this, clonk);
// special effects only ifhit something
if (is_solid || target_obj)
{
var mat = GetMaterial(x2, y2);
var tex = GetTexture(x2, y2);
//Is the material struck made of a diggable material?
if (is_solid && GetMaterialVal("DigFree","Material",mat))
{
var clr = GetAverageTextureColor(tex);
var particles =
{
Prototype = Particles_Dust(),
R = (clr >> 16) & 0xff,
G = (clr >> 8) & 0xff,
B = clr & 0xff,
Size = PV_KeyFrames(0, 0, 0, 200, PV_Random(2, 50), 1000, 0),
};
CreateParticle("Dust", x2, y2, PV_Random(-3, 3), PV_Random(-3, -3), PV_Random(18, 1 * 36), particles, 3);
Sound("Clonk::Action::Dig::Dig?");
}
//It's solid, but not diggable. So it is a hard mineral.
else
{
var spark = Particles_Glimmer();
var pitch = nil;
var sound = "Objects::Pickaxe::Clang?";
if (GetMaterialVal("Density","Material",mat) > MaxPickDensity)
{
sound = "Objects::Pickaxe::ClangHard?";
pitch = RandomX(-20, 20);
spark.B = 255;
spark.R = PV_Random(0, 128, 2);
spark.OnCollision = PC_Bounce();
}
CreateParticle("StarSpark", x2*9/10, y2*9/10, PV_Random(-30, 30), PV_Random(-30, 30), PV_Random(10, 50), spark, 30);
Sound(sound, {pitch = pitch});
}
// Do blastfree after landscape checks are made. Otherwise, mat always returns as "tunnel"
BlastFree(GetX()+x2, GetY()+y2, 5, GetController(),MaxPickDensity);
// Make sure that new loose objects do not directly hit the Clonk and tumble it.
for (var obj in FindObjects(Find_Distance(10, x2, y2), Find_Category(C4D_Object), Find_Layer(), Find_NoContainer()))
{
if (obj->Stuck()) continue;
AddEffect("IntNoHitAllowed", obj, 1, 30, nil, GetID());
}
}
}
func FxIntPickaxeTimer(object clonk, proplist effect, int time)
{
++swingtime;
if (swingtime >= Pickaxe_SwingTime) // Waits three seconds for animation to run (we could have a clonk swing his pick 3 times)
{
DoSwing(clonk, effect.x, effect.y);
swingtime = 0;
}
var angle = Angle(0, 0, effect.x, effect.y);
var speed = 50;
var iPosition = swingtime*180/Pickaxe_SwingTime;
speed = speed*(Cos(iPosition-45, 50)**2)/2500;
// limit angle
angle = BoundBy(angle, 65, 300);
clonk->SetXDir(Sin(angle,+speed),100);
clonk->SetYDir(Cos(angle,-speed),100);
}
// Effects that sets the category of C4D_Objects to C4D_None for some time to prevent those objects from hitting the Clonk.
func FxIntNoHitAllowedStart(object target, effect fx, temp)
{
if (temp) return;
fx.category = target->GetCategory();
target->SetCategory(C4D_None);
}
func FxIntNoHitAllowedStop(object target, effect fx, int reason, temp)
{
if (temp || !target) return;
// If nothing magically changed the category, reset it.
if (target->GetCategory() == C4D_None)
target->SetCategory(fx.category);
}
/*-- Production --*/
public func IsTool() { return true; }
public func IsToolProduct() { return true; }
/*-- Display --*/
public func GetCarryMode(object clonk, bool idle)
{
if (!idle)
return CARRY_HandBack;
else
return CARRY_Back;
}
public func GetCarrySpecial(clonk) { if (using == 1) return "pos_hand2"; }
public func GetCarryTransform()
{
return Trans_Rotate(90, 1, 0, 0);
}
func Definition(def) {
SetProperty("PictureTransformation",Trans_Mul(Trans_Rotate(40, 0, 0, 1),Trans_Rotate(150, 0, 1, 0), Trans_Scale(900), Trans_Translate(600, 400, 1000)),def);
}
/*-- Properties --*/
local Name = "$Name$";
local Description = "$Description$";
local Collectible = true;
//MaxReach is the length of the pick from the clonk's hand
local MaxReach = 12;
// StrikeCone is the size of the cone checked for material hits in degrees.
local StrikeCone = 16;
local MaxPickDensity = 70; // can't pick granite
local ForceFreeHands = true;
local Components = {Wood = 1, Metal = 1};
local BlastIncinerate = 30;
local MaterialIncinerate = true;
local BurnDownTime = 140;
| 412 | 0.832564 | 1 | 0.832564 | game-dev | MEDIA | 0.933763 | game-dev | 0.87512 | 1 | 0.87512 |
Auxilor/libreforge | 3,469 | core/common/src/main/kotlin/com/willfp/libreforge/commands/CommandPointsGive.kt | package com.willfp.libreforge.commands
import com.willfp.eco.core.EcoPlugin
import com.willfp.eco.core.command.impl.Subcommand
import com.willfp.eco.util.toNiceString
import com.willfp.libreforge.globalPoints
import com.willfp.libreforge.points
import com.willfp.libreforge.toFriendlyPointName
import org.bukkit.Bukkit
import org.bukkit.command.CommandSender
import org.bukkit.util.StringUtil
@Suppress("UsagesOfObsoleteApi")
internal class CommandPointsGive(plugin: EcoPlugin): Subcommand(
plugin,
"give",
"libreforge.command.points.give",
false
) {
override fun onExecute(sender: CommandSender, args: MutableList<String>) {
val playerString = args.getOrNull(0)
if (playerString == null) {
sender.sendMessage(plugin.langYml.getMessage("must-specify-player"))
return
}
val pointString = args.getOrNull(1)
if (pointString == null) {
sender.sendMessage(plugin.langYml.getMessage("must-specify-point"))
return
}
val amount = args.getOrNull(2)
if (amount == null) {
sender.sendMessage(plugin.langYml.getMessage("must-specify-amount"))
return
}
val amountNum = amount.toDoubleOrNull()
if (amountNum == null) {
sender.sendMessage(plugin.langYml.getMessage("invalid-amount"))
return
}
if (playerString.equals("global", ignoreCase = true)) {
globalPoints[pointString] = globalPoints[pointString] + amountNum
sender.sendMessage(plugin.langYml.getMessage("points-given")
.replace("%playername%", "server")
.replace("%point%", pointString.toFriendlyPointName())
.replace("%amount%", amountNum.toNiceString())
)
return
}
if (playerString == "*") {
Bukkit.getOnlinePlayers().forEach { player ->
player.points[pointString] = player.points[pointString] + amountNum
}
sender.sendMessage(plugin.langYml.getMessage("points-given-all")
.replace("%point%", pointString.toFriendlyPointName())
.replace("%amount%", amountNum.toNiceString())
)
return
}
val player = Bukkit.getPlayer(playerString)
if (player == null) {
sender.sendMessage(plugin.langYml.getMessage("invalid-player"))
return
}
player.points[pointString] = player.points[pointString] + amountNum
sender.sendMessage(plugin.langYml.getMessage("points-given")
.replace("%playername%", player.name)
.replace("%point%", pointString.toFriendlyPointName())
.replace("%amount%", amountNum.toNiceString())
)
}
override fun tabComplete(sender: CommandSender, args: List<String>): List<String> {
return when(args.size) {
1 -> {
val candidates = Bukkit.getOnlinePlayers().map { it.name }.toMutableList()
candidates.add("global")
candidates.add("*")
StringUtil.copyPartialMatches(args[0], candidates, mutableListOf())
}
2 -> listOf("point")
3 -> mutableListOf(
"1",
"5",
"10",
"100",
"1000"
)
else -> mutableListOf()
}
}
}
| 412 | 0.847117 | 1 | 0.847117 | game-dev | MEDIA | 0.890656 | game-dev | 0.898959 | 1 | 0.898959 |
bazad/xpc-string-leak | 6,254 | README.md | xpc-string-leak
===================================================================================================
<!-- Brandon Azad -->
xpc-string-leak is a proof-of-concept exploit for an out-of-bounds memory read in libxpc. This
exploit uses the vulnerability to read out-of-bounds heap memory from diagnosticd, an unsandboxed
root process with the `task_for_pid-allow` entitlement.
The vulnerability: CVE-2018-4248
---------------------------------------------------------------------------------------------------
On macOS 10.13.5 and iOS 11.4, the function `_xpc_string_deserialize` does not verify that the
deserialized string is of the proper length before creating an XPC string object with
`_xpc_string_create`. This can lead to a heartbleed-style out-of-bounds heap read if the XPC string
is then serialized into another XPC message.
Here is the implementation of `_xpc_string_deserialize`, decompiled using IDA:
```C
OS_xpc_string *__fastcall _xpc_string_deserialize(OS_xpc_serializer *xserializer)
{
OS_xpc_string *xstring; // rbx@1
char *string; // rax@4
char *contents; // [rsp+8h] [rbp-18h]@1
size_t size; // [rsp+10h] [rbp-10h]@1 MAPDST
xstring = 0LL;
contents = 0LL;
size = 0LL;
if ( _xpc_string_get_wire_value(xserializer, (const char **)&contents, &size) )
{
if ( contents[size - 1] || (string = _xpc_try_strdup(contents)) == 0LL )
{
xstring = 0LL;
}
else
{
xstring = _xpc_string_create(string, size - 1);
LOBYTE(xstring->flags) |= 1u;
}
}
return xstring;
}
```
`_xpc_string_deserialize` first calls `_xpc_string_get_wire_value` to retrieve a pointer to the
string data as well as the serialized size of the string, as reported by the string header.
`_xpc_string_deserialize` then checks that the string has a null terminator at the end of its
reported size, but crucially does not check that there is no null terminator earlier in the data.
Finally, it creates a copy of the string on the heap and creates the `OS_xpc_string` object using
`_xpc_string_create`.
Here is the decompiled code for `_xpc_string_create`:
```C
OS_xpc_string *__fastcall _xpc_string_create(const char *string, size_t length)
{
OS_xpc_string *xstring; // rax@1
xstring = (OS_xpc_string *)_xpc_base_create(&OBJC_CLASS___OS_xpc_string, 16LL);
if ( (((_DWORD)length + 4) & 0xFFFFFFFC) + 4 < length )
_xpc_api_misuse("Unreasonably large string");
xstring->wire_length = ((length + 4) & 0xFFFFFFFC) + 4;
xstring->string = string;
xstring->length = length;
return xstring;
}
```
`_xpc_string_create` trusts the value of length supplied by `_xpc_string_deserialize` and sets the
appropriate fields in the `OS_xpc_string` object. At this point, the deserialized string may have a
`length` field that is larger than the allocated string data.
Exploitation
---------------------------------------------------------------------------------------------------
Theoretically, this could be used to trigger memory corruption in services that get the length of
the string using `xpc_string_get_length`, but this pattern seems to be uncommon. A less powerful
but more practical exploit strategy is to get the string to be re-serialized and sent back to us,
giving us a heartbleed-style window into the victim process's memory.
This is the implementation of `_xpc_string_serialize`:
```C
void __fastcall _xpc_string_serialize(OS_xpc_string *string, OS_xpc_serializer *serializer)
{
int type; // [rsp+8h] [rbp-18h]@1
int size; // [rsp+Ch] [rbp-14h]@1
type = *((_DWORD *)&OBJC_CLASS___OS_xpc_string + 10);
_xpc_serializer_append(serializer, &type, 4uLL, 1, 0, 0);
size = LODWORD(string->length) + 1;
_xpc_serializer_append(serializer, &size, 4uLL, 1, 0, 0);
_xpc_serializer_append(serializer, string->string, string->length + 1, 1, 0, 0);
}
```
The `OS_xpc_string`'s `length` parameter is trusted during serialization, meaning that many bytes
are read from the heap into the serialized message. If the deserialized string was shorter than its
reported length, the message will be filled with out-of-bounds heap data.
We're still limited to exploiting XPC services that reflect some part of the XPC message back to
the client, but this is much more common. For example, on macOS and iOS, diagnosticd is a promising
candidate that also happens to be unsandboxed, root, and has `task_for_pid` privileges. Diagnosticd
is responsible for processing diagnostic messages (for example, messages generated by `os_log`) and
streaming them to clients interested in receiving these messages. By registering to receive our own
diagnostic stream and then sending a diagnostic message with a shorter than expected string, we can
obtain a snapshot of some of the data in diagnosticd's heap, which can aid in getting code
execution in the process.
Usage
---------------------------------------------------------------------------------------------------
To build, run `make`. See the top of the Makefile for various build options.
Run the exploit by specifying the size of the leak on the command line:
$ ./xpc-string-leak 0x40
0x2000000000000000 0xe00007ff39bf0992
0x00007fff56858570 0x00007fff7ed23d0e
0x0000000000000000 0x0000000000000000
0x00007fff7ed52be2 0x00007fff7ed29ed6
The leak size must be a multiple of 8 and at least 16.
License
---------------------------------------------------------------------------------------------------
The xpc-string-leak code is released into the public domain. As a courtesy I ask that if you
reference or use any of this code you attribute it to me.
Timeline
---------------------------------------------------------------------------------------------------
I discovered this bug early in 2018 (January or February), but forgot to investigate it until
May. I reported the issue to Apple on May 9, and it was assigned CVE-2018-4248 and patched in [iOS
11.4.1] and [macOS 10.13.6] on July 9.
[iOS 11.4.1]: https://support.apple.com/en-us/HT208938
[macOS 10.13.6]: https://support.apple.com/en-us/HT208937
---------------------------------------------------------------------------------------------------
Brandon Azad
| 412 | 0.953539 | 1 | 0.953539 | game-dev | MEDIA | 0.497247 | game-dev | 0.644714 | 1 | 0.644714 |
MTVehicles/MinetopiaVehicles | 2,337 | src/main/java/nl/mtvehicles/core/commands/vehiclesubs/VehicleMenu.java | package nl.mtvehicles.core.commands.vehiclesubs;
import nl.mtvehicles.core.events.inventory.VehicleMenuOpenEvent;
import nl.mtvehicles.core.infrastructure.dataconfig.DefaultConfig;
import nl.mtvehicles.core.infrastructure.enums.InventoryTitle;
import nl.mtvehicles.core.infrastructure.enums.Message;
import nl.mtvehicles.core.infrastructure.utils.ItemFactory;
import nl.mtvehicles.core.infrastructure.utils.ItemUtils;
import nl.mtvehicles.core.infrastructure.models.MTVSubCommand;
import nl.mtvehicles.core.infrastructure.modules.ConfigModule;
import org.bukkit.Bukkit;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* <b>/vehicle menu</b> - open a GUI menu of all the vehicles.
*/
public class VehicleMenu extends MTVSubCommand {
public static HashMap<UUID, Inventory> beginMenu = new HashMap<>();
public VehicleMenu() {
this.setPlayerCommand(true);
}
@Override
public boolean execute() {
if (!checkPermission("mtvehicles.menu")) return true;
sendMessage(Message.MENU_OPEN);
int menuRows = (int) ConfigModule.defaultConfig.get(DefaultConfig.Option.VEHICLE_MENU_SIZE);
final int menuSize = (menuRows >= 3 && menuRows <= 6) ? menuRows * 9 : 27;
Inventory inv = Bukkit.createInventory(null, menuSize, InventoryTitle.VEHICLE_MENU.getStringTitle());
for (Map<?, ?> vehicle : ConfigModule.vehiclesConfig.getVehicles()) {
int itemDamage = (Integer) vehicle.get("itemDamage");
String name = (String) vehicle.get("name");
String skinItem = (String) vehicle.get("skinItem");
ItemStack itemStack = ItemUtils.getMenuVehicle(ItemUtils.getMaterial(skinItem), itemDamage, name);
if (vehicle.get("nbtValue") == null) {
inv.addItem(itemStack);
continue;
}
inv.addItem(new ItemFactory(itemStack).setNBT((String) vehicle.get("nbtKey"), (String)vehicle.get("nbtValue")).toItemStack());
}
VehicleMenuOpenEvent api = new VehicleMenuOpenEvent(player);
api.call();
if (api.isCancelled()) return true;
beginMenu.put(player.getUniqueId(), inv);
player.openInventory(inv);
return true;
}
}
| 412 | 0.788646 | 1 | 0.788646 | game-dev | MEDIA | 0.851083 | game-dev | 0.955567 | 1 | 0.955567 |
RLBot/RLBot | 1,336 | src/main/python/rlbot/matchcomms/common_uses/set_attributes_message.py | from typing import List, Optional
from rlbot.matchcomms.common_uses.common_keys import TARGET_PLAYER_INDEX
from rlbot.matchcomms.shared import JSON
from rlbot.agents.base_agent import BaseAgent
"""
This message instructs a certain player to persist some attribute.
"""
MESSAGE_KEY = 'setattrs'
ALL_KEYS_ALLOWED = None
def make_set_attributes_message(target_player_index: int, attrs: JSON) -> JSON:
assert type(attrs) is dict
return {
TARGET_PLAYER_INDEX: target_player_index,
MESSAGE_KEY: attrs,
}
def handle_set_attributes_message(msg: JSON, player: BaseAgent, allowed_keys: Optional[List[str]]=ALL_KEYS_ALLOWED) -> bool:
"""
Sets attributes on the player if the message was applicable for this task.
If allowed_keys is specified, any key not in this list is silently dropped.
Returns True iff the message was fully handled by this function.
"""
attrs = msg.get(MESSAGE_KEY, None)
if type(attrs) != dict: return False
if msg.get(TARGET_PLAYER_INDEX, None) != player.index: return False
# Copy values from attrs to the player.
if allowed_keys is ALL_KEYS_ALLOWED:
for k,v in attrs.items():
setattr(player, k, v)
else:
for k in allowed_keys:
if k in attrs:
setattr(player, k, attrs[k])
return True
| 412 | 0.709019 | 1 | 0.709019 | game-dev | MEDIA | 0.538119 | game-dev | 0.712292 | 1 | 0.712292 |
qnpiiz/rich-2.0 | 13,043 | src/main/java/net/minecraft/client/gui/screen/ReadBookScreen.java | package net.minecraft.client.gui.screen;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableList.Builder;
import com.mojang.blaze3d.matrix.MatrixStack;
import com.mojang.blaze3d.systems.RenderSystem;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nullable;
import net.minecraft.client.gui.DialogTexts;
import net.minecraft.client.gui.chat.NarratorChatListener;
import net.minecraft.client.gui.widget.button.Button;
import net.minecraft.client.gui.widget.button.ChangePageButton;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.item.WrittenBookItem;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.nbt.ListNBT;
import net.minecraft.util.IReorderingProcessor;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.ITextProperties;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.util.text.Style;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraft.util.text.event.ClickEvent;
public class ReadBookScreen extends Screen
{
public static final ReadBookScreen.IBookInfo EMPTY_BOOK = new ReadBookScreen.IBookInfo()
{
public int getPageCount()
{
return 0;
}
public ITextProperties func_230456_a_(int p_230456_1_)
{
return ITextProperties.field_240651_c_;
}
};
public static final ResourceLocation BOOK_TEXTURES = new ResourceLocation("textures/gui/book.png");
private ReadBookScreen.IBookInfo bookInfo;
private int currPage;
private List<IReorderingProcessor> cachedPageLines = Collections.emptyList();
private int cachedPage = -1;
private ITextComponent field_243344_s = StringTextComponent.EMPTY;
private ChangePageButton buttonNextPage;
private ChangePageButton buttonPreviousPage;
/** Determines if a sound is played when the page is turned */
private final boolean pageTurnSounds;
public ReadBookScreen(ReadBookScreen.IBookInfo bookInfoIn)
{
this(bookInfoIn, true);
}
public ReadBookScreen()
{
this(EMPTY_BOOK, false);
}
private ReadBookScreen(ReadBookScreen.IBookInfo bookInfoIn, boolean pageTurnSoundsIn)
{
super(NarratorChatListener.EMPTY);
this.bookInfo = bookInfoIn;
this.pageTurnSounds = pageTurnSoundsIn;
}
public void func_214155_a(ReadBookScreen.IBookInfo p_214155_1_)
{
this.bookInfo = p_214155_1_;
this.currPage = MathHelper.clamp(this.currPage, 0, p_214155_1_.getPageCount());
this.updateButtons();
this.cachedPage = -1;
}
/**
* Moves the book to the specified page and returns true if it exists, false otherwise
*/
public boolean showPage(int pageNum)
{
int i = MathHelper.clamp(pageNum, 0, this.bookInfo.getPageCount() - 1);
if (i != this.currPage)
{
this.currPage = i;
this.updateButtons();
this.cachedPage = -1;
return true;
}
else
{
return false;
}
}
/**
* I'm not sure why this exists. The function it calls is public and does all of the work
*/
protected boolean showPage2(int pageNum)
{
return this.showPage(pageNum);
}
protected void init()
{
this.addDoneButton();
this.addChangePageButtons();
}
protected void addDoneButton()
{
this.addButton(new Button(this.width / 2 - 100, 196, 200, 20, DialogTexts.GUI_DONE, (p_214161_1_) ->
{
this.mc.displayGuiScreen((Screen)null);
}));
}
protected void addChangePageButtons()
{
int i = (this.width - 192) / 2;
int j = 2;
this.buttonNextPage = this.addButton(new ChangePageButton(i + 116, 159, true, (p_214159_1_) ->
{
this.nextPage();
}, this.pageTurnSounds));
this.buttonPreviousPage = this.addButton(new ChangePageButton(i + 43, 159, false, (p_214158_1_) ->
{
this.previousPage();
}, this.pageTurnSounds));
this.updateButtons();
}
private int getPageCount()
{
return this.bookInfo.getPageCount();
}
/**
* Moves the display back one page
*/
protected void previousPage()
{
if (this.currPage > 0)
{
--this.currPage;
}
this.updateButtons();
}
/**
* Moves the display forward one page
*/
protected void nextPage()
{
if (this.currPage < this.getPageCount() - 1)
{
++this.currPage;
}
this.updateButtons();
}
private void updateButtons()
{
this.buttonNextPage.visible = this.currPage < this.getPageCount() - 1;
this.buttonPreviousPage.visible = this.currPage > 0;
}
public boolean keyPressed(int keyCode, int scanCode, int modifiers)
{
if (super.keyPressed(keyCode, scanCode, modifiers))
{
return true;
}
else
{
switch (keyCode)
{
case 266:
this.buttonPreviousPage.onPress();
return true;
case 267:
this.buttonNextPage.onPress();
return true;
default:
return false;
}
}
}
public void render(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks)
{
this.renderBackground(matrixStack);
RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F);
this.mc.getTextureManager().bindTexture(BOOK_TEXTURES);
int i = (this.width - 192) / 2;
int j = 2;
this.blit(matrixStack, i, 2, 0, 0, 192, 192);
if (this.cachedPage != this.currPage)
{
ITextProperties itextproperties = this.bookInfo.func_238806_b_(this.currPage);
this.cachedPageLines = this.font.trimStringToWidth(itextproperties, 114);
this.field_243344_s = new TranslationTextComponent("book.pageIndicator", this.currPage + 1, Math.max(this.getPageCount(), 1));
}
this.cachedPage = this.currPage;
int i1 = this.font.getStringPropertyWidth(this.field_243344_s);
this.font.func_243248_b(matrixStack, this.field_243344_s, (float)(i - i1 + 192 - 44), 18.0F, 0);
int k = Math.min(128 / 9, this.cachedPageLines.size());
for (int l = 0; l < k; ++l)
{
IReorderingProcessor ireorderingprocessor = this.cachedPageLines.get(l);
this.font.func_238422_b_(matrixStack, ireorderingprocessor, (float)(i + 36), (float)(32 + l * 9), 0);
}
Style style = this.func_238805_a_((double)mouseX, (double)mouseY);
if (style != null)
{
this.renderComponentHoverEffect(matrixStack, style, mouseX, mouseY);
}
super.render(matrixStack, mouseX, mouseY, partialTicks);
}
public boolean mouseClicked(double mouseX, double mouseY, int button)
{
if (button == 0)
{
Style style = this.func_238805_a_(mouseX, mouseY);
if (style != null && this.handleComponentClicked(style))
{
return true;
}
}
return super.mouseClicked(mouseX, mouseY, button);
}
public boolean handleComponentClicked(Style style)
{
ClickEvent clickevent = style.getClickEvent();
if (clickevent == null)
{
return false;
}
else if (clickevent.getAction() == ClickEvent.Action.CHANGE_PAGE)
{
String s = clickevent.getValue();
try
{
int i = Integer.parseInt(s) - 1;
return this.showPage2(i);
}
catch (Exception exception)
{
return false;
}
}
else
{
boolean flag = super.handleComponentClicked(style);
if (flag && clickevent.getAction() == ClickEvent.Action.RUN_COMMAND)
{
this.mc.displayGuiScreen((Screen)null);
}
return flag;
}
}
@Nullable
public Style func_238805_a_(double p_238805_1_, double p_238805_3_)
{
if (this.cachedPageLines.isEmpty())
{
return null;
}
else
{
int i = MathHelper.floor(p_238805_1_ - (double)((this.width - 192) / 2) - 36.0D);
int j = MathHelper.floor(p_238805_3_ - 2.0D - 30.0D);
if (i >= 0 && j >= 0)
{
int k = Math.min(128 / 9, this.cachedPageLines.size());
if (i <= 114 && j < 9 * k + k)
{
int l = j / 9;
if (l >= 0 && l < this.cachedPageLines.size())
{
IReorderingProcessor ireorderingprocessor = this.cachedPageLines.get(l);
return this.mc.fontRenderer.getCharacterManager().func_243239_a(ireorderingprocessor, i);
}
else
{
return null;
}
}
else
{
return null;
}
}
else
{
return null;
}
}
}
public static List<String> nbtPagesToStrings(CompoundNBT p_214157_0_)
{
ListNBT listnbt = p_214157_0_.getList("pages", 8).copy();
Builder<String> builder = ImmutableList.builder();
for (int i = 0; i < listnbt.size(); ++i)
{
builder.add(listnbt.getString(i));
}
return builder.build();
}
public interface IBookInfo
{
int getPageCount();
ITextProperties func_230456_a_(int p_230456_1_);
default ITextProperties func_238806_b_(int p_238806_1_)
{
return p_238806_1_ >= 0 && p_238806_1_ < this.getPageCount() ? this.func_230456_a_(p_238806_1_) : ITextProperties.field_240651_c_;
}
static ReadBookScreen.IBookInfo func_216917_a(ItemStack p_216917_0_)
{
Item item = p_216917_0_.getItem();
if (item == Items.WRITTEN_BOOK)
{
return new ReadBookScreen.WrittenBookInfo(p_216917_0_);
}
else
{
return (ReadBookScreen.IBookInfo)(item == Items.WRITABLE_BOOK ? new ReadBookScreen.UnwrittenBookInfo(p_216917_0_) : ReadBookScreen.EMPTY_BOOK);
}
}
}
public static class UnwrittenBookInfo implements ReadBookScreen.IBookInfo
{
private final List<String> pages;
public UnwrittenBookInfo(ItemStack p_i50617_1_)
{
this.pages = func_216919_b(p_i50617_1_);
}
private static List<String> func_216919_b(ItemStack p_216919_0_)
{
CompoundNBT compoundnbt = p_216919_0_.getTag();
return (List<String>)(compoundnbt != null ? ReadBookScreen.nbtPagesToStrings(compoundnbt) : ImmutableList.of());
}
public int getPageCount()
{
return this.pages.size();
}
public ITextProperties func_230456_a_(int p_230456_1_)
{
return ITextProperties.func_240652_a_(this.pages.get(p_230456_1_));
}
}
public static class WrittenBookInfo implements ReadBookScreen.IBookInfo
{
private final List<String> pages;
public WrittenBookInfo(ItemStack p_i50616_1_)
{
this.pages = func_216921_b(p_i50616_1_);
}
private static List<String> func_216921_b(ItemStack stack)
{
CompoundNBT compoundnbt = stack.getTag();
return (List<String>)(compoundnbt != null && WrittenBookItem.validBookTagContents(compoundnbt) ? ReadBookScreen.nbtPagesToStrings(compoundnbt) : ImmutableList.of(ITextComponent.Serializer.toJson((new TranslationTextComponent("book.invalid.tag")).mergeStyle(TextFormatting.DARK_RED))));
}
public int getPageCount()
{
return this.pages.size();
}
public ITextProperties func_230456_a_(int p_230456_1_)
{
String s = this.pages.get(p_230456_1_);
try
{
ITextProperties itextproperties = ITextComponent.Serializer.getComponentFromJson(s);
if (itextproperties != null)
{
return itextproperties;
}
}
catch (Exception exception)
{
}
return ITextProperties.func_240652_a_(s);
}
}
}
| 412 | 0.840481 | 1 | 0.840481 | game-dev | MEDIA | 0.840818 | game-dev | 0.977477 | 1 | 0.977477 |
BluSunrize/ImmersiveEngineering | 3,075 | src/main/java/blusunrize/immersiveengineering/client/render/tile/WatermillRenderer.java | /*
* BluSunrize
* Copyright (c) 2017
*
* This code is licensed under "Blu's License of Common Sense"
* Details can be found in the license file in the root folder of this project
*/
package blusunrize.immersiveengineering.client.render.tile;
import blusunrize.immersiveengineering.api.ApiUtils;
import blusunrize.immersiveengineering.api.IEProperties;
import blusunrize.immersiveengineering.api.client.IVertexBufferHolder;
import blusunrize.immersiveengineering.api.utils.SafeChunkUtils;
import blusunrize.immersiveengineering.common.blocks.wooden.WatermillBlockEntity;
import blusunrize.immersiveengineering.common.register.IEBlocks.WoodenDevices;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.Direction.Axis;
import net.minecraft.util.Mth;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.AABB;
import net.neoforged.neoforge.client.model.data.ModelData;
import org.joml.Quaternionf;
public class WatermillRenderer extends IEBlockEntityRenderer<WatermillBlockEntity>
{
public static final String NAME = "watermill";
public static DynamicModel MODEL;
private static final IVertexBufferHolder MODEL_BUFFER = IVertexBufferHolder.create(() -> {
BlockState state = WoodenDevices.WATERMILL.defaultBlockState()
.setValue(IEProperties.FACING_HORIZONTAL, Direction.NORTH);
return MODEL.get().getQuads(state, null, ApiUtils.RANDOM_SOURCE, ModelData.EMPTY, null);
});
@Override
public void render(WatermillBlockEntity tile, float partialTicks, PoseStack transform, MultiBufferSource bufferIn,
int combinedLightIn, int combinedOverlayIn)
{
if(!SafeChunkUtils.isChunkSafe(tile.getLevelNonnull(), tile.getBlockPos()))
return;
transform.pushPose();
transform.translate(.5, .5, .5);
if(tile.getFacing().getAxis()==Axis.X)
transform.mulPose(new Quaternionf().rotateY(Mth.HALF_PI));
float wheelRotation = (float)(Mth.TWO_PI*(tile.getRotation()+partialTicks*tile.getSpeed()));
transform.mulPose(new Quaternionf().rotateZ(wheelRotation));
transform.translate(-.5, -.5, -.5);
MODEL_BUFFER.render(RenderType.cutoutMipped(), combinedLightIn, combinedOverlayIn, bufferIn, transform);
transform.popPose();
}
public static void reset()
{
MODEL_BUFFER.reset();
}
@Override
public AABB getRenderBoundingBox(WatermillBlockEntity watermill)
{
if(watermill.renderAABB==null)
{
BlockPos pos = watermill.getBlockPos();
Direction facing = watermill.getFacing();
if(watermill.offset[0]==0&&watermill.offset[1]==0)
watermill.renderAABB = new AABB(
pos.getX()-(facing.getAxis()==Axis.Z?2: 0),
pos.getY()-2,
pos.getZ()-(facing.getAxis()==Axis.Z?0: 2),
pos.getX()+(facing.getAxis()==Axis.Z?3: 1),
pos.getY()+3,
pos.getZ()+(facing.getAxis()==Axis.Z?1: 3)
);
else
watermill.renderAABB = new AABB(pos);
}
return watermill.renderAABB;
}
} | 412 | 0.878763 | 1 | 0.878763 | game-dev | MEDIA | 0.919306 | game-dev,graphics-rendering | 0.962211 | 1 | 0.962211 |
NeoLoader/NeoLoader | 4,834 | 7-Zip/7z920/CPP/Windows/Menu.h | // Windows/Menu.h
#ifndef __WINDOWS_MENU_H
#define __WINDOWS_MENU_H
#include "Common/MyString.h"
#include "Windows/Defs.h"
namespace NWindows {
struct CMenuItem
{
UString StringValue;
UINT fMask;
UINT fType;
UINT fState;
UINT wID;
HMENU hSubMenu;
HBITMAP hbmpChecked;
HBITMAP hbmpUnchecked;
ULONG_PTR dwItemData;
// LPTSTR dwTypeData;
// UINT cch;
// HBITMAP hbmpItem;
bool IsString() const // change it MIIM_STRING
{ return ((fMask & MIIM_TYPE) != 0 && (fType == MFT_STRING)); }
bool IsSeparator() const { return (fType == MFT_SEPARATOR); }
CMenuItem(): fMask(0), fType(0), fState(0), wID(0), hSubMenu(0), hbmpChecked(0),
hbmpUnchecked(0), dwItemData(0) {}
};
class CMenu
{
HMENU _menu;
public:
CMenu(): _menu(NULL) {};
operator HMENU() const { return _menu; }
void Attach(HMENU menu) { _menu = menu; }
HMENU Detach()
{
HMENU menu = _menu;
_menu = NULL;
return menu;
}
bool Create()
{
_menu = ::CreateMenu();
return (_menu != NULL);
}
bool CreatePopup()
{
_menu = ::CreatePopupMenu();
return (_menu != NULL);
}
bool Destroy()
{
if (_menu == NULL)
return false;
return BOOLToBool(::DestroyMenu(Detach()));
}
int GetItemCount()
{
#ifdef UNDER_CE
for (int i = 0;; i++)
{
CMenuItem item;
item.fMask = MIIM_STATE;
if (!GetItem(i, true, item))
return i;
}
#else
return GetMenuItemCount(_menu);
#endif
}
HMENU GetSubMenu(int pos) { return ::GetSubMenu(_menu, pos); }
#ifndef UNDER_CE
bool GetItemString(UINT idItem, UINT flag, CSysString &result)
{
result.Empty();
int len = ::GetMenuString(_menu, idItem, 0, 0, flag);
len = ::GetMenuString(_menu, idItem, result.GetBuffer(len + 2), len + 1, flag);
result.ReleaseBuffer();
return (len != 0);
}
UINT GetItemID(int pos) { return ::GetMenuItemID(_menu, pos); }
UINT GetItemState(UINT id, UINT flags) { return ::GetMenuState(_menu, id, flags); }
#endif
bool GetItemInfo(UINT itemIndex, bool byPosition, LPMENUITEMINFO itemInfo)
{ return BOOLToBool(::GetMenuItemInfo(_menu, itemIndex, BoolToBOOL(byPosition), itemInfo)); }
bool SetItemInfo(UINT itemIndex, bool byPosition, LPMENUITEMINFO itemInfo)
{ return BOOLToBool(::SetMenuItemInfo(_menu, itemIndex, BoolToBOOL(byPosition), itemInfo)); }
bool AppendItem(UINT flags, UINT_PTR newItemID, LPCTSTR newItem)
{ return BOOLToBool(::AppendMenu(_menu, flags, newItemID, newItem)); }
bool Insert(UINT position, UINT flags, UINT_PTR idNewItem, LPCTSTR newItem)
{ return BOOLToBool(::InsertMenu(_menu, position, flags, idNewItem, newItem)); }
#ifndef UNDER_CE
bool InsertItem(UINT itemIndex, bool byPosition, LPCMENUITEMINFO itemInfo)
{ return BOOLToBool(::InsertMenuItem(_menu, itemIndex, BoolToBOOL(byPosition), itemInfo)); }
#endif
bool RemoveItem(UINT item, UINT flags) { return BOOLToBool(::RemoveMenu(_menu, item, flags)); }
void RemoveAllItemsFrom(UINT index) { while (RemoveItem(index, MF_BYPOSITION)); }
void RemoveAllItems() { RemoveAllItemsFrom(0); }
#ifndef _UNICODE
bool GetItemInfo(UINT itemIndex, bool byPosition, LPMENUITEMINFOW itemInfo)
{ return BOOLToBool(::GetMenuItemInfoW(_menu, itemIndex, BoolToBOOL(byPosition), itemInfo)); }
bool InsertItem(UINT itemIndex, bool byPosition, LPMENUITEMINFOW itemInfo)
{ return BOOLToBool(::InsertMenuItemW(_menu, itemIndex, BoolToBOOL(byPosition), itemInfo)); }
bool SetItemInfo(UINT itemIndex, bool byPosition, LPMENUITEMINFOW itemInfo)
{ return BOOLToBool(::SetMenuItemInfoW(_menu, itemIndex, BoolToBOOL(byPosition), itemInfo)); }
bool AppendItem(UINT flags, UINT_PTR newItemID, LPCWSTR newItem);
#endif
bool GetItem(UINT itemIndex, bool byPosition, CMenuItem &item);
bool SetItem(UINT itemIndex, bool byPosition, const CMenuItem &item);
bool InsertItem(UINT itemIndex, bool byPosition, const CMenuItem &item);
int Track(UINT flags, int x, int y, HWND hWnd) { return ::TrackPopupMenuEx(_menu, flags, x, y, hWnd, NULL); }
bool CheckRadioItem(UINT idFirst, UINT idLast, UINT idCheck, UINT flags)
{ return BOOLToBool(::CheckMenuRadioItem(_menu, idFirst, idLast, idCheck, flags)); }
DWORD CheckItem(UINT id, UINT uCheck) { return ::CheckMenuItem(_menu, id, uCheck); }
DWORD CheckItemByID(UINT id, bool check) { return CheckItem(id, MF_BYCOMMAND | (check ? MF_CHECKED : MF_UNCHECKED)); }
BOOL EnableItem(UINT uIDEnableItem, UINT uEnable) { return EnableMenuItem(_menu, uIDEnableItem, uEnable); }
};
class CMenuDestroyer
{
CMenu *_menu;
public:
CMenuDestroyer(CMenu &menu): _menu(&menu) {}
CMenuDestroyer(): _menu(0) {}
~CMenuDestroyer() { if (_menu) _menu->Destroy(); }
void Attach(CMenu &menu) { _menu = &menu; }
void Disable() { _menu = 0; }
};
}
#endif
| 412 | 0.880382 | 1 | 0.880382 | game-dev | MEDIA | 0.414843 | game-dev | 0.619736 | 1 | 0.619736 |
ravendb/docs | 12,905 | versioned_docs/version-7.0/client-api/operations/counters/_counter-batch-csharp.mdx | import Admonition from '@theme/Admonition';
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
import CodeBlock from '@theme/CodeBlock';
*CounterBatchOperation* allows you to operate on multiple counters (`Increment`, `Get`, `Delete`) of different documents in a **single request**.
## Syntax
<TabItem value="counter_batch_op" label="counter_batch_op">
<CodeBlock language="csharp">
{`public CounterBatchOperation(CounterBatch counterBatch)
`}
</CodeBlock>
</TabItem>
| Parameter | | |
|------------------|----------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------|
| **counterBatch** | `CounterBatch` | An object that holds a list of `DocumentCountersOperation`.<br/>Each element in the list describes the counter operations to perform for a specific document |
<TabItem value="counter_batch" label="counter_batch">
<CodeBlock language="csharp">
{`public class CounterBatch
\{
public bool ReplyWithAllNodesValues; // A flag that indicates if the results should include a
// dictionary of counter values per database node
public List<DocumentCountersOperation> Documents = new List<DocumentCountersOperation>();
\}
`}
</CodeBlock>
</TabItem>
#### DocumentCountersOperation
<TabItem value="document_counters_op" label="document_counters_op">
<CodeBlock language="csharp">
{`public class DocumentCountersOperation
\{
public string DocumentId; // Id of the document that holds the counters
public List<CounterOperation> Operations; // A list of counter operations to perform
\}
`}
</CodeBlock>
</TabItem>
#### CounterOperation
<TabItem value="counter_operation" label="counter_operation">
<CodeBlock language="csharp">
{`public class CounterOperation
\{
public CounterOperationType Type;
public string CounterName;
public long Delta; // the value to increment by
\}
`}
</CodeBlock>
</TabItem>
#### CounterOperationType
<TabItem value="counter_operation_type" label="counter_operation_type">
<CodeBlock language="csharp">
{`public enum CounterOperationType
\{
Increment,
Delete,
Get
\}
`}
</CodeBlock>
</TabItem>
<Admonition type="info" title="Document updates as a result of a counter operation " id="document-updates-as-a-result-of-a-counter-operation" href="#document-updates-as-a-result-of-a-counter-operation">
A document that has counters holds all its counter names in the `metadata`.
Therefore, when creating a new counter, the parent document is modified, as the counter's name needs to be added to the metadata.
Deleting a counter also modifies the parent document, as the counter's name needs to be removed from the metadata.
Incrementing an existing counter will not modify the parent document.
Even if a `DocumentCountersOperation` contains several `CounterOperation` items that affect the document's metadata (create, delete),
the parent document will be modified **only once**, after all the `CounterOperation` items in this `DocumentCountersOperation` have been processed.
If `DocumentCountersOperation` doesn't contain any `CounterOperation` that affects the metadata, the parent document won't be modified.
</Admonition>
## Return Value
* *CounterBatchOperation* returns a `CountersDetail` object, which holds a list of `CounterDetail` objects.
* If a `CounterOperationType` is `Increment` or `Get`, a `CounterDetail` object will be added to the result.
`Delete` operations will not be included in the result.
<TabItem value="counters_detail" label="counters_detail">
<CodeBlock language="csharp">
{`public class CountersDetail
\{
public List<CounterDetail> Counters;
\}
`}
</CodeBlock>
</TabItem>
<TabItem value="counter_detail" label="counter_detail">
<CodeBlock language="csharp">
{`public class CounterDetail
\{
public string DocumentId; // ID of the document that holds the counter
public string CounterName; // The counter name
public long TotalValue; // Total counter value
public Dictionary<string, long> CounterValues; // A dictionary of counter values per database node
public long Etag; // Counter Etag
public string ChangeVector; // Change vector of the counter
\}
`}
</CodeBlock>
</TabItem>
## Examples
Assume we have two documents, *"users/1"* and *"users/2"*, that hold 3 counters each -
*"likes"*, *"dislikes"* and *"downloads"* - with values 10, 20 and 30 (respectively)
### Example #1 : Increment Multiple Counters in a Batch
<TabItem value="counter_batch_exmpl1" label="counter_batch_exmpl1">
<CodeBlock language="csharp">
{`var operationResult = store.Operations.Send(new CounterBatchOperation(new CounterBatch
\{
Documents = new List<DocumentCountersOperation>
\{
new DocumentCountersOperation
\{
DocumentId = "users/1",
Operations = new List<CounterOperation>
\{
new CounterOperation
\{
Type = CounterOperationType.Increment,
CounterName = "likes",
Delta = 5
\},
new CounterOperation
\{
// No Delta specified, value will be incremented by 1
// (From RavenDB 6.2 on, the default Delta is 1)
Type = CounterOperationType.Increment,
CounterName = "dislikes"
\}
\}
\},
new DocumentCountersOperation
\{
DocumentId = "users/2",
Operations = new List<CounterOperation>
\{
new CounterOperation
\{
Type = CounterOperationType.Increment,
CounterName = "likes",
Delta = 100
\},
new CounterOperation
\{
// this will create a new counter "score", with initial value 50
// "score" will be added to counter-names in "users/2" metadata
Type = CounterOperationType.Increment,
CounterName = "score",
Delta = 50
\}
\}
\}
\}
\}));
`}
</CodeBlock>
</TabItem>
#### Result:
<TabItem value="json" label="json">
<CodeBlock language="json">
{`\{
"Counters":
[
\{
"DocumentId" : "users/1",
"CounterName" : "likes",
"TotalValue" : 15,
"CounterValues" : null
\},
\{
"DocumentId" : "users/1",
"CounterName" : "dislikes",
"TotalValue" : 20,
"CounterValues" : null
\},
\{
"DocumentId" : "users/2",
"CounterName" : "likes",
"TotalValue" : 110,
"CounterValues" : null
\},
\{
"DocumentId" : "users/2",
"CounterName" : "score",
"TotalValue" : 50,
"CounterValues" : null
\}
]
\}
`}
</CodeBlock>
</TabItem>
### Example #2 : Get Multiple Counters in a Batch
<TabItem value="counter_batch_exmpl2" label="counter_batch_exmpl2">
<CodeBlock language="csharp">
{`var operationResult = store.Operations.Send(new CounterBatchOperation(new CounterBatch
\{
Documents = new List<DocumentCountersOperation>
\{
new DocumentCountersOperation
\{
DocumentId = "users/1",
Operations = new List<CounterOperation>
\{
new CounterOperation
\{
Type = CounterOperationType.Get,
CounterName = "likes"
\},
new CounterOperation
\{
Type = CounterOperationType.Get,
CounterName = "downloads"
\}
\}
\},
new DocumentCountersOperation
\{
DocumentId = "users/2",
Operations = new List<CounterOperation>
\{
new CounterOperation
\{
Type = CounterOperationType.Get,
CounterName = "likes"
\},
new CounterOperation
\{
Type = CounterOperationType.Get,
CounterName = "score"
\}
\}
\}
\}
\}));
`}
</CodeBlock>
</TabItem>
#### Result:
<TabItem value="json" label="json">
<CodeBlock language="json">
{`\{
"Counters":
[
\{
"DocumentId" : "users/1",
"CounterName" : "likes",
"TotalValue" : 15,
"CounterValues" : null
\},
\{
"DocumentId" : "users/1",
"CounterName" : "downloads",
"TotalValue" : 30,
"CounterValues" : null
\},
\{
"DocumentId" : "users/2",
"CounterName" : "likes",
"TotalValue" : 110,
"CounterValues" : null
\},
\{
"DocumentId" : "users/2",
"CounterName" : "score",
"TotalValue" : 50,
"CounterValues" : null
\}
]
\}
`}
</CodeBlock>
</TabItem>
### Example #3 : Delete Multiple Counters in a Batch
<TabItem value="counter_batch_exmpl3" label="counter_batch_exmpl3">
<CodeBlock language="csharp">
{`var operationResult = store.Operations.Send(new CounterBatchOperation(new CounterBatch
\{
Documents = new List<DocumentCountersOperation>
\{
new DocumentCountersOperation
\{
DocumentId = "users/1",
Operations = new List<CounterOperation>
\{
// "likes" and "dislikes" will be removed from counter-names in "users/1" metadata
new CounterOperation
\{
Type = CounterOperationType.Delete,
CounterName = "likes"
\},
new CounterOperation
\{
Type = CounterOperationType.Delete,
CounterName = "dislikes"
\}
\}
\},
new DocumentCountersOperation
\{
DocumentId = "users/2",
Operations = new List<CounterOperation>
\{
// "downloads" will be removed from counter-names in "users/2" metadata
new CounterOperation
\{
Type = CounterOperationType.Delete,
CounterName = "downloads"
\}
\}
\}
\}
\}));
`}
</CodeBlock>
</TabItem>
#### Result:
<TabItem value="json" label="json">
<CodeBlock language="json">
{`\{
"Counters": []
\}
`}
</CodeBlock>
</TabItem>
### Example #4 : Mix Different Types of CounterOperations in a Batch
<TabItem value="counter_batch_exmpl4" label="counter_batch_exmpl4">
<CodeBlock language="csharp">
{`var operationResult = store.Operations.Send(new CounterBatchOperation(new CounterBatch
\{
Documents = new List<DocumentCountersOperation>
\{
new DocumentCountersOperation
\{
DocumentId = "users/1",
Operations = new List<CounterOperation>
\{
new CounterOperation
\{
Type = CounterOperationType.Increment,
CounterName = "likes",
Delta = 30
\},
new CounterOperation
\{
// The results will include null for this 'Get'
// since we deleted the "dislikes" counter in the previous example flow
Type = CounterOperationType.Get,
CounterName = "dislikes"
\},
new CounterOperation
\{
Type = CounterOperationType.Delete,
CounterName = "downloads"
\}
\}
\},
new DocumentCountersOperation
\{
DocumentId = "users/2",
Operations = new List<CounterOperation>
\{
new CounterOperation
\{
Type = CounterOperationType.Get,
CounterName = "likes"
\},
new CounterOperation
\{
Type = CounterOperationType.Delete,
CounterName = "dislikes"
\}
\}
\}
\}
\}));
`}
</CodeBlock>
</TabItem>
#### Result:
* Note: The `Delete` operations are Not included in the results.
<TabItem value="json" label="json">
<CodeBlock language="json">
{`\{
"Counters":
[
\{
"DocumentId" : "users/1",
"CounterName" : "likes",
"TotalValue" : 30,
"CounterValues" : null
\},
null,
\{
"DocumentId" : "users/2",
"CounterName" : "likes",
"TotalValue" : 110,
"CounterValues" : null
\}
]
\}
`}
</CodeBlock>
</TabItem>
| 412 | 0.773758 | 1 | 0.773758 | game-dev | MEDIA | 0.221053 | game-dev | 0.831747 | 1 | 0.831747 |
ericraio/vanilla-wow-addons | 28,416 | f/FuBar_GroupFu/GroupFu.lua | local dewdrop = DewdropLib:GetInstance('1.0');
local tablet = TabletLib:GetInstance('1.0');
local metrognome = Metrognome:GetInstance("1");
local babble = BabbleLib:GetInstance("1.0");
GroupFu = FuBarPlugin:new({
name = GroupFuLocals.NAME,
description = GroupFuLocals.DESCRIPTION,
version = "1.4.7.4",
releaseDate = "2006-07-10",
aceCompatible = 103,
fuCompatible = 102,
author = "Etten",
email = "idbrain@gmail.com",
website = "http://etten.wowinterface.com",
category = "interface",
db = AceDatabase:new("GroupFuDB"),
defaults = {
RollOnClick = true,
ShowMLName = false,
OutputChannel = "PARTY",
OutputDetail = "SHORT",
ClearTimer = 30,
StandardRollsOnly = true,
ShowRollCount = false,
AnnounceRollCountdown = false,
IgnoreDuplicates = true,
DeleteRolls = true,
ShowClassLevel = false,
TextMode = "GROUPFU",
LootColorTable = {}
},
hasIcon = GroupFuLocals.DEFAULT_ICON,
clickableTooltip = true,
cannotDetachTooltip = false,
canHideText = true,
updateTime = 1.0,
-- Localization Tags
loc = GroupFuLocals,
ENDGROUPFU = true
});
function GroupFu:Initialize()
if self.data.version < self.versionNumber then
self.data.Colors = nil;
self.data.Rolls = nil;
self.data.RollCount = nil;
self.data.Threshold = nil;
self.data.LootType = nil;
end
if not self.tmpdata then
self.tmpdata = {};
end
end
function GroupFu:Enable()
self:RegisterEvent("CHAT_MSG_SYSTEM");
self:RegisterEvent("PARTY_MEMBERS_CHANGED", "Update");
self:RegisterEvent("PARTY_LOOT_METHOD_CHANGED", "Update");
self:RegisterEvent("RAID_ROSTER_UPDATE", "Update");
if not self.data.LootColorTable or table.getn(self.data.LootColorTable) == 0 then
for i=0,6 do
local r, g, b, hex = GetItemQualityColor(i);
self.data.LootColorTable[i] =
{
Red = r,
Green = g,
Blue = b,
Hex = hex,
Threshold = i,
Desc = getglobal("ITEM_QUALITY".. i .. "_DESC")
};
end
end
self:ClearRolls();
self.tmpdata.TimeSinceLastRoll = 0;
metrognome:Register("MGtimer", self.CheckRollTimeout, self.updateTime, self);
metrognome:Start("MGtimer");
end
function GroupFu:Disable()
self:ClearRolls();
metrognome:Stop("MGtimer");
end
function GroupFu:MenuSettings(level, value, inTooltip)
if not inTooltip then
if level == 1 then
dewdrop:AddLine(
'text', self.loc.MENU_OUTPUT,
'value', "MENU_OUTPUT",
'hasArrow', true
);
dewdrop:AddLine(
'text', self.loc.MENU_CLEAR,
'value', "MENU_CLEAR",
'hasArrow', true
);
dewdrop:AddLine(
'text', self.loc.MENU_DETAIL,
'value', "MENU_DETAIL",
'hasArrow', true
);
dewdrop:AddLine(
'text', self.loc.MENU_MODE,
'value', "MENU_MODE",
'hasArrow', true
);
dewdrop:AddLine(
'text', self.loc.MENU_PERFORMROLL,
'value', self.loc.MENU_PERFORMROLL,
'func', function() self:ToggleOption("RollOnClick") end,
'checked', self.data.RollOnClick
);
dewdrop:AddLine(
'text', self.loc.MENU_STANDARDROLLSONLY,
'value', self.loc.MENU_STANDARDROLLSONLY,
'func', function() self:ToggleOption("StandardRollsOnly") end,
'checked', self.data.StandardRollsOnly
);
dewdrop:AddLine(
'text', self.loc.MENU_SHOWROLLCOUNT,
'value', self.loc.MENU_SHOWROLLCOUNT,
'func', function() self:ToggleOption("ShowRollCount") end,
'checked', self.data.ShowRollCount
);
dewdrop:AddLine(
'text', self.loc.MENU_IGNOREDUPES,
'value', self.loc.MENU_IGNOREDUPES,
'func', function() self:ToggleOption("IgnoreDuplicates") end,
'checked', self.data.IgnoreDuplicates
);
dewdrop:AddLine(
'text', self.loc.MENU_AUTODELETE,
'value', self.loc.MENU_AUTODELETE,
'func', function() self:ToggleOption("DeleteRolls") end,
'checked', self.data.DeleteRolls
);
dewdrop:AddLine(
'text', self.loc.MENU_ANNOUNCEROLLCOUNTDOWN,
'value', self.loc.MENU_ANNOUNCEROLLCOUNTDOWN,
'func', function() self:ToggleOption("AnnounceRollCountdown") end,
'checked', self.data.AnnounceRollCountdown
);
dewdrop:AddLine(
'text', self.loc.MENU_SHOWCLASSLEVEL,
'value', self.loc.MENU_SHOWCLASSLEVEL,
'func', function() self:ToggleOption("ShowClassLevel") end,
'checked', self.data.ShowClassLevel
);
dewdrop:AddLine(
'text', self.loc.MENU_SHOWMLNAME,
'value', self.loc.MENU_SHOWMLNAME,
'func', function() self:ToggleOption("ShowMLName") end,
'checked', self.data.ShowMLName
);
dewdrop:AddLine(
'text', self.loc.MENU_GROUP,
'value', "MENU_GROUP",
'hasArrow', true
);
elseif level == 2 then
if value == "MENU_OUTPUT" then
dewdrop:AddLine(
'text', self.loc.MENU_OUTPUT_AUTO,
'value', "AUTO",
'func', function() self:ToggleOutputChannel("AUTO") end,
'isRadio', true,
'checked', self:IsOutputChannel("AUTO")
);
dewdrop:AddLine(
'text', self.loc.MENU_OUTPUT_LOCAL,
'value', "LOCAL",
'func', function() self:ToggleOutputChannel("LOCAL") end,
'isRadio', true,
'checked', self:IsOutputChannel("LOCAL")
);
dewdrop:AddLine(
'text', self.loc.MENU_OUTPUT_SAY,
'value', "SAY",
'func', function() self:ToggleOutputChannel("SAY") end,
'isRadio', true,
'checked', self:IsOutputChannel("SAY")
);
dewdrop:AddLine(
'text', self.loc.MENU_OUTPUT_PARTY,
'value', "PARTY",
'func', function() self:ToggleOutputChannel("PARTY") end,
'isRadio', true,
'checked', self:IsOutputChannel("PARTY")
);
dewdrop:AddLine(
'text', self.loc.MENU_OUTPUT_RAID,
'value', "RAID",
'func', function() self:ToggleOutputChannel("RAID") end,
'isRadio', true,
'checked', self:IsOutputChannel("RAID")
);
dewdrop:AddLine(
'text', self.loc.MENU_OUTPUT_GUILD,
'value', "GUILD",
'func', function() self:ToggleOutputChannel("GUILD") end,
'isRadio', true,
'checked', self:IsOutputChannel("GUILD")
);
elseif value == "MENU_CLEAR" then
dewdrop:AddLine(
'text', self.loc.MENU_CLEAR_NEVER,
'value', 0,
'func', function() self:ToggleClearTimer(0) end,
'isRadio', true,
'checked', self:IsClearTimer(0)
);
dewdrop:AddLine(
'text', self.loc.MENU_CLEAR_15SEC,
'value', 15,
'func', function() self:ToggleClearTimer(15) end,
'isRadio', true,
'checked', self:IsClearTimer(15)
);
dewdrop:AddLine(
'text', self.loc.MENU_CLEAR_30SEC,
'value', 30,
'func', function() self:ToggleClearTimer(30) end,
'isRadio', true,
'checked', self:IsClearTimer(30)
);
dewdrop:AddLine(
'text', self.loc.MENU_CLEAR_45SEC,
'value', 45,
'func', function() self:ToggleClearTimer(45) end,
'isRadio', true,
'checked', self:IsClearTimer(45)
);
dewdrop:AddLine(
'text', self.loc.MENU_CLEAR_60SEC,
'value', 60,
'func', function() self:ToggleClearTimer(60) end,
'isRadio', true,
'checked', self:IsClearTimer(60)
);
elseif value == "MENU_DETAIL" then
dewdrop:AddLine(
'text', self.loc.MENU_DETAIL_SHORT,
'value', "SHORT",
'func', function() self:ToggleOutputDetail("SHORT") end,
'isRadio', true,
'checked', self:IsOutputDetail("SHORT")
);
dewdrop:AddLine(
'text', self.loc.MENU_DETAIL_LONG,
'value', "LONG",
'func', function() self:ToggleOutputDetail("LONG") end,
'isRadio', true,
'checked', self:IsOutputDetail("LONG")
);
dewdrop:AddLine(
'text', self.loc.MENU_DETAIL_FULL,
'value', "FULL",
'func', function() self:ToggleOutputDetail("FULL") end,
'isRadio', true,
'checked', self:IsOutputDetail("FULL")
);
elseif value == "MENU_MODE" then
dewdrop:AddLine(
'text', self.loc.MENU_MODE_GROUPFU,
'value', "GROUPFU",
'func', function() self:ToggleTextMode("GROUPFU") end,
'isRadio', true,
'checked', self:IsTextMode("GROUPFU")
);
dewdrop:AddLine(
'text', self.loc.MENU_MODE_ROLLSFU,
'value', "ROLLSFU",
'func', function() self:ToggleTextMode("ROLLSFU") end,
'isRadio', true,
'checked', self:IsTextMode("ROLLSFU")
);
dewdrop:AddLine(
'text', self.loc.MENU_MODE_LOOTTYFU,
'value', "LOOTTYFU",
'func', function() self:ToggleTextMode("LOOTTYFU") end,
'isRadio', true,
'checked', self:IsTextMode("LOOTTYFU")
);
elseif value == "MENU_GROUP" then
dewdrop:AddLine(
'text', self.loc.MENU_GROUP_LEAVE,
'value', "MENU_GROUP_LEAVE",
'func', function() LeaveParty() end,
'notCheckable', true
);
if IsPartyLeader() or IsRaidLeader() then
dewdrop:AddLine(
'text', self.loc.MENU_GROUP_RAID,
'value', "MENU_GROUP_RAID",
'func', function() ConvertToRaid() end,
'notCheckable', true
);
dewdrop:AddLine(
'text', self.loc.MENU_GROUP_LOOT,
'value', "MENU_GROUP_LOOT",
'hasArrow', true
);
dewdrop:AddLine(
'text', self.loc.MENU_GROUP_THRESHOLD,
'value', "MENU_GROUP_THRESHOLD",
'hasArrow', true
);
end
end
elseif level == 3 then
if value == "MENU_GROUP_LOOT" then
dewdrop:AddLine(
'text', self.loc.TEXT_GROUP,
'value', "TEXT_GROUP",
'func', function() self:SetLootType("group") end,
'isRadio', true,
'checked', self:IsLootType("group")
);
dewdrop:AddLine(
'text', self.loc.TEXT_FFA,
'value', "TEXT_FFA",
'func', function() self:SetLootType("freeforall") end,
'isRadio', true,
'checked', self:IsLootType("freeforall")
);
dewdrop:AddLine(
'text', self.loc.TEXT_MASTER,
'value', "TEXT_MASTER",
'func', function() self:SetLootType("master") end,
'isRadio', true,
'checked', self:IsLootType("master")
);
dewdrop:AddLine(
'text', self.loc.TEXT_NBG,
'value', "TEXT_NBG",
'func', function() self:SetLootType("needbeforegreed") end,
'isRadio', true,
'checked', self:IsLootType("needbeforegreed")
);
dewdrop:AddLine(
'text', self.loc.TEXT_RR,
'value', "TEXT_RR",
'func', function() self:SetLootType("roundrobin") end,
'isRadio', true,
'checked', self:IsLootType("roundrobin")
);
elseif value == "MENU_GROUP_THRESHOLD" then
local mnuGroupThrshldDesc, mnuGroupThrshldThrshld, mnuGroupThrshldHex
for j=0,6 do
mnuGroupThrshldDesc = self.data.LootColorTable[j].Desc;
mnuGroupThrshldThrshld = self.data.LootColorTable[j].Threshold;
mnuGroupThrshldHex = self.data.LootColorTable[j].Hex;
dewdrop:AddLine(
'text', format("%s%s", mnuGroupThrshldHex, mnuGroupThrshldDesc .. "(" .. mnuGroupThrshldThrshld .. ")"),
'func', function(val) self:SetLootThreshold(val) end,
'arg1', mnuGroupThrshldThrshld,
'isRadio', true,
'checked', self:IsLootThreshold(mnuGroupThrshldThrshld)
);
end
end
end
end
end
function GroupFu:UpdateData()
if (GetNumPartyMembers() > 0) or (GetNumRaidMembers() > 0) then
self.tmpdata.LootType = GetLootMethod();
self.tmpdata.Threshold = GetLootThreshold();
else
self.tmpdata.LootType, self.tmpdata.Threshold = nil, nil;
end
local i, highRoll, rollLink;
highRoll = 0;
if(self.tmpdata.RollCount > 0) then
for i = 1, self.tmpdata.RollCount do
if ((self.tmpdata.Rolls[i].Roll > highRoll) and ((not self.data.StandardRollsOnly) or ((self.tmpdata.Rolls[i].Min == 1) and (self.tmpdata.Rolls[i].Max == 100)))) then
highRoll = self.tmpdata.Rolls[i].Roll;
rollLink = i;
end
end
self.tmpdata.LastWinner = self.tmpdata.Rolls[rollLink].Player .. " [" .. FuBarUtils.Colorize("00FF00", highRoll) .. "]";
if((self.tmpdata.Rolls[rollLink].Min ~= 1) or (self.tmpdata.Rolls[rollLink].Max ~= 100)) then
self.tmpdata.LastWinner = self.tmpdata.LastWinner .. " (" .. self.tmpdata.Rolls[rollLink].Min .. "-" .. self.tmpdata.Rolls[rollLink].Max .. ")";
end
else
self.tmpdata.LastWinner = nil;
end
end
function GroupFu:UpdateText()
if self.data.TextMode == "ROLLSFU" then
if self.tmpdata.LastWinner ~= nil then
if self.data.ShowRollCount then
if GetNumRaidMembers() > 0 then
self:SetText( string.format(self.loc.FORMAT_TEXT_ROLLCOUNT, self.tmpdata.LastWinner, self.tmpdata.RollCount, GetNumRaidMembers()) );
elseif GetNumPartyMembers() > 0 then
self:SetText( string.format(self.loc.FORMAT_TEXT_ROLLCOUNT, self.tmpdata.LastWinner, self.tmpdata.RollCount, GetNumPartyMembers()+1) );
else
self:SetText(self.tmpdata.LastWinner);
end
else
self:SetText(self.tmpdata.LastWinner);
end
else
self:SetText(self.loc.TEXT_NOROLLS);
end
elseif self.data.TextMode == "LOOTTYFU" then
if self.tmpdata.LootType == solo then
self:SetText(string.format("%s%s", "|cff888888", self:GetLootTypeText()));
else
if not self.tmpdata.Threshold then
self:UpdateData();
end
self:SetText(string.format("%s%s", self.data.LootColorTable[self.tmpdata.Threshold].Hex, self:GetLootTypeText()));
end
else
if self.tmpdata.LastWinner ~= nil then
if self.data.ShowRollCount then
if GetNumRaidMembers() > 0 then
self:SetText( string.format(self.loc.FORMAT_TEXT_ROLLCOUNT, self.tmpdata.LastWinner, self.tmpdata.RollCount, GetNumRaidMembers()) );
elseif GetNumPartyMembers() > 0 then
self:SetText( string.format(self.loc.FORMAT_TEXT_ROLLCOUNT, self.tmpdata.LastWinner, self.tmpdata.RollCount, GetNumPartyMembers()+1) );
else
self:SetText(self.tmpdata.LastWinner);
end
else
self:SetText(self.tmpdata.LastWinner);
end
else
if self.tmpdata.LootType == solo then
self:SetText(string.format("%s%s", "|cff888888", self:GetLootTypeText()));
else
if not self.tmpdata.Threshold then
self:UpdateData();
end
self:SetText(string.format("%s%s", self.data.LootColorTable[self.tmpdata.Threshold].Hex, self:GetLootTypeText()));
end
end
end
end
function GroupFu:UpdateTooltip()
local cat;
cat = tablet:AddCategory(
'text', self.loc.TOOLTIP_CAT_LOOTING,
'columns', 2
);
if self.tmpdata.LootType == "group" then
if not self.tmpdata.Threshold then
self:UpdateData();
end
cat:AddLine(
'text', self.loc.TOOLTIP_METHOD .. ":",
'text2', string.format("%s%s", self.data.LootColorTable[self.tmpdata.Threshold].Hex, self.loc.TEXT_GROUP)
);
elseif self.tmpdata.LootType == "master" then
if self.data.ShowMLName and self.tmpdata.MLName then
if not self.tmpdata.Threshold then
self:UpdateData();
end
cat:AddLine(
'text', self.loc.TOOLTIP_METHOD .. ":",
'text2', string.format("%s%s", self.data.LootColorTable[self.tmpdata.Threshold].Hex, self.loc.TEXT_MASTER .. "(" .. self.tmpdata.MLName .. ")")
);
else
if not self.tmpdata.Threshold then
self:UpdateData();
end
cat:AddLine(
'text', self.loc.TOOLTIP_METHOD .. ":",
'text2', string.format("%s%s", self.data.LootColorTable[self.tmpdata.Threshold].Hex, self.loc.TEXT_MASTER)
);
end
elseif self.tmpdata.LootType == "freeforall" then
if not self.tmpdata.Threshold then
self:UpdateData();
end
cat:AddLine(
'text', self.loc.TOOLTIP_METHOD .. ":",
'text2', string.format("%s%s", self.data.LootColorTable[self.tmpdata.Threshold].Hex, self.loc.TEXT_FFA)
);
elseif self.tmpdata.LootType == "roundrobin" then
if not self.tmpdata.Threshold then
self:UpdateData();
end
cat:AddLine(
'text', self.loc.TOOLTIP_METHOD .. ":",
'text2', string.format("%s%s", self.data.LootColorTable[self.tmpdata.Threshold].Hex, self.loc.TEXT_RR)
);
elseif self.tmpdata.LootType == "needbeforegreed" then
if not self.tmpdata.Threshold then
self:UpdateData();
end
cat:AddLine(
'text', self.loc.TOOLTIP_METHOD .. ":",
'text2', string.format("%s%s", self.data.LootColorTable[self.tmpdata.Threshold].Hex, self.loc.TEXT_NBG)
);
else
if not self.tmpdata.Threshold then
self:UpdateData();
end
cat:AddLine(
'text', self.loc.TOOLTIP_METHOD .. ":",
'text2', string.format("%s%s", "|cff888888", self.loc.TEXT_SOLO)
);
end
cat = tablet:AddCategory(
'text', self.loc.TOOLTIP_CAT_ROLLS,
'columns', 2
);
if(self.tmpdata.RollCount > 0) then
local a, b, highRoll, rollLink, tallied, color, l, r;
if self.data.ShowRollCount then
if GetNumRaidMembers() > 0 then
cat:AddLine(
'text', string.format(self.loc.FORMAT_TOOLTIP_ROLLCOUNT, self.tmpdata.RollCount, GetNumRaidMembers() )
);
elseif GetNumPartyMembers() > 0 then
cat:AddLine(
'text', string.format(self.loc.FORMAT_TOOLTIP_ROLLCOUNT, self.tmpdata.RollCount, GetNumPartyMembers()+1 )
);
end
end
tallied = {};
for a=1,self.tmpdata.RollCount do
tallied[a] = 0;
end
for a=1,self.tmpdata.RollCount do
highRoll = 0;
rollLink = 0;
for b=1,self.tmpdata.RollCount do
if((self.data.StandardRollsOnly) and ((self.tmpdata.Rolls[b].Min ~= 1) or (self.tmpdata.Rolls[b].Max ~= 100))) then
tallied[b] = 1;
end
if((self.tmpdata.Rolls[b].Roll > highRoll) and (tallied[b] == 0)) then
highRoll = self.tmpdata.Rolls[b].Roll;
rollLink = b;
end
end
if(rollLink ~= 0) then
r = self.tmpdata.Rolls[rollLink].Player;
if(self.data.ShowClassLevel) then
local hexcolor = babble.GetClassHexColor(self.tmpdata.Rolls[rollLink].Class);
r = string.format("|cff%s%s %d %s%s", hexcolor, r, self.tmpdata.Rolls[rollLink].Level, string.sub(self.tmpdata.Rolls[rollLink].Class,1,1), string.lower(string.sub(self.tmpdata.Rolls[rollLink].Class,2)));
end
l = self.tmpdata.Rolls[rollLink].Roll;
if((self.tmpdata.Rolls[rollLink].Min ~= 1) or (self.tmpdata.Rolls[rollLink].Max ~= 100)) then
l = l .. " (" .. self.tmpdata.Rolls[rollLink].Min .. "-" .. self.tmpdata.Rolls[rollLink].Max .. ")";
end
cat:AddLine(
'text', r,
'text2', l
);
tallied[rollLink] = 1;
end
end
else
cat:AddLine (
'text', self.loc.TEXT_NOROLLS,
'text2', ""
);
end
if(self.data.RollOnClick) then
tablet:SetHint(self.loc.TOOLTIP_HINT_ROLLS);
else
tablet:SetHint(self.loc.TOOLTIP_HINT_NOROLLS);
end
end
function GroupFu:OnClick()
if(IsControlKeyDown()) then
if(self.tmpdata.RollCount > 0) then
local i, highRoll, highRoller;
highRoll = 0;
highRoller = "";
for i = 1, self.tmpdata.RollCount do
if ((self.tmpdata.Rolls[i].Roll > highRoll) and ((not self.data.StandardRollsOnly) or ((self.tmpdata.Rolls[i].Min == 1) and (self.tmpdata.Rolls[i].Max == 100)))) then
highRoll = self.tmpdata.Rolls[i].Roll;
highRoller = self.tmpdata.Rolls[i].Player;
end
end
-- Output the winner to the specified output channel
self:AnnounceOutput(format(self.loc.FORMAT_ANNOUNCE_WIN, highRoller, highRoll, self.tmpdata.RollCount));
if((self.data.OutputDetail == "LONG") or (self.data.OutputDetail == "FULL")) then
local a, b, rollLink, tallied, message, count;
tallied = {};
count = 0;
message = "";
for a=1,self.tmpdata.RollCount do
tallied[a] = 0;
end
for a=1,self.tmpdata.RollCount do
highRoll = 0;
rollLink = 0;
for b=1,self.tmpdata.RollCount do
if((self.data.StandardRollsOnly) and ((self.tmpdata.Rolls[b].min ~= 1) or (self.tmpdata.Rolls[b].max ~= 100))) then
tallied[b] = 1;
end
if((self.tmpdata.Rolls[b].Roll > highRoll) and (tallied[b] == 0)) then
highRoll = self.tmpdata.Rolls[b].Roll;
rollLink = b;
end
end
if(rollLink ~= 0) then
message = message .. "#" .. a .. " " .. self.tmpdata.Rolls[rollLink].Player .. " [" .. self.tmpdata.Rolls[rollLink].Roll .. "]";
if((self.data.OutputDetail == "FULL") and ((self.tmpdata.Rolls[rollLink].Min ~= 1) or (self.tmpdata.Rolls[rollLink].Max ~= 100))) then
message = message .. " (" .. self.tmpdata.Rolls[rollLink].Min .. "-" .. self.tmpdata.Rolls[rollLink].Max .. ")";
end
message = message .. ", ";
count = count + 1;
tallied[rollLink] = 1;
end
if((count == 10) or (a == self.tmpdata.RollCount)) then
message = string.sub(message, 1, -3);
self:AnnounceOutput(message);
message = "";
count = 0;
end
end
end
if(self.data.DeleteRolls) then
self:ClearRolls();
end
end
elseif(IsShiftKeyDown()) then
self:ClearRolls();
else
if(self.data.RollOnClick) then
RandomRoll("1", "100");
end
end
end
function GroupFu:CHAT_MSG_SYSTEM()
local player, roll, min_roll, max_roll, mlname;
-- Trap name of master looter if it has changed
_, _, mlname = string.find(arg1, self.loc.SEARCH_MASTERLOOTER);
if mlname then
self.tmpdata.MLName = mlname;
self:Update();
end
-- Trap rolls
_, _, player, roll, min_roll, max_roll = string.find(arg1, self.loc.SEARCH_ROLLS);
if(player) then
if((self.data.StandardRollsOnly) and ((tonumber(min_roll) ~= 1) or (tonumber(max_roll) ~= 100))) then
return;
end
if((self.tmpdata.RollCount > 0) and (self.data.IgnoreDuplicates)) then
local i;
for i=1,self.tmpdata.RollCount do
if(self.tmpdata.Rolls[i].Player == player) then
return;
end
end
end
self.tmpdata.RollCount = self.tmpdata.RollCount + 1;
self.tmpdata.Rolls[self.tmpdata.RollCount] = {};
self.tmpdata.Rolls[self.tmpdata.RollCount].Roll = tonumber(roll);
self.tmpdata.Rolls[self.tmpdata.RollCount].Player = player;
self.tmpdata.Rolls[self.tmpdata.RollCount].Min = tonumber(min_roll);
self.tmpdata.Rolls[self.tmpdata.RollCount].Max = tonumber(max_roll);
if(player == UnitName("player")) then
_, self.tmpdata.Rolls[self.tmpdata.RollCount].Class = UnitClass("player");
self.tmpdata.Rolls[self.tmpdata.RollCount].Level = UnitLevel("player");
elseif(GetNumRaidMembers() > 0) then
local i, z;
z = GetNumRaidMembers();
for i=1,z do
if(player == UnitName("raid"..i)) then
_, self.tmpdata.Rolls[self.tmpdata.RollCount].Class = UnitClass("raid"..i);
self.tmpdata.Rolls[self.tmpdata.RollCount].Level = UnitLevel("raid"..i);
break;
end
end
elseif(GetNumPartyMembers() > 0) then
local i, z;
z = GetNumPartyMembers();
for i=1,z do
if(player == UnitName("party"..i)) then
_, self.tmpdata.Rolls[self.tmpdata.RollCount].Class = UnitClass("party"..i);
self.tmpdata.Rolls[self.tmpdata.RollCount].Level = UnitLevel("party"..i);
end
end
else
self.tmpdata.Rolls[self.tmpdata.RollCount].Class = "";
self.tmpdata.Rolls[self.tmpdata.RollCount].Level = 0;
end
if (self.data.ClearTimer > 0) and not self.data.AnnounceRollCountdown then
self.tmpdata.TimeSinceLastRoll = 0;
end
self:Update();
end
end
function GroupFu:ToggleOption(opt)
self.data[opt] = not self.data[opt];
self:Update();
return self.data[opt];
end
function GroupFu:ToggleOutputChannel(channel)
self.data.OutputChannel = channel;
self:Update();
return self.data.OutputChannel;
end
function GroupFu:IsOutputChannel(channel)
if self.data.OutputChannel == channel then
return true;
else
return false;
end
end
function GroupFu:ToggleOutputDetail(detail)
self.data.OutputDetail = detail;
self:Update();
return self.data.OutputDetail;
end
function GroupFu:IsOutputDetail(detail)
if self.data.OutputDetail == detail then
return true;
else
return false;
end
end
function GroupFu:ToggleTextMode(mode)
self.data.TextMode = mode;
self:Update();
return self.data.TextMode;
end
function GroupFu:IsTextMode(mode)
if self.data.TextMode == mode then
return true;
else
return false;
end
end
function GroupFu:ToggleClearTimer(timeout)
self.data.ClearTimer = timeout;
self:Update();
return self.data.ClearTimer;
end
function GroupFu:IsClearTimer(timeout)
if self.data.ClearTimer == timeout then
return true;
else
return false;
end
end
function GroupFu:ClearRolls()
self.tmpdata.Rolls = {};
self.tmpdata.RollCount = 0;
self.tmpdata.TimeSinceLastRoll = 0;
self:Update();
end
function GroupFu:IsLootType(loottype)
if GetLootMethod() == loottype then
return true;
else
return false;
end
end
function GroupFu:SetLootType(loottype)
if loottype == "master" then
SetLootMethod(loottype,UnitName("player"),2);
else
SetLootMethod(loottype);
end
self:Update();
dewdrop:Close(3);
end
function GroupFu:IsLootThreshold(threshold)
if GetLootThreshold() == threshold then
return true;
else
return false;
end
end
function GroupFu:SetLootThreshold(threshold)
SetLootThreshold(threshold)
self:Update();
dewdrop:Close(3);
end
function GroupFu:GetLootTypeText()
if self.tmpdata.LootType == "group" then
return self.loc.TEXT_GROUP;
elseif self.tmpdata.LootType == "master" then
if self.data.ShowMLName and self.tmpdata.MLName then
return self.loc.TEXT_MASTER .. "(" .. self.tmpdata.MLName .. ")";
else
return self.loc.TEXT_MASTER;
end
elseif self.tmpdata.LootType == "freeforall" then
return self.loc.TEXT_FFA;
elseif self.tmpdata.LootType == "roundrobin" then
return self.loc.TEXT_RR;
elseif self.tmpdata.LootType == "needbeforegreed" then
return self.loc.TEXT_NBG;
else
return self.loc.TEXT_SOLO;
end
end
function GroupFu:CheckRollTimeout()
if ((self.tmpdata.RollCount > 0) and (self.data.ClearTimer > 0)) then
self.tmpdata.TimeSinceLastRoll = self.tmpdata.TimeSinceLastRoll + self.updateTime;
if (self.data.AnnounceRollCountdown) then
if( self.tmpdata.TimeSinceLastRoll == (self.data.ClearTimer-10) ) then
self:AnnounceOutput( self.loc.TEXT_ENDING10 );
elseif( self.tmpdata.TimeSinceLastRoll == (self.data.ClearTimer-5) ) then
self:AnnounceOutput( self.loc.TEXT_ENDING5 );
elseif( self.tmpdata.TimeSinceLastRoll == (self.data.ClearTimer-4) ) then
self:AnnounceOutput( self.loc.TEXT_ENDING4 );
elseif( self.tmpdata.TimeSinceLastRoll == (self.data.ClearTimer-3) ) then
self:AnnounceOutput( self.loc.TEXT_ENDING3 );
elseif( self.tmpdata.TimeSinceLastRoll == (self.data.ClearTimer-2) ) then
self:AnnounceOutput( self.loc.TEXT_ENDING2 );
elseif( self.tmpdata.TimeSinceLastRoll == (self.data.ClearTimer-1) ) then
self:AnnounceOutput( self.loc.TEXT_ENDING1 );
elseif( self.tmpdata.TimeSinceLastRoll == self.data.ClearTimer ) then
self:AnnounceOutput( self.loc.TEXT_ENDED );
if(self.tmpdata.RollCount > 0) then
local i, highRoll, highRoller;
highRoll = 0;
highRoller = "";
for i = 1, self.tmpdata.RollCount do
if ((self.tmpdata.Rolls[i].Roll > highRoll) and ((not self.data.StandardRollsOnly) or ((self.tmpdata.Rolls[i].Min == 1) and (self.tmpdata.Rolls[i].Max == 100)))) then
highRoll = self.tmpdata.Rolls[i].Roll;
highRoller = self.tmpdata.Rolls[i].Player;
end
end
self:AnnounceOutput(format(self.loc.FORMAT_ANNOUNCE_WIN, highRoller, highRoll, self.tmpdata.RollCount));
end
self:ClearRolls();
end
elseif( self.tmpdata.TimeSinceLastRoll == self.data.ClearTimer ) then
self:ClearRolls();
end
end
end
function GroupFu:AnnounceOutput( mymessage )
if( self.data.OutputChannel == "LOCAL" ) then
DEFAULT_CHAT_FRAME:AddMessage(mymessage);
elseif ( self.data.OutputChannel == "AUTO" ) then
if ( GetNumRaidMembers() > 0 ) then
SendChatMessage(mymessage, "RAID");
elseif ( GetNumPartyMembers() > 0 ) then
SendChatMessage(mymessage, "PARTY");
else
DEFAULT_CHAT_FRAME:AddMessage(mymessage);
end
else
SendChatMessage(mymessage, self.data.OutputChannel);
end
end
GroupFu:RegisterForLoad(); | 412 | 0.971826 | 1 | 0.971826 | game-dev | MEDIA | 0.813328 | game-dev | 0.96625 | 1 | 0.96625 |
asdflj/AE2Things | 2,175 | src/main/java/com/asdflj/ae2thing/common/storage/backpack/BaseBackpackHandler.java | package com.asdflj.ae2thing.common.storage.backpack;
import java.util.Collections;
import java.util.List;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.FluidTank;
public abstract class BaseBackpackHandler implements IInventory {
protected final IInventory inv;
public BaseBackpackHandler(IInventory inv) {
this.inv = inv;
}
@Override
public int getSizeInventory() {
return inv.getSizeInventory();
}
@Override
public ItemStack getStackInSlot(int slotIn) {
return this.inv.getStackInSlot(slotIn);
}
@Override
public ItemStack decrStackSize(int index, int count) {
return this.inv.decrStackSize(index, count);
}
public boolean hasFluidTank() {
return false;
}
public List<FluidTank> getFluidTanks() {
return Collections.emptyList();
}
public void markFluidAsDirty() {
}
@Override
public ItemStack getStackInSlotOnClosing(int index) {
return this.inv.getStackInSlotOnClosing(index);
}
@Override
public void setInventorySlotContents(int index, ItemStack stack) {
this.inv.setInventorySlotContents(index, stack);
}
@Override
public String getInventoryName() {
return this.inv.getInventoryName();
}
@Override
public boolean hasCustomInventoryName() {
return this.inv.hasCustomInventoryName();
}
@Override
public int getInventoryStackLimit() {
return this.inv.getInventoryStackLimit();
}
@Override
public void markDirty() {
this.inv.markDirty();
}
@Override
public boolean isUseableByPlayer(EntityPlayer player) {
return this.inv.isUseableByPlayer(player);
}
@Override
public void openInventory() {
this.inv.openInventory();
}
@Override
public void closeInventory() {
this.inv.closeInventory();
}
@Override
public boolean isItemValidForSlot(int index, ItemStack stack) {
return this.inv.isItemValidForSlot(index, stack);
}
}
| 412 | 0.878385 | 1 | 0.878385 | game-dev | MEDIA | 0.887589 | game-dev | 0.955254 | 1 | 0.955254 |
reisenx/2110101-COMP-PROG | 2,140 | GE-Grader-Examination/G6702-Exam-2567-S2/Grader-01/2567_2_Q1_A3/README.md | <p align="left">
<a href="../../README.md">
<img src="../../../../Z99-OTHERS/00-common/00-back.png" style="width:10%">
</a>
</p>
<div align="center">
<h1>
Snake and Ladders ★★☆ (
<a href="https://drive.google.com/file/d/1v0FWx0yP8K58KgW9GwB-JNcxdg_KzSO7/view?usp=sharing">
<code>2567_2_Q1_A3</code>
</a>
)
</h1>
</div>
# Contents
- [**Solution**](#solution)
---
<div align="center">
<h2>เฉลยอย่างละเอียดจะตามมาทีหลัง</h2>
</div>
---
# Solution
```python
# --------------------------------------------------
# File Name : 2567_2_Q1_A3.py
# Problem : Snakes and Ladders
# Author : Worralop Srichainont
# Date : 2025-07-29
# --------------------------------------------------
# Input number of rows of the table
rows = int(input())
# Initialize the game board
game_board = []
# Input the game board
for i in range(rows):
# Input each line of the game board
line = input().strip().split()
# Add the reversed line on even rows counting from the bottom
if (rows - i - 1) % 2 == 0:
game_board += line[::-1]
# Add the line on odd rows counting from the bottom
else:
game_board += line
# Reverse the entire game board to correct the order
game_board = game_board[::-1]
# Input the dice rolls
dice_rolls = [int(roll) for roll in input().split()]
# Initialize the list to keep track of the game process
# and the index of the current position
game_process = []
idx = -1
# Process the game based on the dice rolls
for roll in dice_rolls:
# Update the index based on the dice roll
idx += roll
# Check if the index is on snake or ladder grid
if (idx < len(game_board) - 1) and (game_board[idx] != "."):
# Move to the position indicated by the snake or ladder
idx = int(game_board[idx][1:]) - 1
# Append the current position to the game process
if idx < len(game_board) - 1:
game_process.append(str(idx + 1))
# Check if the player has reached the end of the game board
else:
game_process.append("win")
break
# Output the game process
print(" ".join(game_process))
```
| 412 | 0.619863 | 1 | 0.619863 | game-dev | MEDIA | 0.559893 | game-dev,cli-devtools | 0.652645 | 1 | 0.652645 |
ForestDango/Hollow-Knight-Demo | 1,101 | Assets/PlayMaker/Actions/Math/FloatDivide.cs | // (c) Copyright HutongGames, LLC 2010-2013. All rights reserved.
using UnityEngine;
namespace HutongGames.PlayMaker.Actions
{
[ActionCategory(ActionCategory.Math)]
[Tooltip("Divides one Float by another.")]
public class FloatDivide : FsmStateAction
{
[RequiredField]
[UIHint(UIHint.Variable)]
[Tooltip("The float variable to divide.")]
public FsmFloat floatVariable;
[RequiredField]
[Tooltip("Divide the float variable by this value.")]
public FsmFloat divideBy;
[Tooltip("Repeat every frame. Useful if the variables are changing.")]
public bool everyFrame;
public override void Reset()
{
floatVariable = null;
divideBy = null;
everyFrame = false;
}
public override void OnEnter()
{
floatVariable.Value /= divideBy.Value;
if (!everyFrame)
{
Finish();
}
}
public override void OnUpdate()
{
floatVariable.Value /= divideBy.Value;
}
#if UNITY_EDITOR
public override string AutoName()
{
return ActionHelpers.AutoName(this, floatVariable, divideBy);
}
#endif
}
} | 412 | 0.852798 | 1 | 0.852798 | game-dev | MEDIA | 0.961146 | game-dev | 0.889199 | 1 | 0.889199 |
CortezRomeo/ClansPlus | 3,088 | clansplus-plugin/src/main/java/com/cortezromeo/clansplus/clan/subject/RemoveManager.java | package com.cortezromeo.clansplus.clan.subject;
import com.cortezromeo.clansplus.Settings;
import com.cortezromeo.clansplus.api.enums.Rank;
import com.cortezromeo.clansplus.api.enums.Subject;
import com.cortezromeo.clansplus.api.storage.IClanData;
import com.cortezromeo.clansplus.api.storage.IPlayerData;
import com.cortezromeo.clansplus.clan.ClanManager;
import com.cortezromeo.clansplus.clan.SubjectManager;
import com.cortezromeo.clansplus.language.Messages;
import com.cortezromeo.clansplus.storage.PluginDataManager;
import com.cortezromeo.clansplus.util.MessageUtil;
import org.bukkit.entity.Player;
public class RemoveManager extends SubjectManager {
public RemoveManager(Rank rank, Player player, String playerName, Player target, String targetName) {
super(rank, player, playerName, target, targetName);
}
@Override
public boolean execute() {
if (!isPlayerInClan()) {
MessageUtil.sendMessage(player, Messages.MUST_BE_IN_CLAN);
return false;
}
if (!Settings.CLAN_SETTING_PERMISSION_DEFAULT_FORCED)
setRequiredRank(getPlayerClanData().getSubjectPermission().get(Subject.REMOVEMANAGER));
if (!isPlayerRankSatisfied()) {
MessageUtil.sendMessage(player, Messages.REQUIRED_RANK.replace("%requiredRank%", ClanManager.getFormatRank(getRequiredRank())));
return false;
}
if (playerName.equals(targetName)) {
MessageUtil.sendMessage(player, Messages.SELF_TARGETED_ERROR);
return false;
}
if (!isTargetInClan()) {
MessageUtil.sendMessage(player, Messages.TARGET_MUST_BE_IN_CLAN.replace("%player%", targetName));
return false;
}
IPlayerData targetData = PluginDataManager.getPlayerDatabase(targetName);
IClanData playerClanData = getPlayerClanData();
if (!isTargetAndPlayerInTheSameClan()) {
MessageUtil.sendMessage(player, Messages.TARGET_CLAN_MEMBERSHIP_ERROR.replace("%player%", targetName));
return false;
}
if (targetData.getRank() != Rank.MANAGER) {
MessageUtil.sendMessage(player, Messages.NOT_A_MANAGER.replace("%player%", targetName));
return false;
}
targetData.setRank(Rank.MEMBER);
PluginDataManager.savePlayerDatabaseToStorage(targetName, targetData);
PluginDataManager.saveClanDatabaseToStorage(playerClanData.getName(), playerClanData);
MessageUtil.sendMessage(player, Messages.REMOVE_A_MANAGER_SUCCESS.replace("%clan%", getPlayerClanData().getName()).replace("%player%", targetName));
MessageUtil.sendMessage(target, Messages.MANAGER_REMOVED.replace("%clan%", getPlayerClanData().getName()).replace("%player%", playerName));
ClanManager.alertClan(playerClanData.getName(), Messages.CLAN_BROADCAST_MANAGER_REMOVED.replace("%player%", playerName).replace("%target%", targetName).replace("%rank%", ClanManager.getFormatRank(PluginDataManager.getPlayerDatabase(playerName).getRank())));
return true;
}
}
| 412 | 0.760629 | 1 | 0.760629 | game-dev | MEDIA | 0.692032 | game-dev | 0.70168 | 1 | 0.70168 |
mattneub/Programming-iOS-Book-Examples | 2,774 | iOS13bookExamples/bk1ch04p193whereClauses/bk1ch04p193whereClauses/ViewController.swift |
import UIKit
// =====
protocol Wieldable {
}
struct Sword : Wieldable {
}
struct Bow : Wieldable {
}
protocol Fighter {
// associatedtype Enemy where Enemy : Fighter // in Swift 4.1, we can recurse directly
associatedtype Enemy : Fighter
associatedtype Weapon : Wieldable
func steal(weapon:Self.Enemy.Weapon, from:Self.Enemy)
}
struct Soldier : Fighter {
typealias Weapon = Sword
typealias Enemy = Archer
func steal(weapon:Bow, from:Archer) {
}
}
struct Archer : Fighter {
typealias Weapon = Bow
typealias Enemy = Soldier
func steal (weapon:Sword, from:Soldier) {
}
}
struct Camp<T:Fighter> {
var spy : T.Enemy?
}
// =====
class Dog {}
class FlyingDog : Dog, Flier {}
protocol Flier {
}
protocol Walker {
}
protocol Generic {
associatedtype T : Flier, Walker // T must adopt Flier and Walker
associatedtype UU where UU:Flier // STOP PRESS! this is legal in Swift 4!
// and == would have been legal here too!
associatedtype U : Dog, Flier // legal: this is basically an inheritance declaration!
}
protocol JustKidding {
func flyAndWalk<T> (_ f:T) -> String where T:Walker, T:Flier
}
struct JustTesting {
func flyAndWalk<T: Flier> (_ f:T) {}
func flyAndWalk2<T: Flier & Walker> (_ f:T) {}
func flyAndWalk3<T: Flier & Dog> (_ f:T) {}
}
struct JustTesting2 {
func flyAndWalk<T> (_ f:T) where T: Flier {}
func flyAndWalk2<T> (_ f:T) where T: Flier & Walker {}
func flyAndWalk2a<T> (_ f:T) where T: Flier, T: Walker {}
func flyAndWalk3<T> (_ f:T) where T: Flier & Dog {}
func flyAndWalk3a<T> (_ f:T) where T: Flier, T: Dog {}
}
func flyAndWalk<T> (_ f:T) -> String where T:Walker, T:Flier {return "ha"}
// func flyAndWalkNOT<T:Walker, T: Flier>(_ f: T) {}
func flyAndWalkBis<T> (_ f:T) where T:Walker & Flier {}
func flyAndWalk2<T : Walker & Flier> (_ f:T) {}
func flyAndWalk3<T> (_ f:T) where T:Flier, T:Dog {}
func flyAndWalk3Bis<T> (_ f:T) where T:Flier & Dog {} // Legal in Swift 4!
func flyAndWalk3BisBis<T: Flier & Dog> (_ f:T) {} // Legal in Swift 4!
// func flyAndWalk4<T where T == Dog> (f:T) {}
struct Bird : Flier, Walker {}
struct Kiwi : Walker {}
struct S : Generic {
typealias T = Bird
typealias UU = Bird
typealias U = FlyingDog
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var c = Camp<Soldier>()
c.spy = Archer()
// c.spy = Soldier() // nope
var c2 = Camp<Archer>()
c2.spy = Soldier()
// c2.spy = Archer()
// flyAndWalk(Kiwi())
// flyAndWalk2(Kiwi())
_ = flyAndWalk(Bird())
flyAndWalk2(Bird())
flyAndWalk3(FlyingDog())
}
}
| 412 | 0.919824 | 1 | 0.919824 | game-dev | MEDIA | 0.546452 | game-dev | 0.788029 | 1 | 0.788029 |
TornadoWay85/85HWBPBASE_ANTISS_MEMESS_2024 | 7,602 | halflife-master/dlls/crowbar.cpp | /***
*
* Copyright (c) 1996-2001, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
#include "extdll.h"
#include "util.h"
#include "cbase.h"
#include "monsters.h"
#include "weapons.h"
#include "nodes.h"
#include "player.h"
#include "gamerules.h"
#define CROWBAR_BODYHIT_VOLUME 128
#define CROWBAR_WALLHIT_VOLUME 512
LINK_ENTITY_TO_CLASS( weapon_crowbar, CCrowbar );
enum gauss_e {
CROWBAR_IDLE = 0,
CROWBAR_DRAW,
CROWBAR_HOLSTER,
CROWBAR_ATTACK1HIT,
CROWBAR_ATTACK1MISS,
CROWBAR_ATTACK2MISS,
CROWBAR_ATTACK2HIT,
CROWBAR_ATTACK3MISS,
CROWBAR_ATTACK3HIT
};
void CCrowbar::Spawn( )
{
Precache( );
m_iId = WEAPON_CROWBAR;
SET_MODEL(ENT(pev), "models/w_crowbar.mdl");
m_iClip = -1;
FallInit();// get ready to fall down.
}
void CCrowbar::Precache( void )
{
PRECACHE_MODEL("models/v_crowbar.mdl");
PRECACHE_MODEL("models/w_crowbar.mdl");
PRECACHE_MODEL("models/p_crowbar.mdl");
PRECACHE_SOUND("weapons/cbar_hit1.wav");
PRECACHE_SOUND("weapons/cbar_hit2.wav");
PRECACHE_SOUND("weapons/cbar_hitbod1.wav");
PRECACHE_SOUND("weapons/cbar_hitbod2.wav");
PRECACHE_SOUND("weapons/cbar_hitbod3.wav");
PRECACHE_SOUND("weapons/cbar_miss1.wav");
m_usCrowbar = PRECACHE_EVENT ( 1, "events/crowbar.sc" );
}
int CCrowbar::GetItemInfo(ItemInfo *p)
{
p->pszName = STRING(pev->classname);
p->pszAmmo1 = NULL;
p->iMaxAmmo1 = -1;
p->pszAmmo2 = NULL;
p->iMaxAmmo2 = -1;
p->iMaxClip = WEAPON_NOCLIP;
p->iSlot = 0;
p->iPosition = 0;
p->iId = WEAPON_CROWBAR;
p->iWeight = CROWBAR_WEIGHT;
return 1;
}
BOOL CCrowbar::Deploy( )
{
return DefaultDeploy( "models/v_crowbar.mdl", "models/p_crowbar.mdl", CROWBAR_DRAW, "crowbar" );
}
void CCrowbar::Holster( int skiplocal /* = 0 */ )
{
m_pPlayer->m_flNextAttack = UTIL_WeaponTimeBase() + 0.5;
SendWeaponAnim( CROWBAR_HOLSTER );
}
void FindHullIntersection( const Vector &vecSrc, TraceResult &tr, float *mins, float *maxs, edict_t *pEntity )
{
int i, j, k;
float distance;
float *minmaxs[2] = {mins, maxs};
TraceResult tmpTrace;
Vector vecHullEnd = tr.vecEndPos;
Vector vecEnd;
distance = 1e6f;
vecHullEnd = vecSrc + ((vecHullEnd - vecSrc)*2);
UTIL_TraceLine( vecSrc, vecHullEnd, dont_ignore_monsters, pEntity, &tmpTrace );
if ( tmpTrace.flFraction < 1.0 )
{
tr = tmpTrace;
return;
}
for ( i = 0; i < 2; i++ )
{
for ( j = 0; j < 2; j++ )
{
for ( k = 0; k < 2; k++ )
{
vecEnd.x = vecHullEnd.x + minmaxs[i][0];
vecEnd.y = vecHullEnd.y + minmaxs[j][1];
vecEnd.z = vecHullEnd.z + minmaxs[k][2];
UTIL_TraceLine( vecSrc, vecEnd, dont_ignore_monsters, pEntity, &tmpTrace );
if ( tmpTrace.flFraction < 1.0 )
{
float thisDistance = (tmpTrace.vecEndPos - vecSrc).Length();
if ( thisDistance < distance )
{
tr = tmpTrace;
distance = thisDistance;
}
}
}
}
}
}
void CCrowbar::PrimaryAttack()
{
if (! Swing( 1 ))
{
SetThink( &CCrowbar::SwingAgain );
pev->nextthink = gpGlobals->time + 0.1;
}
}
void CCrowbar::Smack( )
{
DecalGunshot( &m_trHit, BULLET_PLAYER_CROWBAR );
}
void CCrowbar::SwingAgain( void )
{
Swing( 0 );
}
int CCrowbar::Swing( int fFirst )
{
int fDidHit = FALSE;
TraceResult tr;
UTIL_MakeVectors (m_pPlayer->pev->v_angle);
Vector vecSrc = m_pPlayer->GetGunPosition( );
Vector vecEnd = vecSrc + gpGlobals->v_forward * 32;
UTIL_TraceLine( vecSrc, vecEnd, dont_ignore_monsters, ENT( m_pPlayer->pev ), &tr );
#ifndef CLIENT_DLL
if ( tr.flFraction >= 1.0 )
{
UTIL_TraceHull( vecSrc, vecEnd, dont_ignore_monsters, head_hull, ENT( m_pPlayer->pev ), &tr );
if ( tr.flFraction < 1.0 )
{
// Calculate the point of intersection of the line (or hull) and the object we hit
// This is and approximation of the "best" intersection
CBaseEntity *pHit = CBaseEntity::Instance( tr.pHit );
if ( !pHit || pHit->IsBSPModel() )
FindHullIntersection( vecSrc, tr, VEC_DUCK_HULL_MIN, VEC_DUCK_HULL_MAX, m_pPlayer->edict() );
vecEnd = tr.vecEndPos; // This is the point on the actual surface (the hull could have hit space)
}
}
#endif
PLAYBACK_EVENT_FULL( FEV_NOTHOST, m_pPlayer->edict(), m_usCrowbar,
0.0, (float *)&g_vecZero, (float *)&g_vecZero, 0, 0, 0,
0.0, 0, 0.0 );
if ( tr.flFraction >= 1.0 )
{
if (fFirst)
{
// miss
m_flNextPrimaryAttack = GetNextAttackDelay(0.5);
// player "shoot" animation
m_pPlayer->SetAnimation( PLAYER_ATTACK1 );
}
}
else
{
switch( ((m_iSwing++) % 2) + 1 )
{
case 0:
SendWeaponAnim( CROWBAR_ATTACK1HIT ); break;
case 1:
SendWeaponAnim( CROWBAR_ATTACK2HIT ); break;
case 2:
SendWeaponAnim( CROWBAR_ATTACK3HIT ); break;
}
// player "shoot" animation
m_pPlayer->SetAnimation( PLAYER_ATTACK1 );
#ifndef CLIENT_DLL
// hit
fDidHit = TRUE;
CBaseEntity *pEntity = CBaseEntity::Instance(tr.pHit);
ClearMultiDamage( );
if ( (m_flNextPrimaryAttack + 1 < UTIL_WeaponTimeBase() ) || g_pGameRules->IsMultiplayer() )
{
// first swing does full damage
pEntity->TraceAttack(m_pPlayer->pev, gSkillData.plrDmgCrowbar, gpGlobals->v_forward, &tr, DMG_CLUB );
}
else
{
// subsequent swings do half
pEntity->TraceAttack(m_pPlayer->pev, gSkillData.plrDmgCrowbar / 2, gpGlobals->v_forward, &tr, DMG_CLUB );
}
ApplyMultiDamage( m_pPlayer->pev, m_pPlayer->pev );
// play thwack, smack, or dong sound
float flVol = 1.0;
int fHitWorld = TRUE;
if (pEntity)
{
if ( pEntity->Classify() != CLASS_NONE && pEntity->Classify() != CLASS_MACHINE )
{
// play thwack or smack sound
switch( RANDOM_LONG(0,2) )
{
case 0:
EMIT_SOUND(ENT(m_pPlayer->pev), CHAN_ITEM, "weapons/cbar_hitbod1.wav", 1, ATTN_NORM); break;
case 1:
EMIT_SOUND(ENT(m_pPlayer->pev), CHAN_ITEM, "weapons/cbar_hitbod2.wav", 1, ATTN_NORM); break;
case 2:
EMIT_SOUND(ENT(m_pPlayer->pev), CHAN_ITEM, "weapons/cbar_hitbod3.wav", 1, ATTN_NORM); break;
}
m_pPlayer->m_iWeaponVolume = CROWBAR_BODYHIT_VOLUME;
if ( !pEntity->IsAlive() )
return TRUE;
else
flVol = 0.1;
fHitWorld = FALSE;
}
}
// play texture hit sound
// UNDONE: Calculate the correct point of intersection when we hit with the hull instead of the line
if (fHitWorld)
{
float fvolbar = TEXTURETYPE_PlaySound(&tr, vecSrc, vecSrc + (vecEnd-vecSrc)*2, BULLET_PLAYER_CROWBAR);
if ( g_pGameRules->IsMultiplayer() )
{
// override the volume here, cause we don't play texture sounds in multiplayer,
// and fvolbar is going to be 0 from the above call.
fvolbar = 1;
}
// also play crowbar strike
switch( RANDOM_LONG(0,1) )
{
case 0:
EMIT_SOUND_DYN(ENT(m_pPlayer->pev), CHAN_ITEM, "weapons/cbar_hit1.wav", fvolbar, ATTN_NORM, 0, 98 + RANDOM_LONG(0,3));
break;
case 1:
EMIT_SOUND_DYN(ENT(m_pPlayer->pev), CHAN_ITEM, "weapons/cbar_hit2.wav", fvolbar, ATTN_NORM, 0, 98 + RANDOM_LONG(0,3));
break;
}
// delay the decal a bit
m_trHit = tr;
}
m_pPlayer->m_iWeaponVolume = flVol * CROWBAR_WALLHIT_VOLUME;
#endif
m_flNextPrimaryAttack = GetNextAttackDelay(0.25);
SetThink( &CCrowbar::Smack );
pev->nextthink = UTIL_WeaponTimeBase() + 0.2;
}
return fDidHit;
}
| 412 | 0.929357 | 1 | 0.929357 | game-dev | MEDIA | 0.984995 | game-dev | 0.709111 | 1 | 0.709111 |
RAUI-labs/raui | 2,091 | crates/core/src/widget/component/containers/grid_box.rs | use crate::{
PropsData, make_widget, pre_hooks,
widget::{
component::interactive::navigation::{
NavContainerActive, NavItemActive, NavJumpActive, use_nav_container_active,
use_nav_item, use_nav_jump_direction_active,
},
context::WidgetContext,
node::WidgetNode,
unit::grid::{GridBoxItemLayout, GridBoxItemNode, GridBoxNode},
utils::Transform,
},
};
use serde::{Deserialize, Serialize};
#[derive(PropsData, Debug, Default, Clone, Serialize, Deserialize)]
#[props_data(crate::props::PropsData)]
#[prefab(crate::Prefab)]
pub struct GridBoxProps {
#[serde(default)]
pub cols: usize,
#[serde(default)]
pub rows: usize,
#[serde(default)]
pub transform: Transform,
}
#[pre_hooks(use_nav_container_active, use_nav_jump_direction_active, use_nav_item)]
pub fn nav_grid_box(mut context: WidgetContext) -> WidgetNode {
let WidgetContext {
key,
props,
listed_slots,
..
} = context;
let props = props
.clone()
.without::<NavContainerActive>()
.without::<NavJumpActive>()
.without::<NavItemActive>();
make_widget!(grid_box)
.key(key)
.merge_props(props)
.listed_slots(listed_slots)
.into()
}
pub fn grid_box(context: WidgetContext) -> WidgetNode {
let WidgetContext {
id,
props,
listed_slots,
..
} = context;
let GridBoxProps {
cols,
rows,
transform,
} = props.read_cloned_or_default();
let items = listed_slots
.into_iter()
.filter_map(|slot| {
if let Some(props) = slot.props() {
let layout = props.read_cloned_or_default::<GridBoxItemLayout>();
Some(GridBoxItemNode { slot, layout })
} else {
None
}
})
.collect::<Vec<_>>();
GridBoxNode {
id: id.to_owned(),
props: props.clone(),
items,
cols,
rows,
transform,
}
.into()
}
| 412 | 0.95561 | 1 | 0.95561 | game-dev | MEDIA | 0.69638 | game-dev | 0.868358 | 1 | 0.868358 |
Fluorohydride/ygopro-scripts | 3,970 | c3779662.lua | --剣闘獣アンダバタエ
function c3779662.initial_effect(c)
c:EnableReviveLimit()
aux.AddFusionProcCodeFun(c,7573135,aux.FilterBoolFunction(Card.IsFusionSetCard,0x1019),2,true,true)
aux.AddContactFusionProcedure(c,c3779662.cfilter,LOCATION_ONFIELD,0,aux.ContactFusionSendToDeck(c)):SetValue(SUMMON_VALUE_SELF)
--spsummon condition
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetCode(EFFECT_SPSUMMON_CONDITION)
e1:SetValue(c3779662.splimit)
c:RegisterEffect(e1)
--extra summon
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(3779662,4))
e3:SetCategory(CATEGORY_SPECIAL_SUMMON)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e3:SetCode(EVENT_SPSUMMON_SUCCESS)
e3:SetProperty(EFFECT_FLAG_DELAY)
e3:SetCondition(c3779662.espcon)
e3:SetTarget(c3779662.esptg)
e3:SetOperation(c3779662.espop)
c:RegisterEffect(e3)
--special summon
local e6=Effect.CreateEffect(c)
e6:SetDescription(aux.Stringid(3779662,5))
e6:SetCategory(CATEGORY_SPECIAL_SUMMON)
e6:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e6:SetCode(EVENT_PHASE+PHASE_BATTLE)
e6:SetRange(LOCATION_MZONE)
e6:SetCondition(c3779662.spcon)
e6:SetCost(c3779662.spcost)
e6:SetTarget(c3779662.sptg)
e6:SetOperation(c3779662.spop)
c:RegisterEffect(e6)
end
function c3779662.splimit(e,se,sp,st)
return e:GetHandler():GetLocation()~=LOCATION_EXTRA
end
function c3779662.cfilter(c)
return (c:IsFusionCode(7573135) or c:IsFusionSetCard(0x1019) and c:IsType(TYPE_MONSTER))
and c:IsAbleToDeckOrExtraAsCost()
end
function c3779662.espcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetSummonType()==SUMMON_TYPE_SPECIAL+SUMMON_VALUE_SELF
end
function c3779662.espfilter(c,e,tp)
return c:IsSetCard(0x1019) and c:IsType(TYPE_FUSION) and c:IsLevelBelow(7)
and c:IsCanBeSpecialSummoned(e,0,tp,true,false) and Duel.GetLocationCountFromEx(tp,tp,nil,c)>0
end
function c3779662.esptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c3779662.espfilter,tp,LOCATION_EXTRA,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_EXTRA)
end
function c3779662.espop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c3779662.espfilter,tp,LOCATION_EXTRA,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,true,false,POS_FACEUP)
end
end
function c3779662.spcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetBattledGroupCount()>0
end
function c3779662.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
local c=e:GetHandler()
if chk==0 then return c:IsAbleToExtraAsCost() end
Duel.SendtoDeck(c,nil,SEQ_DECKTOP,REASON_COST)
end
function c3779662.spfilter(c,e,tp)
return c:IsSetCard(0x1019) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c3779662.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then
local ft=Duel.GetLocationCount(tp,LOCATION_MZONE)
if e:GetHandler():GetSequence()<5 then ft=ft+1 end
return ft>1 and not Duel.IsPlayerAffectedByEffect(tp,59822133)
and Duel.IsExistingMatchingCard(c3779662.spfilter,tp,LOCATION_DECK,0,2,nil,e,tp)
end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,2,tp,LOCATION_DECK)
end
function c3779662.spop(e,tp,eg,ep,ev,re,r,rp)
if Duel.IsPlayerAffectedByEffect(tp,59822133) then return end
if Duel.GetLocationCount(tp,LOCATION_MZONE)<2 then return end
local g=Duel.GetMatchingGroup(c3779662.spfilter,tp,LOCATION_DECK,0,nil,e,tp)
if g:GetCount()>=2 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local sg=g:Select(tp,2,2,nil)
local tc=sg:GetFirst()
Duel.SpecialSummonStep(tc,0,tp,tp,false,false,POS_FACEUP)
tc:RegisterFlagEffect(tc:GetOriginalCode(),RESET_EVENT+RESETS_STANDARD+RESET_DISABLE,0,0)
tc=sg:GetNext()
Duel.SpecialSummonStep(tc,0,tp,tp,false,false,POS_FACEUP)
tc:RegisterFlagEffect(tc:GetOriginalCode(),RESET_EVENT+RESETS_STANDARD+RESET_DISABLE,0,0)
Duel.SpecialSummonComplete()
end
end
| 412 | 0.949176 | 1 | 0.949176 | game-dev | MEDIA | 0.967918 | game-dev | 0.973446 | 1 | 0.973446 |
MMMaellon/SmartObjectSync | 8,192 | Packages/com.vrchat.base/Runtime/VRCSDK/Plugins/UniTask/Runtime/Internal/PlayerLoopRunner.cs |
using System;
using UnityEngine;
namespace Cysharp.Threading.Tasks.Internal
{
internal sealed class PlayerLoopRunner
{
const int InitialSize = 16;
readonly PlayerLoopTiming timing;
readonly object runningAndQueueLock = new object();
readonly object arrayLock = new object();
readonly Action<Exception> unhandledExceptionCallback;
int tail = 0;
bool running = false;
IPlayerLoopItem[] loopItems = new IPlayerLoopItem[InitialSize];
MinimumQueue<IPlayerLoopItem> waitQueue = new MinimumQueue<IPlayerLoopItem>(InitialSize);
public PlayerLoopRunner(PlayerLoopTiming timing)
{
this.unhandledExceptionCallback = ex => Debug.LogException(ex);
this.timing = timing;
}
public void AddAction(IPlayerLoopItem item)
{
lock (runningAndQueueLock)
{
if (running)
{
waitQueue.Enqueue(item);
return;
}
}
lock (arrayLock)
{
// Ensure Capacity
if (loopItems.Length == tail)
{
Array.Resize(ref loopItems, checked(tail * 2));
}
loopItems[tail++] = item;
}
}
public int Clear()
{
lock (arrayLock)
{
var rest = 0;
for (var index = 0; index < loopItems.Length; index++)
{
if (loopItems[index] != null)
{
rest++;
}
loopItems[index] = null;
}
tail = 0;
return rest;
}
}
// delegate entrypoint.
public void Run()
{
// for debugging, create named stacktrace.
#if DEBUG
switch (timing)
{
case PlayerLoopTiming.Initialization:
Initialization();
break;
case PlayerLoopTiming.LastInitialization:
LastInitialization();
break;
case PlayerLoopTiming.EarlyUpdate:
EarlyUpdate();
break;
case PlayerLoopTiming.LastEarlyUpdate:
LastEarlyUpdate();
break;
case PlayerLoopTiming.FixedUpdate:
FixedUpdate();
break;
case PlayerLoopTiming.LastFixedUpdate:
LastFixedUpdate();
break;
case PlayerLoopTiming.PreUpdate:
PreUpdate();
break;
case PlayerLoopTiming.LastPreUpdate:
LastPreUpdate();
break;
case PlayerLoopTiming.Update:
Update();
break;
case PlayerLoopTiming.LastUpdate:
LastUpdate();
break;
case PlayerLoopTiming.PreLateUpdate:
PreLateUpdate();
break;
case PlayerLoopTiming.LastPreLateUpdate:
LastPreLateUpdate();
break;
case PlayerLoopTiming.PostLateUpdate:
PostLateUpdate();
break;
case PlayerLoopTiming.LastPostLateUpdate:
LastPostLateUpdate();
break;
#if UNITY_2020_2_OR_NEWER
case PlayerLoopTiming.TimeUpdate:
TimeUpdate();
break;
case PlayerLoopTiming.LastTimeUpdate:
LastTimeUpdate();
break;
#endif
default:
break;
}
#else
RunCore();
#endif
}
void Initialization() => RunCore();
void LastInitialization() => RunCore();
void EarlyUpdate() => RunCore();
void LastEarlyUpdate() => RunCore();
void FixedUpdate() => RunCore();
void LastFixedUpdate() => RunCore();
void PreUpdate() => RunCore();
void LastPreUpdate() => RunCore();
void Update() => RunCore();
void LastUpdate() => RunCore();
void PreLateUpdate() => RunCore();
void LastPreLateUpdate() => RunCore();
void PostLateUpdate() => RunCore();
void LastPostLateUpdate() => RunCore();
#if UNITY_2020_2_OR_NEWER
void TimeUpdate() => RunCore();
void LastTimeUpdate() => RunCore();
#endif
[System.Diagnostics.DebuggerHidden]
void RunCore()
{
lock (runningAndQueueLock)
{
running = true;
}
lock (arrayLock)
{
var j = tail - 1;
for (int i = 0; i < loopItems.Length; i++)
{
var action = loopItems[i];
if (action != null)
{
try
{
if (!action.MoveNext())
{
loopItems[i] = null;
}
else
{
continue; // next i
}
}
catch (Exception ex)
{
loopItems[i] = null;
try
{
unhandledExceptionCallback(ex);
}
catch { }
}
}
// find null, loop from tail
while (i < j)
{
var fromTail = loopItems[j];
if (fromTail != null)
{
try
{
if (!fromTail.MoveNext())
{
loopItems[j] = null;
j--;
continue; // next j
}
else
{
// swap
loopItems[i] = fromTail;
loopItems[j] = null;
j--;
goto NEXT_LOOP; // next i
}
}
catch (Exception ex)
{
loopItems[j] = null;
j--;
try
{
unhandledExceptionCallback(ex);
}
catch { }
continue; // next j
}
}
else
{
j--;
}
}
tail = i; // loop end
break; // LOOP END
NEXT_LOOP:
continue;
}
lock (runningAndQueueLock)
{
running = false;
while (waitQueue.Count != 0)
{
if (loopItems.Length == tail)
{
Array.Resize(ref loopItems, checked(tail * 2));
}
loopItems[tail++] = waitQueue.Dequeue();
}
}
}
}
}
}
| 412 | 0.888912 | 1 | 0.888912 | game-dev | MEDIA | 0.387289 | game-dev | 0.982118 | 1 | 0.982118 |
katalash/DSMapStudio | 1,316 | HKX2/Autogen/hkpBreakableConstraintData.cs | using SoulsFormats;
using System.Collections.Generic;
using System.Numerics;
namespace HKX2
{
public partial class hkpBreakableConstraintData : hkpWrappedConstraintData
{
public override uint Signature { get => 1070475939; }
public hkpBridgeAtoms m_atoms;
public float m_solverResultLimit;
public bool m_removeWhenBroken;
public bool m_revertBackVelocityOnBreak;
public override void Read(PackFileDeserializer des, BinaryReaderEx br)
{
base.Read(des, br);
m_atoms = new hkpBridgeAtoms();
m_atoms.Read(des, br);
br.ReadUInt32();
m_solverResultLimit = br.ReadSingle();
m_removeWhenBroken = br.ReadBoolean();
m_revertBackVelocityOnBreak = br.ReadBoolean();
br.ReadUInt32();
br.ReadUInt16();
}
public override void Write(PackFileSerializer s, BinaryWriterEx bw)
{
base.Write(s, bw);
m_atoms.Write(s, bw);
bw.WriteUInt32(0);
bw.WriteSingle(m_solverResultLimit);
bw.WriteBoolean(m_removeWhenBroken);
bw.WriteBoolean(m_revertBackVelocityOnBreak);
bw.WriteUInt32(0);
bw.WriteUInt16(0);
}
}
}
| 412 | 0.861144 | 1 | 0.861144 | game-dev | MEDIA | 0.671742 | game-dev | 0.8646 | 1 | 0.8646 |
lge-ros2/cloisim | 1,098 | Assets/Scripts/Tools/SDF/Parser/DebugLogWriter.cs | /*
* Copyright (c) 2020 LG Electronics Inc.
*
* SPDX-License-Identifier: MIT
*/
using UnityEngine;
using System.IO;
public class DebugLogWriter : TextWriter
{
private bool isError = false;
private bool showOnDisplay = false;
public DebugLogWriter(in bool errorLog = false)
{
//Debug.Log("Initialized!!!");
isError = errorLog;
}
public override void Write(string value)
{
if (value != null)
{
base.Write(value);
Print(value);
}
}
public override void WriteLine(string value)
{
if (value != null)
{
base.Write(value + "\n");
Print(value);
}
}
public void SetShowOnDisplayOnce()
{
showOnDisplay = true;
}
private void Print(in string value)
{
if (isError)
{
Debug.LogWarning(value);
if (showOnDisplay)
{
Main.UIController?.SetErrorMessage(value);
showOnDisplay = false;
}
}
else
{
Debug.Log(value);
if (showOnDisplay)
{
Main.UIController?.SetEventMessage(value);
showOnDisplay = false;
}
}
}
public override System.Text.Encoding Encoding
{
get { return System.Text.Encoding.UTF8; }
}
} | 412 | 0.771525 | 1 | 0.771525 | game-dev | MEDIA | 0.500126 | game-dev | 0.698769 | 1 | 0.698769 |
tanersener/mobile-ffmpeg | 2,070 | src/tesseract/textord/sortflts.h | /**********************************************************************
* File: sortflts.h (Formerly sfloats.h)
* Description: Code to maintain a sorted list of floats.
* Author: Ray Smith
* Created: Mon Oct 4 16:15:40 BST 1993
*
* (C) Copyright 1993, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#ifndef SORTFLTS_H
#define SORTFLTS_H
#include "elst.h"
class SORTED_FLOAT:public ELIST_LINK
{
friend class SORTED_FLOATS;
public:
SORTED_FLOAT() {
} //empty constructor
SORTED_FLOAT( //create one
float value, //value of entry
inT32 key) { //reference
entry = value;
address = key;
}
private:
float entry; //value of float
inT32 address; //key
};
ELISTIZEH (SORTED_FLOAT)
class SORTED_FLOATS
{
public:
/** empty constructor */
SORTED_FLOATS() {
it.set_to_list (&list);
}
/**
* add sample
* @param value sample float
* @param key retrieval key
*/
void add(float value,
inT32 key);
/**
* delete sample
* @param key key to delete
*/
void remove(inT32 key);
/**
* index to list
* @param index item to get
*/
float operator[] (inT32 index);
private:
SORTED_FLOAT_LIST list; //list of floats
SORTED_FLOAT_IT it; //iterator built-in
};
#endif
| 412 | 0.807641 | 1 | 0.807641 | game-dev | MEDIA | 0.268488 | game-dev | 0.552293 | 1 | 0.552293 |
keijiro/Skinner | 28,518 | Assets/PostProcessing/Editor/Models/ColorGradingModelEditor.cs | using UnityEngine;
using UnityEngine.PostProcessing;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace UnityEditor.PostProcessing
{
using Settings = ColorGradingModel.Settings;
using Tonemapper = ColorGradingModel.Tonemapper;
using ColorWheelMode = ColorGradingModel.ColorWheelMode;
[PostProcessingModelEditor(typeof(ColorGradingModel))]
public class ColorGradingModelEditor : PostProcessingModelEditor
{
static GUIContent[] s_Tonemappers =
{
new GUIContent("None"),
new GUIContent("Filmic (ACES)"),
new GUIContent("Neutral")
};
struct TonemappingSettings
{
public SerializedProperty tonemapper;
public SerializedProperty neutralBlackIn;
public SerializedProperty neutralWhiteIn;
public SerializedProperty neutralBlackOut;
public SerializedProperty neutralWhiteOut;
public SerializedProperty neutralWhiteLevel;
public SerializedProperty neutralWhiteClip;
}
struct BasicSettings
{
public SerializedProperty exposure;
public SerializedProperty temperature;
public SerializedProperty tint;
public SerializedProperty hueShift;
public SerializedProperty saturation;
public SerializedProperty contrast;
}
struct ChannelMixerSettings
{
public SerializedProperty[] channels;
public SerializedProperty currentEditingChannel;
}
struct ColorWheelsSettings
{
public SerializedProperty mode;
public SerializedProperty log;
public SerializedProperty linear;
}
static GUIContent[] s_Curves =
{
new GUIContent("YRGB"),
new GUIContent("Hue VS Hue"),
new GUIContent("Hue VS Sat"),
new GUIContent("Sat VS Sat"),
new GUIContent("Lum VS Sat")
};
struct CurvesSettings
{
public SerializedProperty master;
public SerializedProperty red;
public SerializedProperty green;
public SerializedProperty blue;
public SerializedProperty hueVShue;
public SerializedProperty hueVSsat;
public SerializedProperty satVSsat;
public SerializedProperty lumVSsat;
public SerializedProperty currentEditingCurve;
public SerializedProperty curveY;
public SerializedProperty curveR;
public SerializedProperty curveG;
public SerializedProperty curveB;
}
TonemappingSettings m_Tonemapping;
BasicSettings m_Basic;
ChannelMixerSettings m_ChannelMixer;
ColorWheelsSettings m_ColorWheels;
CurvesSettings m_Curves;
CurveEditor m_CurveEditor;
Dictionary<SerializedProperty, Color> m_CurveDict;
// Neutral tonemapping curve helper
const int k_CurveResolution = 24;
const float k_NeutralRangeX = 2f;
const float k_NeutralRangeY = 1f;
Vector3[] m_RectVertices = new Vector3[4];
Vector3[] m_LineVertices = new Vector3[2];
Vector3[] m_CurveVertices = new Vector3[k_CurveResolution];
Rect m_NeutralCurveRect;
public override void OnEnable()
{
// Tonemapping settings
m_Tonemapping = new TonemappingSettings
{
tonemapper = FindSetting((Settings x) => x.tonemapping.tonemapper),
neutralBlackIn = FindSetting((Settings x) => x.tonemapping.neutralBlackIn),
neutralWhiteIn = FindSetting((Settings x) => x.tonemapping.neutralWhiteIn),
neutralBlackOut = FindSetting((Settings x) => x.tonemapping.neutralBlackOut),
neutralWhiteOut = FindSetting((Settings x) => x.tonemapping.neutralWhiteOut),
neutralWhiteLevel = FindSetting((Settings x) => x.tonemapping.neutralWhiteLevel),
neutralWhiteClip = FindSetting((Settings x) => x.tonemapping.neutralWhiteClip)
};
// Basic settings
m_Basic = new BasicSettings
{
exposure = FindSetting((Settings x) => x.basic.postExposure),
temperature = FindSetting((Settings x) => x.basic.temperature),
tint = FindSetting((Settings x) => x.basic.tint),
hueShift = FindSetting((Settings x) => x.basic.hueShift),
saturation = FindSetting((Settings x) => x.basic.saturation),
contrast = FindSetting((Settings x) => x.basic.contrast)
};
// Channel mixer
m_ChannelMixer = new ChannelMixerSettings
{
channels = new[]
{
FindSetting((Settings x) => x.channelMixer.red),
FindSetting((Settings x) => x.channelMixer.green),
FindSetting((Settings x) => x.channelMixer.blue)
},
currentEditingChannel = FindSetting((Settings x) => x.channelMixer.currentEditingChannel)
};
// Color wheels
m_ColorWheels = new ColorWheelsSettings
{
mode = FindSetting((Settings x) => x.colorWheels.mode),
log = FindSetting((Settings x) => x.colorWheels.log),
linear = FindSetting((Settings x) => x.colorWheels.linear)
};
// Curves
m_Curves = new CurvesSettings
{
master = FindSetting((Settings x) => x.curves.master.curve),
red = FindSetting((Settings x) => x.curves.red.curve),
green = FindSetting((Settings x) => x.curves.green.curve),
blue = FindSetting((Settings x) => x.curves.blue.curve),
hueVShue = FindSetting((Settings x) => x.curves.hueVShue.curve),
hueVSsat = FindSetting((Settings x) => x.curves.hueVSsat.curve),
satVSsat = FindSetting((Settings x) => x.curves.satVSsat.curve),
lumVSsat = FindSetting((Settings x) => x.curves.lumVSsat.curve),
currentEditingCurve = FindSetting((Settings x) => x.curves.e_CurrentEditingCurve),
curveY = FindSetting((Settings x) => x.curves.e_CurveY),
curveR = FindSetting((Settings x) => x.curves.e_CurveR),
curveG = FindSetting((Settings x) => x.curves.e_CurveG),
curveB = FindSetting((Settings x) => x.curves.e_CurveB)
};
// Prepare the curve editor and extract curve display settings
m_CurveDict = new Dictionary<SerializedProperty, Color>();
var settings = CurveEditor.Settings.defaultSettings;
m_CurveEditor = new CurveEditor(settings);
AddCurve(m_Curves.master, new Color(1f, 1f, 1f), 2, false);
AddCurve(m_Curves.red, new Color(1f, 0f, 0f), 2, false);
AddCurve(m_Curves.green, new Color(0f, 1f, 0f), 2, false);
AddCurve(m_Curves.blue, new Color(0f, 0.5f, 1f), 2, false);
AddCurve(m_Curves.hueVShue, new Color(1f, 1f, 1f), 0, true);
AddCurve(m_Curves.hueVSsat, new Color(1f, 1f, 1f), 0, true);
AddCurve(m_Curves.satVSsat, new Color(1f, 1f, 1f), 0, false);
AddCurve(m_Curves.lumVSsat, new Color(1f, 1f, 1f), 0, false);
}
void AddCurve(SerializedProperty prop, Color color, uint minPointCount, bool loop)
{
var state = CurveEditor.CurveState.defaultState;
state.color = color;
state.visible = false;
state.minPointCount = minPointCount;
state.onlyShowHandlesOnSelection = true;
state.zeroKeyConstantValue = 0.5f;
state.loopInBounds = loop;
m_CurveEditor.Add(prop, state);
m_CurveDict.Add(prop, color);
}
public override void OnDisable()
{
m_CurveEditor.RemoveAll();
}
public override void OnInspectorGUI()
{
DoGUIFor("Tonemapping", DoTonemappingGUI);
EditorGUILayout.Space();
DoGUIFor("Basic", DoBasicGUI);
EditorGUILayout.Space();
DoGUIFor("Channel Mixer", DoChannelMixerGUI);
EditorGUILayout.Space();
DoGUIFor("Trackballs", DoColorWheelsGUI);
EditorGUILayout.Space();
DoGUIFor("Grading Curves", DoCurvesGUI);
}
void DoGUIFor(string title, Action func)
{
EditorGUILayout.LabelField(title, EditorStyles.boldLabel);
EditorGUI.indentLevel++;
func();
EditorGUI.indentLevel--;
}
void DoTonemappingGUI()
{
int tid = EditorGUILayout.Popup(EditorGUIHelper.GetContent("Tonemapper"), m_Tonemapping.tonemapper.intValue, s_Tonemappers);
if (tid == (int)Tonemapper.Neutral)
{
DrawNeutralTonemappingCurve();
EditorGUILayout.PropertyField(m_Tonemapping.neutralBlackIn, EditorGUIHelper.GetContent("Black In"));
EditorGUILayout.PropertyField(m_Tonemapping.neutralWhiteIn, EditorGUIHelper.GetContent("White In"));
EditorGUILayout.PropertyField(m_Tonemapping.neutralBlackOut, EditorGUIHelper.GetContent("Black Out"));
EditorGUILayout.PropertyField(m_Tonemapping.neutralWhiteOut, EditorGUIHelper.GetContent("White Out"));
EditorGUILayout.PropertyField(m_Tonemapping.neutralWhiteLevel, EditorGUIHelper.GetContent("White Level"));
EditorGUILayout.PropertyField(m_Tonemapping.neutralWhiteClip, EditorGUIHelper.GetContent("White Clip"));
}
m_Tonemapping.tonemapper.intValue = tid;
}
void DrawNeutralTonemappingCurve()
{
using (new GUILayout.HorizontalScope())
{
GUILayout.Space(EditorGUI.indentLevel * 15f);
m_NeutralCurveRect = GUILayoutUtility.GetRect(128, 80);
}
// Background
m_RectVertices[0] = PointInRect( 0f, 0f);
m_RectVertices[1] = PointInRect(k_NeutralRangeX, 0f);
m_RectVertices[2] = PointInRect(k_NeutralRangeX, k_NeutralRangeY);
m_RectVertices[3] = PointInRect( 0f, k_NeutralRangeY);
Handles.DrawSolidRectangleWithOutline(
m_RectVertices,
Color.white * 0.1f,
Color.white * 0.4f
);
// Horizontal lines
for (var i = 1; i < k_NeutralRangeY; i++)
DrawLine(0, i, k_NeutralRangeX, i, 0.4f);
// Vertical lines
for (var i = 1; i < k_NeutralRangeX; i++)
DrawLine(i, 0, i, k_NeutralRangeY, 0.4f);
// Label
Handles.Label(
PointInRect(0, k_NeutralRangeY) + Vector3.right,
"Neutral Tonemapper", EditorStyles.miniLabel
);
// Precompute some values
var tonemap = ((ColorGradingModel)target).settings.tonemapping;
const float scaleFactor = 20f;
const float scaleFactorHalf = scaleFactor * 0.5f;
float inBlack = tonemap.neutralBlackIn * scaleFactor + 1f;
float outBlack = tonemap.neutralBlackOut * scaleFactorHalf + 1f;
float inWhite = tonemap.neutralWhiteIn / scaleFactor;
float outWhite = 1f - tonemap.neutralWhiteOut / scaleFactor;
float blackRatio = inBlack / outBlack;
float whiteRatio = inWhite / outWhite;
const float a = 0.2f;
float b = Mathf.Max(0f, Mathf.LerpUnclamped(0.57f, 0.37f, blackRatio));
float c = Mathf.LerpUnclamped(0.01f, 0.24f, whiteRatio);
float d = Mathf.Max(0f, Mathf.LerpUnclamped(0.02f, 0.20f, blackRatio));
const float e = 0.02f;
const float f = 0.30f;
float whiteLevel = tonemap.neutralWhiteLevel;
float whiteClip = tonemap.neutralWhiteClip / scaleFactorHalf;
// Tonemapping curve
var vcount = 0;
while (vcount < k_CurveResolution)
{
float x = k_NeutralRangeX * vcount / (k_CurveResolution - 1);
float y = NeutralTonemap(x, a, b, c, d, e, f, whiteLevel, whiteClip);
if (y < k_NeutralRangeY)
{
m_CurveVertices[vcount++] = PointInRect(x, y);
}
else
{
if (vcount > 1)
{
// Extend the last segment to the top edge of the rect.
var v1 = m_CurveVertices[vcount - 2];
var v2 = m_CurveVertices[vcount - 1];
var clip = (m_NeutralCurveRect.y - v1.y) / (v2.y - v1.y);
m_CurveVertices[vcount - 1] = v1 + (v2 - v1) * clip;
}
break;
}
}
if (vcount > 1)
{
Handles.color = Color.white * 0.9f;
Handles.DrawAAPolyLine(2.0f, vcount, m_CurveVertices);
}
}
void DrawLine(float x1, float y1, float x2, float y2, float grayscale)
{
m_LineVertices[0] = PointInRect(x1, y1);
m_LineVertices[1] = PointInRect(x2, y2);
Handles.color = Color.white * grayscale;
Handles.DrawAAPolyLine(2f, m_LineVertices);
}
Vector3 PointInRect(float x, float y)
{
x = Mathf.Lerp(m_NeutralCurveRect.x, m_NeutralCurveRect.xMax, x / k_NeutralRangeX);
y = Mathf.Lerp(m_NeutralCurveRect.yMax, m_NeutralCurveRect.y, y / k_NeutralRangeY);
return new Vector3(x, y, 0);
}
float NeutralCurve(float x, float a, float b, float c, float d, float e, float f)
{
return ((x * (a * x + c * b) + d * e) / (x * (a * x + b) + d * f)) - e / f;
}
float NeutralTonemap(float x, float a, float b, float c, float d, float e, float f, float whiteLevel, float whiteClip)
{
x = Mathf.Max(0f, x);
// Tonemap
float whiteScale = 1f / NeutralCurve(whiteLevel, a, b, c, d, e, f);
x = NeutralCurve(x * whiteScale, a, b, c, d, e, f);
x *= whiteScale;
// Post-curve white point adjustment
x /= whiteClip;
return x;
}
void DoBasicGUI()
{
EditorGUILayout.PropertyField(m_Basic.exposure, EditorGUIHelper.GetContent("Post Exposure (EV)"));
EditorGUILayout.PropertyField(m_Basic.temperature);
EditorGUILayout.PropertyField(m_Basic.tint);
EditorGUILayout.PropertyField(m_Basic.hueShift);
EditorGUILayout.PropertyField(m_Basic.saturation);
EditorGUILayout.PropertyField(m_Basic.contrast);
}
void DoChannelMixerGUI()
{
int currentChannel = m_ChannelMixer.currentEditingChannel.intValue;
EditorGUI.BeginChangeCheck();
{
using (new EditorGUILayout.HorizontalScope())
{
EditorGUILayout.PrefixLabel("Channel");
if (GUILayout.Toggle(currentChannel == 0, EditorGUIHelper.GetContent("Red|Red output channel."), EditorStyles.miniButtonLeft)) currentChannel = 0;
if (GUILayout.Toggle(currentChannel == 1, EditorGUIHelper.GetContent("Green|Green output channel."), EditorStyles.miniButtonMid)) currentChannel = 1;
if (GUILayout.Toggle(currentChannel == 2, EditorGUIHelper.GetContent("Blue|Blue output channel."), EditorStyles.miniButtonRight)) currentChannel = 2;
}
}
if (EditorGUI.EndChangeCheck())
{
GUI.FocusControl(null);
}
var serializedChannel = m_ChannelMixer.channels[currentChannel];
m_ChannelMixer.currentEditingChannel.intValue = currentChannel;
var v = serializedChannel.vector3Value;
v.x = EditorGUILayout.Slider(EditorGUIHelper.GetContent("Red|Modify influence of the red channel within the overall mix."), v.x, -2f, 2f);
v.y = EditorGUILayout.Slider(EditorGUIHelper.GetContent("Green|Modify influence of the green channel within the overall mix."), v.y, -2f, 2f);
v.z = EditorGUILayout.Slider(EditorGUIHelper.GetContent("Blue|Modify influence of the blue channel within the overall mix."), v.z, -2f, 2f);
serializedChannel.vector3Value = v;
}
void DoColorWheelsGUI()
{
int wheelMode = m_ColorWheels.mode.intValue;
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Space(15);
if (GUILayout.Toggle(wheelMode == (int)ColorWheelMode.Linear, "Linear", EditorStyles.miniButtonLeft)) wheelMode = (int)ColorWheelMode.Linear;
if (GUILayout.Toggle(wheelMode == (int)ColorWheelMode.Log, "Log", EditorStyles.miniButtonRight)) wheelMode = (int)ColorWheelMode.Log;
}
m_ColorWheels.mode.intValue = wheelMode;
EditorGUILayout.Space();
if (wheelMode == (int)ColorWheelMode.Linear)
{
EditorGUILayout.PropertyField(m_ColorWheels.linear);
WheelSetTitle(GUILayoutUtility.GetLastRect(), "Linear Controls");
}
else if (wheelMode == (int)ColorWheelMode.Log)
{
EditorGUILayout.PropertyField(m_ColorWheels.log);
WheelSetTitle(GUILayoutUtility.GetLastRect(), "Log Controls");
}
}
static void WheelSetTitle(Rect position, string label)
{
var matrix = GUI.matrix;
var rect = new Rect(position.x - 10f, position.y, TrackballGroupDrawer.m_Size, TrackballGroupDrawer.m_Size);
GUIUtility.RotateAroundPivot(-90f, rect.center);
GUI.Label(rect, label, FxStyles.centeredMiniLabel);
GUI.matrix = matrix;
}
void ResetVisibleCurves()
{
foreach (var curve in m_CurveDict)
{
var state = m_CurveEditor.GetCurveState(curve.Key);
state.visible = false;
m_CurveEditor.SetCurveState(curve.Key, state);
}
}
void SetCurveVisible(SerializedProperty prop)
{
var state = m_CurveEditor.GetCurveState(prop);
state.visible = true;
m_CurveEditor.SetCurveState(prop, state);
}
bool SpecialToggle(bool value, string name, out bool rightClicked)
{
var rect = GUILayoutUtility.GetRect(EditorGUIHelper.GetContent(name), EditorStyles.toolbarButton);
var e = Event.current;
rightClicked = (e.type == EventType.MouseUp && rect.Contains(e.mousePosition) && e.button == 1);
return GUI.Toggle(rect, value, name, EditorStyles.toolbarButton);
}
static Material s_MaterialSpline;
void DoCurvesGUI()
{
EditorGUILayout.Space();
EditorGUI.indentLevel -= 2;
ResetVisibleCurves();
using (new EditorGUI.DisabledGroupScope(serializedProperty.serializedObject.isEditingMultipleObjects))
{
int curveEditingId = 0;
// Top toolbar
using (new GUILayout.HorizontalScope(EditorStyles.toolbar))
{
curveEditingId = EditorGUILayout.Popup(m_Curves.currentEditingCurve.intValue, s_Curves, EditorStyles.toolbarPopup, GUILayout.MaxWidth(150f));
bool y = false, r = false, g = false, b = false;
if (curveEditingId == 0)
{
EditorGUILayout.Space();
bool rightClickedY, rightClickedR, rightClickedG, rightClickedB;
y = SpecialToggle(m_Curves.curveY.boolValue, "Y", out rightClickedY);
r = SpecialToggle(m_Curves.curveR.boolValue, "R", out rightClickedR);
g = SpecialToggle(m_Curves.curveG.boolValue, "G", out rightClickedG);
b = SpecialToggle(m_Curves.curveB.boolValue, "B", out rightClickedB);
if (!y && !r && !g && !b)
{
r = g = b = false;
y = true;
}
if (rightClickedY || rightClickedR || rightClickedG || rightClickedB)
{
y = rightClickedY;
r = rightClickedR;
g = rightClickedG;
b = rightClickedB;
}
if (y) SetCurveVisible(m_Curves.master);
if (r) SetCurveVisible(m_Curves.red);
if (g) SetCurveVisible(m_Curves.green);
if (b) SetCurveVisible(m_Curves.blue);
m_Curves.curveY.boolValue = y;
m_Curves.curveR.boolValue = r;
m_Curves.curveG.boolValue = g;
m_Curves.curveB.boolValue = b;
}
else
{
switch (curveEditingId)
{
case 1: SetCurveVisible(m_Curves.hueVShue);
break;
case 2: SetCurveVisible(m_Curves.hueVSsat);
break;
case 3: SetCurveVisible(m_Curves.satVSsat);
break;
case 4: SetCurveVisible(m_Curves.lumVSsat);
break;
}
}
GUILayout.FlexibleSpace();
if (GUILayout.Button("Reset", EditorStyles.toolbarButton))
{
switch (curveEditingId)
{
case 0:
if (y) m_Curves.master.animationCurveValue = AnimationCurve.Linear(0f, 0f, 1f, 1f);
if (r) m_Curves.red.animationCurveValue = AnimationCurve.Linear(0f, 0f, 1f, 1f);
if (g) m_Curves.green.animationCurveValue = AnimationCurve.Linear(0f, 0f, 1f, 1f);
if (b) m_Curves.blue.animationCurveValue = AnimationCurve.Linear(0f, 0f, 1f, 1f);
break;
case 1: m_Curves.hueVShue.animationCurveValue = new AnimationCurve();
break;
case 2: m_Curves.hueVSsat.animationCurveValue = new AnimationCurve();
break;
case 3: m_Curves.satVSsat.animationCurveValue = new AnimationCurve();
break;
case 4: m_Curves.lumVSsat.animationCurveValue = new AnimationCurve();
break;
}
}
m_Curves.currentEditingCurve.intValue = curveEditingId;
}
// Curve area
var settings = m_CurveEditor.settings;
var rect = GUILayoutUtility.GetAspectRect(2f);
var innerRect = settings.padding.Remove(rect);
if (Event.current.type == EventType.Repaint)
{
// Background
EditorGUI.DrawRect(rect, new Color(0.15f, 0.15f, 0.15f, 1f));
if (s_MaterialSpline == null)
s_MaterialSpline = new Material(Shader.Find("Hidden/Post FX/UI/Curve Background")) { hideFlags = HideFlags.HideAndDontSave };
if (curveEditingId == 1 || curveEditingId == 2)
DrawBackgroundTexture(innerRect, 0);
else if (curveEditingId == 3 || curveEditingId == 4)
DrawBackgroundTexture(innerRect, 1);
// Bounds
Handles.color = Color.white;
Handles.DrawSolidRectangleWithOutline(innerRect, Color.clear, new Color(0.8f, 0.8f, 0.8f, 0.5f));
// Grid setup
Handles.color = new Color(1f, 1f, 1f, 0.05f);
int hLines = (int)Mathf.Sqrt(innerRect.width);
int vLines = (int)(hLines / (innerRect.width / innerRect.height));
// Vertical grid
int gridOffset = Mathf.FloorToInt(innerRect.width / hLines);
int gridPadding = ((int)(innerRect.width) % hLines) / 2;
for (int i = 1; i < hLines; i++)
{
var offset = i * Vector2.right * gridOffset;
offset.x += gridPadding;
Handles.DrawLine(innerRect.position + offset, new Vector2(innerRect.x, innerRect.yMax - 1) + offset);
}
// Horizontal grid
gridOffset = Mathf.FloorToInt(innerRect.height / vLines);
gridPadding = ((int)(innerRect.height) % vLines) / 2;
for (int i = 1; i < vLines; i++)
{
var offset = i * Vector2.up * gridOffset;
offset.y += gridPadding;
Handles.DrawLine(innerRect.position + offset, new Vector2(innerRect.xMax - 1, innerRect.y) + offset);
}
}
// Curve editor
if (m_CurveEditor.OnGUI(rect))
{
Repaint();
GUI.changed = true;
}
if (Event.current.type == EventType.Repaint)
{
// Borders
Handles.color = Color.black;
Handles.DrawLine(new Vector2(rect.x, rect.y - 18f), new Vector2(rect.xMax, rect.y - 18f));
Handles.DrawLine(new Vector2(rect.x, rect.y - 19f), new Vector2(rect.x, rect.yMax));
Handles.DrawLine(new Vector2(rect.x, rect.yMax), new Vector2(rect.xMax, rect.yMax));
Handles.DrawLine(new Vector2(rect.xMax, rect.yMax), new Vector2(rect.xMax, rect.y - 18f));
// Selection info
var selection = m_CurveEditor.GetSelection();
if (selection.curve != null && selection.keyframeIndex > -1)
{
var key = selection.keyframe.Value;
var infoRect = innerRect;
infoRect.x += 5f;
infoRect.width = 100f;
infoRect.height = 30f;
GUI.Label(infoRect, string.Format("{0}\n{1}", key.time.ToString("F3"), key.value.ToString("F3")), FxStyles.preLabel);
}
}
}
/*
EditorGUILayout.HelpBox(
@"Curve editor cheat sheet:
- [Del] or [Backspace] to remove a key
- [Ctrl] to break a tangent handle
- [Shift] to align tangent handles
- [Double click] to create a key on the curve(s) at mouse position
- [Alt] + [Double click] to create a key on the curve(s) at a given time",
MessageType.Info);
*/
EditorGUILayout.Space();
EditorGUI.indentLevel += 2;
}
void DrawBackgroundTexture(Rect rect, int pass)
{
float scale = EditorGUIUtility.pixelsPerPoint;
var oldRt = RenderTexture.active;
var rt = RenderTexture.GetTemporary(Mathf.CeilToInt(rect.width * scale), Mathf.CeilToInt(rect.height * scale), 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear);
s_MaterialSpline.SetFloat("_DisabledState", GUI.enabled ? 1f : 0.5f);
s_MaterialSpline.SetFloat("_PixelScaling", EditorGUIUtility.pixelsPerPoint);
Graphics.Blit(null, rt, s_MaterialSpline, pass);
RenderTexture.active = oldRt;
GUI.DrawTexture(rect, rt);
RenderTexture.ReleaseTemporary(rt);
}
}
}
| 412 | 0.976228 | 1 | 0.976228 | game-dev | MEDIA | 0.443378 | game-dev,graphics-rendering | 0.95672 | 1 | 0.95672 |
iDigitalFlame/XMT | 3,630 | device/winapi/mem_v11.go | //go:build windows && cgo && freemem && go1.11 && !go1.12
// +build windows,cgo,freemem,go1.11,!go1.12
// Copyright (C) 2020 - 2023 iDigitalFlame
//
// 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
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//
package winapi
import "unsafe"
const (
x64 = 1 << (^uintptr(0) >> 63) / 2
arenaL1Bits = 1 << (6 * x64)
arenaL2Bits = 1 << ((x64*48 + (1-x64)*32) - 22 - (6 * x64))
)
//go:linkname gcBitsArenas runtime.gcBitsArenas
var gcBitsArenas [4]uintptr
type mheap struct {
_ uintptr
_ [128][2]uintptr
freeLarge *treapNode
_ [128][2]uintptr
_, _ uintptr
_, _, _ uint32
allspans []*mspan
_ [2]struct {
_, _, _, _ uintptr
_ uint32
}
_, _, _, _ uint64
_ float64
_, _, _, _ uint64
_ [67]uint64
arenas [arenaL1Bits]*[arenaL2Bits]uintptr
heapArenaAlloc linearAlloc
arenaHints *arenaHint
area linearAlloc
_ [134]struct {
_ uintptr
_ uint8
_, _, _, _ uintptr
_ uint64
_ [cacheLineSize - ((5*ptrSize)+9)%cacheLineSize]byte
}
spanalloc fixalloc
cachealloc fixalloc
treapalloc fixalloc
specialfinalizeralloc fixalloc
specialprofilealloc fixalloc
_ uintptr
arenaHintAlloc fixalloc
}
type mspan struct {
_, _ *mspan
_ uintptr
startAddr uintptr
}
type fixalloc struct {
_, _, _, _ uintptr
chunk uintptr
_ uint32
inuse uintptr
_ uintptr
_ bool
}
type treapNode struct {
_, _ uintptr
parent *treapNode
_ uintptr
spanKey uintptr
}
type arenaHint struct {
addr uintptr
_ bool
next *arenaHint
}
type linearAlloc struct {
next uintptr
mapped, _ uintptr
}
func enumRuntimeMemory(h *mheap, m memoryMap) {
for x := h.freeLarge; x != nil; x = x.parent {
m.add(x.spanKey)
}
for i := 1; i < len(gcBitsArenas); i++ {
m.add(gcBitsArenas[i])
}
if len(h.allspans) > 0 {
for i := range h.allspans {
if h.allspans[i] != nil {
m.add(h.allspans[i].startAddr)
}
}
m.add(uintptr(unsafe.Pointer(&h.allspans[0])))
}
for i := range h.arenas {
if h.arenas[i] == nil {
continue
}
if m.add(uintptr(unsafe.Pointer(h.arenas[i]))); x64 == 0 {
continue
}
for z := range h.arenas[i] {
if h.arenas[i][z] == 0 {
continue
}
m.add(uintptr(unsafe.Pointer(h.arenas[i][z])))
}
}
if m.add(h.area.next); h.area.mapped > 2 {
m.add(h.area.mapped - 2)
}
if m.add(h.heapArenaAlloc.next); h.heapArenaAlloc.mapped > 2 {
m.add(h.heapArenaAlloc.mapped - 2)
}
for x := h.arenaHints; x != nil; x = x.next {
m.add(x.addr)
}
m.add(h.spanalloc.chunk)
m.add(h.spanalloc.inuse)
m.add(h.cachealloc.chunk)
m.add(h.cachealloc.inuse)
m.add(h.treapalloc.chunk)
m.add(h.treapalloc.inuse)
m.add(h.specialfinalizeralloc.chunk)
m.add(h.specialfinalizeralloc.inuse)
m.add(h.specialprofilealloc.chunk)
m.add(h.specialprofilealloc.inuse)
m.add(h.arenaHintAlloc.chunk)
m.add(h.arenaHintAlloc.inuse)
}
| 412 | 0.797081 | 1 | 0.797081 | game-dev | MEDIA | 0.50345 | game-dev | 0.632407 | 1 | 0.632407 |
x3bits/MikuMikuXR | 22,137 | Assets/_Packs/JsonDotNet/Source/WinRT/Linq/RT_JContainer.cs | #if (UNITY_WINRT || UNITY_WP_8_1) && !UNITY_EDITOR && !UNITY_WP8
#region License
// Copyright (c) 2007 James Newton-King
//
// 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.
#endregion
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Threading;
using Newtonsoft.Json.Utilities;
using System.Collections;
using System.Globalization;
using System.ComponentModel;
using System.Linq;
namespace Newtonsoft.Json.Linq
{
/// <summary>
/// Represents a token that can contain other tokens.
/// </summary>
public abstract class JContainer : JToken, IList<JToken>, IList
{
internal NotifyCollectionChangedEventHandler _collectionChanged;
/// <summary>
/// Occurs when the items list of the collection has changed, or the collection is reset.
/// </summary>
public event NotifyCollectionChangedEventHandler CollectionChanged
{
add { _collectionChanged += value; }
remove { _collectionChanged -= value; }
}
/// <summary>
/// Gets the container's children tokens.
/// </summary>
/// <value>The container's children tokens.</value>
protected abstract IList<JToken> ChildrenTokens { get; }
private object _syncRoot;
private bool _busy;
internal JContainer()
{
}
internal JContainer(JContainer other)
: this()
{
ValidationUtils.ArgumentNotNull(other, "c");
foreach (JToken child in other)
{
Add(child);
}
}
internal void CheckReentrancy()
{
if (_busy)
throw new InvalidOperationException("Cannot change {0} during a collection change event.".FormatWith(CultureInfo.InvariantCulture, GetType()));
}
internal virtual IList<JToken> CreateChildrenCollection()
{
return new List<JToken>();
}
/// <summary>
/// Raises the <see cref="CollectionChanged"/> event.
/// </summary>
/// <param name="e">The <see cref="NotifyCollectionChangedEventArgs"/> instance containing the event data.</param>
protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
NotifyCollectionChangedEventHandler handler = _collectionChanged;
if (handler != null)
{
_busy = true;
try
{
handler(this, e);
}
finally
{
_busy = false;
}
}
}
/// <summary>
/// Gets a value indicating whether this token has child tokens.
/// </summary>
/// <value>
/// <c>true</c> if this token has child values; otherwise, <c>false</c>.
/// </value>
public override bool HasValues
{
get { return ChildrenTokens.Count > 0; }
}
internal bool ContentsEqual(JContainer container)
{
if (container == this)
return true;
IList<JToken> t1 = ChildrenTokens;
IList<JToken> t2 = container.ChildrenTokens;
if (t1.Count != t2.Count)
return false;
for (int i = 0; i < t1.Count; i++)
{
if (!t1[i].DeepEquals(t2[i]))
return false;
}
return true;
}
/// <summary>
/// Get the first child token of this token.
/// </summary>
/// <value>
/// A <see cref="JToken"/> containing the first child token of the <see cref="JToken"/>.
/// </value>
public override JToken First
{
get { return ChildrenTokens.FirstOrDefault(); }
}
/// <summary>
/// Get the last child token of this token.
/// </summary>
/// <value>
/// A <see cref="JToken"/> containing the last child token of the <see cref="JToken"/>.
/// </value>
public override JToken Last
{
get { return ChildrenTokens.LastOrDefault(); }
}
/// <summary>
/// Returns a collection of the child tokens of this token, in document order.
/// </summary>
/// <returns>
/// An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> containing the child tokens of this <see cref="JToken"/>, in document order.
/// </returns>
public override JEnumerable<JToken> Children()
{
return new JEnumerable<JToken>(ChildrenTokens);
}
/// <summary>
/// Returns a collection of the child values of this token, in document order.
/// </summary>
/// <typeparam name="T">The type to convert the values to.</typeparam>
/// <returns>
/// A <see cref="IEnumerable{T}"/> containing the child values of this <see cref="JToken"/>, in document order.
/// </returns>
public override IEnumerable<T> Values<T>()
{
return ChildrenTokens.Convert<JToken, T>();
}
/// <summary>
/// Returns a collection of the descendant tokens for this token in document order.
/// </summary>
/// <returns>An <see cref="IEnumerable{JToken}"/> containing the descendant tokens of the <see cref="JToken"/>.</returns>
public IEnumerable<JToken> Descendants()
{
foreach (JToken o in ChildrenTokens)
{
yield return o;
JContainer c = o as JContainer;
if (c != null)
{
foreach (JToken d in c.Descendants())
{
yield return d;
}
}
}
}
internal bool IsMultiContent(object content)
{
return (content is IEnumerable && !(content is string) && !(content is JToken) && !(content is byte[]));
}
internal JToken EnsureParentToken(JToken item, bool skipParentCheck)
{
if (item == null)
return new JValue((object) null);
if (skipParentCheck)
return item;
// to avoid a token having multiple parents or creating a recursive loop, create a copy if...
// the item already has a parent
// the item is being added to itself
// the item is being added to the root parent of itself
if (item.Parent != null || item == this || (item.HasValues && Root == item))
item = item.CloneToken();
return item;
}
private class JTokenReferenceEqualityComparer : IEqualityComparer<JToken>
{
public static readonly JTokenReferenceEqualityComparer Instance = new JTokenReferenceEqualityComparer();
public bool Equals(JToken x, JToken y)
{
return ReferenceEquals(x, y);
}
public int GetHashCode(JToken obj)
{
if (obj == null)
return 0;
return obj.GetHashCode();
}
}
internal int IndexOfItem(JToken item)
{
return ChildrenTokens.IndexOf(item, JTokenReferenceEqualityComparer.Instance);
}
internal virtual void InsertItem(int index, JToken item, bool skipParentCheck)
{
if (index > ChildrenTokens.Count)
throw new ArgumentOutOfRangeException("index", "Index must be within the bounds of the List.");
CheckReentrancy();
item = EnsureParentToken(item, skipParentCheck);
JToken previous = (index == 0) ? null : ChildrenTokens[index - 1];
// haven't inserted new token yet so next token is still at the inserting index
JToken next = (index == ChildrenTokens.Count) ? null : ChildrenTokens[index];
ValidateToken(item, null);
item.Parent = this;
item.Previous = previous;
if (previous != null)
previous.Next = item;
item.Next = next;
if (next != null)
next.Previous = item;
ChildrenTokens.Insert(index, item);
if (_collectionChanged != null)
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, index));
}
internal virtual void RemoveItemAt(int index)
{
if (index < 0)
throw new ArgumentOutOfRangeException("index", "Index is less than 0.");
if (index >= ChildrenTokens.Count)
throw new ArgumentOutOfRangeException("index", "Index is equal to or greater than Count.");
CheckReentrancy();
JToken item = ChildrenTokens[index];
JToken previous = (index == 0) ? null : ChildrenTokens[index - 1];
JToken next = (index == ChildrenTokens.Count - 1) ? null : ChildrenTokens[index + 1];
if (previous != null)
previous.Next = next;
if (next != null)
next.Previous = previous;
item.Parent = null;
item.Previous = null;
item.Next = null;
ChildrenTokens.RemoveAt(index);
if (_collectionChanged != null)
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item, index));
}
internal virtual bool RemoveItem(JToken item)
{
int index = IndexOfItem(item);
if (index >= 0)
{
RemoveItemAt(index);
return true;
}
return false;
}
internal virtual JToken GetItem(int index)
{
return ChildrenTokens[index];
}
internal virtual void SetItem(int index, JToken item)
{
if (index < 0)
throw new ArgumentOutOfRangeException("index", "Index is less than 0.");
if (index >= ChildrenTokens.Count)
throw new ArgumentOutOfRangeException("index", "Index is equal to or greater than Count.");
JToken existing = ChildrenTokens[index];
if (IsTokenUnchanged(existing, item))
return;
CheckReentrancy();
item = EnsureParentToken(item, false);
ValidateToken(item, existing);
JToken previous = (index == 0) ? null : ChildrenTokens[index - 1];
JToken next = (index == ChildrenTokens.Count - 1) ? null : ChildrenTokens[index + 1];
item.Parent = this;
item.Previous = previous;
if (previous != null)
previous.Next = item;
item.Next = next;
if (next != null)
next.Previous = item;
ChildrenTokens[index] = item;
existing.Parent = null;
existing.Previous = null;
existing.Next = null;
if (_collectionChanged != null)
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, item, existing, index));
}
internal virtual void ClearItems()
{
CheckReentrancy();
foreach (JToken item in ChildrenTokens)
{
item.Parent = null;
item.Previous = null;
item.Next = null;
}
ChildrenTokens.Clear();
if (_collectionChanged != null)
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
internal virtual void ReplaceItem(JToken existing, JToken replacement)
{
if (existing == null || existing.Parent != this)
return;
int index = IndexOfItem(existing);
SetItem(index, replacement);
}
internal virtual bool ContainsItem(JToken item)
{
return (IndexOfItem(item) != -1);
}
internal virtual void CopyItemsTo(Array array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException("array");
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException("arrayIndex", "arrayIndex is less than 0.");
if (arrayIndex >= array.Length && arrayIndex != 0)
throw new ArgumentException("arrayIndex is equal to or greater than the length of array.");
if (Count > array.Length - arrayIndex)
throw new ArgumentException("The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array.");
int index = 0;
foreach (JToken token in ChildrenTokens)
{
array.SetValue(token, arrayIndex + index);
index++;
}
}
internal static bool IsTokenUnchanged(JToken currentValue, JToken newValue)
{
JValue v1 = currentValue as JValue;
if (v1 != null)
{
// null will get turned into a JValue of type null
if (v1.Type == JTokenType.Null && newValue == null)
return true;
return v1.Equals(newValue);
}
return false;
}
internal virtual void ValidateToken(JToken o, JToken existing)
{
ValidationUtils.ArgumentNotNull(o, "o");
if (o.Type == JTokenType.Property)
throw new ArgumentException("Can not add {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, o.GetType(), GetType()));
}
/// <summary>
/// Adds the specified content as children of this <see cref="JToken"/>.
/// </summary>
/// <param name="content">The content to be added.</param>
public virtual void Add(object content)
{
AddInternal(ChildrenTokens.Count, content, false);
}
internal void AddAndSkipParentCheck(JToken token)
{
AddInternal(ChildrenTokens.Count, token, true);
}
/// <summary>
/// Adds the specified content as the first children of this <see cref="JToken"/>.
/// </summary>
/// <param name="content">The content to be added.</param>
public void AddFirst(object content)
{
AddInternal(0, content, false);
}
internal void AddInternal(int index, object content, bool skipParentCheck)
{
if (IsMultiContent(content))
{
IEnumerable enumerable = (IEnumerable)content;
int multiIndex = index;
foreach (object c in enumerable)
{
AddInternal(multiIndex, c, skipParentCheck);
multiIndex++;
}
}
else
{
JToken item = CreateFromContent(content);
InsertItem(index, item, skipParentCheck);
}
}
internal JToken CreateFromContent(object content)
{
if (content is JToken)
return (JToken)content;
return new JValue(content);
}
/// <summary>
/// Creates an <see cref="JsonWriter"/> that can be used to add tokens to the <see cref="JToken"/>.
/// </summary>
/// <returns>An <see cref="JsonWriter"/> that is ready to have content written to it.</returns>
public JsonWriter CreateWriter()
{
return new JTokenWriter(this);
}
/// <summary>
/// Replaces the children nodes of this token with the specified content.
/// </summary>
/// <param name="content">The content.</param>
public void ReplaceAll(object content)
{
ClearItems();
Add(content);
}
/// <summary>
/// Removes the child nodes from this token.
/// </summary>
public void RemoveAll()
{
ClearItems();
}
internal void ReadTokenFrom(JsonReader reader)
{
int startDepth = reader.Depth;
if (!reader.Read())
throw JsonReaderException.Create(reader, "Error reading {0} from JsonReader.".FormatWith(CultureInfo.InvariantCulture, GetType().Name));
ReadContentFrom(reader);
int endDepth = reader.Depth;
if (endDepth > startDepth)
throw JsonReaderException.Create(reader, "Unexpected end of content while loading {0}.".FormatWith(CultureInfo.InvariantCulture, GetType().Name));
}
internal void ReadContentFrom(JsonReader r)
{
ValidationUtils.ArgumentNotNull(r, "r");
IJsonLineInfo lineInfo = r as IJsonLineInfo;
JContainer parent = this;
do
{
if (parent is JProperty && ((JProperty)parent).Value != null)
{
if (parent == this)
return;
parent = parent.Parent;
}
switch (r.TokenType)
{
case JsonToken.None:
// new reader. move to actual content
break;
case JsonToken.StartArray:
JArray a = new JArray();
a.SetLineInfo(lineInfo);
parent.Add(a);
parent = a;
break;
case JsonToken.EndArray:
if (parent == this)
return;
parent = parent.Parent;
break;
case JsonToken.StartObject:
JObject o = new JObject();
o.SetLineInfo(lineInfo);
parent.Add(o);
parent = o;
break;
case JsonToken.EndObject:
if (parent == this)
return;
parent = parent.Parent;
break;
case JsonToken.StartConstructor:
JConstructor constructor = new JConstructor(r.Value.ToString());
constructor.SetLineInfo(constructor);
parent.Add(constructor);
parent = constructor;
break;
case JsonToken.EndConstructor:
if (parent == this)
return;
parent = parent.Parent;
break;
case JsonToken.String:
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.Date:
case JsonToken.Boolean:
case JsonToken.Bytes:
JValue v = new JValue(r.Value);
v.SetLineInfo(lineInfo);
parent.Add(v);
break;
case JsonToken.Comment:
v = JValue.CreateComment(r.Value.ToString());
v.SetLineInfo(lineInfo);
parent.Add(v);
break;
case JsonToken.Null:
v = new JValue(null, JTokenType.Null);
v.SetLineInfo(lineInfo);
parent.Add(v);
break;
case JsonToken.Undefined:
v = new JValue(null, JTokenType.Undefined);
v.SetLineInfo(lineInfo);
parent.Add(v);
break;
case JsonToken.PropertyName:
string propertyName = r.Value.ToString();
JProperty property = new JProperty(propertyName);
property.SetLineInfo(lineInfo);
JObject parentObject = (JObject) parent;
// handle multiple properties with the same name in JSON
JProperty existingPropertyWithName = parentObject.Property(propertyName);
if (existingPropertyWithName == null)
parent.Add(property);
else
existingPropertyWithName.Replace(property);
parent = property;
break;
default:
throw new InvalidOperationException("The JsonReader should not be on a token of type {0}.".FormatWith(CultureInfo.InvariantCulture, r.TokenType));
}
}
while (r.Read());
}
internal int ContentsHashCode()
{
int hashCode = 0;
foreach (JToken item in ChildrenTokens)
{
hashCode ^= item.GetDeepHashCode();
}
return hashCode;
}
#region IList<JToken> Members
int IList<JToken>.IndexOf(JToken item)
{
return IndexOfItem(item);
}
void IList<JToken>.Insert(int index, JToken item)
{
InsertItem(index, item, false);
}
void IList<JToken>.RemoveAt(int index)
{
RemoveItemAt(index);
}
JToken IList<JToken>.this[int index]
{
get { return GetItem(index); }
set { SetItem(index, value); }
}
#endregion
#region ICollection<JToken> Members
void ICollection<JToken>.Add(JToken item)
{
Add(item);
}
void ICollection<JToken>.Clear()
{
ClearItems();
}
bool ICollection<JToken>.Contains(JToken item)
{
return ContainsItem(item);
}
void ICollection<JToken>.CopyTo(JToken[] array, int arrayIndex)
{
CopyItemsTo(array, arrayIndex);
}
bool ICollection<JToken>.IsReadOnly
{
get { return false; }
}
bool ICollection<JToken>.Remove(JToken item)
{
return RemoveItem(item);
}
#endregion
private JToken EnsureValue(object value)
{
if (value == null)
return null;
if (value is JToken)
return (JToken) value;
throw new ArgumentException("Argument is not a JToken.");
}
#region IList Members
int IList.Add(object value)
{
Add(EnsureValue(value));
return Count - 1;
}
void IList.Clear()
{
ClearItems();
}
bool IList.Contains(object value)
{
return ContainsItem(EnsureValue(value));
}
int IList.IndexOf(object value)
{
return IndexOfItem(EnsureValue(value));
}
void IList.Insert(int index, object value)
{
InsertItem(index, EnsureValue(value), false);
}
bool IList.IsFixedSize
{
get { return false; }
}
bool IList.IsReadOnly
{
get { return false; }
}
void IList.Remove(object value)
{
RemoveItem(EnsureValue(value));
}
void IList.RemoveAt(int index)
{
RemoveItemAt(index);
}
object IList.this[int index]
{
get { return GetItem(index); }
set { SetItem(index, EnsureValue(value)); }
}
#endregion
#region ICollection Members
void ICollection.CopyTo(Array array, int index)
{
CopyItemsTo(array, index);
}
/// <summary>
/// Gets the count of child JSON tokens.
/// </summary>
/// <value>The count of child JSON tokens</value>
public int Count
{
get { return ChildrenTokens.Count; }
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
Interlocked.CompareExchange(ref _syncRoot, new object(), null);
return _syncRoot;
}
}
#endregion
}
}
#endif | 412 | 0.933264 | 1 | 0.933264 | game-dev | MEDIA | 0.195831 | game-dev | 0.977446 | 1 | 0.977446 |
bergerhealer/TrainCarts | 11,865 | src/main/java/com/bergerkiller/bukkit/tc/attachments/particle/VirtualDisplayBoundingBox.java | package com.bergerkiller.bukkit.tc.attachments.particle;
import com.bergerkiller.bukkit.common.math.OrientedBoundingBox;
import com.bergerkiller.bukkit.common.math.Quaternion;
import com.bergerkiller.bukkit.common.utils.EntityUtil;
import com.bergerkiller.bukkit.common.utils.MaterialUtil;
import com.bergerkiller.bukkit.common.utils.MathUtil;
import com.bergerkiller.bukkit.common.wrappers.BlockData;
import com.bergerkiller.bukkit.common.wrappers.DataWatcher;
import com.bergerkiller.bukkit.tc.Util;
import com.bergerkiller.bukkit.tc.attachments.VirtualDisplayEntity;
import com.bergerkiller.bukkit.tc.attachments.api.AttachmentManager;
import com.bergerkiller.bukkit.tc.attachments.api.AttachmentViewer;
import com.bergerkiller.generated.net.minecraft.network.protocol.game.PacketPlayOutEntityDestroyHandle;
import com.bergerkiller.generated.net.minecraft.network.protocol.game.PacketPlayOutEntityMetadataHandle;
import com.bergerkiller.generated.net.minecraft.network.protocol.game.PacketPlayOutEntityTeleportHandle;
import com.bergerkiller.generated.net.minecraft.network.protocol.game.PacketPlayOutMountHandle;
import com.bergerkiller.generated.net.minecraft.network.protocol.game.PacketPlayOutSpawnEntityHandle;
import com.bergerkiller.generated.net.minecraft.network.protocol.game.PacketPlayOutSpawnEntityLivingHandle;
import com.bergerkiller.generated.net.minecraft.world.entity.DisplayHandle;
import com.bergerkiller.generated.net.minecraft.world.entity.EntityHandle;
import org.bukkit.ChatColor;
import org.bukkit.entity.EntityType;
import org.bukkit.util.Vector;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.stream.Collectors;
/**
* Uses 12 block display entities to create "lines" making up the bounding box
*/
public class VirtualDisplayBoundingBox extends VirtualBoundingBox {
private final int mountEntityId;
private final List<Line> lines = Arrays.asList(
// Along X
Line.transform(t -> t.applyPosition(0.0, 1.0, 1.0)
.applyScaleX(1.0)),
Line.transform(t -> t.applyPosition(0.0, 0.0, 1.0)
.applyScaleX(1.0)),
Line.transform(t -> t.applyPosition(0.0, 1.0, 0.0)
.applyScaleX(1.0)),
Line.transform(t -> t.applyPosition(0.0, 0.0, 0.0)
.applyScaleX(1.0)),
// Along Z
Line.transform(t -> t.applyPosition(1.0, 1.0, 0.0)
.applyScaleZ(1.0)),
Line.transform(t -> t.applyPosition(1.0, 0.0, 0.0)
.applyScaleZ(1.0)),
Line.transform(t -> t.applyPosition(0.0, 1.0, 0.0)
.applyScaleZ(1.0)),
Line.transform(t -> t.applyPosition(0.0, 0.0, 0.0)
.applyScaleZ(1.0)),
// Along Y
Line.transform(t -> t.applyPosition(1.0, 0.0, 1.0)
.applyScaleY(1.0)),
Line.transform(t -> t.applyPosition(1.0, 0.0, 0.0)
.applyScaleY(1.0)),
Line.transform(t -> t.applyPosition(0.0, 0.0, 1.0)
.applyScaleY(1.0)),
Line.transform(t -> t.applyPosition(0.0, 0.0, 0.0)
.applyScaleY(1.0))
);
private final int[] lineEntityIds;
private final List<UUID> lineEntityUUIDs;
// Position info
private final Vector position = new Vector();
private final Vector size = new Vector();
private final Quaternion rotation = new Quaternion();
public VirtualDisplayBoundingBox(AttachmentManager manager) {
super(manager);
this.mountEntityId = EntityUtil.getUniqueEntityId();
this.lineEntityIds = lines.stream().mapToInt(l -> l.entityId).toArray();
this.lineEntityUUIDs = lines.stream().map(l -> l.entityUUID).collect(Collectors.toList());
}
@Override
public void update(OrientedBoundingBox boundingBox) {
MathUtil.setVector(position, boundingBox.getPosition());
MathUtil.setVector(size, boundingBox.getSize());
rotation.setTo(boundingBox.getOrientation());
double minSize = 0.02 * Util.absMinAxis(size);
double lineThickness = Math.min(0.3, minSize);
for (Line line : lines) {
LineTransformer transformer = new LineTransformer(line.metadata, lineThickness);
line.transform.accept(transformer);
}
}
@Override
protected void sendSpawnPackets(AttachmentViewer viewer, Vector motion) {
for (Line line : lines) {
line.spawn(viewer, position, motion);
}
// Spawn invisible marker armorstand mount
{
PacketPlayOutSpawnEntityLivingHandle spawnPacket = PacketPlayOutSpawnEntityLivingHandle.createNew();
spawnPacket.setEntityId(mountEntityId);
spawnPacket.setEntityUUID(UUID.randomUUID());
spawnPacket.setEntityType(EntityType.ARMOR_STAND);
spawnPacket.setPosX(position.getX() - motion.getX());
spawnPacket.setPosY(position.getY() - motion.getY());
spawnPacket.setPosZ(position.getZ() - motion.getZ());
spawnPacket.setMotX(motion.getX());
spawnPacket.setMotY(motion.getY());
spawnPacket.setMotZ(motion.getZ());
spawnPacket.setYaw(0.0f);
spawnPacket.setPitch(0.0f);
spawnPacket.setHeadYaw(0.0f);
viewer.sendEntityLivingSpawnPacket(spawnPacket, VirtualDisplayEntity.ARMORSTAND_MOUNT_METADATA);
}
// Mount all line blocks into the armorstand
viewer.send(PacketPlayOutMountHandle.createNew(mountEntityId, lineEntityIds));
}
@Override
protected void sendDestroyPackets(AttachmentViewer viewer) {
int[] ids = Arrays.copyOf(lineEntityIds, lineEntityIds.length + 1);
ids[ids.length - 1] = mountEntityId;
viewer.send(PacketPlayOutEntityDestroyHandle.createNewMultiple(ids));
}
@Override
protected void applyGlowing(ChatColor color) {
byte data = (color != null) ? (byte) EntityHandle.DATA_FLAG_GLOWING : (byte) 0;
for (Line line : lines) {
line.metadata.set(EntityHandle.DATA_FLAGS, data);
}
}
@Override
protected void applyGlowColorForViewer(AttachmentViewer viewer, ChatColor color) {
viewer.updateGlowColor(lineEntityUUIDs, color);
}
@Override
public void syncPosition(boolean absolute) {
// Sync metadata of the display blocks
for (Line line : lines) {
broadcast(line.createMetaPacket(false));
}
// Just sync absolute all the time, this isn't used often enough for it to warrant a lot of code
// int entityId, double posX, double posY, double posZ, float yaw, float pitch, boolean onGround)
broadcast(PacketPlayOutEntityTeleportHandle.createNew(mountEntityId,
position.getX(), position.getY(), position.getZ(),
0.0f, 0.0f, false));
}
@Override
public boolean containsEntityId(int entityId) {
return entityId == mountEntityId;
}
private static class Line {
private final Consumer<LineTransformer> transform;
public final int entityId;
public final UUID entityUUID;
private final DataWatcher metadata;
private static final DataWatcher.Prototype LINE_METADATA = DataWatcher.Prototype.build()
.setClientByteDefault(EntityHandle.DATA_FLAGS, 0)
.setClientDefault(DisplayHandle.DATA_TRANSLATION, new Vector())
.setClientDefault(DisplayHandle.DATA_LEFT_ROTATION, new Quaternion())
.setClientDefault(DisplayHandle.DATA_SCALE, new Vector(1, 1, 1))
.setClientDefault(DisplayHandle.DATA_INTERPOLATION_DURATION, 0)
.set(DisplayHandle.DATA_INTERPOLATION_DURATION, 3)
.setClientDefault(DisplayHandle.DATA_INTERPOLATION_START_DELTA_TICKS, 0)
.setClientDefault(DisplayHandle.BlockDisplayHandle.DATA_BLOCK_STATE, BlockData.AIR)
.set(DisplayHandle.BlockDisplayHandle.DATA_BLOCK_STATE, BlockData.fromMaterial(
MaterialUtil.getMaterial("BLACK_CONCRETE")))
.create();
public static Line transform(Consumer<LineTransformer> transform) {
return new Line(transform);
}
private Line(Consumer<LineTransformer> transform) {
this.transform = transform;
entityId = EntityUtil.getUniqueEntityId();
entityUUID = UUID.randomUUID();
metadata = LINE_METADATA.create();
}
public PacketPlayOutEntityMetadataHandle createMetaPacket(boolean includeUnchangedData) {
return PacketPlayOutEntityMetadataHandle.createNew(this.entityId, metadata, includeUnchangedData);
}
public void spawn(AttachmentViewer viewer, Vector position, Vector motion) {
// Spawn the display entity itself
{
PacketPlayOutSpawnEntityHandle spawnPacket = PacketPlayOutSpawnEntityHandle.createNew();
spawnPacket.setEntityId(this.entityId);
spawnPacket.setEntityUUID(this.entityUUID);
spawnPacket.setEntityType(VirtualDisplayEntity.BLOCK_DISPLAY_ENTITY_TYPE);
spawnPacket.setPosX(position.getX() - motion.getX());
spawnPacket.setPosY(position.getY() - motion.getY());
spawnPacket.setPosZ(position.getZ() - motion.getZ());
spawnPacket.setMotX(motion.getX());
spawnPacket.setMotY(motion.getY());
spawnPacket.setMotZ(motion.getZ());
spawnPacket.setYaw(0.0f);
spawnPacket.setPitch(0.0f);
viewer.send(spawnPacket);
viewer.send(createMetaPacket(true));
}
}
}
private class LineTransformer {
public final DataWatcher metadata;
public final double lineThickness;
public LineTransformer(DataWatcher metadata, double lineThickness) {
this.metadata = metadata;
this.lineThickness = lineThickness;
}
/**
* Generates the starting position of the line
*
* @param tx Position weight (X)
* @param ty Position weight (Y)
* @param tz Position weight (Z)
* @return this
*/
public LineTransformer applyPosition(double tx, double ty, double tz) {
Vector v = new Vector((-0.5 + tx) * size.getX() - tx * lineThickness,
(-0.5 + ty) * size.getY() - ty * lineThickness,
(-0.5 + tz) * size.getZ() - tz * lineThickness);
rotation.transformPoint(v);
metadata.forceSet(DisplayHandle.DATA_LEFT_ROTATION, rotation);
metadata.forceSet(DisplayHandle.DATA_TRANSLATION, v);
metadata.forceSet(DisplayHandle.DATA_INTERPOLATION_START_DELTA_TICKS, 0);
return this;
}
public LineTransformer applyScaleX(double x) {
metadata.forceSet(DisplayHandle.DATA_SCALE, new Vector(size.getX() * x, lineThickness, lineThickness));
return this;
}
public LineTransformer applyScaleY(double y) {
metadata.forceSet(DisplayHandle.DATA_SCALE, new Vector(lineThickness, size.getY() * y, lineThickness));
return this;
}
public LineTransformer applyScaleZ(double z) {
metadata.forceSet(DisplayHandle.DATA_SCALE, new Vector(lineThickness, lineThickness, size.getZ() * z));
return this;
}
}
}
| 412 | 0.846456 | 1 | 0.846456 | game-dev | MEDIA | 0.874154 | game-dev | 0.947134 | 1 | 0.947134 |
tahayvr/omarchist | 23,558 | src-tauri/src/services/themes/optimized_theme_loader.rs | use super::color_extraction::ColorExtractor;
use super::get_sys_themes::SysTheme;
use crate::types::ThemeColors;
use dirs;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tokio::sync::RwLock;
use tokio::task::JoinHandle;
/// Lightweight theme metadata for faster initial responses
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ThemeMetadata {
pub dir: String,
pub title: String,
pub is_system: bool,
pub is_custom: bool,
pub has_colors: bool,
pub has_image: bool,
}
/// Color extraction cache to avoid recomputation
#[derive(Debug, Clone)]
pub struct ColorCache {
cache: Arc<RwLock<HashMap<String, Option<ThemeColors>>>>,
}
impl Default for ColorCache {
fn default() -> Self {
Self::new()
}
}
impl ColorCache {
pub fn new() -> Self {
Self {
cache: Arc::new(RwLock::new(HashMap::new())),
}
}
/// Get cached colors for a theme directory
pub async fn get(&self, theme_dir: &str) -> Option<Option<ThemeColors>> {
let cache = self.cache.read().await;
cache.get(theme_dir).cloned()
}
/// Cache colors for a theme directory
pub async fn set(&self, theme_dir: String, colors: Option<ThemeColors>) {
let mut cache = self.cache.write().await;
cache.insert(theme_dir, colors);
}
/// Clear the cache
pub async fn clear(&self) {
let mut cache = self.cache.write().await;
cache.clear();
}
/// Get cache size
pub async fn size(&self) -> usize {
let cache = self.cache.read().await;
cache.len()
}
}
/// Optimized theme loader with parallel processing and caching
pub struct OptimizedThemeLoader {
color_cache: ColorCache,
}
impl OptimizedThemeLoader {
pub fn new() -> Self {
Self {
color_cache: ColorCache::new(),
}
}
/// Optimized helper function to convert directory name to title
fn dir_name_to_title(dir_name: &str) -> String {
let mut title = String::with_capacity(dir_name.len() + 10);
let mut capitalize_next = true;
for ch in dir_name.chars() {
match ch {
'-' | '_' => {
title.push(' ');
capitalize_next = true;
},
c if capitalize_next => {
title.extend(c.to_uppercase());
capitalize_next = false;
},
c => {
title.push(c);
},
}
}
title
}
/// Load themes with parallel processing for better performance
pub async fn load_themes_parallel(&self) -> Result<Vec<SysTheme>, String> {
let home_dir =
dirs::home_dir().ok_or_else(|| "Failed to get home directory".to_string())?;
let themes_dir = home_dir.join(".config/omarchy/themes");
if !themes_dir.exists() {
return Err(format!("Themes directory does not exist: {themes_dir:?}"));
}
// Collect all theme directory paths
let theme_paths = self.collect_theme_paths(&themes_dir)?;
if theme_paths.is_empty() {
return Ok(Vec::new());
}
log::info!(
"Loading {} themes with parallel processing",
theme_paths.len()
);
// Process themes in parallel using tokio::spawn
let mut handles: Vec<JoinHandle<Result<SysTheme, String>>> = Vec::new();
for path in theme_paths {
let color_cache = self.color_cache.clone();
let handle = tokio::spawn(async move {
Self::generate_theme_from_directory_async(&path, color_cache).await
});
handles.push(handle);
}
// Collect results from all parallel tasks
let mut themes = Vec::new();
let mut errors = Vec::new();
for handle in handles {
match handle.await {
Ok(Ok(theme)) => themes.push(theme),
Ok(Err(e)) => errors.push(e),
Err(e) => errors.push(format!("Task join error: {e}")),
}
}
// Log any errors but continue with successful themes
if !errors.is_empty() {
log::warn!(
"Encountered {} errors during parallel theme loading: {:?}",
errors.len(),
errors
);
}
log::info!("Successfully loaded {} themes in parallel", themes.len());
Ok(themes)
}
/// Load only theme metadata for faster initial responses
pub async fn load_theme_metadata_only(&self) -> Result<Vec<ThemeMetadata>, String> {
let home_dir =
dirs::home_dir().ok_or_else(|| "Failed to get home directory".to_string())?;
let themes_dir = home_dir.join(".config/omarchy/themes");
if !themes_dir.exists() {
return Err(format!("Themes directory does not exist: {themes_dir:?}"));
}
let theme_paths = self.collect_theme_paths(&themes_dir)?;
if theme_paths.is_empty() {
return Ok(Vec::new());
}
log::info!("Loading metadata for {} themes", theme_paths.len());
// Process metadata in parallel
let mut handles: Vec<JoinHandle<Result<ThemeMetadata, String>>> = Vec::new();
for path in theme_paths {
let handle = tokio::spawn(async move { Self::generate_theme_metadata(&path).await });
handles.push(handle);
}
// Collect metadata results
let mut metadata = Vec::new();
let mut errors = Vec::new();
for handle in handles {
match handle.await {
Ok(Ok(meta)) => metadata.push(meta),
Ok(Err(e)) => errors.push(e),
Err(e) => errors.push(format!("Metadata task join error: {e}")),
}
}
if !errors.is_empty() {
log::warn!(
"Encountered {} errors during metadata loading: {:?}",
errors.len(),
errors
);
}
log::info!("Successfully loaded metadata for {} themes", metadata.len());
Ok(metadata)
}
/// Collect all theme directory paths
fn collect_theme_paths(&self, themes_dir: &Path) -> Result<Vec<PathBuf>, String> {
let entries = fs::read_dir(themes_dir)
.map_err(|e| format!("Failed to read themes directory: {e}"))?;
let mut theme_paths = Vec::new();
for entry in entries {
let entry = entry.map_err(|e| format!("Failed to read directory entry: {e}"))?;
let path = entry.path();
if path.is_dir() {
theme_paths.push(path);
}
}
Ok(theme_paths)
}
/// Generate theme metadata only (lightweight operation)
async fn generate_theme_metadata(theme_dir: &Path) -> Result<ThemeMetadata, String> {
let dir_name = theme_dir
.file_name()
.and_then(|name| name.to_str())
.ok_or_else(|| "Invalid directory name".to_string())?;
// Convert directory name to a nice title (optimized)
let title = Self::dir_name_to_title(dir_name);
let is_custom = theme_dir.join("custom_theme.json").is_file();
// Check if the theme directory is a symlink (system theme)
let is_system = if is_custom {
false
} else {
fs::symlink_metadata(theme_dir)
.map(|m| m.file_type().is_symlink())
.unwrap_or(false)
};
// Check if theme has color configuration files
let has_colors = theme_dir.join("custom_theme.json").exists()
|| theme_dir.join("alacritty.toml").exists();
// Check if theme has image files
let has_image = Self::has_image_files(theme_dir);
Ok(ThemeMetadata {
dir: dir_name.to_string(),
title,
is_system,
is_custom,
has_colors,
has_image,
})
}
/// Check if directory contains image files
fn has_image_files(theme_dir: &Path) -> bool {
if let Ok(entries) = fs::read_dir(theme_dir) {
for entry in entries.flatten() {
let file_path = entry.path();
if file_path.is_file() {
if let Some(extension) = file_path.extension().and_then(|ext| ext.to_str()) {
let ext_lower = extension.to_lowercase();
if matches!(
ext_lower.as_str(),
"png" | "jpg" | "jpeg" | "webp" | "gif" | "svg"
) {
return true;
}
}
}
}
}
false
}
/// Generate full theme from directory with async color extraction and caching
async fn generate_theme_from_directory_async(
theme_dir: &Path,
color_cache: ColorCache,
) -> Result<SysTheme, String> {
let dir_name = theme_dir
.file_name()
.and_then(|name| name.to_str())
.ok_or_else(|| "Invalid directory name".to_string())?;
// Convert directory name to a nice title (optimized)
let title = Self::dir_name_to_title(dir_name);
let is_custom = theme_dir.join("custom_theme.json").is_file();
// Check if the theme directory is a symlink (system theme)
let is_system = if is_custom {
false
} else {
fs::symlink_metadata(theme_dir)
.map(|m| m.file_type().is_symlink())
.unwrap_or(false)
};
// Extract colors with caching
let colors = Self::extract_theme_colors_cached(theme_dir, is_custom, &color_cache).await;
// Load image asynchronously
let image_path = Self::load_theme_image_async(theme_dir).await;
Ok(SysTheme {
dir: dir_name.to_string(),
title,
description: format!("Auto-generated theme from {dir_name}"),
image: image_path,
is_system,
is_custom,
colors,
})
}
/// Extract theme colors with caching to avoid recomputation
async fn extract_theme_colors_cached(
theme_dir: &Path,
is_custom: bool,
color_cache: &ColorCache,
) -> Option<ThemeColors> {
let dir_name = theme_dir.file_name()?.to_str()?.to_string();
// Check cache first
if let Some(cached_colors) = color_cache.get(&dir_name).await {
log::debug!("Using cached colors for theme: {dir_name}");
return cached_colors;
}
// Extract colors if not cached
let colors = Self::extract_theme_colors_direct(theme_dir, is_custom);
// Cache the result (even if None)
color_cache.set(dir_name.clone(), colors.clone()).await;
log::debug!("Cached colors for theme: {dir_name}");
colors
}
/// Direct color extraction (moved from original implementation)
fn extract_theme_colors_direct(theme_dir: &Path, is_custom: bool) -> Option<ThemeColors> {
if is_custom {
// For custom themes, try to extract from custom_theme.json
let custom_theme_path = theme_dir.join("custom_theme.json");
if custom_theme_path.exists() {
match fs::read_to_string(&custom_theme_path) {
Ok(content) => match serde_json::from_str::<serde_json::Value>(&content) {
Ok(theme_data) => {
if let Some(colors) =
ColorExtractor::extract_from_custom_theme(&theme_data)
{
return Some(colors);
}
},
Err(e) => {
log::warn!(
"Failed to parse custom theme JSON at {custom_theme_path:?}: {e}"
);
},
},
Err(e) => {
log::warn!(
"Failed to read custom theme file at {custom_theme_path:?}: {e}"
);
},
}
}
}
// For system themes or fallback, try to extract from alacritty.toml
let alacritty_config_path = theme_dir.join("alacritty.toml");
if alacritty_config_path.exists() {
if let Some(colors) =
ColorExtractor::extract_from_alacritty_config(&alacritty_config_path)
{
return Some(colors);
}
}
None
}
/// Load theme image asynchronously
async fn load_theme_image_async(theme_dir: &Path) -> String {
// This is I/O bound, so we can spawn it as a blocking task
let theme_dir_path = theme_dir.to_path_buf();
let theme_dir_display = theme_dir.display().to_string();
match tokio::task::spawn_blocking(move || Self::find_and_convert_image(&theme_dir_path))
.await
{
Ok(Ok(image_path)) => image_path,
Ok(Err(e)) => {
log::warn!("Failed to load image for theme {theme_dir_display}: {e}");
String::new()
},
Err(e) => {
log::warn!("Image loading task failed for theme {theme_dir_display}: {e}");
String::new()
},
}
}
/// Find and convert image to data URL (blocking operation)
fn find_and_convert_image(theme_dir: &Path) -> Result<String, String> {
if let Ok(entries) = fs::read_dir(theme_dir) {
for entry in entries.flatten() {
let file_path = entry.path();
if file_path.is_file() {
if let Some(extension) = file_path.extension().and_then(|ext| ext.to_str()) {
let ext_lower = extension.to_lowercase();
if matches!(
ext_lower.as_str(),
"png" | "jpg" | "jpeg" | "webp" | "gif" | "svg"
) {
return Self::convert_image_to_data_url(&file_path);
}
}
}
}
}
Ok(String::new())
}
/// Convert a local image file to a base64 data URL
fn convert_image_to_data_url(image_path: &Path) -> Result<String, String> {
if !image_path.exists() {
return Err(format!("Image file does not exist: {image_path:?}"));
}
let image_data =
fs::read(image_path).map_err(|e| format!("Failed to read image file: {e}"))?;
// Determine MIME type based on file extension
let mime_type = match image_path.extension().and_then(|ext| ext.to_str()) {
Some("png") => "image/png",
Some("jpg") | Some("jpeg") => "image/jpeg",
Some("gif") => "image/gif",
Some("webp") => "image/webp",
Some("svg") => "image/svg+xml",
_ => "image/png", // Default to PNG
};
let base64_data = Self::base64_encode(&image_data);
Ok(format!("data:{mime_type};base64,{base64_data}"))
}
/// Optimized base64 encoding function with pre-allocated capacity
fn base64_encode(data: &[u8]) -> String {
if data.is_empty() {
return String::new();
}
const CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
// Pre-allocate with exact capacity to avoid reallocations
let output_len = data.len().div_ceil(3) * 4;
let mut result = String::with_capacity(output_len);
for chunk in data.chunks(3) {
let mut buf = [0u8; 3];
for (i, &byte) in chunk.iter().enumerate() {
buf[i] = byte;
}
let b = ((buf[0] as u32) << 16) | ((buf[1] as u32) << 8) | (buf[2] as u32);
result.push(CHARS[((b >> 18) & 63) as usize] as char);
result.push(CHARS[((b >> 12) & 63) as usize] as char);
result.push(if chunk.len() > 1 {
CHARS[((b >> 6) & 63) as usize] as char
} else {
'='
});
result.push(if chunk.len() > 2 {
CHARS[(b & 63) as usize] as char
} else {
'='
});
}
result
}
/// Clear the color cache
pub async fn clear_cache(&self) {
self.color_cache.clear().await;
log::info!("Color extraction cache cleared");
}
/// Get cache statistics
pub async fn get_cache_stats(&self) -> (usize,) {
let size = self.color_cache.size().await;
(size,)
}
}
impl Default for OptimizedThemeLoader {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
use std::fs;
use tempfile::TempDir;
#[tokio::test]
async fn test_color_cache() {
let cache = ColorCache::new();
// Test empty cache
assert!(cache.get("test").await.is_none());
assert_eq!(cache.size().await, 0);
// Test caching colors
let colors = ColorExtractor::get_fallback_colors();
cache.set("test".to_string(), Some(colors.clone())).await;
assert_eq!(cache.size().await, 1);
let cached = cache.get("test").await.unwrap().unwrap();
assert_eq!(cached.primary.background, colors.primary.background);
// Test caching None
cache.set("empty".to_string(), None).await;
assert_eq!(cache.size().await, 2);
assert!(cache.get("empty").await.unwrap().is_none());
// Test cache clear
cache.clear().await;
assert_eq!(cache.size().await, 0);
}
#[tokio::test]
async fn test_generate_theme_metadata() {
let temp_dir = TempDir::new().unwrap();
let theme_dir = temp_dir.path().join("test-theme");
fs::create_dir(&theme_dir).unwrap();
// Create a custom theme file
let custom_theme_data = json!({
"alacritty": {
"colors": {
"primary": {
"background": "#121212",
"foreground": "#bebebe"
}
}
}
});
fs::write(
theme_dir.join("custom_theme.json"),
custom_theme_data.to_string(),
)
.unwrap();
// Create an image file
fs::write(theme_dir.join("preview.png"), b"fake image data").unwrap();
let metadata = OptimizedThemeLoader::generate_theme_metadata(&theme_dir)
.await
.unwrap();
assert_eq!(metadata.dir, "test-theme");
assert_eq!(metadata.title, "Test Theme");
assert!(metadata.is_custom);
assert!(!metadata.is_system);
assert!(metadata.has_colors);
assert!(metadata.has_image);
}
#[tokio::test]
async fn test_extract_theme_colors_cached() {
let temp_dir = TempDir::new().unwrap();
let theme_dir = temp_dir.path().join("cached-theme");
fs::create_dir(&theme_dir).unwrap();
// Create alacritty config with complete color scheme
let alacritty_config = "[colors.primary]\nbackground = \"#1a1a1a\"\nforeground = \"#ffffff\"\n\n[colors.normal]\nblack = \"#000000\"\nred = \"#ff5555\"\ngreen = \"#50fa7b\"\nyellow = \"#f1fa8c\"\nblue = \"#8be9fd\"\nmagenta = \"#ff79c6\"\ncyan = \"#8be9fd\"\nwhite = \"#ffffff\"";
fs::write(theme_dir.join("alacritty.toml"), alacritty_config).unwrap();
let cache = ColorCache::new();
// First call should extract and cache
let colors1 =
OptimizedThemeLoader::extract_theme_colors_cached(&theme_dir, false, &cache).await;
assert!(colors1.is_some());
assert_eq!(cache.size().await, 1);
// Second call should use cache
let colors2 =
OptimizedThemeLoader::extract_theme_colors_cached(&theme_dir, false, &cache).await;
assert!(colors2.is_some());
assert_eq!(cache.size().await, 1); // Size shouldn't change
// Colors should be the same
let c1 = colors1.unwrap();
let c2 = colors2.unwrap();
assert_eq!(c1.primary.background, c2.primary.background);
}
#[test]
fn test_has_image_files() {
let temp_dir = TempDir::new().unwrap();
let theme_dir = temp_dir.path().join("image-test");
fs::create_dir(&theme_dir).unwrap();
// No images initially
assert!(!OptimizedThemeLoader::has_image_files(&theme_dir));
// Add a PNG file
fs::write(theme_dir.join("preview.png"), b"fake png").unwrap();
assert!(OptimizedThemeLoader::has_image_files(&theme_dir));
// Add a non-image file
let theme_dir2 = temp_dir.path().join("no-image-test");
fs::create_dir(&theme_dir2).unwrap();
fs::write(theme_dir2.join("config.toml"), b"config data").unwrap();
assert!(!OptimizedThemeLoader::has_image_files(&theme_dir2));
}
#[test]
fn test_convert_image_to_data_url() {
let temp_dir = TempDir::new().unwrap();
let image_path = temp_dir.path().join("test.png");
fs::write(&image_path, b"fake png data").unwrap();
let result = OptimizedThemeLoader::convert_image_to_data_url(&image_path).unwrap();
assert!(result.starts_with("data:image/png;base64,"));
assert!(result.len() > 30); // Should have base64 encoded data
}
#[test]
fn test_base64_encode() {
let data = b"hello world";
let encoded = OptimizedThemeLoader::base64_encode(data);
assert_eq!(encoded, "aGVsbG8gd29ybGQ=");
let empty_data = b"";
let empty_encoded = OptimizedThemeLoader::base64_encode(empty_data);
assert_eq!(empty_encoded, "");
}
}
#[tokio::test]
async fn test_metadata_loading_performance() {
// Test that metadata loading works correctly
let loader = OptimizedThemeLoader::new();
let result = loader.load_theme_metadata_only().await;
match result {
Ok(metadata) => {
// Verify metadata structure if themes exist
for meta in metadata {
assert!(!meta.dir.is_empty());
assert!(!meta.title.is_empty());
}
},
Err(e) => {
assert!(e.contains("Themes directory does not exist"));
},
}
}
#[tokio::test]
async fn test_cache_statistics() {
let loader = OptimizedThemeLoader::new();
// Initially cache should be empty
let (cache_size,) = loader.get_cache_stats().await;
assert_eq!(cache_size, 0);
// Add something to cache
let cache = &loader.color_cache;
let colors = ColorExtractor::get_fallback_colors();
cache.set("test-theme".to_string(), Some(colors)).await;
// Cache size should increase
let (cache_size,) = loader.get_cache_stats().await;
assert_eq!(cache_size, 1);
// Clear cache
loader.clear_cache().await;
// Cache should be empty again
let (cache_size,) = loader.get_cache_stats().await;
assert_eq!(cache_size, 0);
}
| 412 | 0.92156 | 1 | 0.92156 | game-dev | MEDIA | 0.259165 | game-dev | 0.976836 | 1 | 0.976836 |
EphemeralSpace/ephemeral-space | 15,509 | Content.Server/Pointing/EntitySystems/PointingSystem.cs | using System.Linq;
using Content.Server.Administration.Logs;
using Content.Server.Pointing.Components;
using Content.Shared.CCVar;
using Content.Shared.Database;
using Content.Shared.Examine;
using Content.Shared.Eye;
using Content.Shared.Ghost;
using Content.Shared.IdentityManagement;
using Content.Shared.Input;
using Content.Shared.Interaction;
using Content.Shared.Inventory;
using Content.Shared.Mind;
using Content.Shared.Pointing;
using Content.Shared.Popups;
using JetBrains.Annotations;
using Robust.Server.GameObjects;
using Robust.Server.Player;
using Robust.Shared.Configuration;
using Robust.Shared.Containers;
using Robust.Shared.Enums;
using Robust.Shared.GameStates;
using Robust.Shared.Input.Binding;
using Robust.Shared.Map;
using Robust.Shared.Player;
using Robust.Shared.Replays;
using Robust.Shared.Timing;
namespace Content.Server.Pointing.EntitySystems
{
[UsedImplicitly]
internal sealed class PointingSystem : SharedPointingSystem
{
[Dependency] private readonly IConfigurationManager _config = default!;
[Dependency] private readonly IReplayRecordingManager _replay = default!;
[Dependency] private readonly IMapManager _mapManager = default!;
[Dependency] private readonly IPlayerManager _playerManager = default!;
[Dependency] private readonly ITileDefinitionManager _tileDefinitionManager = default!;
[Dependency] private readonly IGameTiming _gameTiming = default!;
[Dependency] private readonly RotateToFaceSystem _rotateToFaceSystem = default!;
[Dependency] private readonly SharedContainerSystem _container = default!;
[Dependency] private readonly SharedPopupSystem _popup = default!;
[Dependency] private readonly VisibilitySystem _visibilitySystem = default!;
[Dependency] private readonly SharedMindSystem _minds = default!;
[Dependency] private readonly SharedTransformSystem _transform = default!;
[Dependency] private readonly SharedMapSystem _map = default!;
[Dependency] private readonly IAdminLogManager _adminLogger = default!;
[Dependency] private readonly ExamineSystemShared _examine = default!;
private TimeSpan _pointDelay = TimeSpan.FromSeconds(0.5f);
/// <summary>
/// A dictionary of players to the last time that they
/// pointed at something.
/// </summary>
private readonly Dictionary<ICommonSession, TimeSpan> _pointers = new();
private const float PointingRange = 15f;
private void GetCompState(Entity<PointingArrowComponent> entity, ref ComponentGetState args)
{
args.State = new SharedPointingArrowComponentState
{
StartPosition = entity.Comp.StartPosition,
EndTime = entity.Comp.EndTime
};
}
private void OnPlayerStatusChanged(object? sender, SessionStatusEventArgs e)
{
if (e.NewStatus != SessionStatus.Disconnected)
{
return;
}
_pointers.Remove(e.Session);
}
// TODO: FOV
private void SendMessage(
EntityUid source,
IEnumerable<ICommonSession> viewers,
EntityUid pointed,
string selfMessage,
string viewerMessage,
string? viewerPointedAtMessage = null)
{
var netSource = GetNetEntity(source);
foreach (var viewer in viewers)
{
if (viewer.AttachedEntity is not {Valid: true} viewerEntity)
{
continue;
}
var message = viewerEntity == source
? selfMessage
: viewerEntity == pointed && viewerPointedAtMessage != null
? viewerPointedAtMessage
: viewerMessage;
// Someone pointing at YOU is slightly more important
var popupType = viewerEntity == pointed ? PopupType.Medium : PopupType.Small;
RaiseNetworkEvent(new PopupEntityEvent(message, popupType, netSource), viewerEntity);
}
_replay.RecordServerMessage(new PopupEntityEvent(viewerMessage, PopupType.Small, netSource));
}
public bool InRange(EntityUid pointer, EntityCoordinates coordinates)
{
if (HasComp<GhostComponent>(pointer))
{
return _transform.InRange(Transform(pointer).Coordinates, coordinates, 15);
}
else
{
return _examine.InRangeUnOccluded(pointer, coordinates, 15, predicate: e => e == pointer);
}
}
public bool TryPoint(ICommonSession? session, EntityCoordinates coordsPointed, EntityUid pointed)
{
if (session?.AttachedEntity is not { } player)
{
Log.Warning($"Player {session} attempted to point without any attached entity");
return false;
}
if (!coordsPointed.IsValid(EntityManager))
{
Log.Warning($"Player {ToPrettyString(player)} attempted to point at invalid coordinates: {coordsPointed}");
return false;
}
if (_pointers.TryGetValue(session, out var lastTime) &&
_gameTiming.CurTime < lastTime + _pointDelay)
{
return false;
}
if (HasComp<PointingArrowComponent>(pointed))
{
// this is a pointing arrow. no pointing here...
return false;
}
if (!CanPoint(player))
{
return false;
}
if (!InRange(player, coordsPointed))
{
_popup.PopupEntity(Loc.GetString("pointing-system-try-point-cannot-reach"), player, player);
return false;
}
var mapCoordsPointed = _transform.ToMapCoordinates(coordsPointed);
_rotateToFaceSystem.TryFaceCoordinates(player, mapCoordsPointed.Position);
var arrow = Spawn("PointingArrow", coordsPointed);
if (TryComp<PointingArrowComponent>(arrow, out var pointing))
{
pointing.StartPosition = _transform.ToCoordinates((arrow, Transform(arrow)), _transform.ToMapCoordinates(Transform(player).Coordinates)).Position;
pointing.EndTime = _gameTiming.CurTime + PointDuration;
Dirty(arrow, pointing);
}
if (EntityQuery<PointingArrowAngeringComponent>().FirstOrDefault() != null)
{
if (TryComp<PointingArrowComponent>(arrow, out var pointingArrowComponent))
{
pointingArrowComponent.Rogue = true;
}
}
var layer = (int) VisibilityFlags.Normal;
if (TryComp(player, out VisibilityComponent? playerVisibility))
{
var arrowVisibility = EnsureComp<VisibilityComponent>(arrow);
layer = playerVisibility.Layer;
_visibilitySystem.SetLayer((arrow, arrowVisibility), (ushort) layer);
}
// Get players that are in range and whose visibility layer matches the arrow's.
bool ViewerPredicate(ICommonSession playerSession)
{
if (!_minds.TryGetMind(playerSession, out _, out var mind) ||
mind.CurrentEntity is not { Valid: true } ent ||
!TryComp(ent, out EyeComponent? eyeComp) ||
(eyeComp.VisibilityMask & layer) == 0)
return false;
return _transform.GetMapCoordinates(ent).InRange(_transform.GetMapCoordinates(player), PointingRange);
}
var viewers = Filter.Empty()
.AddWhere(session1 => ViewerPredicate(session1))
.Recipients;
string selfMessage;
string viewerMessage;
string? viewerPointedAtMessage = null;
var playerName = Identity.Entity(player, EntityManager);
if (Exists(pointed))
{
var pointedName = Identity.Entity(pointed, EntityManager);
EntityUid? containingInventory = null;
// Search up through the target's containing containers until we find an inventory
var inventoryQuery = GetEntityQuery<InventoryComponent>();
foreach (var container in _container.GetContainingContainers(pointed))
{
if (inventoryQuery.HasComp(container.Owner))
{
// We want the innermost inventory, since that's the "owner" of the item
containingInventory = container.Owner;
break;
}
}
var pointingAtSelf = player == pointed;
// Are we in a mob's inventory?
if (containingInventory != null)
{
var item = pointed;
var itemName = Identity.Entity(item, EntityManager);
// Target the pointing at the item's holder
pointed = containingInventory.Value;
pointedName = Identity.Entity(pointed, EntityManager);
var pointingAtOwnItem = player == pointed;
if (pointingAtOwnItem)
{
// You point at your item
selfMessage = Loc.GetString("pointing-system-point-in-own-inventory-self", ("item", itemName));
// Urist McPointer points at his item
viewerMessage = Loc.GetString("pointing-system-point-in-own-inventory-others", ("item", itemName), ("pointer", playerName));
}
else
{
// You point at Urist McHands' item
selfMessage = Loc.GetString("pointing-system-point-in-other-inventory-self", ("item", itemName), ("wearer", pointedName));
// Urist McPointer points at Urist McWearer's item
viewerMessage = Loc.GetString("pointing-system-point-in-other-inventory-others", ("item", itemName), ("pointer", playerName), ("wearer", pointedName));
// Urist McPointer points at your item
viewerPointedAtMessage = Loc.GetString("pointing-system-point-in-other-inventory-target", ("item", itemName), ("pointer", playerName));
}
}
else
{
selfMessage = pointingAtSelf
// You point at yourself
? Loc.GetString("pointing-system-point-at-self")
// You point at Urist McTarget
: Loc.GetString("pointing-system-point-at-other", ("other", pointedName));
viewerMessage = pointingAtSelf
// Urist McPointer points at himself
? Loc.GetString("pointing-system-point-at-self-others", ("otherName", playerName), ("other", playerName))
// Urist McPointer points at Urist McTarget
: Loc.GetString("pointing-system-point-at-other-others", ("otherName", playerName), ("other", pointedName));
// Urist McPointer points at you
viewerPointedAtMessage = Loc.GetString("pointing-system-point-at-you-other", ("otherName", playerName));
}
var ev = new AfterPointedAtEvent(pointed);
RaiseLocalEvent(player, ref ev);
var gotev = new AfterGotPointedAtEvent(player);
RaiseLocalEvent(pointed, ref gotev);
_adminLogger.Add(LogType.Action, LogImpact.Low, $"{ToPrettyString(player):user} pointed at {ToPrettyString(pointed):target} {Transform(pointed).Coordinates}");
}
else
{
TileRef? tileRef = null;
string? position = null;
if (_mapManager.TryFindGridAt(mapCoordsPointed, out var gridUid, out var grid))
{
position = $"EntId={gridUid} {_map.WorldToTile(gridUid, grid, mapCoordsPointed.Position)}";
tileRef = _map.GetTileRef(gridUid, grid, _map.WorldToTile(gridUid, grid, mapCoordsPointed.Position));
}
var tileDef = _tileDefinitionManager[tileRef?.Tile.TypeId ?? 0];
var name = Loc.GetString(tileDef.Name);
selfMessage = Loc.GetString("pointing-system-point-at-tile", ("tileName", name));
viewerMessage = Loc.GetString("pointing-system-other-point-at-tile", ("otherName", playerName), ("tileName", name));
_adminLogger.Add(LogType.Action, LogImpact.Low, $"{ToPrettyString(player):user} pointed at {name} {(position == null ? mapCoordsPointed : position)}");
}
_pointers[session] = _gameTiming.CurTime;
SendMessage(player, viewers, pointed, selfMessage, viewerMessage, viewerPointedAtMessage);
return true;
}
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<PointingArrowComponent, ComponentGetState>(GetCompState);
SubscribeNetworkEvent<PointingAttemptEvent>(OnPointAttempt);
_playerManager.PlayerStatusChanged += OnPlayerStatusChanged;
CommandBinds.Builder
.Bind(ContentKeyFunctions.Point, new PointerInputCmdHandler(TryPoint))
.Register<PointingSystem>();
Subs.CVar(_config, CCVars.PointingCooldownSeconds, v => _pointDelay = TimeSpan.FromSeconds(v), true);
}
private void OnPointAttempt(PointingAttemptEvent ev, EntitySessionEventArgs args)
{
var target = GetEntity(ev.Target);
if (TryComp(target, out TransformComponent? xformTarget))
TryPoint(args.SenderSession, xformTarget.Coordinates, target);
else
Log.Warning($"User {args.SenderSession} attempted to point at a non-existent entity uid: {ev.Target}");
}
public override void Shutdown()
{
base.Shutdown();
_playerManager.PlayerStatusChanged -= OnPlayerStatusChanged;
_pointers.Clear();
}
public override void Update(float frameTime)
{
var currentTime = _gameTiming.CurTime;
var query = AllEntityQuery<PointingArrowComponent>();
while (query.MoveNext(out var uid, out var component))
{
Update((uid, component), currentTime);
}
}
private void Update(Entity<PointingArrowComponent> pointing, TimeSpan currentTime)
{
// TODO: That pause PR
var component = pointing.Comp;
if (component.EndTime > currentTime)
return;
if (component.Rogue)
{
RemComp<PointingArrowComponent>(pointing);
EnsureComp<RoguePointingArrowComponent>(pointing);
return;
}
Del(pointing);
}
}
}
| 412 | 0.980028 | 1 | 0.980028 | game-dev | MEDIA | 0.708019 | game-dev | 0.978111 | 1 | 0.978111 |
Lupusa87/LupusaBlazorDemos | 88,063 | BlazorChessComponent/Engine/ChessEngine.cs | using BlazorSvgHelper.Classes;
using BlazorSvgHelper.Classes.SubClasses;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.JSInterop;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace BlazorChessComponent.Engine
{
public class ChessEngine
{
public CompSettings compSettings = new CompSettings();
public myCell MyCell = new myCell("lightyellow", "#FFA500");
bool aqvs_roqis_ufleba = true;
bool aqvs_mokle_roqis_ufleba = true;
bool aqvs_grdzeli_roqis_ufleba = true;
bool Player_Has_Shax = false;
bool Opposite_Has_Shax = false;
bool Drag_Mode = false;
bool Drag_Figure_isDefined = false;
bool Replay_Mode = true;
bool Select_New_Figure_Mode = false;
int Select_New_Figure_X = -1;
public myCell MyCell_Moklulebi = new myCell("white", "#FFA500");
myPoint MyPoint = new myPoint();
int Current_Move = 1;
public int PlayerColor = 1;
public int OppositeColor = 2;
int Player_Total_Seconds = 300; //60*5
int Opposite_Total_Seconds = 300;
List<string> Board_Array_moklulebi_Player_Color = new List<string>();
List<string> Board_Array_moklulebi_Opposite_Color = new List<string>();
string[] Board_Array_ImageFiles = new string[] { "1P", "1R", "1K", "1B", "1Q", "1A", "2P", "2R", "2K", "2B", "2Q", "2A" };
public string[] Board_Array_Letters = new string[] { "A", "B", "C", "D", "E", "F", "G", "H" };
List<string> Board_Array_potenciuri_svlebi = new List<string>();
List<int> Board_Array_potenciuri_gavlit_mosaklavi_paiki = new List<int>(); // x კოორდინატს ვინახავთ მარტო იმის დასადგენად მარჯვენაა თუ მარცხენა, y ყოველთვის 4 იქნება
string[] Board_Array_Moves = new string[] { "A2A3", "I7I6", "B1C3", "H7H6" };
int Curr_Replay_Index = 0;
int loaded_Images = 0;
public myColors MyColors = new myColors();
public mylineWidths MylineWidths = new mylineWidths();
public bool ar_avantot_ujrebi;
Timer timer_Replay;
Timer timer_Game;
myFigure Curr_Figure = new myFigure();
myFigure Next_Figure = new myFigure();
myFigure tmp_Figure = new myFigure();
string All_Figures = "PRKBQA";
string All_Figures_Without_King = "PRKBQ";
// let Board_Array: string[] =
// ["e", "e", "e", "e", "e", "a", "e", "e",
// "p", "e", "e", "e", "e", "e", "e", "R",
// "e", "e", "e", "e", "e", "K", "e", "e",
// "e", "e", "e", "e", "e", "e", "e", "e",
// "P", "e", "e", "e", "e", "e", "e", "e",
// "e", "e", "e", "e", "e", "e", "e", "e",
// "e", "e", "e", "e", "e", "e", "e", "e",
// "e", "A", "e", "e", "e", "e", "e", "e"];
public string[] Board_Array = new string[] {
"r", "k", "b", "q", "a", "b", "k", "r",
"p", "p", "p", "p", "p", "p", "p", "p",
"e", "e", "e", "e", "e", "e", "e", "e",
"e", "e", "e", "e", "e", "e", "e", "e",
"e", "e", "e", "e", "e", "e", "e", "e",
"e", "e", "e", "e", "e", "e", "e", "e",
"P", "P", "P", "P", "P", "P", "P", "P",
"R", "K", "B", "Q", "A", "B", "K", "R"};
string Board_Scheme = "rkbqabkrppppppppeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeePPPPPPPPRKBQABKR";
public ChessEngine(bool PlayerOrOpposite)
{
if (PlayerOrOpposite)
{
PlayerColor = 1;
OppositeColor = 2;
Current_Move = 1;
}
else
{
Reverse_Board();
PlayerColor = 2;
OppositeColor = 1;
Current_Move = 1;
}
}
public void GetBoundingClientRect(string RectID)
{
BChessCJsInterop.GetElementBoundingClientRect(RectID, DotNetObjectReference.Create(this));
}
public void StartTimer()
{
if (timer_Game == null)
{
timer_Game = new Timer(TimerGameCallback, null, 1000, 1000);
}
}
void Opposite_Has_Made_Move()
{
}
public void cmd_mouseDown(MouseEventArgs e)
{
compSettings.rects_list = new List<rect>();
if (Current_Move == PlayerColor)
{
Drag_Mode = true;
Drag_Figure_isDefined = false;
// JsInterop.SetCursor("move");
double x = e.ClientX - compSettings.BoardPositionX - MyCell.width * 0.5;
double y = e.ClientY - compSettings.BoardPositionY - MyCell.height * 0.5;
if (x > 0 && y > 0)
{
Select_Cell(x, y);
}
}
}
public void cmd_mouseUp(MouseEventArgs e)
{
if (Current_Move == PlayerColor)
{
Drag_Mode = false;
if (Drag_Figure_isDefined)
{
ujraze_figuris_dasma(Curr_Figure.X, Curr_Figure.Y, Curr_Figure.kodi);
Drag_Figure_isDefined = false;
}
BChessCJsInterop.SetCursor();
double x = e.ClientX - compSettings.BoardPositionX - MyCell.width * 0.5;
double y = e.ClientY - compSettings.BoardPositionY - MyCell.height * 0.5;
if (x > 0 && y > 0)
{
Select_Cell(x, y);
}
}
}
void mausis_gasvla_dafidan()
{
Drag_Mode = false;
if (Drag_Figure_isDefined)
{
ujraze_figuris_dasma(Curr_Figure.X, Curr_Figure.Y, Curr_Figure.kodi);
Drag_Figure_isDefined = false;
}
//compSettings.Curr_Comp_Board.Refresh();
Clear_Curr_And_Next_Figures();
}
public void cmd_mouseMove(MouseEventArgs e)
{
if (Current_Move == PlayerColor)
{
if (Select_New_Figure_Mode)
{
double x = e.ClientX - compSettings.BoardPositionX - MyCell.width * 0.5;
double y = e.ClientY - compSettings.BoardPositionY - MyCell.height * 0.5;
if (x > 0 && y > 0)
{
double My_x = x - x % MyCell.width;
double My_y = y - y % MyCell.height;
int Curr_X = (int)Math.Floor(My_x / MyCell.width);
int Curr_Y = (int)Math.Floor(My_y / MyCell.height);
if (Curr_X >= 0 && Curr_X <= 7 && Curr_Y >= 0 && Curr_Y <= 7)
{
if (Curr_X == Select_New_Figure_X && Curr_Y < 4)
{
paikis_gayvana(Select_New_Figure_X, Curr_Y);
}
}
}
}
else
{
if (Drag_Mode)
{
if (Drag_Figure_isDefined == false)
{
ujris_gatavisufleba(Curr_Figure.X, Curr_Figure.Y);
Drag_Figure_isDefined = true;
}
double x = e.ClientX - compSettings.BoardPositionX - MyCell.width * 0.5;
double y = e.ClientY - compSettings.BoardPositionY - MyCell.height * 0.5;
if (x > 0 && y > 0)
{
double My_x = x - x % MyCell.width;
double My_y = y - y % MyCell.height;
double Curr_X = Math.Floor(My_x / MyCell.width);
double Curr_Y = Math.Floor(My_y / MyCell.height);
if (Curr_X >= 0 && Curr_X <= 7 && Curr_Y >= 0 && Curr_Y <= 7)
{
// compSettings.Curr_Comp_Board.Refresh();
// context_Board.drawImage(game_Images[PlayerColor.ToString() + Curr_Figure.kodi.ToUpper()], x, y, MyCell.width, MyCell.height);
}
else
{
mausis_gasvla_dafidan();
}
}
else
{
mausis_gasvla_dafidan();
}
}
}
}
}
bool is_my_figure(string p, int par_visi_poziciidan)
{
if (p == "e")
{
return false;
}
if (par_visi_poziciidan == 1)
{
return !MyFunctions.is_lower_case(p);
}
else
{
return MyFunctions.is_lower_case(p);
}
}
bool Get_Cell_Color_By_Coordinates(int x, int y)
{
return MyFunctions.Get_Cell_Color_By_Index(Get_Board_Index(x, y));
}
void Select_Cell(double x, double y)
{
double My_x = x - x % MyCell.width;
double My_y = y - y % MyCell.height;
int Curr_X = (int)Math.Floor(My_x / MyCell.width);
int Curr_Y = (int)Math.Floor(My_y / MyCell.height);
if (Curr_X >= 0 && Curr_X <= 7 && Curr_Y >= 0 && Curr_Y <= 7)
{
if (Select_New_Figure_Mode == false)
{
int Curr_index = Get_Board_Index(Curr_X, Curr_Y);
string kodi = Board_Array[Curr_index].ToString();
if (Curr_Figure.isDefined == false)
{
monishvnuli_figuris_anteba(My_x, My_y, Curr_X, Curr_Y, Curr_index, kodi);
}
else
{
if ((Curr_Figure.X == Curr_X) && (Curr_Figure.Y == Curr_Y)) // ვამოწმებთ თავის თავზე!
{
// არაფერს არ ვაკეთებთ
//compSettings.Curr_Comp_Board.Refresh();
}
else
{
if (Board_Array_potenciuri_svlebi.ToList().IndexOf(Curr_X.ToString() + Curr_Y.ToString()) > -1)
{
Next_Figure.isDefined = true;
Next_Figure.X = Curr_X;
Next_Figure.Y = Curr_Y;
Next_Figure.index = -1;
Next_Figure.kodi = kodi;
svlis_gaketeba_Player();
}
else
{
Clear_Curr_And_Next_Figures();
}
}
}
}
else
{
if (Curr_X == Select_New_Figure_X)
{
string Par_Extra = "Q";
switch (Curr_Y)
{
case 1:
Par_Extra = "R";
break;
case 2:
Par_Extra = "B";
break;
case 3:
Par_Extra = "K";
break;
default:
Par_Extra = "Q";
break;
}
string old_Code = Board_Array[Get_Board_Index(Curr_Figure.X, Curr_Figure.Y)];
if (PlayerColor == 2)
{
Par_Extra = Par_Extra.ToLower();
}
Curr_Figure.kodi = Par_Extra;
Board_Array[Get_Board_Index(Curr_Figure.X, Curr_Figure.Y)] = Par_Extra;
ujraze_mimdinare_figuris_dasma(Next_Figure.X, Next_Figure.Y);
ujris_gatavisufleba(Curr_Figure.X, Curr_Figure.Y);
svlis_chawera("=" + Par_Extra);
Clear_Curr_And_Next_Figures();
Select_New_Figure_Mode = false;
Select_New_Figure_X = -1;
}
}
}
}
void monishvnuli_figuris_anteba(double My_x, double My_y, int Curr_X, int Curr_Y, int Curr_index, string kodi)
{
if (kodi != "e")
{
if (is_my_figure(kodi, PlayerColor))
{
compSettings.rects_list.Add(new rect
{
x = My_x + MyCell.width / 2 + MylineWidths.selected_cell,
y = My_y + MyCell.height / 2 + MylineWidths.selected_cell,
width = MyCell.width - MylineWidths.selected_cell * 2,
height = MyCell.height - MylineWidths.selected_cell * 2,
fill="none",
stroke = MyColors.selected_cell,
stroke_width = MylineWidths.selected_cell,
});
Curr_Figure.isDefined = true;
Curr_Figure.X = Curr_X;
Curr_Figure.Y = Curr_Y;
Curr_Figure.index = Curr_index;
Curr_Figure.kodi = kodi;
Find_Moves(PlayerColor);
}
else
{
Clear_Curr_And_Next_Figures();
}
}
else
{
Clear_Curr_And_Next_Figures();
}
}
bool figuris_gadaadgilebit_ixsneba_shaxi()
{
bool result = false;
if (Curr_Figure.kodi.ToLower() != "a")
{
// დროებით ფიგურის აღება რომ შემოწმდეს იხსნება თუ არა შახი
ujris_gatavisufleba(Curr_Figure.X, Curr_Figure.Y);
string King_Letter = "A";
if (PlayerColor == 2)
{
King_Letter = King_Letter.ToLower();
}
// მეფის კოორდინატების მოძებნა
int King_X = 0;
int King_Y = 0;
int King_Index = Board_Array.ToList().IndexOf(King_Letter);
if (King_Index > -1)
{
King_X = (King_Index) % 8;
King_Y = (King_Index - King_X) / 8;
result = ujra_aris_tu_ara_muqaris_qvesh(King_X, King_Y, PlayerColor);
}
else
{
BChessCJsInterop.alert("არალოგიკური შეცდომა, მეფე ვერ მოიძებნა დაფაზე! (function figuris_gadaadgilebit_ixsneba_shaxi)");
}
// აღებული ფიგურის დაბრუნება თავის პოზიციაზე
ujraze_figuris_dasma(Curr_Figure.X, Curr_Figure.Y, Curr_Figure.kodi);
}
return result;
}
public void acxadebs_shaxs_an_gardes(int par_vin_acxadebs)
{
string King_Letter = string.Empty;
string Queen_Letter = string.Empty;
double My_x = 0;
double My_y = 0;
int mowinaaRmdege = 0;
if (par_vin_acxadebs == 1)
{
King_Letter = "a";
Queen_Letter = "q";
mowinaaRmdege = 2;
}
else
{
King_Letter = "A";
Queen_Letter = "Q";
mowinaaRmdege = 1;
}
if (mowinaaRmdege == OppositeColor)
{
Opposite_Has_Shax = false;
}
else
{
Player_Has_Shax = false;
}
//მეფის კოორდინატების მოძებნა
int tmp_X = 0;
int tmp_Y = 0;
int tmp_Index = Board_Array.ToList().IndexOf(King_Letter);
if (tmp_Index > -1)
{
tmp_X = (tmp_Index) % 8;
tmp_Y = (tmp_Index - tmp_X) / 8;
if (ujra_aris_tu_ara_muqaris_qvesh(tmp_X, tmp_Y, mowinaaRmdege))
{
if (mowinaaRmdege == 2)
{
Opposite_Has_Shax = true;
}
else
{
Player_Has_Shax = true;
}
if (!ar_avantot_ujrebi)
{
My_x = tmp_X * MyCell.width + MyCell.width * 0.5;
My_y = tmp_Y * MyCell.height + MyCell.height * 0.5;
compSettings.rects_list.Add(new rect
{
x = My_x + MylineWidths.shaxi_an_garde,
y = My_y + MylineWidths.shaxi_an_garde,
width = MyCell.width - MylineWidths.selected_cell * 2,
height = MyCell.height - MylineWidths.selected_cell * 2,
fill = "none",
stroke = MyColors.shaxi_an_garde,
stroke_width = MylineWidths.shaxi_an_garde,
});
}
}
else
{
if (mowinaaRmdege == 2)
{
Opposite_Has_Shax = false;
}
else
{
Player_Has_Shax = false;
}
}
}
tmp_Index = Board_Array.ToList().IndexOf(Queen_Letter);
if (tmp_Index > -1)
{
tmp_X = (tmp_Index) % 8;
tmp_Y = (tmp_Index - tmp_X) / 8;
if (ujra_aris_tu_ara_muqaris_qvesh(tmp_X, tmp_Y, mowinaaRmdege))
{
if (!ar_avantot_ujrebi)
{
My_x = tmp_X * MyCell.width + MyCell.width * 0.5;
My_y = tmp_Y * MyCell.height + MyCell.height * 0.5;
compSettings.rects_list.Add(new rect
{
x = My_x + MylineWidths.shaxi_an_garde,
y = My_y + MylineWidths.shaxi_an_garde,
width = MyCell.width - MylineWidths.selected_cell * 2,
height = MyCell.height - MylineWidths.selected_cell * 2,
fill = "none",
stroke = MyColors.shaxi_an_garde,
stroke_width = MylineWidths.shaxi_an_garde,
});
}
}
}
}
void Game_Over(string t)
{
if (timer_Game != null)
{
timer_Game.Dispose();
}
BChessCJsInterop.alert("Game over - " + t);
}
void Clear_Curr_And_Next_Figures()
{
Curr_Figure.isDefined = false;
Curr_Figure.X = -1;
Curr_Figure.Y = -1;
Curr_Figure.index = -1;
Curr_Figure.kodi = "";
Next_Figure.isDefined = false;
Next_Figure.X = -1;
Next_Figure.Y = -1;
Next_Figure.index = -1;
Next_Figure.kodi = "";
}
void myLog(string text)
{
compSettings.Log_list.Add(text);
}
void ujris_anteba(int x, int y, int par_visi_poziciidan)
{
if (Curr_Figure.kodi.ToLower() == "a" && ujra_aris_tu_ara_muqaris_qvesh(x, y, par_visi_poziciidan))
{
// არ ვანთებთ უჯრას
}
else
{
if (Can_Move(x, y, par_visi_poziciidan))
{
Board_Array_potenciuri_svlebi.Add(x + "" + y);
if (!ar_avantot_ujrebi)
{
double My_x = x * MyCell.width + MyCell.width * 0.5;
double My_y = y * MyCell.height + MyCell.height * 0.5;
compSettings.rects_list.Add(new rect
{
x = My_x + MylineWidths.potenciuri_svla,
y = My_y + MylineWidths.potenciuri_svla,
width = MyCell.width - MylineWidths.selected_cell * 2,
height = MyCell.height - MylineWidths.selected_cell * 2,
fill = "none",
stroke = MyColors.potenciuri_svla,
stroke_width = MylineWidths.potenciuri_svla,
});
}
}
}
}
bool Can_Move(int x, int y, int par_visi_poziciidan)
{
bool result = true;
bool tmp_saved_state = ar_avantot_ujrebi;
ar_avantot_ujrebi = true;
string[] tmp_array = Board_Array.Clone() as string[];
if (par_visi_poziciidan == PlayerColor)
{
Player_Has_Shax = false;
}
else
{
Opposite_Has_Shax = false;
}
Next_Figure.isDefined = true;
Next_Figure.X = x;
Next_Figure.Y = y;
Next_Figure.index = Get_Board_Index(Next_Figure.X, Next_Figure.Y);
Next_Figure.kodi = Board_Array[Next_Figure.index];
fiqtiuri_svlis_gaketeba();
Next_Figure.isDefined = false;
Next_Figure.X = -1;
Next_Figure.Y = -1;
Next_Figure.index = -1;
Next_Figure.kodi = "";
if (par_visi_poziciidan == PlayerColor)
{
// თუ ამ სვლის გაკეთების შემდეგ მეფეს გაეხსნება შახი, ან არსებული შახი არ მოეხსნება, ეს სვლა უარყოფილია
acxadebs_shaxs_an_gardes(OppositeColor);
result = !Player_Has_Shax;
}
else
{
// თუ ამ სვლის გაკეთების შემდეგ მეფეს გაეხსნება შახი, ან არსებული შახი არ მოეხსნება, ეს სვლა უარყოფილია
acxadebs_shaxs_an_gardes(PlayerColor);
result = !Opposite_Has_Shax;
}
Board_Array = tmp_array.Clone() as string[];
ar_avantot_ujrebi = tmp_saved_state;
return result;
}
void Find_Moves(int par_visi_poziciidan)
{
Board_Array_potenciuri_svlebi = new List<string>();
Board_Array_potenciuri_gavlit_mosaklavi_paiki = new List<int>();
switch (Curr_Figure.kodi.ToLower())
{
case "p":
Find_Moves_Paiki(par_visi_poziciidan);
break;
case "r":
Find_Moves_Etli(8, par_visi_poziciidan);
break;
case "k":
Find_Moves_Mxedari(par_visi_poziciidan);
break;
case "b":
Find_Moves_Oficeri(8, par_visi_poziciidan);
break;
case "q":
Find_Moves_Dedofali(par_visi_poziciidan);
break;
case "a":
Find_Moves_Mefe(par_visi_poziciidan);
break;
default:
break;
}
}
int Get_Board_Index(int x, int y)
{
return y * 8 + x;
}
void fiqtiuri_svlis_gaketeba()
{
// პაიკის მიერ პაიკის გავლით აყვანა
if (Curr_Figure.kodi.ToLower() == "p")
{
if (Board_Array_potenciuri_gavlit_mosaklavi_paiki.Count > 0)
{
if (Board_Array_potenciuri_gavlit_mosaklavi_paiki.ToList().IndexOf(Next_Figure.X) > 0)
{
ujris_gatavisufleba(Next_Figure.X, Next_Figure.Y + 1);
}
}
}
ujraze_mimdinare_figuris_dasma(Next_Figure.X, Next_Figure.Y);
ujris_gatavisufleba(Curr_Figure.X, Curr_Figure.Y);
}
void svlis_gaketeba_Player()
{
if (Board_Array_potenciuri_svlebi.ToList().IndexOf(Next_Figure.X + "" + Next_Figure.Y) > -1 || Replay_Mode)
{
if (Next_Figure.kodi != "e")
{
Board_Array_moklulebi_Opposite_Color.Add(Next_Figure.kodi.ToLower());
paint_moklulebi();
}
else
{
// პაიკის მიერ პაიკის გავლით აყვანა
if (Curr_Figure.kodi.ToLower() == "p")
{
if (Board_Array_potenciuri_gavlit_mosaklavi_paiki.Count > 0)
{
if (Board_Array_potenciuri_gavlit_mosaklavi_paiki.ToList().IndexOf(Next_Figure.X) > 0)
{
ujris_gatavisufleba(Next_Figure.X, Next_Figure.Y + 1);
Board_Array_moklulebi_Opposite_Color.Add("p");
paint_moklulebi();
}
}
}
}
if (Curr_Figure.kodi.ToLower() == "p" && Next_Figure.Y == 0)
{
Select_New_Figure_Mode = true;
Select_New_Figure_X = Next_Figure.X;
paikis_gayvana(Next_Figure.X, 0);
}
else
{
if (Curr_Figure.kodi.ToLower() == "r")
{
if (Curr_Figure.X == 7 && Curr_Figure.Y == 7)
{
aqvs_mokle_roqis_ufleba = false;
}
if (Curr_Figure.X == 0 && Curr_Figure.Y == 7)
{
aqvs_grdzeli_roqis_ufleba = false;
}
}
if (Curr_Figure.kodi.ToLower() == "a")
{
if (aqvs_roqis_ufleba)
{
aqvs_roqis_ufleba = false;
// aketebs mokle roqs
if (PlayerColor == 1)
{
if (Curr_Figure.X == 4 && Curr_Figure.Y == 7 && Next_Figure.X == 6 && Next_Figure.Y == 7 && aqvs_mokle_roqis_ufleba)
{
Board_Array[Get_Board_Index(5, 7)] = Board_Array[Get_Board_Index(7, 7)];
ujris_gatavisufleba(7, 7);
}
}
else
{
if (Curr_Figure.X == 3 && Curr_Figure.Y == 7 && Next_Figure.X == 1 && Next_Figure.Y == 7 && aqvs_mokle_roqis_ufleba)
{
Board_Array[Get_Board_Index(2, 7)] = Board_Array[Get_Board_Index(0, 7)];
ujris_gatavisufleba(0, 7);
}
}
// aketebs grdzel roqs
if (PlayerColor == 1)
{
if (Curr_Figure.X == 4 && Curr_Figure.Y == 7 && Next_Figure.X == 2 && Next_Figure.Y == 7 && aqvs_grdzeli_roqis_ufleba)
{
Board_Array[Get_Board_Index(3, 7)] = Board_Array[Get_Board_Index(0, 7)];
ujris_gatavisufleba(0, 7);
}
}
else
{
if (Curr_Figure.X == 3 && Curr_Figure.Y == 7 && Next_Figure.X == 5 && Next_Figure.Y == 7 && aqvs_grdzeli_roqis_ufleba)
{
Board_Array[Get_Board_Index(4, 7)] = Board_Array[Get_Board_Index(7, 7)];
ujris_gatavisufleba(7, 7);
}
}
}
}
ujraze_mimdinare_figuris_dasma(Next_Figure.X, Next_Figure.Y);
string svla = svlis_chawera("");
ujris_gatavisufleba(Curr_Figure.X, Curr_Figure.Y);
Clear_Curr_And_Next_Figures();
aris_mati_an_pati(OppositeColor);
Current_Move = OppositeColor;
compSettings.rects_list = new List<rect>();
compSettings.Curr_comp.NotifyMadeMove(svla);
}
}
}
void paikis_gayvana(int x, int selected_index)
{
//paint_Board();
//context_Board.fillStyle = "lightyellow";
//context_Board.fillRect(x * MyCell.width + MyCell.width / 2, MyCell.height / 2, MyCell.width, MyCell.height * 4);
//context_Board.strokeStyle = MyColors.paikis_gayvanis_charcho;
//context_Board.lineWidth = MylineWidths.paikis_gayvanis_charcho;
//context_Board.strokeRect(x * MyCell.width + MyCell.width / 2, MyCell.height / 2, MyCell.width, MyCell.height * 4);
//context_Board.drawImage(game_Images[PlayerColor.ToString() + "Q"], x * MyCell.width + MyCell.width / 2, 0 * MyCell.height + MyCell.height / 2, MyCell.width, MyCell.height);
//context_Board.drawImage(game_Images[PlayerColor.ToString() + "R"], x * MyCell.width + MyCell.width / 2, 1 * MyCell.height + MyCell.height / 2, MyCell.width, MyCell.height);
//context_Board.drawImage(game_Images[PlayerColor.ToString() + "B"], x * MyCell.width + MyCell.width / 2, 2 * MyCell.height + MyCell.height / 2, MyCell.width, MyCell.height);
//context_Board.drawImage(game_Images[PlayerColor.ToString() + "K"], x * MyCell.width + MyCell.width / 2, 3 * MyCell.height + MyCell.height / 2, MyCell.width, MyCell.height);
//context_Board.strokeStyle = MyColors.paikis_gayvanis_monishvna;
//context_Board.lineWidth = MylineWidths.paikis_gayvanis_monishvna;
//context_Board.strokeRect(x * MyCell.width + MyCell.width / 2 + MylineWidths.paikis_gayvanis_monishvna, selected_index * MyCell.height + MyCell.height / 2 + MylineWidths.paikis_gayvanis_monishvna, MyCell.width - MylineWidths.paikis_gayvanis_monishvna * 2, MyCell.height - MylineWidths.paikis_gayvanis_monishvna * 2);
}
void svlis_gaketeba_Opposite()
{
if (Next_Figure.kodi != "e")
{
Board_Array_moklulebi_Player_Color.Add(Next_Figure.kodi.ToLower());
paint_moklulebi();
}
else
{
// პაიკის მიერ პაიკის გავლით აყვანა
// if (Curr_Figure.figuris_kodi == 3) {
// if (Board_Array_potenciuri_gavlit_mosaklavi_paiki.length > 0) {
// if (Board_Array_potenciuri_gavlit_mosaklavi_paiki.ToList().IndexOf(x) > 0) {
// ujris_gatavisufleba(x, y + 1);
// Board_Array_moklulebi_Opposite_Color.push(3);
// paint_moklulebi();
// }
// }
// }
}
ujraze_mimdinare_figuris_dasma(Next_Figure.X, Next_Figure.Y);
ujris_gatavisufleba(Curr_Figure.X, Curr_Figure.Y);
svlis_chawera("");
Clear_Curr_And_Next_Figures();
aris_mati_an_pati(PlayerColor);
Current_Move = PlayerColor;
compSettings.rects_list = new List<rect>();
}
string ujris_misamarti(int x, int y)
{
return Board_Array_Letters[x] + (8 - y);
}
public void svlis_gaketeba_misamartidan(string par_code, int par_vin_aketebs_svlas)
{
string sawyisi = par_code.Substring(0, 2);
Clear_Curr_And_Next_Figures();
Curr_Figure.isDefined = true;
Curr_Figure.X = Board_Array_Letters.ToList().IndexOf(sawyisi.Substring(0, 1));
Curr_Figure.Y = 8 - int.Parse(sawyisi.Substring(1, 1));
Curr_Figure.index = Get_Board_Index(Curr_Figure.X, Curr_Figure.Y);
Curr_Figure.kodi = Board_Array[Curr_Figure.index].ToString();
string saboloo = par_code.Substring(2, 2);
Next_Figure.isDefined = true;
Next_Figure.X = Board_Array_Letters.ToList().IndexOf(saboloo.Substring(0, 1));
Next_Figure.Y = 8 - int.Parse(saboloo.Substring(1, 1));
Next_Figure.index = Get_Board_Index(Next_Figure.X, Next_Figure.Y);
Next_Figure.kodi = Board_Array[Next_Figure.index].ToString();
if (par_vin_aketebs_svlas == PlayerColor)
{
svlis_gaketeba_Player();
}
else
{
svlis_gaketeba_Opposite();
}
}
void ujraze_mimdinare_figuris_dasma(int x, int y)
{
Board_Array[Get_Board_Index(x, y)] = Curr_Figure.kodi;
}
void ujraze_figuris_dasma(int x, int y, string figuris_kodi)
{
Board_Array[Get_Board_Index(x, y)] = figuris_kodi;
}
void ujris_gatavisufleba(int x, int y)
{
Board_Array[Get_Board_Index(x, y)] = "e";
}
int koordinatis_Semowmeba(int Par_X, int Par_Y, int par_visi_poziciidan)
{
int result = 0;
if (Par_Y < 0) return result;
if (Par_Y > 7) return result;
if (Par_X < 0) return result;
if (Par_X > 7) return result;
// 1 - დააბრუნოს თუ უჯრა თავისუფალია
// 2 - დააბრუნოს თუ უჯრაზე დგას მისი ფიგურა
// 3 - დააბრუნოს თუ უჯრაზე დგას მოწინააღმდეგის ფიგურა
// 4 - დააბრუნოს თუ უჯრაზე დგას მოწინააღმდეგის მეფე
string Code = Board_Array[Get_Board_Index(Par_X, Par_Y)];
if (Code == "e") //ე.ი. ცარიელია
{
result = 1;
}
else
{
if (is_my_figure(Code, par_visi_poziciidan)) //ე.ი. მისიანი დევს
{
result = 2;
}
else //ე.ი. მოწინააღმდეგე დევს
{
if (Code.ToLower() == "a") // ე.ი მოწინააღმდეგის მეფეა და მოკვლა არ შეიძლება
{
result = 4;
}
else
{
result = 3;
}
}
}
return result;
}
void Find_Moves_Paiki(int par_visi_poziciidan)
{
int tmp_result = 0;
// უნდა ვნახოთ უშლის თუ არა ხელს რამე წინ წასვლაში
tmp_result = koordinatis_Semowmeba(Curr_Figure.X, Curr_Figure.Y - 1, par_visi_poziciidan);
if (tmp_result == 1)
{
ujris_anteba(Curr_Figure.X, Curr_Figure.Y - 1, par_visi_poziciidan);
// უნდა ვნახოთ 2-ის უფლება თუ აქვს
if (Curr_Figure.Y == 6) //ე.ი. საწყის პოზიციაზეა
{
tmp_result = koordinatis_Semowmeba(Curr_Figure.X, Curr_Figure.Y - 2, par_visi_poziciidan);
if (tmp_result == 1) //ე.ი. ცარიელია
{
ujris_anteba(Curr_Figure.X, Curr_Figure.Y - 2, par_visi_poziciidan);
}
}
}
// უნდა ვნახოთ მოსაკლავი თუ აქვს რამე გვერდებზე
tmp_result = koordinatis_Semowmeba(Curr_Figure.X + 1, Curr_Figure.Y - 1, par_visi_poziciidan);
if (tmp_result == 3)
{
ujris_anteba(Curr_Figure.X + 1, Curr_Figure.Y - 1, par_visi_poziciidan);
}
tmp_result = koordinatis_Semowmeba(Curr_Figure.X - 1, Curr_Figure.Y - 1, par_visi_poziciidan);
if (tmp_result == 3)
{
ujris_anteba(Curr_Figure.X - 1, Curr_Figure.Y - 1, par_visi_poziciidan);
}
// ჩაჭრა არის დასამუშავებელი
// UC არაა საკმარისი ეს კოდი შეიძლება პაიკი თითო სვლით არის ამონაწევი და ამ დროს უფლება აღარ აქვს, მოსაფიქრებელია რამე
if ((Curr_Figure.Y) == 3)
{
if (Curr_Figure.X < 7) // ე.ი. არ დგას მარჯვენა კუთხეში
{
int marjvena_ori_wina_chawra = koordinatis_Semowmeba(Curr_Figure.X + 1, Curr_Figure.Y - 2, par_visi_poziciidan);
if (marjvena_ori_wina_chawra == 1) //ე.ი. ცარიელია
{
int marjvena_wina_chawra = koordinatis_Semowmeba(Curr_Figure.X + 1, Curr_Figure.Y - 1, par_visi_poziciidan);
if (marjvena_wina_chawra == 1) //ე.ი. ცარიელია
{
string marjvena_mezoblis_kodi = Board_Array[Get_Board_Index(Curr_Figure.X + 1, Curr_Figure.Y)];
if (marjvena_mezoblis_kodi != "e") //ე.ი. ცარიელი არაა
{
if (!is_my_figure(marjvena_mezoblis_kodi, par_visi_poziciidan) && marjvena_mezoblis_kodi.ToLower() == "p")
{
// მეზობელი არის მოწინააღმდეგე და თან პაიკი
Board_Array_potenciuri_gavlit_mosaklavi_paiki.Add(Curr_Figure.X + 1);
ujris_anteba(Curr_Figure.X + 1, Curr_Figure.Y - 1, par_visi_poziciidan);
}
}
}
}
}
if (Curr_Figure.X > 0) // ე.ი. არ დგას მარცხენა კუთხეში
{
int marcxena_ori_wina_chawra = koordinatis_Semowmeba(Curr_Figure.X - 1, Curr_Figure.Y - 2, par_visi_poziciidan);
if (marcxena_ori_wina_chawra == 1) //ე.ი. ცარიელია
{
int marcxena_wina_chawra = koordinatis_Semowmeba(Curr_Figure.X - 1, Curr_Figure.Y - 1, par_visi_poziciidan);
if (marcxena_wina_chawra == 1) //ე.ი. ცარიელია
{
string marcxena_mezoblis_kodi = Board_Array[Get_Board_Index(Curr_Figure.X - 1, Curr_Figure.Y)];
if (marcxena_mezoblis_kodi != "e") //ე.ი. ცარიელი არაა
{
if (!is_my_figure(marcxena_mezoblis_kodi, par_visi_poziciidan) && marcxena_mezoblis_kodi.ToLower() == "p")
{
// მეზობელი არის მოწინააღმდეგე და თან პაიკი
Board_Array_potenciuri_gavlit_mosaklavi_paiki.Add(Curr_Figure.X - 1);
ujris_anteba(Curr_Figure.X - 1, Curr_Figure.Y - 1, par_visi_poziciidan);
}
}
}
}
}
}
}
void Find_Moves_Etli(int Par_limit, int par_visi_poziciidan)
{
int tmp_result = 0;
// წინა მიმართულების დამუშავება
for (int i = 1; i < Par_limit; i++)
{
tmp_result = koordinatis_Semowmeba(Curr_Figure.X, Curr_Figure.Y - i, par_visi_poziciidan);
if (tmp_result == 0)
{
//გავიდა დაფის გარეთ;
break;
}
if (tmp_result == 1)
{
ujris_anteba(Curr_Figure.X, Curr_Figure.Y - i, par_visi_poziciidan);
}
else
{
if (tmp_result == 3) //შეხვდა მოწინააღმდეგე
{
ujris_anteba(Curr_Figure.X, Curr_Figure.Y - i, par_visi_poziciidan);
}
break;
}
}
// უკანა მიმართულების დამუშავება
for (int i = 1; i < Par_limit; i++)
{
tmp_result = koordinatis_Semowmeba(Curr_Figure.X, Curr_Figure.Y + i, par_visi_poziciidan);
if (tmp_result == 0)
{
//გავიდა დაფის გარეთ;
break;
}
if (tmp_result == 1)
{
ujris_anteba(Curr_Figure.X, Curr_Figure.Y + i, par_visi_poziciidan);
}
else
{
if (tmp_result == 3) //შეხვდა მოწინააღმდეგე
{
ujris_anteba(Curr_Figure.X, Curr_Figure.Y + i, par_visi_poziciidan);
}
break;
}
}
// მარჯვენა მიმართულების დამუშავება
for (int i = 1; i < Par_limit; i++)
{
tmp_result = koordinatis_Semowmeba(Curr_Figure.X + i, Curr_Figure.Y, par_visi_poziciidan);
if (tmp_result == 0)
{
//გავიდა დაფის გარეთ;
break;
}
if (tmp_result == 1)
{
ujris_anteba(Curr_Figure.X + i, Curr_Figure.Y, par_visi_poziciidan);
}
else
{
if (tmp_result == 3) //შეხვდა მოწინააღმდეგე
{
ujris_anteba(Curr_Figure.X + i, Curr_Figure.Y, par_visi_poziciidan);
}
break;
}
}
// მარცხენა მიმართულების დამუშავება
for (int i = 1; i < Par_limit; i++)
{
tmp_result = koordinatis_Semowmeba(Curr_Figure.X - i, Curr_Figure.Y, par_visi_poziciidan);
if (tmp_result == 0)
{
//გავიდა დაფის გარეთ;
break;
}
if (tmp_result == 1)
{
ujris_anteba(Curr_Figure.X - i, Curr_Figure.Y, par_visi_poziciidan);
}
else
{
if (tmp_result == 3) //შეხვდა მოწინააღმდეგე
{
ujris_anteba(Curr_Figure.X - i, Curr_Figure.Y, par_visi_poziciidan);
}
break;
}
}
}
void Find_Moves_Mxedari(int par_visi_poziciidan)
{
int tmp_result = 0;
// წინა მარჯვენა გრძელი მიმართულების დამუშავება
tmp_result = koordinatis_Semowmeba(Curr_Figure.X + 1, Curr_Figure.Y - 2, par_visi_poziciidan);
if (tmp_result == 1 || tmp_result == 3)
{
ujris_anteba(Curr_Figure.X + 1, Curr_Figure.Y - 2, par_visi_poziciidan);
}
// წინა მარჯვენა მოკლე მიმართულების დამუშავება
tmp_result = koordinatis_Semowmeba(Curr_Figure.X + 2, Curr_Figure.Y - 1, par_visi_poziciidan);
if (tmp_result == 1 || tmp_result == 3)
{
ujris_anteba(Curr_Figure.X + 2, Curr_Figure.Y - 1, par_visi_poziciidan);
}
// უკანა მარჯვენა გრძელი მიმართულების დამუშავება
tmp_result = koordinatis_Semowmeba(Curr_Figure.X + 2, Curr_Figure.Y + 1, par_visi_poziciidan);
if (tmp_result == 1 || tmp_result == 3)
{
ujris_anteba(Curr_Figure.X + 2, Curr_Figure.Y + 1, par_visi_poziciidan);
}
// უკანა მარჯვენა მოკლე მიმართულების დამუშავება
tmp_result = koordinatis_Semowmeba(Curr_Figure.X + 1, Curr_Figure.Y + 2, par_visi_poziciidan);
if (tmp_result == 1 || tmp_result == 3)
{
ujris_anteba(Curr_Figure.X + 1, Curr_Figure.Y + 2, par_visi_poziciidan);
}
// უკანა მარცხენა გრძელი მიმართულება
tmp_result = koordinatis_Semowmeba(Curr_Figure.X - 1, Curr_Figure.Y + 2, par_visi_poziciidan);
if (tmp_result == 1 || tmp_result == 3)
{
ujris_anteba(Curr_Figure.X - 1, Curr_Figure.Y + 2, par_visi_poziciidan);
}
// უკანა მარცხენა მოკლე მიმართულება
tmp_result = koordinatis_Semowmeba(Curr_Figure.X - 2, Curr_Figure.Y + 1, par_visi_poziciidan);
if (tmp_result == 1 || tmp_result == 3)
{
ujris_anteba(Curr_Figure.X - 2, Curr_Figure.Y + 1, par_visi_poziciidan);
}
// წინა მარცხენა გრძელი მიმართულება
tmp_result = koordinatis_Semowmeba(Curr_Figure.X - 1, Curr_Figure.Y - 2, par_visi_poziciidan);
if (tmp_result == 1 || tmp_result == 3)
{
ujris_anteba(Curr_Figure.X - 1, Curr_Figure.Y - 2, par_visi_poziciidan);
}
// წინა მარცხენა მოკლე მიმართულება
tmp_result = koordinatis_Semowmeba(Curr_Figure.X - 2, Curr_Figure.Y - 1, par_visi_poziciidan);
if (tmp_result == 1 || tmp_result == 3)
{
ujris_anteba(Curr_Figure.X - 2, Curr_Figure.Y - 1, par_visi_poziciidan);
}
}
void Find_Moves_Oficeri(int Par_limit, int par_visi_poziciidan)
{
int tmp_result = 0;
// მარჯვენა ზედა მიმართულება
for (int i = 1; i < Par_limit; i++)
{
tmp_result = koordinatis_Semowmeba(Curr_Figure.X + i, Curr_Figure.Y - i, par_visi_poziciidan);
if (tmp_result == 0)
{
//გავიდა დაფის გარეთ;
break;
}
if (tmp_result == 1)
{
ujris_anteba(Curr_Figure.X + i, Curr_Figure.Y - i, par_visi_poziciidan);
}
else
{
if (tmp_result == 3) //შეხვდა მოწინააღმდეგე
{
ujris_anteba(Curr_Figure.X + i, Curr_Figure.Y - i, par_visi_poziciidan);
}
break;
}
}
// მარჯვენა ქვედა მიმართულება
for (int i = 1; i < Par_limit; i++)
{
tmp_result = koordinatis_Semowmeba(Curr_Figure.X + i, Curr_Figure.Y + i, par_visi_poziciidan);
if (tmp_result == 0)
{
//გავიდა დაფის გარეთ;
break;
}
if (tmp_result == 1)
{
ujris_anteba(Curr_Figure.X + i, Curr_Figure.Y + i, par_visi_poziciidan);
}
else
{
if (tmp_result == 3) //შეხვდა მოწინააღმდეგე
{
ujris_anteba(Curr_Figure.X + i, Curr_Figure.Y + i, par_visi_poziciidan);
}
break;
}
}
// მარცხენა ზედა მიმართულება
for (int i = 1; i < Par_limit; i++)
{
tmp_result = koordinatis_Semowmeba(Curr_Figure.X - i, Curr_Figure.Y - i, par_visi_poziciidan);
if (tmp_result == 0)
{
//გავიდა დაფის გარეთ;
break;
}
if (tmp_result == 1)
{
ujris_anteba(Curr_Figure.X - i, Curr_Figure.Y - i, par_visi_poziciidan);
}
else
{
if (tmp_result == 3) //შეხვდა მოწინააღმდეგე
{
ujris_anteba(Curr_Figure.X - i, Curr_Figure.Y - i, par_visi_poziciidan);
}
break;
}
}
// მარცხენა ქვედა მიმართულება
for (int i = 1; i < Par_limit; i++)
{
tmp_result = koordinatis_Semowmeba(Curr_Figure.X - i, Curr_Figure.Y + i, par_visi_poziciidan);
if (tmp_result == 0)
{
//გავიდა დაფის გარეთ;
break;
}
if (tmp_result == 1)
{
ujris_anteba(Curr_Figure.X - i, Curr_Figure.Y + i, par_visi_poziciidan);
}
else
{
if (tmp_result == 3) //შეხვდა მოწინააღმდეგე
{
ujris_anteba(Curr_Figure.X - i, Curr_Figure.Y + i, par_visi_poziciidan);
}
break;
}
}
}
void Find_Moves_Dedofali(int par_visi_poziciidan)
{
Find_Moves_Etli(8, par_visi_poziciidan);
Find_Moves_Oficeri(8, par_visi_poziciidan);
}
void Find_Moves_Mefe(int par_visi_poziciidan)
{
Find_Moves_Etli(2, par_visi_poziciidan);
Find_Moves_Oficeri(2, par_visi_poziciidan);
int tmp_result = 0;
bool tmp_aris_muqaris_qvesh = false;
tmp_aris_muqaris_qvesh = ujra_aris_tu_ara_muqaris_qvesh(Curr_Figure.X, Curr_Figure.Y, par_visi_poziciidan);
if (tmp_aris_muqaris_qvesh == false)
{
if (aqvs_roqis_ufleba)
{
// mokle roqi
if (aqvs_mokle_roqis_ufleba)
{
if (PlayerColor == 1)
{
tmp_result = koordinatis_Semowmeba(Curr_Figure.X + 1, Curr_Figure.Y, PlayerColor);
tmp_aris_muqaris_qvesh = ujra_aris_tu_ara_muqaris_qvesh(Curr_Figure.X + 1, Curr_Figure.Y, PlayerColor);
if (tmp_result == 1 && tmp_aris_muqaris_qvesh == false)
{
tmp_result = koordinatis_Semowmeba(Curr_Figure.X + 2, Curr_Figure.Y, PlayerColor);
tmp_aris_muqaris_qvesh = ujra_aris_tu_ara_muqaris_qvesh(Curr_Figure.X + 2, Curr_Figure.Y, PlayerColor);
if (tmp_result == 1 && tmp_aris_muqaris_qvesh == false)
{
string etlis_ujra = Board_Array[Get_Board_Index(Curr_Figure.X + 3, Curr_Figure.Y)];
if (etlis_ujra != "e")
{
if (etlis_ujra.ToLower() == "r")
{
ujris_anteba(Curr_Figure.X + 2, Curr_Figure.Y, par_visi_poziciidan);
}
}
}
}
}
else
{
tmp_result = koordinatis_Semowmeba(Curr_Figure.X - 1, Curr_Figure.Y, PlayerColor);
tmp_aris_muqaris_qvesh = ujra_aris_tu_ara_muqaris_qvesh(Curr_Figure.X - 1, Curr_Figure.Y, PlayerColor);
if (tmp_result == 1 && tmp_aris_muqaris_qvesh == false)
{
tmp_result = koordinatis_Semowmeba(Curr_Figure.X - 2, Curr_Figure.Y, PlayerColor);
tmp_aris_muqaris_qvesh = ujra_aris_tu_ara_muqaris_qvesh(Curr_Figure.X - 2, Curr_Figure.Y, PlayerColor);
if (tmp_result == 1 && tmp_aris_muqaris_qvesh == false)
{
string etlis_ujra = Board_Array[Get_Board_Index(Curr_Figure.X - 3, Curr_Figure.Y)].ToString();
if (etlis_ujra != "e")
{
if (etlis_ujra.ToLower() == "r")
{
ujris_anteba(Curr_Figure.X - 2, Curr_Figure.Y, par_visi_poziciidan);
}
}
}
}
}
}
// grdzeli roqi
if (aqvs_grdzeli_roqis_ufleba)
{
if (PlayerColor == 1)
{
tmp_result = koordinatis_Semowmeba(Curr_Figure.X - 1, Curr_Figure.Y, PlayerColor);
tmp_aris_muqaris_qvesh = ujra_aris_tu_ara_muqaris_qvesh(Curr_Figure.X - 1, Curr_Figure.Y, PlayerColor);
if (tmp_result == 1 && tmp_aris_muqaris_qvesh == false)
{
tmp_result = koordinatis_Semowmeba(Curr_Figure.X - 2, Curr_Figure.Y, PlayerColor);
tmp_aris_muqaris_qvesh = ujra_aris_tu_ara_muqaris_qvesh(Curr_Figure.X - 2, Curr_Figure.Y, PlayerColor);
if (tmp_result == 1 && tmp_aris_muqaris_qvesh == false)
{
tmp_result = koordinatis_Semowmeba(Curr_Figure.X - 3, Curr_Figure.Y, PlayerColor);
tmp_aris_muqaris_qvesh = ujra_aris_tu_ara_muqaris_qvesh(Curr_Figure.X - 3, Curr_Figure.Y, PlayerColor);
if (tmp_result == 1 && tmp_aris_muqaris_qvesh == false)
{
string etlis_ujra = Board_Array[Get_Board_Index(Curr_Figure.X - 4, Curr_Figure.Y)].ToString();
if (etlis_ujra != "e")
{
if (etlis_ujra.ToLower() == "r")
{
ujris_anteba(Curr_Figure.X - 2, Curr_Figure.Y, par_visi_poziciidan);
}
}
}
}
}
}
else
{
tmp_result = koordinatis_Semowmeba(Curr_Figure.X + 1, Curr_Figure.Y, PlayerColor);
tmp_aris_muqaris_qvesh = ujra_aris_tu_ara_muqaris_qvesh(Curr_Figure.X + 1, Curr_Figure.Y, PlayerColor);
if (tmp_result == 1 && tmp_aris_muqaris_qvesh == false)
{
tmp_result = koordinatis_Semowmeba(Curr_Figure.X + 2, Curr_Figure.Y, PlayerColor);
tmp_aris_muqaris_qvesh = ujra_aris_tu_ara_muqaris_qvesh(Curr_Figure.X + 2, Curr_Figure.Y, PlayerColor);
if (tmp_result == 1 && tmp_aris_muqaris_qvesh == false)
{
tmp_result = koordinatis_Semowmeba(Curr_Figure.X + 3, Curr_Figure.Y, PlayerColor);
tmp_aris_muqaris_qvesh = ujra_aris_tu_ara_muqaris_qvesh(Curr_Figure.X + 3, Curr_Figure.Y, PlayerColor);
if (tmp_result == 1 && tmp_aris_muqaris_qvesh == false)
{
string etlis_ujra = Board_Array[Get_Board_Index(Curr_Figure.X + 4, Curr_Figure.Y)].ToString();
if (etlis_ujra != "e")
{
if (etlis_ujra.ToLower() == "r")
{
ujris_anteba(Curr_Figure.X + 2, Curr_Figure.Y, par_visi_poziciidan);
}
}
}
}
}
}
}
}
}
}
void paint_moklulebi()
{
// არ წაშალო, შეიძლება მოკლულების ბადე საჭირო იყოს!!!!!!!!!!!!!!!!
// let row_index = 0;
// let column_index = 0;
// for (let index = 0; index < 32; index++) {
// if (index > 7) {
// column_index = (index) % 8;
// row_index = (index - column_index) / 8;
// }
// else {
// column_index = index;
// row_index = 0;
// }
// if ((index + row_index) % 2 == 0) {
// context_moklulebi.fillStyle = MyCell_Moklulebi.white_color;
// }
// else {
// context_moklulebi.fillStyle = MyCell_Moklulebi.black_color;
// }
// context_moklulebi.fillRect(MyCell_Moklulebi.width * column_index, MyCell_Moklulebi.height * row_index, MyCell_Moklulebi.width, MyCell_Moklulebi.height);
// }
int paikebis_raodenoba = 0;
int etlebis_raodenoba = 0;
int mxedrebis_raodenoba = 0;
int oficrebis_raodenoba = 0;
string kodi = "";
foreach (string i in Board_Array_moklulebi_Opposite_Color)
{
kodi = i.ToUpper();
switch (kodi)
{
case "P":
Add_Killed_Figure(OppositeColor + "" + kodi, paikebis_raodenoba * MyCell_Moklulebi.width + MyCell_Moklulebi.width * 0.2, MyCell_Moklulebi.height * 0.2, MyCell_Moklulebi.width, MyCell_Moklulebi.height);
paikebis_raodenoba++;
break;
case "R":
if (etlebis_raodenoba == 0)
{
Add_Killed_Figure(OppositeColor + "" + kodi, MyCell_Moklulebi.width * 0.2, 1.2 * MyCell_Moklulebi.height, MyCell_Moklulebi.width, MyCell_Moklulebi.height);
}
else
{
Add_Killed_Figure(OppositeColor + "" + kodi, 7.2 * MyCell_Moklulebi.width, 1.2 * MyCell_Moklulebi.height, MyCell_Moklulebi.width, MyCell_Moklulebi.height);
}
etlebis_raodenoba++;
break;
case "K":
if (mxedrebis_raodenoba == 0)
{
Add_Killed_Figure(OppositeColor + "" + kodi, 1.2 * MyCell_Moklulebi.width, 1.2 * MyCell_Moklulebi.height, MyCell_Moklulebi.width, MyCell_Moklulebi.height);
}
else
{
Add_Killed_Figure(OppositeColor + "" + kodi, 6.2 * MyCell_Moklulebi.width, 1.2 * MyCell_Moklulebi.height, MyCell_Moklulebi.width, MyCell_Moklulebi.height);
}
mxedrebis_raodenoba++;
break;
case "B":
if (oficrebis_raodenoba == 0)
{
Add_Killed_Figure(OppositeColor + "" + kodi, 2.2 * MyCell_Moklulebi.width, 1.2 * MyCell_Moklulebi.height, MyCell_Moklulebi.width, MyCell_Moklulebi.height);
}
else
{
Add_Killed_Figure(OppositeColor + "" + kodi, 5.2 * MyCell_Moklulebi.width, 1.2 * MyCell_Moklulebi.height, MyCell_Moklulebi.width, MyCell_Moklulebi.height);
}
oficrebis_raodenoba++;
break;
case "Q":
Add_Killed_Figure(OppositeColor + "" + kodi, 3.2 * MyCell_Moklulebi.width, 1.2 * MyCell_Moklulebi.height, MyCell_Moklulebi.width, MyCell_Moklulebi.height);
break;
default:
break;
}
}
paikebis_raodenoba = 0;
etlebis_raodenoba = 0;
mxedrebis_raodenoba = 0;
oficrebis_raodenoba = 0;
kodi = "";
foreach (string i in Board_Array_moklulebi_Player_Color)
{
kodi = i.ToUpper();
switch (kodi)
{
case "P":
Add_Killed_Figure(PlayerColor + "" + kodi, paikebis_raodenoba * MyCell_Moklulebi.width + MyCell_Moklulebi.width * 0.2, 2.2 * MyCell_Moklulebi.height, MyCell_Moklulebi.width, MyCell_Moklulebi.height);
paikebis_raodenoba++;
break;
case "R":
if (etlebis_raodenoba == 0)
{
Add_Killed_Figure(PlayerColor + "" + kodi, MyCell_Moklulebi.width * 0.2, 3.2 * MyCell_Moklulebi.height, MyCell_Moklulebi.width, MyCell_Moklulebi.height);
}
else
{
Add_Killed_Figure(PlayerColor + "" + kodi, 7.2 * MyCell_Moklulebi.width, 3.2 * MyCell_Moklulebi.height, MyCell_Moklulebi.width, MyCell_Moklulebi.height);
}
etlebis_raodenoba++;
break;
case "K":
if (mxedrebis_raodenoba == 0)
{
Add_Killed_Figure(PlayerColor + "" + kodi, 1.2 * MyCell_Moklulebi.width, 3.2 * MyCell_Moklulebi.height, MyCell_Moklulebi.width, MyCell_Moklulebi.height);
}
else
{
Add_Killed_Figure(PlayerColor + "" + kodi, 6.2 * MyCell_Moklulebi.width, 3.2 * MyCell_Moklulebi.height, MyCell_Moklulebi.width, MyCell_Moklulebi.height);
}
mxedrebis_raodenoba++;
break;
case "B":
if (oficrebis_raodenoba == 0)
{
Add_Killed_Figure(PlayerColor + "" + kodi, 2.2 * MyCell_Moklulebi.width, 3.2 * MyCell_Moklulebi.height, MyCell_Moklulebi.width, MyCell_Moklulebi.height);
}
else
{
Add_Killed_Figure(PlayerColor + "" + kodi, 5.2 * MyCell_Moklulebi.width, 3.2 * MyCell_Moklulebi.height, MyCell_Moklulebi.width, MyCell_Moklulebi.height);
}
oficrebis_raodenoba++;
break;
case "Q":
Add_Killed_Figure(PlayerColor + "" + kodi, 3.2 * MyCell_Moklulebi.width, 3.2 * MyCell_Moklulebi.height, MyCell_Moklulebi.width, MyCell_Moklulebi.height);
break;
default:
break;
}
}
compSettings.Curr_Comp_Stat.Refresh();
}
void Add_Killed_Figure(string _img, double _x, double _y, double _w, double _h)
{
compSettings.KilledFigures_list.Add(new image
{
x = _x,
y = _y,
width = _w,
height = _h,
href = "content/images/style3/" + _img + ".png",
onclick = BoolOptionsEnum.Yes,
});
}
string svlis_chawera(string par_Extra)
{
string sawyisi_misamarti = ujris_misamarti(Curr_Figure.X, Curr_Figure.Y);
string saboloo_misamarti = ujris_misamarti(Next_Figure.X, Next_Figure.Y);
if (Current_Move == 1)
{
compSettings.Moves_list.Add("white - " + sawyisi_misamarti + " - " + saboloo_misamarti + par_Extra);
}
else
{
compSettings.Moves_list.Add("black - " + sawyisi_misamarti + " - " + saboloo_misamarti + par_Extra);
}
compSettings.Curr_comp.Refresh();
return sawyisi_misamarti + saboloo_misamarti;
}
public void Cmd_Replay()
{
if (timer_Game != null)
{
timer_Game.Dispose();
}
timer_Replay = new Timer(TimerReplayCallback, null, 0, 1000);
}
void TimerReplayCallback(Object stateInfo)
{
if (Curr_Replay_Index < Board_Array_Moves.Length)
{
svlis_gaketeba_misamartidan(Board_Array_Moves[Curr_Replay_Index], Current_Move);
Curr_Replay_Index++;
}
else
{
timer_Replay.Dispose();
}
}
string get_figuris_kodi(int x, int y)
{
return Board_Array[Get_Board_Index(x, y)];
}
string get_relevant_case(string p, int par_visi_poziciidan)
{
if (par_visi_poziciidan == 1)
{
return p.ToUpper();
}
else
{
return p.ToLower();
}
}
bool ujra_aris_tu_ara_muqaris_qvesh(int x, int y, int par_visi_poziciidan)
{
bool result = false;
string mownaaRmdegis_figuris_kodi = string.Empty;
int tmp_result = 0;
// ზედა ჰორიზონტალური მიმართულების დამუშავება
for (int i = 1; i < 8; i++)
{
tmp_result = koordinatis_Semowmeba(x, y - i, par_visi_poziciidan);
if (tmp_result == 0 || tmp_result == 2)
{
break;
}
else
{
if (tmp_result == 3 || tmp_result == 4)
{
mownaaRmdegis_figuris_kodi = get_figuris_kodi(x, y - i);
if (mownaaRmdegis_figuris_kodi.ToLower() == "a" && i == 1)
{
return true;
}
if (mownaaRmdegis_figuris_kodi.ToLower() == "q" || mownaaRmdegis_figuris_kodi.ToLower() == "r")
{
return true;
}
break;
}
}
}
// ქვედა ჰორიზონტალური მიმართულების დამუშავება
for (int i = 1; i < 8; i++)
{
tmp_result = koordinatis_Semowmeba(x, y + i, par_visi_poziciidan);
if (tmp_result == 0 || tmp_result == 2)
{
break;
}
else
{
if (tmp_result == 3 || tmp_result == 4)
{
mownaaRmdegis_figuris_kodi = get_figuris_kodi(x, y + i);
if (mownaaRmdegis_figuris_kodi.ToLower() == "a" && i == 1)
{
return true;
}
if (mownaaRmdegis_figuris_kodi.ToLower() == "q" || mownaaRmdegis_figuris_kodi.ToLower() == "r")
{
return true;
}
break;
}
}
}
// მარჯვენა ჰორიზონტალური მიმართულების დამუშავება
for (int i = 1; i < 8; i++)
{
tmp_result = koordinatis_Semowmeba(x + i, y, par_visi_poziciidan);
if (tmp_result == 0 || tmp_result == 2)
{
break;
}
else
{
if (tmp_result == 3 || tmp_result == 4)
{
mownaaRmdegis_figuris_kodi = get_figuris_kodi(x + i, y);
if (mownaaRmdegis_figuris_kodi.ToLower() == "a" && i == 1)
{
return true;
}
if (mownaaRmdegis_figuris_kodi.ToLower() == "q" || mownaaRmdegis_figuris_kodi.ToLower() == "r")
{
return true;
}
break;
}
}
}
// მარცხენა ჰორიზონტალური მიმართულების დამუშავება
for (int i = 1; i < 8; i++)
{
tmp_result = koordinatis_Semowmeba(x - i, y, par_visi_poziciidan);
if (tmp_result == 0 || tmp_result == 2)
{
break;
}
else
{
if (tmp_result == 3 || tmp_result == 4)
{
mownaaRmdegis_figuris_kodi = get_figuris_kodi(x - i, y);
if (mownaaRmdegis_figuris_kodi.ToLower() == "a" && i == 1)
{
return true;
}
if (mownaaRmdegis_figuris_kodi.ToLower() == "q" || mownaaRmdegis_figuris_kodi.ToLower() == "r")
{
return true;
}
break;
}
}
}
// მარჯვენა ზედა დიაგონალური მიმართულების დამუშავება
for (int i = 1; i < 8; i++)
{
tmp_result = koordinatis_Semowmeba(x + i, y - i, par_visi_poziciidan);
if (tmp_result == 0 || tmp_result == 2)
{
break;
}
else
{
if (tmp_result == 3 || tmp_result == 4)
{
mownaaRmdegis_figuris_kodi = get_figuris_kodi(x + i, y - i);
if (mownaaRmdegis_figuris_kodi.ToLower() == "a" && i == 1)
{
return true;
}
if (mownaaRmdegis_figuris_kodi.ToLower() == "q" || mownaaRmdegis_figuris_kodi.ToLower() == "b")
{
return true;
}
if (mownaaRmdegis_figuris_kodi.ToLower() == "p" && i == 1 && par_visi_poziciidan == PlayerColor)
{
return true;
}
break;
}
}
}
// მარჯვენა ქვედა დიაგონალური მიმართულების დამუშავება
for (int i = 1; i < 8; i++)
{
tmp_result = koordinatis_Semowmeba(x + i, y + i, par_visi_poziciidan);
if (tmp_result == 0 || tmp_result == 2)
{
break;
}
else
{
if (tmp_result == 3 || tmp_result == 4)
{
mownaaRmdegis_figuris_kodi = get_figuris_kodi(x + i, y + i);
if (mownaaRmdegis_figuris_kodi.ToLower() == "a" && i == 1)
{
return true;
}
if (mownaaRmdegis_figuris_kodi.ToLower() == "q" || mownaaRmdegis_figuris_kodi.ToLower() == "b")
{
return true;
}
if (mownaaRmdegis_figuris_kodi.ToLower() == "p" && i == 1 && par_visi_poziciidan == OppositeColor)
{
return true;
}
break;
}
}
}
// მარცხენა ზედა დიაგონალური მიმართულების დამუშავება
for (int i = 1; i < 8; i++)
{
tmp_result = koordinatis_Semowmeba(x - i, y - i, par_visi_poziciidan);
if (tmp_result == 0 || tmp_result == 2)
{
break;
}
else
{
if (tmp_result == 3 || tmp_result == 4)
{
mownaaRmdegis_figuris_kodi = get_figuris_kodi(x - i, y - i);
if (mownaaRmdegis_figuris_kodi.ToLower() == "a" && i == 1)
{
return true;
}
if (mownaaRmdegis_figuris_kodi.ToLower() == "q" || mownaaRmdegis_figuris_kodi.ToLower() == "b")
{
return true;
}
if (mownaaRmdegis_figuris_kodi.ToLower() == "p" && i == 1 && par_visi_poziciidan == PlayerColor)
{
return true;
}
break;
}
}
}
// მარცხენა ქვედა დიაგონალური მიმართულების დამუშავება
for (int i = 1; i < 8; i++)
{
tmp_result = koordinatis_Semowmeba(x - i, y + i, par_visi_poziciidan);
if (tmp_result == 0 || tmp_result == 2)
{
break;
}
else
{
if (tmp_result == 3 || tmp_result == 4)
{
mownaaRmdegis_figuris_kodi = get_figuris_kodi(x - i, y + i);
if (mownaaRmdegis_figuris_kodi.ToLower() == "a" && i == 1)
{
return true;
}
if (mownaaRmdegis_figuris_kodi.ToLower() == "q" || mownaaRmdegis_figuris_kodi.ToLower() == "b")
{
return true;
}
if (mownaaRmdegis_figuris_kodi.ToLower() == "p" && i == 1 && par_visi_poziciidan == OppositeColor)
{
return true;
}
break;
}
}
}
// მხედრის წინა მარჯვენა გრძელი მიმართულების დამუშავება
tmp_result = koordinatis_Semowmeba(x + 1, y - 2, par_visi_poziciidan);
if (tmp_result == 3)
{
mownaaRmdegis_figuris_kodi = get_figuris_kodi(x + 1, y - 2);
if (mownaaRmdegis_figuris_kodi.ToLower() == "k")
{
return true;
}
}
// მხედრის წინა მარჯვენა მოკლე მიმართულების დამუშავება
tmp_result = koordinatis_Semowmeba(x + 2, y - 1, par_visi_poziciidan);
if (tmp_result == 3)
{
mownaaRmdegis_figuris_kodi = get_figuris_kodi(x + 2, y - 1);
if (mownaaRmdegis_figuris_kodi.ToLower() == "k")
{
return true;
}
}
// მხედრის უკანა მარჯვენა გრძელი მიმართულების დამუშავება
tmp_result = koordinatis_Semowmeba(x + 2, y + 1, par_visi_poziciidan);
if (tmp_result == 3)
{
mownaaRmdegis_figuris_kodi = get_figuris_kodi(x + 2, y + 1);
if (mownaaRmdegis_figuris_kodi.ToLower() == "k")
{
return true;
}
}
// მხედრის უკანა მარჯვენა მოკლე მიმართულების დამუშავება
tmp_result = koordinatis_Semowmeba(x + 1, y + 2, par_visi_poziciidan);
if (tmp_result == 3)
{
mownaaRmdegis_figuris_kodi = get_figuris_kodi(x + 1, y + 2);
if (mownaaRmdegis_figuris_kodi.ToLower() == "k")
{
return true;
}
}
// მხედრის უკანა მარცხენა გრძელი მიმართულება
tmp_result = koordinatis_Semowmeba(x - 1, y + 2, par_visi_poziciidan);
if (tmp_result == 3)
{
mownaaRmdegis_figuris_kodi = get_figuris_kodi(x - 1, y + 2);
if (mownaaRmdegis_figuris_kodi.ToLower() == "k")
{
return true;
}
}
// მხედრის უკანა მარცხენა მოკლე მიმართულება
tmp_result = koordinatis_Semowmeba(x - 2, y + 1, par_visi_poziciidan);
if (tmp_result == 3)
{
mownaaRmdegis_figuris_kodi = get_figuris_kodi(x - 2, y + 1);
if (mownaaRmdegis_figuris_kodi.ToLower() == "k")
{
return true;
}
}
// მხედრის წინა მარცხენა გრძელი მიმართულება
tmp_result = koordinatis_Semowmeba(x - 1, y - 2, par_visi_poziciidan);
if (tmp_result == 3)
{
mownaaRmdegis_figuris_kodi = get_figuris_kodi(x - 1, y - 2);
if (mownaaRmdegis_figuris_kodi.ToLower() == "k")
{
return true;
}
}
// მხედრის წინა მარცხენა მოკლე მიმართულება
tmp_result = koordinatis_Semowmeba(x - 2, y - 2, par_visi_poziciidan);
if (tmp_result == 3)
{
mownaaRmdegis_figuris_kodi = get_figuris_kodi(x - 2, y - 2);
if (mownaaRmdegis_figuris_kodi.ToLower() == "k")
{
return true;
}
}
return result;
}
void Reverse_Board()
{
string tmp_code = string.Empty;
for (var index = 0; index < Board_Array.Length / 2; index++)
{
tmp_code = Board_Array[index];
Board_Array[index] = Board_Array[63 - index];
Board_Array[63 - index] = tmp_code;
}
}
void aris_mati_an_pati(int par_vin_waago)
{
bool result = true;
bool has_shax = false;
if (par_vin_waago == PlayerColor)
{
has_shax = Player_Has_Shax;
}
else
{
has_shax = Opposite_Has_Shax;
}
string King_Letter = "A";
if (par_vin_waago == OppositeColor)
{
King_Letter = King_Letter.ToLower();
}
Save_Or_Restore_Curr_Figure(false);
ar_avantot_ujrebi = true;
List<string> tmp_Board_Array_potenciuri_svlebi = new List<string>(Board_Array_potenciuri_svlebi);
List<int> tmp_Board_Array_potenciuri_gavlit_mosaklavi_paiki = new List<int>(Board_Array_potenciuri_gavlit_mosaklavi_paiki);
Board_Array_potenciuri_svlebi = new List<string>();
Board_Array_potenciuri_gavlit_mosaklavi_paiki = new List<int>();
int King_Index = Board_Array.ToList().IndexOf(King_Letter);
Curr_Figure.isDefined = true;
Curr_Figure.X = King_Index % 8;
Curr_Figure.Y = (King_Index - Curr_Figure.X) / 8;
Curr_Figure.index = King_Index;
Curr_Figure.kodi = Board_Array[King_Index];
Find_Moves_Mefe(par_vin_waago);
if (Board_Array_potenciuri_svlebi.Count > 0)
{
result = false;
}
else
{
if (has_Other_Figures(PlayerColor))
{
for (var index = 0; index < Board_Array.Length; index++)
{
if (is_my_figure(Board_Array[index], par_vin_waago))
{
if (Board_Array[index].ToLower() != "a")
{
Curr_Figure.isDefined = true;
Curr_Figure.X = index % 8;
Curr_Figure.Y = (index - Curr_Figure.X) / 8;
Curr_Figure.index = index;
Curr_Figure.kodi = Board_Array[index];
Find_Moves(par_vin_waago);
if (Board_Array_potenciuri_svlebi.Count > 0)
{
result = false;
break;
}
}
}
}
}
else
{
result = true;
}
}
Board_Array_potenciuri_svlebi = new List<string>(tmp_Board_Array_potenciuri_svlebi);
Board_Array_potenciuri_gavlit_mosaklavi_paiki = new List<int>(tmp_Board_Array_potenciuri_gavlit_mosaklavi_paiki);
ar_avantot_ujrebi = false;
Save_Or_Restore_Curr_Figure(true);
if (result)
{
if (has_shax)
{
Game_Over("mati");
}
else
{
Game_Over("pati");
}
}
}
void Save_Or_Restore_Curr_Figure(bool Save_false_Or_Restore_true)
{
if (Save_false_Or_Restore_true)
{
Curr_Figure.isDefined = tmp_Figure.isDefined;
Curr_Figure.X = tmp_Figure.X;
Curr_Figure.Y = tmp_Figure.Y;
Curr_Figure.index = tmp_Figure.index;
Curr_Figure.kodi = tmp_Figure.kodi;
}
else
{
tmp_Figure.isDefined = Curr_Figure.isDefined;
tmp_Figure.X = Curr_Figure.X;
tmp_Figure.Y = Curr_Figure.Y;
tmp_Figure.index = Curr_Figure.index;
tmp_Figure.kodi = Curr_Figure.kodi;
}
}
bool has_Other_Figures(int par_PlayerColor)
{
bool result = false;
for (var index = 0; index < All_Figures_Without_King.Length; index++)
{
if (par_PlayerColor == 1)
{
if (Board_Array.ToList().IndexOf(All_Figures_Without_King[index].ToString().ToUpper()) > -1)
{
result = true;
break;
}
}
else
{
if (Board_Array.ToList().IndexOf(All_Figures_Without_King[index].ToString().ToLower()) > -1)
{
result = true;
break;
}
}
}
return result;
}
private void TimerGameCallback(Object stateInfo)
{
Timertick();
}
public void Timertick()
{
if (Current_Move == PlayerColor)
{
if (Player_Total_Seconds > 0)
{
Player_Total_Seconds--;
compSettings.Curr_comp.PlayerTime = TimeSpan.FromSeconds(Player_Total_Seconds).ToString(@"mm\:ss");
}
else
{
Game_Over("time");
compSettings.Curr_comp.NotifyGameOver();
}
}
else
{
if (Opposite_Total_Seconds > 0)
{
Opposite_Total_Seconds--;
compSettings.Curr_comp.OppositeTime = TimeSpan.FromSeconds(Opposite_Total_Seconds).ToString(@"mm\:ss");
}
else
{
Game_Over("time");
compSettings.Curr_comp.NotifyGameOver();
}
}
compSettings.Curr_comp.Refresh();
}
public int GetPlayerScore()
{
int score = 0;
foreach (string item in Board_Array_moklulebi_Opposite_Color)
{
switch (item)
{
case "p":
score += 1;
break;
case "r":
score += 5;
break;
case "b":
case "k":
score += 3;
break;
case "q":
score += 10;
break;
default:
break;
}
}
return score;
}
public int GetOppositeScore()
{
int score = 0;
foreach (string item in Board_Array_moklulebi_Player_Color)
{
switch (item)
{
case "p":
score += 1;
break;
case "r":
score += 5;
break;
case "b":
case "k":
score += 3;
break;
case "q":
score += 10;
break;
default:
break;
}
}
return score;
}
[JSInvokable]
public void invokeFromjs(string id, string x, string y)
{
compSettings.BoardPositionX = double.Parse(x);
compSettings.BoardPositionY = double.Parse(y);
}
}
}
| 412 | 0.539363 | 1 | 0.539363 | game-dev | MEDIA | 0.525521 | game-dev | 0.815002 | 1 | 0.815002 |
STREGAsGate/GateEngine | 2,500 | Sources/GateEngine/ECS/StateMachine/StateMachine.swift | /*
* Copyright © 2025 Dustin Collins (Strega's Gate)
* All Rights Reserved.
*
* http://stregasgate.com
*/
public struct StateMachine {
public private(set) var currentState: any State
public init(initialState: any State.Type) {
self.currentState = initialState.init()
}
@MainActor
internal mutating func updateState(for entity: Entity, context: ECSContext, input: HID, deltaTime: Float) {
currentState.update(for: entity, inContext: context, input: input, withTimePassed: deltaTime)
guard currentState.canMoveToNextState(for: entity, context: context, input: input) else {return}
for state in currentState.possibleNextStates(for: entity, context: context, input: input) {
if state.canBecomeCurrentState(for: entity, from: currentState, context: context, input: input) {
currentState.willMoveToNextState(for: entity, nextState: state, context: context, input: input)
let previousState = currentState
currentState = state.init()
currentState.apply(to: entity, previousState: previousState, context: context, input: input)
currentState.update(for: entity, inContext: context, input: input, withTimePassed: deltaTime)
return
}
}
}
}
@MainActor
public protocol State {
nonisolated init()
func apply(to entity: Entity, previousState: some State, context: ECSContext, input: HID)
func update(for entity: Entity, inContext context: ECSContext, input: HID, withTimePassed deltaTime: Float)
func canMoveToNextState(for entity: Entity, context: ECSContext, input: HID) -> Bool
func possibleNextStates(for entity: Entity, context: ECSContext, input: HID) -> [any State.Type]
func willMoveToNextState(for entity: Entity, nextState: any State.Type, context: ECSContext, input: HID)
static func canBecomeCurrentState(for entity: Entity, from currentState: some State, context: ECSContext, input: HID) -> Bool
}
public extension State {
func canMoveToNextState(for entity: Entity, context: ECSContext, input: HID) -> Bool {
return true
}
func willMoveToNextState(for entity: Entity, nextState: any State.Type, context: ECSContext, input: HID) {
}
static func canBecomeCurrentState(for entity: Entity, from currentState: some State, context: ECSContext, input: HID) -> Bool {
return true
}
}
| 412 | 0.894559 | 1 | 0.894559 | game-dev | MEDIA | 0.613316 | game-dev | 0.710428 | 1 | 0.710428 |
sprunk-engine/sprunk-engine | 4,591 | doc/dependency-injection.md | # Dependency Injection Documentation
## Overview
The dependency injection system in the game engine allows for the registration, resolution, and management of dependencies within the `GameObject` hierarchy. This system is designed to facilitate the decoupling of components and promote modularity by allowing dependencies to be injected into behaviors and other objects at runtime.
## Key Components
### Containers and Dependency Resolution
**`DependencyContainer`**: Manages dependency registration and resolution using a `Map`.
It be used independently of gameobject structure. Key methods:
- `register<T>(token, instance)`: Registers a class instance.
- `resolve<T>(token)`: Resolves a registered instance by its constructor.
**Decorators**:
- `@Inject(token, recursive?)`: Injects a dependency into a property, optionally searching up the hierarchy.
- `@InjectGlobal(token)`: Injects a dependency from the global container.
### Automatic Dependency Injection with GameObjects
Every gameobject has a container that is used to resolve dependencies for its behaviors. When a behavior is added to a gameobject, the container will automatically resolve and inject any dependencies into the behavior. The system leverages the `GameObject` hierarchy, allowing dependencies to be shared across parent and child objects.
**IMPORTANT :** If you want to inject a dependency into a behavior with the `@Inject` or the `@InjectGlobal` decorator, you will need to enable experimentalDecorators in your tsconfig.json file.
```json
{
"compilerOptions": {
/* Meta decorators */
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}
```
1. **Registration**:
- Dependencies (e.g., behaviors or engine components) are registered in a `DependencyContainer` associated with a `GameObject` or the global container (`GameEngineWindow`).
2. **Injection**:
- When a `Behavior` or a child `GameObject` is added to a `GameObject`, the system scans its properties for `@Inject` or `@InjectGlobal` decorators.
- For `@Inject`:
- The dependency is resolved from the current `GameObject`'s container.
- If `recursive` is enabled, the system searches up the `GameObject` hierarchy (parent containers) for the dependency. If enabled, it can also search the global container (`GameEngineWindow`)
- For `@InjectGlobal`:
- The dependency is resolved directly from the global container (e.g., `GameEngineWindow`).
- *Note that the `@Inject` used in a GameObject resolve the dependency from the **parent** GameObject container so you don't need to set recursive to true to access the parent GameObject dependencies.*
3. **Resolution**:
- If a dependency is not found in the local or parent containers, the system falls back to the global container.
- If no matching dependency is found, an error is thrown.
## Usage Examples
### Registering and Resolving Dependencies
```typescript
const container = new DependencyContainer();
const dependency = new TestDependency();
// Register the dependency
container.register(TestDependency, dependency);
// Resolve the dependency
const resolvedDependency = container.resolve(TestDependency);
console.log(resolvedDependency.value); // Output: "Hello, World!"
```
### Injecting Dependencies into Behaviors
```typescript
class LocalDependency {
public value: string = "Local Dependency";
}
class TestBehavior {
@Inject(LocalDependency)
public localDependency: LocalDependency;
}
const gameObject = new GameObject();
const localDependency = new LocalDependency();
// Register the dependency
gameObject.addBehavior(localDependency);
const behavior = new TestBehavior();
//Here the local dependency will be injected into the behavior (but it will also register TestBehavior as a dependency)
gameObject.addBehavior(behavior);
console.log(behavior.localDependency.value); // Output: "Local Dependency"
```
### Injecting Global Dependencies
```typescript
class GlobalDependency {
public value: string = "Global Dependency";
}
class TestBehaviorWithGlobalDependencies {
@InjectGlobal(GlobalDependency)
public globalDependency: GlobalDependency;
}
const window = new GameEngineWindow(new ManualTicker());
const gameObject = new GameObject();
window.root.addChild(gameObject);
const globalDependency = new GlobalDependency();
window.injectionContainer.register(GlobalDependency, globalDependency);
const behavior = new TestBehaviorWithGlobalDependencies();
gameObject.addBehavior(behavior);
console.log(behavior.globalDependency.value); // Output: "Global Dependency"
``` | 412 | 0.894563 | 1 | 0.894563 | game-dev | MEDIA | 0.877307 | game-dev | 0.523811 | 1 | 0.523811 |
rafalh/dashfaction | 12,685 | game_patch/object/entity.cpp | #include <patch_common/CodeInjection.h>
#include <patch_common/FunHook.h>
#include <patch_common/CallHook.h>
#include <patch_common/AsmWriter.h>
#include <xlog/xlog.h>
#include "../os/console.h"
#include "../rf/entity.h"
#include "../rf/corpse.h"
#include "../rf/weapon.h"
#include "../rf/player/player.h"
#include "../rf/particle_emitter.h"
#include "../rf/os/frametime.h"
#include "../rf/sound/sound.h"
#include "../rf/debris.h"
#include "../rf/misc.h"
#include "../main/main.h"
rf::Timestamp g_player_jump_timestamp;
CodeInjection stuck_to_ground_when_jumping_fix{
0x0042891E,
[](auto& regs) {
rf::Entity* entity = regs.esi;
if (entity->local_player) {
// Skip land handling code for next 64 ms (like in PF)
g_player_jump_timestamp.set(64);
}
},
};
CodeInjection stuck_to_ground_when_using_jump_pad_fix{
0x00486B60,
[](auto& regs) {
rf::Entity* entity = regs.esi;
if (entity->local_player) {
// Skip land handling code for next 64 ms
g_player_jump_timestamp.set(64);
}
},
};
CodeInjection stuck_to_ground_fix{
0x00487F82,
[](auto& regs) {
rf::Entity* entity = regs.esi;
if (entity->local_player && g_player_jump_timestamp.valid() && !g_player_jump_timestamp.elapsed()) {
// Jump to jump handling code that sets entity to falling movement mode
regs.eip = 0x00487F7B;
}
},
};
CodeInjection entity_water_decelerate_fix{
0x0049D82A,
[](auto& regs) {
rf::Entity* entity = regs.esi;
float vel_factor = 1.0f - (rf::frametime * 4.5f);
entity->p_data.vel.x *= vel_factor;
entity->p_data.vel.y *= vel_factor;
entity->p_data.vel.z *= vel_factor;
regs.eip = 0x0049D835;
},
};
FunHook<void(rf::Entity&, rf::Vector3&)> entity_on_land_hook{
0x00419830,
[](rf::Entity& entity, rf::Vector3& pos) {
entity_on_land_hook.call_target(entity, pos);
entity.p_data.vel.y = 0.0f;
},
};
CallHook<void(rf::Entity&)> entity_make_run_after_climbing_patch{
0x00430D5D,
[](rf::Entity& entity) {
entity_make_run_after_climbing_patch.call_target(entity);
entity.p_data.vel.y = 0.0f;
},
};
FunHook<void(rf::EntityFireInfo&, int)> entity_fire_switch_parent_to_corpse_hook{
0x0042F510,
[](rf::EntityFireInfo& fire_info, int corpse_handle) {
rf::Corpse* corpse = rf::corpse_from_handle(corpse_handle);
fire_info.parent_hobj = corpse_handle;
rf::entity_fire_init_bones(&fire_info, corpse);
for (auto& emitter_ptr : fire_info.emitters) {
if (emitter_ptr) {
emitter_ptr->parent_handle = corpse_handle;
}
}
fire_info.time_limited = true;
fire_info.time = 0.0f;
corpse->corpse_flags |= 0x200;
},
};
CallHook<bool(rf::Object*)> entity_update_liquid_status_obj_is_player_hook{
{
0x004292E3,
0x0042932A,
0x004293F4,
},
[](rf::Object* obj) {
return obj == rf::local_player_entity;
},
};
CallHook<bool(const rf::Vector3&, const rf::Vector3&, rf::PhysicsData*, rf::PCollisionOut*)> entity_maybe_stop_crouching_collide_spheres_world_hook{
0x00428AB9,
[](const rf::Vector3& p1, const rf::Vector3& p2, rf::PhysicsData* pd, rf::PCollisionOut* collision) {
// Temporarly disable collisions with liquid faces
auto collision_flags = pd->collision_flags;
pd->collision_flags &= ~0x1000;
bool result = entity_maybe_stop_crouching_collide_spheres_world_hook.call_target(p1, p2, pd, collision);
pd->collision_flags = collision_flags;
return result;
},
};
CodeInjection entity_process_post_hidden_injection{
0x0041E4C8,
[](auto& regs) {
rf::Entity* ep = regs.esi;
// Make sure move sound is muted
if (ep->move_sound_handle != -1) {
rf::snd_change_3d(ep->move_sound_handle, ep->pos, rf::zero_vector, 0.0f);
}
},
};
CodeInjection entity_render_weapon_in_hands_silencer_visibility_injection{
0x00421D39,
[](auto& regs) {
rf::Entity* ep = regs.esi;
if (!rf::weapon_is_glock(ep->ai.current_primary_weapon)) {
regs.eip = 0x00421D3F;
}
},
};
CodeInjection waypoints_read_lists_oob_fix{
0x00468E54,
[](auto& regs) {
constexpr int max_waypoint_lists = 32;
int& num_waypoint_lists = addr_as_ref<int>(0x0064E398);
int index = regs.eax;
int num_lists = regs.ecx;
if (index >= max_waypoint_lists && index < num_lists) {
xlog::error("Too many waypoint lists (limit is {})! Overwritting the last list.", max_waypoint_lists);
// reduce count by one and keep index unchanged
--num_waypoint_lists;
regs.ecx = num_waypoint_lists;
// skip EBP update to fix OOB write
regs.eip = 0x00468E5B;
}
},
};
CodeInjection waypoints_read_nodes_oob_fix{
0x00468DB1,
[](auto& regs) {
constexpr int max_waypoint_list_nodes = 128;
int node_index = regs.eax + 1;
int& num_nodes = *static_cast<int*>(regs.ebp);
if (node_index >= max_waypoint_list_nodes && node_index < num_nodes) {
xlog::error("Too many waypoint list nodes (limit is {})! Overwritting the last endpoint.", max_waypoint_list_nodes);
// reduce count by one and keep node index unchanged
--num_nodes;
// Set EAX and ECX based on skipped instructions but do not update EBX to fix OOB write
regs.eax = node_index - 1;
regs.ecx = num_nodes;
regs.eip = 0x00468DB8;
}
},
};
CodeInjection entity_fire_update_all_freeze_fix{
0x0042EF31,
[](auto& regs) {
void* fire = regs.esi;
void* next_fire = regs.ebp;
if (fire == next_fire) {
// only one object was on the list and it got deleted so exit the loop
regs.eip = 0x0042F2AF;
} else {
// go to the next object
regs.esi = next_fire;
}
},
};
CodeInjection entity_process_pre_hide_riot_shield_injection{
0x0041DAFF,
[](auto& regs) {
rf::Entity* ep = regs.esi;
int hidden = regs.eax;
if (hidden) {
auto shield = rf::obj_from_handle(ep->riot_shield_handle);
if (shield) {
rf::obj_hide(shield);
}
}
},
};
constexpr int gore_setting_gibs = 2;
static FunHook entity_blood_throw_gibs_hook{
0x0042E3C0,
[](int handle) {
static const char *gib_chunk_filenames[] = {
"meatchunk1.v3d",
"meatchunk2.v3d",
"meatchunk3.v3d",
"meatchunk4.v3d",
"meatchunk5.v3d",
};
auto& gib_impact_sound_set = addr_as_ref<rf::ImpactSoundSet*>(0x0062F75C);
if (rf::player_gore_setting < gore_setting_gibs) {
return;
}
constexpr int eif_ambient = 0x800000;
rf::Entity* ep = rf::entity_from_handle(handle);
if (ep && ep->info->flags & eif_ambient) {
// bats and fish
return;
}
constexpr int flash_material = 3;
rf::Object* objp = rf::obj_from_handle(handle);
if (objp && (objp->type == rf::OT_ENTITY || objp->type == rf::OT_CORPSE) && objp->material == flash_material) {
rf::DebrisCreateStruct dcs{};
for (int i = 0; i < 10; ++i) {
dcs.pos = objp->pos;
dcs.vel.rand_quick();
dcs.vel *= 10.0; // PS2 demo uses 15
dcs.vel += objp->p_data.vel * 0.5;
dcs.orient.rand_quick();
dcs.spin.rand_quick();
float scale = rf::fl_rand_range(10.0, 25.0);
dcs.spin *= scale;
dcs.lifespan_ms = 5000; // 5 sec. PS2 demo uses 2.7 sec.
dcs.material = flash_material;
dcs.explosion_index = -1;
dcs.debris_flags = 4;
dcs.obj_flags = 0x8000; // OF_START_HIDDEN
dcs.iss = gib_impact_sound_set;
int file_index = rand() % std::size(gib_chunk_filenames);
auto dp = rf::debris_create(objp->handle, gib_chunk_filenames[file_index], 0.3, &dcs, 0, -1.0);
if (dp) {
dp->obj_flags |= rf::OF_INVULNERABLE;
}
}
}
},
};
static FunHook<float(rf::Entity*, float, int, int, int)> entity_damage_hook{
0x0041A350,
[](rf::Entity *damaged_ep, float damage, int killer_handle, int damage_type, int killer_uid) {
float result = entity_damage_hook.call_target(damaged_ep, damage, killer_handle, damage_type, killer_uid);
if (
rf::player_gore_setting >= gore_setting_gibs
&& damaged_ep->life < -100.0 // high damage taken
&& damaged_ep->material == 3 // flash material
&& (damage_type == 3 || damage_type == 9) // armor piercing bullet or scalding
&& damaged_ep->radius < 2.0 // make sure only small entities use gibs
) {
damaged_ep->entity_flags = damaged_ep->entity_flags | 0x80; // throw gibs
}
return result;
},
};
CallHook<void(rf::Entity&)> entity_update_muzzle_flash_light_hook{
0x0041E814,
[](rf::Entity& ep) {
if (g_game_config.muzzle_flash) {
entity_update_muzzle_flash_light_hook.call_target(ep);
}
},
};
ConsoleCommand2 muzzle_flash_cmd{
"muzzle_flash",
[]() {
g_game_config.muzzle_flash = !g_game_config.muzzle_flash;
g_game_config.save();
rf::console::print("Muzzle flash lights are {}", g_game_config.muzzle_flash ? "enabled" : "disabled");
},
"Toggle muzzle flash dynamic lights",
};
ConsoleCommand2 gibs_cmd{
"gibs",
[]() {
rf::player_gore_setting = rf::player_gore_setting == gore_setting_gibs ? 1 : gore_setting_gibs;
rf::console::print("Gibs are {}", rf::player_gore_setting == gore_setting_gibs ? "enabled" : "disabled");
},
};
void entity_do_patch()
{
// Fix player being stuck to ground when jumping, especially when FPS is greater than 200
stuck_to_ground_when_jumping_fix.install();
stuck_to_ground_when_using_jump_pad_fix.install();
stuck_to_ground_fix.install();
// Fix water deceleration on high FPS
AsmWriter(0x0049D816).nop(5);
entity_water_decelerate_fix.install();
// Fix flee AI mode on high FPS by avoiding clearing velocity in Y axis in EntityMakeRun
AsmWriter(0x00428121, 0x0042812B).nop();
AsmWriter(0x0042809F, 0x004280A9).nop();
entity_on_land_hook.install();
entity_make_run_after_climbing_patch.install();
// Increase entity simulation max distance
// TODO: create a config property for this
if (g_game_config.disable_lod_models) {
write_mem<float>(0x00589548, 100.0f);
}
// Fix crash when particle emitter allocation fails during entity ignition
entity_fire_switch_parent_to_corpse_hook.install();
// Fix buzzing sound when some player is floating in water
entity_update_liquid_status_obj_is_player_hook.install();
// Fix entity staying in crouched state after entering liquid
entity_maybe_stop_crouching_collide_spheres_world_hook.install();
// Use local_player variable for weapon shell distance calculation instead of local_player_entity
// in entity_eject_shell. Fixed debris pool being exhausted when local player is dead.
AsmWriter(0x0042A223, 0x0042A232).mov(asm_regs::ecx, {&rf::local_player});
// Fix move sound not being muted if entity is created hidden (example: jeep in L18S3)
entity_process_post_hidden_injection.install();
// Do not show glock with silencer in 3rd person view if current primary weapon is not a glock
entity_render_weapon_in_hands_silencer_visibility_injection.install();
// Fix OOB writes in waypoint list read code
waypoints_read_lists_oob_fix.install();
waypoints_read_nodes_oob_fix.install();
// Fix possible freeze when burning entity is destroyed
entity_fire_update_all_freeze_fix.install();
// Hide riot shield third person model if entity is hidden (e.g. in cutscenes)
entity_process_pre_hide_riot_shield_injection.install();
// Add gibs support
entity_blood_throw_gibs_hook.install();
entity_damage_hook.install();
// Don't create muzzle flash lights
entity_update_muzzle_flash_light_hook.install();
// Commands
gibs_cmd.register_cmd();
muzzle_flash_cmd.register_cmd();
}
| 412 | 0.971574 | 1 | 0.971574 | game-dev | MEDIA | 0.969526 | game-dev | 0.960603 | 1 | 0.960603 |
emd4600/Spore-ModAPI | 6,497 | Spore ModAPI/Spore/Simulator/cScenarioPlayMode.h | #pragma once
#include <Spore\App\IMessageListener.h>
#include <Spore\App\MessageListenerData.h>
#include <Spore\Simulator\cScenarioGoal.h>
#include <Spore\Audio\AudioSystem.h>
#include <Spore\MathUtils.h>
#include <EASTL\string.h>
#include <EASTL\map.h>
#include <EASTL\vector.h>
#define cScenarioPlayModePtr eastl::intrusive_ptr<Simulator::cScenarioPlayMode>
namespace Simulator
{
class cScenarioPlayModeGoal
{
public:
/* 00h */ bool mIsCompleted;
/* 01h */ bool field_1; // true if goal is collect, bring or allyWith
/// How many of the tasks in this goal have been completed
/* 04h */ int mCount;
/// Maps cGameData ID to ??
/* 08h */ eastl::map<uint32_t, int> field_8;
/* 24h */ cScenarioGoal mGoal;
};
ASSERT_SIZE(cScenarioPlayModeGoal, 0x1AC);
struct cScenarioPlaySummary
{
/* 00h */ int mNumCreaturesKilled;
/* 04h */ int mNumBuildingsDestroyed;
/* 08h */ int mNumVehiclesDestroyed;
/* 0Ch */ int mNumCastMembersDefended;
/* 10h */ int mNumCreaturesBefriended;
/* 14h */ int mNumObjectsCollected;
/* 18h */ int field_18;
/* 1Ch */ int mNumGoalsCompleted;
/* 20h */ int mNumDeaths;
/* 24h */ int mNumPosseMembersLost;
/* 28h */ int mAmountDamageDealt;
/* 2Ch */ int mNumTimesUsedJetPack;
/* 30h */ int mNumTimesUsedSprint;
/* 34h */ int mNumBarrelsDestroyed;
/* 38h */ int mNumCastMembersTalkedTo;
/* 3Ch */ float mAmountHealthRegained;
/* 40h */ float mAmountDamageReceived;
/* 44h */ float mAmountEnergyUsed;
};
ASSERT_SIZE(cScenarioPlaySummary, 0x48);
class cScenarioPlayMode
: public App::IUnmanagedMessageListener
, public DefaultRefCounted
{
public:
//TODO check sub_F1EFC0
/// Called when starting the adventure in Play Mode.
void Initialize();
/// Sets the current act index of the active adventure.
void SetCurrentAct(int actIndex, bool = false);
/// Skips the adventure up to the given act index. Also works in reverse, i. e. going back to previous acts in the adventure.
/// Using the same index as the current act will reset the adventure to the beginning of said act.
void JumpToAct(int actIndex);
/// Sets the active state of the adventure.
void SetState(ScenarioPlayModeState state);
/// Updates the current, active goals of the adventure.
bool UpdateGoals();
/// Update function of the adventure.
void Update(int deltaTime);
/// Completes the act, then moves the adventure into the next act. If in the last act, the adventure completes.
void CompleteAct();
/// Called by Update(). Checks if the current goals are clearable or not.
void CheckGoalProgress();
/// Removes objects that are supposed to be invisible during the current act.
static void RemoveInvisibleClasses();
static void ReadScenarioTuning();
public:
/* 0Ch */ cScenarioPlaySummary mSummary;
/* 54h */ eastl::string16 mFailReason;
/// Goals for the current act
/* 64h */ eastl::vector<cScenarioPlayModeGoal> mCurrentGoals;
/* 78h */ int field_78; // not initialized
/* 7Ch */ App::MessageListenerData mMessageListenerData;
/// Current state of the adventure play mode.
/// 0 is pre-init in editor play mode, 1 is intro, 2 seems to be pre-init in quick-play, 3 is gameplay, 5 is adventure completed and 6 is adventure failed (death or failed/invalid goals)
/* 90h */ ScenarioPlayModeState mCurrentPlayModeState; // not initialized
/// Controls what state the ending cinematic of the adventure is in. Set to 0 when ending procedure begins, 1 when cinematic activates, and 2 after player leaves the cinematic sequence.
/* 94h */ int mCurrentEndCinematicState; // not initialized
/// The clock activates when mCurrentEndCinematicState is set to 0. It counts up to around 2000 units (milliseconds), after which the ending cinematic activates and mCurrentEndCinematicState is set to 1.
/* 98h */ Clock mCinematicDelay;
/* B0h */ int field_B0; // not initialized
/* B4h */ int field_B4; // not initialized
/// Index of the current act (0 is first act, 1 is second, etc)
/* B8h */ int mCurrentActIndex; // not initialized
/// Time limit of the current act, in milliseconds (negative number if no time limit)
/* BCh */ long mTimeLimitMS;
/// The playtime of the current adventure in milliseconds. It pauses counting when the game is paused, and it records its count to display it at the results screen.
/// If the adventure is shared, it will also be sent to the adventure's high scores in the Spore servers if the player is logged in.
/* C0h */ int mCurrentTimeMS;
/// The amount of Spore points the captain is rewarded at the end of a successful adventure.
/* C4h */ int mAdventurePoints; // not initialized
/* C8h */ int field_C8; // not initialized
/* CCh */ int field_CC; // not initialized
/* D0h */ int field_D0; // not initialized
/// Index of the dialog box being displayed during talk-to goal cinematic (-1 is the initial fade-in + creature greeting animation, 0 is first dialog box, 1 is second etc.)
/* D4h */ int mCurrentDialogBoxIndex; // not initialized
/* D8h */ int field_D8; // not initialized
/// Used for move-to goals. Distance of the nearest target to the player.
/* DCh */ float mDistanceToClosestMoveToTarget;
/// Coordinates of the move-to goal target's location.
/* E0h */ Math::Vector3 mMoveToGoalLocation;
/* ECh */ bool field_EC;
/* F0h */ Audio::AudioTrack mMusicTrack;
/* F4h */ uint32_t mCurrentMusicId;
/// The duration the captain fade-in effect is active during intro cutscene. Counts down to 0.
/* F8h */ float mIntroFadeinTimer;
/// Set to true when mIntroFadeinTimer begins counting. Set to false when mIntroBeamdownTimer is less than or equal to 0.
/* FCh */ bool mIsIntroFadeinActive;
/// Initially set to false but set to true when adventure begins.
/* FDh */ bool mIsAdventureActive;
/* 100h */ int field_100;
};
ASSERT_SIZE(cScenarioPlayMode, 0x108);
namespace Addresses(cScenarioPlayMode)
{
DeclareAddress(Initialize); // 0xF1F450, 0xF1F060
DeclareAddress(SetCurrentAct); // 0xF1F260, 0xF1EE70
DeclareAddress(JumpToAct); // 0xF1F7B0, 0xF1F3C0
DeclareAddress(SetState); // 0xF1ADB0, 0xF1A9C0
DeclareAddress(UpdateGoals); // 0xF1C780, 0xF1C390
DeclareAddress(Update); // 0xF1FD50, 0xF1F960
DeclareAddress(CompleteAct); // 0xF1F680, 0xF1F290
DeclareAddress(CheckGoalProgress); // 0xF1F8D0, 0xF1F4E0
DeclareAddress(RemoveInvisibleClasses); // 0xF1AFD0, 0xF1ABE0
DeclareAddress(ReadScenarioTuning); // 0xF1E2F0, 0xF1DF00
}
} | 412 | 0.729796 | 1 | 0.729796 | game-dev | MEDIA | 0.919298 | game-dev | 0.766537 | 1 | 0.766537 |
mellinoe/veldrid-samples | 7,137 | src/Common/RawList.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
#if !VALIDATE
using System.Diagnostics;
#endif
namespace Common
{
/// <summary>
/// A resizable, generic list which exposes direct access to its underlying array.
/// </summary>
/// <typeparam name="T">The type of elements stored in the list.</typeparam>
public class RawList<T> : IEnumerable<T>
{
private T[] _items;
private uint _count;
public const uint DefaultCapacity = 4;
private const float GrowthFactor = 2f;
public RawList() : this(DefaultCapacity) { }
public RawList(uint capacity)
{
#if VALIDATE
if (capacity > int.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(capacity));
}
#else
Debug.Assert(capacity <= int.MaxValue);
#endif
_items = capacity == 0 ? Array.Empty<T>() : new T[capacity];
}
public uint Count
{
get => _count;
set
{
Resize(value);
}
}
public T[] Items => _items;
public ArraySegment<T> ArraySegment => new ArraySegment<T>(_items, 0, (int)_count);
public ref T this[uint index]
{
get
{
ValidateIndex(index);
return ref _items[index];
}
}
public ref T this[int index]
{
get
{
ValidateIndex(index);
return ref _items[index];
}
}
public void Add(ref T item)
{
if (_count == _items.Length)
{
Array.Resize(ref _items, (int)(_items.Length * GrowthFactor));
}
_items[_count] = item;
_count += 1;
}
public void Add(T item)
{
if (_count == _items.Length)
{
Array.Resize(ref _items, (int)(_items.Length * GrowthFactor));
}
_items[_count] = item;
_count += 1;
}
public void AddRange(T[] items)
{
#if VALIDATE
if (items == null)
{
throw new ArgumentNullException(nameof(items));
}
#else
Debug.Assert(items != null);
#endif
int requiredSize = (int)(_count + items.Length);
if (requiredSize > _items.Length)
{
Array.Resize(ref _items, (int)(requiredSize * GrowthFactor));
}
Array.Copy(items, 0, _items, (int)_count, items.Length);
_count += (uint)items.Length;
}
public void AddRange(IEnumerable<T> items)
{
#if VALIDATE
if (items == null)
{
throw new ArgumentNullException(nameof(items));
}
#else
Debug.Assert(items != null);
#endif
foreach (T item in items)
{
Add(item);
}
}
public void Replace(uint index, ref T item)
{
ValidateIndex(index);
_items[index] = item;
}
public void Resize(uint count)
{
Array.Resize(ref _items, (int)count);
_count = count;
}
public void Replace(uint index, T item) => Replace(index, ref item);
public bool Remove(ref T item)
{
bool contained = GetIndex(item, out uint index);
if (contained)
{
CoreRemoveAt(index);
}
return contained;
}
public bool Remove(T item)
{
bool contained = GetIndex(item, out uint index);
if (contained)
{
CoreRemoveAt(index);
}
return contained;
}
public void RemoveAt(uint index)
{
ValidateIndex(index);
CoreRemoveAt(index);
}
public void Clear()
{
Array.Clear(_items, 0, _items.Length);
}
public bool GetIndex(T item, out uint index)
{
int signedIndex = Array.IndexOf(_items, item);
index = (uint)signedIndex;
return signedIndex != -1;
}
public void Sort() => Sort(null);
public void Sort(IComparer<T> comparer)
{
#if VALIDATE
if (comparer == null)
{
throw new ArgumentNullException(nameof(comparer));
}
#else
Debug.Assert(comparer != null);
#endif
Array.Sort(_items, comparer);
}
public void TransformAll(Func<T, T> transformation)
{
#if VALIDATE
if (transformation == null)
{
throw new ArgumentNullException(nameof(transformation));
}
#else
Debug.Assert(transformation != null);
#endif
for (int i = 0; i < _count; i++)
{
_items[i] = transformation(_items[i]);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void CoreRemoveAt(uint index)
{
_count -= 1;
Array.Copy(_items, (int)index + 1, _items, (int)index, (int)(_count - index));
_items[_count] = default(T);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ValidateIndex(uint index)
{
#if VALIDATE
if (index >= _count)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
#else
Debug.Assert(index < _count);
#endif
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ValidateIndex(int index)
{
#if VALIDATE
if (index < 0 || index >= _count)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
#else
Debug.Assert(index >= 0 && index < _count);
#endif
}
public Enumerator GetEnumerator() => new Enumerator(this);
IEnumerator<T> IEnumerable<T>.GetEnumerator() => GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public struct Enumerator : IEnumerator<T>
{
private RawList<T> _list;
private int _currentIndex;
public Enumerator(RawList<T> list)
{
_list = list;
_currentIndex = 0;
}
public T Current => _list._items[_currentIndex];
object IEnumerator.Current => Current;
public bool MoveNext()
{
if (_currentIndex != _list._count - 1)
{
_currentIndex += 1;
return true;
}
return false;
}
public void Reset()
{
_currentIndex = 0;
}
public void Dispose() { }
}
}
} | 412 | 0.828379 | 1 | 0.828379 | game-dev | MEDIA | 0.190382 | game-dev | 0.960584 | 1 | 0.960584 |
ixray-team/ixray-1.6-stcop | 4,115 | src/xrGame/stalker_animation_manager.cpp | ////////////////////////////////////////////////////////////////////////////
// Module : stalker_animation_manager.cpp
// Created : 25.02.2003
// Modified : 19.11.2004
// Author : Dmitriy Iassenev
// Description : Stalker animation manager
////////////////////////////////////////////////////////////////////////////
#include "StdAfx.h"
#include "stalker_animation_manager.h"
#include "ai/stalker/ai_stalker.h"
#include "stalker_animation_data_storage.h"
#include "stalker_animation_data.h"
#include "stalker_movement_manager_smart_cover.h"
#include "CharacterPhysicsSupport.h"
// TODO:
// stalker animation manager consists of 5 independent managers,
// they should be represented with the different classes:
// * head
// * torso
// * legs
// * globals
// * script
CStalkerAnimationManager::CStalkerAnimationManager (CAI_Stalker *object) :
m_object ( object ),
m_global ( object ),
m_head ( object ),
m_torso ( object ),
m_legs ( object ),
m_script ( object ),
m_start_new_script_animation( false )
{
}
void CStalkerAnimationManager::reinit ()
{
m_direction_start = 0;
m_current_direction = eMovementDirectionForward;
m_target_direction = eMovementDirectionForward;
m_change_direction_time = 0;
m_looking_back = 0;
m_no_move_actual = false;
m_script_animations.clear ();
m_global.reset ();
m_head.reset ();
m_torso.reset ();
m_legs.reset ();
m_script.reset ();
m_legs.step_dependence (true);
m_global.step_dependence (true);
m_script.step_dependence (true);
m_global.global_animation (true);
m_script.global_animation (true);
m_call_script_callback = false;
m_previous_speed = 0.f;
m_target_speed = 0.f;
m_last_non_zero_speed = m_target_speed;
m_special_danger_move = false;
}
void CStalkerAnimationManager::reload ()
{
m_visual = object().Visual();
m_crouch_state_config = object().SpecificCharacter().crouch_type();
VERIFY ((m_crouch_state_config == 0) || (m_crouch_state_config == 1) || (m_crouch_state_config == -1));
m_crouch_state = m_crouch_state_config;
if (object().already_dead())
return;
m_skeleton_animated = smart_cast<IKinematicsAnimated*>(m_visual);
VERIFY (m_skeleton_animated);
m_data_storage = stalker_animation_data_storage().object(m_skeleton_animated);
VERIFY (m_data_storage);
if (!object().g_Alive())
return;
#ifdef USE_HEAD_BONE_PART_FAKE
VERIFY (!m_data_storage->m_head_animations.A.empty());
u16 bone_part = m_skeleton_animated->LL_GetMotionDef(m_data_storage->m_head_animations.A.front())->bone_or_part;
VERIFY (bone_part != BI_NONE);
m_script_bone_part_mask = CStalkerAnimationPair::all_bone_parts ^ (1 << bone_part);
#endif
assign_bone_callbacks ();
#ifdef DEBUG
global().set_dbg_info (*object().cName(),"Global");
head().set_dbg_info (*object().cName(),"Head ");
torso().set_dbg_info (*object().cName(),"Torso ");
legs().set_dbg_info (*object().cName(),"Legs ");
script().set_dbg_info (*object().cName(),"Script");
#endif
};
void CStalkerAnimationManager::play_fx(float power_factor, int fx_index)
{
VERIFY (fx_index >= 0);
VERIFY (fx_index < (int)m_data_storage->m_part_animations.A[object().movement().body_state()].m_global.A[0].A.size());
#ifdef DEBUG
if (psAI_Flags.is(aiAnimation)) {
LPCSTR name = m_skeleton_animated->LL_MotionDefName_dbg(m_data_storage->m_part_animations.A[object().movement().body_state()].m_global.A[0].A[fx_index]).first;
Msg ("%6d [%s][%s][%s][%f]",Device.dwTimeGlobal,*object().cName(),"FX",name,power_factor);
}
#endif
m_skeleton_animated->PlayFX (m_data_storage->m_part_animations.A[object().movement().body_state()].m_global.A[0].A[fx_index],power_factor);
}
bool CStalkerAnimationManager::standing() const {
CAI_Stalker& obj = object();
stalker_movement_manager_smart_cover& movement = obj.movement();
if (movement.speed(obj.character_physics_support()->movement()) < EPS_L)
return (true);
if (eMovementTypeStand == movement.movement_type())
return (true);
return (false);
} | 412 | 0.926978 | 1 | 0.926978 | game-dev | MEDIA | 0.916276 | game-dev | 0.825318 | 1 | 0.825318 |
CrypticMonkey33/ArchipelagoExplorersOfSky | 5,487 | worlds/adventure/Rules.py | from .Options import BatLogic, DifficultySwitchB
from worlds.generic.Rules import add_rule, set_rule, forbid_item
def set_rules(self) -> None:
world = self.multiworld
use_bat_logic = self.options.bat_logic.value == BatLogic.option_use_logic
set_rule(world.get_entrance("YellowCastlePort", self.player),
lambda state: state.has("Yellow Key", self.player))
set_rule(world.get_entrance("BlackCastlePort", self.player),
lambda state: state.has("Black Key", self.player))
set_rule(world.get_entrance("WhiteCastlePort", self.player),
lambda state: state.has("White Key", self.player))
# a future thing would be to make the bat an actual item, or at least allow it to
# be placed in a castle, which would require some additions to the rules when
# use_bat_logic is true
if not use_bat_logic:
set_rule(world.get_entrance("WhiteCastleSecretPassage", self.player),
lambda state: state.has("Bridge", self.player))
set_rule(world.get_entrance("WhiteCastlePeekPassage", self.player),
lambda state: state.has("Bridge", self.player) or
state.has("Magnet", self.player))
set_rule(world.get_entrance("BlackCastleVaultEntrance", self.player),
lambda state: state.has("Bridge", self.player) or
state.has("Magnet", self.player))
dragon_slay_check = self.options.dragon_slay_check.value
if dragon_slay_check:
if self.difficulty_switch_b == DifficultySwitchB.option_hard_with_unlock_item:
set_rule(world.get_location("Slay Yorgle", self.player),
lambda state: state.has("Sword", self.player) and
state.has("Right Difficulty Switch", self.player))
set_rule(world.get_location("Slay Grundle", self.player),
lambda state: state.has("Sword", self.player) and
state.has("Right Difficulty Switch", self.player))
set_rule(world.get_location("Slay Rhindle", self.player),
lambda state: state.has("Sword", self.player) and
state.has("Right Difficulty Switch", self.player))
else:
set_rule(world.get_location("Slay Yorgle", self.player),
lambda state: state.has("Sword", self.player))
set_rule(world.get_location("Slay Grundle", self.player),
lambda state: state.has("Sword", self.player))
set_rule(world.get_location("Slay Rhindle", self.player),
lambda state: state.has("Sword", self.player))
# really this requires getting the dot item, and having another item or enemy
# in the room, but the dot would be *super evil*
# to actually make randomized, since it is invisible. May add some options
# for how that works in the distant future, but for now, just say you need
# the bridge and black key to get to it, as that simplifies things a lot
set_rule(world.get_entrance("CreditsWall", self.player),
lambda state: state.has("Bridge", self.player) and
state.has("Black Key", self.player))
if not use_bat_logic:
set_rule(world.get_entrance("CreditsToFarSide", self.player),
lambda state: state.has("Magnet", self.player))
# bridge literally does not fit in this space, I think. I'll just exclude it
forbid_item(world.get_location("Dungeon Vault", self.player), "Bridge", self.player)
# don't put magnet in locations that can pull in-logic items out of reach unless the bat is in play
if not use_bat_logic:
forbid_item(world.get_location("Dungeon Vault", self.player), "Magnet", self.player)
forbid_item(world.get_location("Red Maze Vault Entrance", self.player), "Magnet", self.player)
forbid_item(world.get_location("Credits Right Side", self.player), "Magnet", self.player)
# and obviously we don't want to start with the game already won
forbid_item(world.get_location("Inside Yellow Castle", self.player), "Chalice", self.player)
overworld = world.get_region("Overworld", self.player)
for loc in overworld.locations:
forbid_item(loc, "Chalice", self.player)
add_rule(world.get_location("Chalice Home", self.player),
lambda state: state.has("Chalice", self.player) and state.has("Yellow Key", self.player))
# world.random.choice(overworld.locations).progress_type = LocationProgressType.PRIORITY
# all_locations = world.get_locations(self.player).copy()
# while priority_count < get_num_items():
# loc = world.random.choice(all_locations)
# if loc.progress_type == LocationProgressType.DEFAULT:
# loc.progress_type = LocationProgressType.PRIORITY
# priority_count += 1
# all_locations.remove(loc)
# TODO: Add events for dragon_slay_check and trap_bat_check. Here? Elsewhere?
# if self.dragon_slay_check == 1:
# TODO - Randomize bat and dragon start rooms and use those to determine rules
# TODO - for the requirements for the slay event (since we have to get to the
# TODO - dragons and sword to kill them). Unless the dragons are set to be items,
# TODO - which might be a funny option, then they can just be randoed like normal
# TODO - just forbidden from the vaults and all credits room locations
| 412 | 0.931432 | 1 | 0.931432 | game-dev | MEDIA | 0.839371 | game-dev | 0.978333 | 1 | 0.978333 |
Fluorohydride/ygopro-scripts | 6,144 | c92650749.lua | --マチュア・クロニクル
local s,id,o=GetID()
function s.initial_effect(c)
c:EnableCounterPermit(0x25)
aux.AddCodeList(c,78371393)
aux.AddSetNameMonsterList(c,0x1a5)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--counter
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e2:SetCode(EVENT_SPSUMMON_SUCCESS)
e2:SetRange(LOCATION_SZONE)
e2:SetOperation(s.counter)
c:RegisterEffect(e2)
--special summon
local e3=Effect.CreateEffect(c)
e3:SetCategory(CATEGORY_SPECIAL_SUMMON)
e3:SetDescription(aux.Stringid(id,0))
e3:SetCountLimit(1,id)
e3:SetType(EFFECT_TYPE_IGNITION)
e3:SetRange(LOCATION_SZONE)
e3:SetCost(s.cost1)
e3:SetTarget(s.tg1)
e3:SetOperation(s.op1)
c:RegisterEffect(e3)
--to hand from removed
local e4=Effect.CreateEffect(c)
e4:SetCategory(CATEGORY_TOHAND)
e4:SetDescription(aux.Stringid(id,1))
e4:SetCountLimit(1,id)
e4:SetType(EFFECT_TYPE_IGNITION)
e4:SetRange(LOCATION_SZONE)
e4:SetCost(s.cost2)
e4:SetTarget(s.tg2)
e4:SetOperation(s.op2)
c:RegisterEffect(e4)
--remove from deck
local e5=Effect.CreateEffect(c)
e5:SetCategory(CATEGORY_REMOVE)
e5:SetDescription(aux.Stringid(id,2))
e5:SetCountLimit(1,id)
e5:SetType(EFFECT_TYPE_IGNITION)
e5:SetRange(LOCATION_SZONE)
e5:SetCost(s.cost3)
e5:SetTarget(s.tg3)
e5:SetOperation(s.op3)
c:RegisterEffect(e5)
--destory
local e6=Effect.CreateEffect(c)
e6:SetCategory(CATEGORY_DESTROY)
e6:SetDescription(aux.Stringid(id,3))
e6:SetCountLimit(1,id)
e6:SetType(EFFECT_TYPE_IGNITION)
e6:SetRange(LOCATION_SZONE)
e6:SetCost(s.cost4)
e6:SetTarget(s.tg4)
e6:SetOperation(s.op4)
c:RegisterEffect(e6)
--to hand from deck
local e7=Effect.CreateEffect(c)
e7:SetCategory(CATEGORY_TOHAND)
e7:SetDescription(aux.Stringid(id,4))
e7:SetCountLimit(1,id)
e7:SetType(EFFECT_TYPE_IGNITION)
e7:SetRange(LOCATION_SZONE)
e7:SetCost(s.cost5)
e7:SetTarget(s.tg5)
e7:SetOperation(s.op5)
c:RegisterEffect(e7)
end
function s.cfilter(c)
return c:IsSetCard(0x1a5) or aux.IsCodeListed(c,78371393)
end
function s.counter(e,tp,eg,ep,ev,re,r,rp)
if eg:IsExists(s.cfilter,1,nil) then
e:GetHandler():AddCounter(0x25,1)
end
end
function s.cost1(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsCanRemoveCounter(tp,1,0,0x25,1,REASON_COST) end
Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription())
Duel.RemoveCounter(tp,1,0,0x25,1,REASON_COST)
end
function s.filter1(c,e,tp)
return c:IsCode(78371393) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function s.tg1(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(s.filter1,tp,LOCATION_GRAVE,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_GRAVE)
end
function s.op1(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,aux.NecroValleyFilter(s.filter1),tp,LOCATION_GRAVE,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,true,true,POS_FACEUP)
end
end
function s.cost2(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsCanRemoveCounter(tp,1,0,0x25,2,REASON_COST) end
Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription())
Duel.RemoveCounter(tp,1,0,0x25,2,REASON_COST)
end
function s.filter2(c,e,tp)
return c:IsAbleToHand()
end
function s.tg2(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true
and Duel.IsExistingMatchingCard(s.filter2,tp,LOCATION_REMOVED,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_REMOVED)
end
function s.op2(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,s.filter2,tp,LOCATION_REMOVED,0,1,1,nil,e,tp)
local tc=g:GetFirst()
if g:GetCount()>0 then
Duel.HintSelection(g)
Duel.SendtoHand(tc,nil,REASON_EFFECT)
end
end
function s.cost3(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsCanRemoveCounter(tp,1,0,0x25,3,REASON_COST) end
Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription())
Duel.RemoveCounter(tp,1,0,0x25,3,REASON_COST)
end
function s.tg3(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(Card.IsAbleToRemove,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_REMOVE,nil,1,tp,LOCATION_DECK)
end
function s.op3(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectMatchingCard(tp,Card.IsAbleToRemove,tp,LOCATION_DECK,0,1,1,nil)
local tg=g:GetFirst()
if tg==nil then return end
Duel.Remove(tg,POS_FACEUP,REASON_EFFECT)
end
function s.cost4(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsCanRemoveCounter(tp,1,0,0x25,4,REASON_COST) end
Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription())
Duel.RemoveCounter(tp,1,0,0x25,4,REASON_COST)
end
function s.tg4(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(aux.TRUE,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,nil) end
local g=Duel.GetMatchingGroup(aux.TRUE,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0)
end
function s.op4(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectMatchingCard(tp,aux.TRUE,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,1,nil)
if #g>0 then
Duel.HintSelection(g)
Duel.Destroy(g,REASON_EFFECT)
end
end
function s.cost5(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsCanRemoveCounter(tp,1,0,0x25,5,REASON_COST) end
Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription())
Duel.RemoveCounter(tp,1,0,0x25,5,REASON_COST)
end
function s.filter5(c,e,tp)
return c:IsAbleToHand() and c:IsCode(48130397)
end
function s.tg5(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true
and Duel.IsExistingMatchingCard(s.filter5,tp,LOCATION_DECK,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function s.op5(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,s.filter5,tp,LOCATION_DECK,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SendtoHand(g:GetFirst(),nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
| 412 | 0.901299 | 1 | 0.901299 | game-dev | MEDIA | 0.978969 | game-dev | 0.958771 | 1 | 0.958771 |
The-Aether-Team/The-Aether | 3,498 | src/main/java/com/aetherteam/aether/entity/passive/Phyg.java | package com.aetherteam.aether.entity.passive;
import com.aetherteam.aether.AetherTags;
import com.aetherteam.aether.client.AetherSoundEvents;
import com.aetherteam.aether.entity.AetherEntityTypes;
import com.aetherteam.aether.entity.ai.goal.FallingRandomStrollGoal;
import net.minecraft.core.BlockPos;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.AgeableMob;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.ai.attributes.AttributeSupplier;
import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraft.world.entity.ai.goal.*;
import net.minecraft.world.entity.animal.Pig;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.Vec3;
import net.neoforged.api.distmarker.Dist;
import net.neoforged.api.distmarker.OnlyIn;
import javax.annotation.Nullable;
public class Phyg extends WingedAnimal {
public Phyg(EntityType<? extends Phyg> type, Level level) {
super(type, level);
}
@Override
protected void registerGoals() {
this.goalSelector.addGoal(0, new FloatGoal(this));
this.goalSelector.addGoal(1, new PanicGoal(this, 1.25));
this.goalSelector.addGoal(3, new BreedGoal(this, 1.0));
this.goalSelector.addGoal(4, new TemptGoal(this, 1.2, Ingredient.of(AetherTags.Items.PHYG_TEMPTATION_ITEMS), false));
this.goalSelector.addGoal(5, new FollowParentGoal(this, 1.1));
this.goalSelector.addGoal(6, new FallingRandomStrollGoal(this, 1.0));
this.goalSelector.addGoal(7, new LookAtPlayerGoal(this, Player.class, 6.0F));
this.goalSelector.addGoal(8, new RandomLookAroundGoal(this));
}
public static AttributeSupplier.Builder createMobAttributes() {
return Mob.createMobAttributes()
.add(Attributes.MAX_HEALTH, 10.0)
.add(Attributes.MOVEMENT_SPEED, 0.25);
}
@Override
public boolean isFood(ItemStack stack) {
return stack.is(AetherTags.Items.PHYG_TEMPTATION_ITEMS);
}
@Nullable
@Override
protected SoundEvent getAmbientSound() {
return AetherSoundEvents.ENTITY_PHYG_AMBIENT.get();
}
@Nullable
@Override
protected SoundEvent getHurtSound(DamageSource damageSource) {
return AetherSoundEvents.ENTITY_PHYG_HURT.get();
}
@Nullable
@Override
protected SoundEvent getDeathSound() {
return AetherSoundEvents.ENTITY_PHYG_DEATH.get();
}
@Nullable
@Override
protected SoundEvent getSaddledSound() {
return AetherSoundEvents.ENTITY_PHYG_SADDLE.get();
}
@Override
protected void playStepSound(BlockPos pos, BlockState state) {
this.playSound(AetherSoundEvents.ENTITY_PHYG_STEP.get(), 0.15F, 1.0F);
}
@Nullable
@Override
public AgeableMob getBreedOffspring(ServerLevel level, AgeableMob entity) {
return AetherEntityTypes.PHYG.get().create(level);
}
/**
* [CODE COPY] - {@link Pig#getLeashOffset()}.
*/
@OnlyIn(Dist.CLIENT)
public Vec3 getLeashOffset() {
return new Vec3(0.0, 0.6F * this.getEyeHeight(), this.getBbWidth() * 0.4F);
}
}
| 412 | 0.798387 | 1 | 0.798387 | game-dev | MEDIA | 0.989917 | game-dev | 0.829693 | 1 | 0.829693 |
resonance-audio/resonance-audio-unity-sdk | 10,753 | Assets/ResonanceAudio/Scripts/ResonanceAudioRoomManager.cs | // Copyright 2017 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
/// A class that manages the room effects to be applied to spatial audio sources in the scene.
public static class ResonanceAudioRoomManager {
/// Material type that determines the acoustic properties of a room surface.
public enum SurfaceMaterial {
Transparent = 0, ///< Transparent
AcousticCeilingTiles = 1, ///< Acoustic ceiling tiles
BrickBare = 2, ///< Brick, bare
BrickPainted = 3, ///< Brick, painted
ConcreteBlockCoarse = 4, ///< Concrete block, coarse
ConcreteBlockPainted = 5, ///< Concrete block, painted
CurtainHeavy = 6, ///< Curtain, heavy
FiberglassInsulation = 7, ///< Fiberglass insulation
GlassThin = 8, ///< Glass, thin
GlassThick = 9, ///< Glass, thick
Grass = 10, ///< Grass
LinoleumOnConcrete = 11, ///< Linoleum on concrete
Marble = 12, ///< Marble
Metal = 13, ///< Galvanized sheet metal
ParquetOnConcrete = 14, ///< Parquet on concrete
PlasterRough = 15, ///< Plaster, rough
PlasterSmooth = 16, ///< Plaster, smooth
PlywoodPanel = 17, ///< Plywood panel
PolishedConcreteOrTile = 18, ///< Polished concrete or tile
Sheetrock = 19, ///< Sheetrock
WaterOrIceSurface = 20, ///< Water or ice surface
WoodCeiling = 21, ///< Wood ceiling
WoodPanel = 22 ///< Wood panel
}
/// A serializable dictionary class that maps surface materials from GUIDs. The dictionary is
/// serialized to two lists, one for the keys (GUIDs) and one for the values (surface materials).
[Serializable]
public class SurfaceMaterialDictionary
: Dictionary<string, SurfaceMaterial>, ISerializationCallbackReceiver {
public SurfaceMaterialDictionary() {
guids = new List<string>();
surfaceMaterials = new List<SurfaceMaterial>();
}
/// Serializes the dictionary to two lists.
public void OnBeforeSerialize() {
guids.Clear();
surfaceMaterials.Clear();
foreach (var keyValuePair in this) {
guids.Add(keyValuePair.Key);
surfaceMaterials.Add(keyValuePair.Value);
}
}
/// Deserializes the two lists and fills the dictionary.
public void OnAfterDeserialize() {
this.Clear();
for (int i = 0; i < guids.Count; ++i) {
this.Add(guids[i], surfaceMaterials[i]);
}
}
// List of keys.
[SerializeField]
private List<string> guids;
// List of values.
[SerializeField]
private List<SurfaceMaterial> surfaceMaterials;
}
/// Returns the room effects gain of the current room region for the given |sourcePosition|.
public static float ComputeRoomEffectsGain(Vector3 sourcePosition) {
if (roomEffectsRegions.Count == 0) {
// No room effects present, return default value.
return 1.0f;
}
float distanceToRoom = 0.0f;
var lastRoomEffectsRegion = roomEffectsRegions[roomEffectsRegions.Count - 1];
if (lastRoomEffectsRegion.room != null) {
var room = lastRoomEffectsRegion.room;
bounds.size = Vector3.Scale(room.transform.lossyScale, room.size);
Quaternion rotationInverse = Quaternion.Inverse(room.transform.rotation);
Vector3 relativePosition = rotationInverse * (sourcePosition - room.transform.position);
Vector3 closestPosition = bounds.ClosestPoint(relativePosition);
distanceToRoom = Vector3.Distance(relativePosition, closestPosition);
} else {
var reverbProbe = lastRoomEffectsRegion.reverbProbe;
Vector3 relativePosition = sourcePosition - reverbProbe.transform.position;
if (reverbProbe.regionShape == ResonanceAudioReverbProbe.RegionShape.Box) {
bounds.size = reverbProbe.GetScaledBoxRegionSize();
Quaternion rotationInverse = Quaternion.Inverse(reverbProbe.transform.rotation);
relativePosition = rotationInverse * relativePosition;
Vector3 closestPosition = bounds.ClosestPoint(relativePosition);
distanceToRoom = Vector3.Distance(relativePosition, closestPosition);
} else {
float radius = reverbProbe.GetScaledSphericalRegionRadius();
distanceToRoom = Mathf.Max(0.0f, relativePosition.magnitude - radius);
}
}
return ComputeRoomEffectsAttenuation(distanceToRoom);
}
/// Adds or removes a Resonance Audio room depending on whether the listener is inside |room|.
public static void UpdateRoom(ResonanceAudioRoom room) {
UpdateRoomEffectsRegions(room, IsListenerInsideRoom(room));
UpdateRoomEffects();
}
/// Removes a Resonance Audio room.
public static void RemoveRoom(ResonanceAudioRoom room) {
UpdateRoomEffectsRegions(room, false);
UpdateRoomEffects();
}
/// Adds or removes a Resonance Audio reverb probe depending on whether the listener is inside
/// |reverbProbe|.
public static void UpdateReverbProbe(ResonanceAudioReverbProbe reverbProbe) {
UpdateRoomEffectsRegions(reverbProbe, IsListenerInsideVisibleReverbProbe(reverbProbe));
UpdateRoomEffects();
}
/// Removes a Resonance Audio reverb probe.
public static void RemoveReverbProbe(ResonanceAudioReverbProbe reverbProbe) {
UpdateRoomEffectsRegions(reverbProbe, false);
UpdateRoomEffects();
}
// A struct to encapsulate either a ResonanceAudioRoom or a ResonanceAudioReverbProbe. Only one of
// |room| and |reverbProbe| is not null.
private struct RoomEffectsRegion {
/// Currently active room/reverb probe.
public ResonanceAudioRoom room;
public ResonanceAudioReverbProbe reverbProbe;
public RoomEffectsRegion(ResonanceAudioRoom room, ResonanceAudioReverbProbe reverbProbe) {
this.room = room;
this.reverbProbe = reverbProbe;
}
}
// Container to store the candidate room effects regions in the scene.
private static List<RoomEffectsRegion> roomEffectsRegions = new List<RoomEffectsRegion>();
// Boundaries instance to be used in room detection logic.
private static Bounds bounds = new Bounds(Vector3.zero, Vector3.zero);
// Updates the list of room effects regions with the given |room|.
private static void UpdateRoomEffectsRegions(ResonanceAudioRoom room, bool isEnabled) {
int regionIndex = -1;
for (int i = 0; i < roomEffectsRegions.Count; ++i) {
if (roomEffectsRegions[i].room == room) {
regionIndex = i;
break;
}
}
if (isEnabled && regionIndex == -1) {
roomEffectsRegions.Add(new RoomEffectsRegion(room ,null));
} else if (!isEnabled && regionIndex != -1) {
roomEffectsRegions.RemoveAt(regionIndex);
}
}
// Updates the list of room effects regions with the given |reverbProbe|.
private static void UpdateRoomEffectsRegions(ResonanceAudioReverbProbe reverbProbe,
bool isEnabled) {
int regionIndex = -1;
for (int i = 0; i < roomEffectsRegions.Count; ++i) {
if (roomEffectsRegions[i].reverbProbe == reverbProbe) {
regionIndex = i;
break;
}
}
if (isEnabled && regionIndex == -1) {
roomEffectsRegions.Add(new RoomEffectsRegion(null, reverbProbe));
} else if (!isEnabled && regionIndex != -1) {
roomEffectsRegions.RemoveAt(regionIndex);
}
}
// Updates the room effects of the environment with respect to the current room configuration.
private static void UpdateRoomEffects() {
if (roomEffectsRegions.Count == 0) {
ResonanceAudio.DisableRoomEffects();
return;
}
var lastRoomEffectsRegion = roomEffectsRegions[roomEffectsRegions.Count - 1];
if (lastRoomEffectsRegion.room != null) {
ResonanceAudio.UpdateRoom(lastRoomEffectsRegion.room);
} else {
ResonanceAudio.UpdateReverbProbe(lastRoomEffectsRegion.reverbProbe);
}
}
// Returns the room effects attenuation with respect to the given |distance| to a room region.
private static float ComputeRoomEffectsAttenuation(float distanceToRoom) {
// Shift the attenuation curve by 1.0f to avoid zero division.
float distance = 1.0f + distanceToRoom;
return 1.0f / Mathf.Pow(distance, 2.0f);
}
// Returns whether the listener is currently inside the given |room| boundaries.
private static bool IsListenerInsideRoom(ResonanceAudioRoom room) {
bool isInside = false;
Transform listenerTransform = ResonanceAudio.ListenerTransform;
if (listenerTransform != null) {
Vector3 relativePosition = listenerTransform.position - room.transform.position;
Quaternion rotationInverse = Quaternion.Inverse(room.transform.rotation);
bounds.size = Vector3.Scale(room.transform.lossyScale, room.size);
isInside = bounds.Contains(rotationInverse * relativePosition);
}
return isInside;
}
// Returns whether the listener is currently inside the application region of the given
// |reverb_probe|, subject to the visibility test if |reverbProbe.onlyWhenVisible| is true.
private static bool IsListenerInsideVisibleReverbProbe(ResonanceAudioReverbProbe reverbProbe) {
Transform listenerTransform = ResonanceAudio.ListenerTransform;
if (listenerTransform == null) {
return false;
}
Vector3 relativePosition = listenerTransform.position - reverbProbe.transform.position;
// First the containing test.
if (reverbProbe.regionShape == ResonanceAudioReverbProbe.RegionShape.Sphere) {
if (relativePosition.magnitude > reverbProbe.GetScaledSphericalRegionRadius()) {
return false;
}
} else {
Quaternion rotationInverse = Quaternion.Inverse(reverbProbe.transform.rotation);
bounds.size = reverbProbe.GetScaledBoxRegionSize();
if (!bounds.Contains(rotationInverse * relativePosition)) {
return false;
}
}
// Then the visibility test.
if (reverbProbe.onlyApplyWhenVisible &&
ResonanceAudio.ComputeOcclusion(reverbProbe.transform) > 0.0f) {
return false;
}
return true;
}
}
| 412 | 0.916355 | 1 | 0.916355 | game-dev | MEDIA | 0.935419 | game-dev | 0.970164 | 1 | 0.970164 |
ImplFerris/pico-rex | 3,423 | src/main.rs | #![no_std]
#![no_main]
mod game;
mod sprites;
// use core::sync::atomic::{AtomicBool, Ordering};
use embassy_executor::Spawner;
use embassy_rp::block::ImageDef;
use embassy_rp::peripherals::I2C1;
use embassy_rp::{self as hal, i2c};
use embassy_time::Timer;
use game::{Game, GameState};
use {defmt_rtt as _, panic_probe as _};
use embassy_rp::bind_interrupts;
use embassy_rp::gpio::{Input, Level, Output, Pull};
use ssd1306::mode::DisplayConfig;
use ssd1306::prelude::DisplayRotation;
use ssd1306::size::DisplaySize128x64;
use ssd1306::{I2CDisplayInterface, Ssd1306};
/// Tell the Boot ROM about our application
#[link_section = ".start_block"]
#[used]
pub static IMAGE_DEF: ImageDef = hal::block::ImageDef::secure_exe();
bind_interrupts!(struct Irqs {
I2C1_IRQ => i2c::InterruptHandler<I2C1>;
});
// static JUMP_TRIGGERED: AtomicBool = AtomicBool::new(false);
//
// #[embassy_executor::task]
// async fn button_handler(button: Input<'static>) {
// loop {
// if button.is_low() {
// JUMP_TRIGGERED.store(true, Ordering::Relaxed);
// }
// Timer::after_millis(20).await;
// }
// }
#[embassy_executor::main]
async fn main(_spawner: Spawner) {
let p = embassy_rp::init(Default::default());
// Setting up I2C send text to OLED display
let sda = p.PIN_18;
let scl = p.PIN_19;
let i2c = i2c::I2c::new_async(p.I2C1, scl, sda, Irqs, i2c::Config::default());
let interface = I2CDisplayInterface::new(i2c);
let mut display = Ssd1306::new(interface, DisplaySize128x64, DisplayRotation::Rotate0)
.into_buffered_graphics_mode();
display.init().unwrap();
let button = Input::new(p.PIN_15, Pull::Up);
display.flush().unwrap();
let mut game = Game::new(display);
game.draw_trex().unwrap();
// spawner.spawn(button_handler(button)).unwrap();
let mut clicked_count = 0; // To restart the game when it two times button clicked
loop {
if game.state == GameState::GameOver {
if button.is_low() {
clicked_count += 1;
}
if clicked_count > 2 {
clicked_count = 0;
game = Game::new(game.display);
Timer::after_millis(500).await;
}
Timer::after_millis(50).await;
continue;
}
game.clear_screen().unwrap();
game.draw_score().unwrap();
if button.is_low() {
game.trex_jump();
}
game.move_world().unwrap();
game.draw_ground().unwrap();
game.draw_trex().unwrap();
if game.check_collison() {
game.game_over().unwrap();
game.display.flush().unwrap();
Timer::after_millis(500).await;
continue;
}
game.display.flush().unwrap();
Timer::after_millis(5).await;
}
}
// Program metadata for `picotool info`.
// This isn't needed, but it's recomended to have these minimal entries.
#[link_section = ".bi_entries"]
#[used]
pub static PICOTOOL_ENTRIES: [embassy_rp::binary_info::EntryAddr; 4] = [
embassy_rp::binary_info::rp_program_name!(c"PicoRex"),
embassy_rp::binary_info::rp_program_description!(
c"Dino Game written in Rust for the Pico 2 (RP2350) with SSD1306, using the Embassy framework."
),
embassy_rp::binary_info::rp_cargo_version!(),
embassy_rp::binary_info::rp_program_build_attribute!(),
];
| 412 | 0.843719 | 1 | 0.843719 | game-dev | MEDIA | 0.734857 | game-dev | 0.702188 | 1 | 0.702188 |
racoonman2/ReTerraForged | 1,615 | common/src/main/java/raccoonman/reterraforged/world/worldgen/heightproviders/LegacyCarverHeight.java | package raccoonman.reterraforged.world.worldgen.heightproviders;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.util.RandomSource;
import net.minecraft.world.level.levelgen.WorldGenerationContext;
import net.minecraft.world.level.levelgen.heightproviders.HeightProvider;
import net.minecraft.world.level.levelgen.heightproviders.HeightProviderType;
@Deprecated // pretty sure this can be replicated with UniformHeight
public class LegacyCarverHeight extends HeightProvider {
public static final Codec<LegacyCarverHeight> CODEC = RecordCodecBuilder.create(instance -> instance.group(
Codec.INT.fieldOf("min").forGetter((h) -> h.min),
Codec.INT.fieldOf("variation_min").forGetter((h) -> h.variationMin),
Codec.INT.fieldOf("variation_range").forGetter((h) -> h.variationRange)
).apply(instance, LegacyCarverHeight::new));
private int min;
private int variationMin;
private int variationRange;
private LegacyCarverHeight(int min, int variationMin, int variationRange) {
this.min = min;
this.variationMin = variationMin;
this.variationRange = variationRange;
}
@Override
public int sample(RandomSource random, WorldGenerationContext ctx) {
return this.min + random.nextInt(this.variationMin + random.nextInt(this.variationRange));
}
@Override
public HeightProviderType<LegacyCarverHeight> getType() {
return RTFHeightProviderTypes.LEGACY_CARVER;
}
public static LegacyCarverHeight of(int min, int variationMin, int variationRange) {
return new LegacyCarverHeight(min, variationMin, variationRange);
}
}
| 412 | 0.663584 | 1 | 0.663584 | game-dev | MEDIA | 0.878809 | game-dev | 0.851175 | 1 | 0.851175 |
ruattd/whitelistd | 3,508 | common/src/main/java/io/github/ruattd/fc/whitelistd/SearchList.java | package io.github.ruattd.fc.whitelistd;
import lombok.NonNull;
import java.util.Iterator;
import java.util.function.Predicate;
public interface SearchList {
/**
* 搜索列表的初始化回调方法,将在插件加载时调用
* @param mode 搜索模式,参考 {@link SearchMode}
* @param playerNameCaseSensitive 玩家名称大小写是否敏感,一般不需要关心
*/
void init(@NonNull SearchMode mode, boolean playerNameCaseSensitive, @NonNull String[] args);
/**
* 向搜索列表中添加项目
* @param player 玩家信息
* @return 添加操作的结果
* @see AddItemState
*/
@NonNull
AddItemState addItem(@NonNull PlayerInfo player);
/**
* 从搜索列表中移除指定项目
* @param player 玩家信息
* @return 移除操作的结果
* @see RemoveItemState
*/
@NonNull
RemoveItemState removeItem(@NonNull PlayerInfo player);
/**
* 查询搜索列表: 完整查询
* @param player 玩家信息
* @return 查询结果
* @see QueryResult
*/
@NonNull
QueryResult query(@NonNull PlayerInfo player);
/**
* 清空搜索列表,删除所有玩家信息
* @return 清空操作的结果
* @see ClearState
*/
@NonNull
ClearState clear();
enum AddItemState {
SUCCESSFUL,
DUPLICATE,
IO_ERROR,
NETWORK_ERROR,
UNKNOWN_ERROR,
}
enum RemoveItemState {
SUCCESSFUL,
NOT_FOUND,
IO_ERROR,
NETWORK_ERROR,
UNKNOWN_ERROR,
}
enum ClearState {
SUCCESSFUL,
IO_ERROR,
NETWORK_ERROR,
UNKNOWN_ERROR,
}
/**
* 查询结果
* @param exist 玩家是否存在于搜索列表中: {@code true} 为存在
* @param playerStored 搜索列表中存储的玩家信息
*/
record QueryResult(boolean exist, PlayerInfo playerStored) {}
static QueryResult emptyResult(PlayerInfo player) {
return new QueryResult(false, player);
}
/**
* 获取列表项目总数
* @return 项目总数
*/
int size();
/**
* 获取所有项目
* @return 所有项目
*/
@NonNull
Iterable<PlayerInfo> getItems();
/**
* 获取所有项目并筛选需要的项目
* @param filter 筛选器
* @return 筛选结果
*/
@NonNull
default Iterable<PlayerInfo> getItems(@NonNull Predicate<PlayerInfo> filter) {
return () -> new Iterator<>() {
private PlayerInfo next = null;
private final Iterator<PlayerInfo> allItems = getItems().iterator();
@Override
public boolean hasNext() {
while (this.next == null) {
if (allItems.hasNext()) {
var next = allItems.next();
if (filter.test(next)) this.next = next;
} else {
return false;
}
}
return true;
}
@Override
public PlayerInfo next() {
return next;
}
};
}
/**
* 以索引位置获取多个项目
* @param firstIndex 开始位置
* @param lastIndex 结束位置
* @return 指定项目
* @throws UnsupportedOperationException 搜索列表未实现此功能
* @see SearchList#getItems(int)
*/
@NonNull
default Iterable<PlayerInfo> getItems(int firstIndex, int lastIndex) {
throw new UnsupportedOperationException();
}
/**
* 以索引位置获取多个项目, 为 {@link SearchList#getItems(int, int)} 的重载,
* 默认使用末位索引作为 {@code lastIndex}
* @param firstIndex 开始位置
* @return 指定项目
* @throws UnsupportedOperationException 搜索列表未实现此功能
*/
@NonNull
default Iterable<PlayerInfo> getItems(int firstIndex) {
return getItems(firstIndex, size() - 1);
}
}
| 412 | 0.93446 | 1 | 0.93446 | game-dev | MEDIA | 0.622493 | game-dev | 0.944126 | 1 | 0.944126 |
PCGen/pcgen | 21,124 | data/3e/wizards_of_the_coast/srd/basics/srd_templates_types.lst | # CVS $Revision$ $Author$ -- Fri Jan 1 12:57:05 2016 -- reformated by PCGen PrettyLST v6.06.00
SOURCELONG:System Reference Document SOURCESHORT:SRD SOURCEWEB:http://groups.yahoo.com/group/pcgen/files/3.0%20SRD/ SOURCEDATE:2000-01
# Template Name Visible Source Page Define Stat Combat bonus Bonus to HP Stat bonus Ability Apply Kit Removable? Type Vision
Spellbook VISIBLE:NO KIT:1|Wizard Spell Book
#
# This File is for all "standard" templates used in multiple sources.
#
# - Tir Gwaith
# Template Name Visible Source Page Define Stat Combat bonus Bonus to HP Stat bonus Ability Apply Kit Removable? Type Vision
Construct VISIBLE:NO SOURCEPAGE:srdcreatureoverview DEFINESTAT:NONSTAT|CON ABILITY:Special Ability|AUTOMATIC|Immunity To Disease|Immunity To Mind-Affecting|Immunity To Poison REMOVABLE:YES
# Added all dragons skills to keep the race files down in size.
Dragon VISIBLE:NO SOURCEPAGE:srdcreatureoverview ABILITY:Special Ability|AUTOMATIC|Immunity To Paralysis|Immunity To Sleep REMOVABLE:YES TYPE:Dragon
Elemental VISIBLE:NO SOURCEPAGE:srdcreatureoverview ABILITY:Special Ability|AUTOMATIC|Immunity To Critical Hits|Immunity To Paralysis|Immunity To Poison|Immunity To Stunning REMOVABLE:YES
Incorporeal VISIBLE:NO SOURCEPAGE:srdcreatureoverview DEFINESTAT:NONSTAT|STR BONUS:COMBAT|TOHIT|DEX|TYPE=NotRanged ABILITY:Special Ability|AUTOMATIC|Incorporeal Traits REMOVABLE:YES
Ooze VISIBLE:NO SOURCEPAGE:srdcreatureoverview DEFINESTAT:NONSTAT|INT BONUS:HP|CURRENTMAX|max((SIZE-2),0)*5 BONUS:HP|CURRENTMAX|max((SIZE-6),0)*5 ABILITY:Special Ability|AUTOMATIC|Immunity To Critical Hits|Immunity To Mind-Affecting|Immunity To Paralysis|Immunity To Poison|Immunity To Polymorph|Immunity To Sleep|Immunity To Stunning REMOVABLE:YES
Plant VISIBLE:NO SOURCEPAGE:srdcreatureoverview ABILITY:Special Ability|AUTOMATIC|Immunity To Critical Hits|Immunity To Disease|Immunity To Mind-Affecting|Immunity To Paralysis|Immunity To Poison|Immunity To Sleep|Immunity To Stunning REMOVABLE:YES
Undead VISIBLE:NO SOURCEPAGE:srdcreatureoverview DEFINESTAT:NONSTAT|CON ABILITY:Special Ability|AUTOMATIC|Immunity To Disease|Immunity To Mind-Affecting|Immunity To Paralysis|Immunity To Poison|Immunity To Sleep|Immunity To Stunning REMOVABLE:YES TYPE:Undead VISION:Darkvision (60')
Vermin VISIBLE:NO SOURCEPAGE:srdcreatureoverview DEFINESTAT:NONSTAT|INT ABILITY:Special Ability|AUTOMATIC|Immunity To Mind-Affecting REMOVABLE:YES TYPE:Vermin
#
Mindless VISIBLE:NO DEFINESTAT:NONSTAT|INT
Familiar SOURCEPAGE:srdNPCsFamMntsComps BONUS:COMBAT|AC|((TL+1)/2).INTVAL|TYPE=NaturalArmor.STACK BONUS:STAT|INT|6 ABILITY:Special Ability|AUTOMATIC|Empathic Link|Improved Evasion|Share Spells ABILITY:FEAT|AUTOMATIC|Alertness REMOVABLE:YES
###Block: For races which only have one gender - Satyr, Succubi, Dryads, and so on.
# Template Name Visible Lock Gender Selection
Male VISIBLE:NO GENDERLOCK:Male
Female VISIBLE:NO GENDERLOCK:Female
# ###########
# WORKAROUNDS
# ###########
# Below are workarounds until further functionality is available.
#
###Block:Workarounds
# Template Name Output Name Visible Damage Reduction Source Page Type
Monk Outsider OUTPUTNAME:Outsider VISIBLE:EXPORT DR:20/+1 SOURCEPAGE:srdbasiccharacterclassesi TYPE:Outsider
###Block: Temporary Bonus Templates
# Template Name Visible Source Page Temporary effect description Temporary Bonus
Familiar within arms reach VISIBLE:NO SOURCEPAGE:srdNPCsFamMntsComps TEMPDESC:While a familiar is within arm's reach, the master gains the Alertness feat TEMPBONUS:ANYPC|SKILL|Listen,Spot|2|TYPE=Familiar|!PREABILITY:1,CATEGORY=FEAT,Alertness|PREABILITY:1,CATEGORY=Special Ability,Summon Familiar
###Block: Timeless Body For Druid and Monk
# Template Name Visible Template Minimum Age Maximum Age Required Class Multiple Requirements Stat bonus
Timeless Body VISIBLE:DISPLAY TEMPLATE:CHOOSE:Timeless Body ~ Adult|Timeless Body ~ Middle Age|Timeless Body ~ Old|Timeless Body ~ Venerable PRECLASS:1,Druid=15,Monk=17
Timeless Body ~ Adult VISIBLE:NO !PREAGESET:1,Middle Age BONUS:STAT|STR,CON,DEX|1|PREMULT:2,[PREAGESET:1,Middle Age],[!PREAGESET:1,Old] BONUS:STAT|STR,CON,DEX|3|PREMULT:2,[PREAGESET:1,Old],[!PREAGESET:1,Venerable] BONUS:STAT|STR,CON,DEX|6|PREAGESET:1,Venerable
Timeless Body ~ Middle Age VISIBLE:NO PREMULT:2,[PREAGESET:1,Middle Age],[!PREAGESET:1,Old] BONUS:STAT|STR,CON,DEX|2|PREMULT:2,[PREAGESET:1,Old],[!PREAGESET:1,Venerable] BONUS:STAT|STR,CON,DEX|5|PREAGESET:1,Venerable
Timeless Body ~ Old VISIBLE:NO PREMULT:2,[PREAGESET:1,Old],[!PREAGESET:1,Venerable] BONUS:STAT|STR,CON,DEX|3|PREAGESET:1,Venerable
Timeless Body ~ Venerable VISIBLE:NO PREAGESET:1,Venerable
###Block: Conditional Templates
# Template Name Visible Source Page Temporary effect description Temporary Bonus TEMPVALUE
Ability Damaged (Strength) VISIBLE:NO SOURCEPAGE:srdconditionsummary TEMPDESC:You have temporarily lost 1 or more Strength ability score points TEMPBONUS:ANYPC|STAT|STR|-1*(%CHOICE) TEMPVALUE:MIN=1|MAX=20|TITLE=Stength Damage
Ability Damaged (Dexterity) VISIBLE:NO SOURCEPAGE:srdconditionsummary TEMPDESC:You have temporarily lost 1 or more Dexterity ability score points TEMPBONUS:ANYPC|STAT|DEX|-1*(%CHOICE) TEMPVALUE:MIN=1|MAX=20|TITLE=Dexterity Damage
Ability Damaged (Constitution) VISIBLE:NO SOURCEPAGE:srdconditionsummary TEMPDESC:You have temporarily lost 1 or more Constitution ability score points TEMPBONUS:ANYPC|STAT|CON|-1*(%CHOICE) TEMPVALUE:MIN=1|MAX=20|TITLE=Constitution Damage
Ability Damaged (Intelligence) VISIBLE:NO SOURCEPAGE:srdconditionsummary TEMPDESC:You have temporarily lost 1 or more Intelligence ability score points TEMPBONUS:ANYPC|STAT|INT|-1*(%CHOICE) TEMPVALUE:MIN=1|MAX=20|TITLE=Intelligence Damage
Ability Damaged (Wisdom) VISIBLE:NO SOURCEPAGE:srdconditionsummary TEMPDESC:You have temporarily lost 1 or more Wisdom ability score points TEMPBONUS:ANYPC|STAT|WIS|-1*(%CHOICE) TEMPVALUE:MIN=1|MAX=20|TITLE=Wisdom Damage
Ability Damaged (Charisma) VISIBLE:NO SOURCEPAGE:srdconditionsummary TEMPDESC:You have temporarily lost 1 or more Charisma ability score points TEMPBONUS:ANYPC|STAT|CHA|-1*(%CHOICE) TEMPVALUE:MIN=1|MAX=20|TITLE=Charisma Damage
Blinded VISIBLE:NO SOURCEPAGE:srdconditionsummary TEMPDESC:You cannot see TEMPBONUS:ANYPC|COMBAT|AC|-(max(DEX,0))|TYPE=Ability.STACK TEMPBONUS:ANYPC|SKILL|STAT.STR,STAT.DEX|-4
Cowering VISIBLE:NO SOURCEPAGE:srdconditionsummary TEMPDESC:You are frozen in fear and can take no actions TEMPBONUS:ANYPC|COMBAT|AC|-(max(DEX,0))|TYPE=Ability.STACK
Dazzled VISIBLE:NO SOURCEPAGE:srdconditionsummary TEMPDESC:You are unable to see well because of overstimulation of the eyes TEMPBONUS:ANYPC|COMBAT|TOHIT|-1 TEMPBONUS:ANYPC|SKILL|Search,Spot|-1
Deafened VISIBLE:NO SOURCEPAGE:srdconditionsummary TEMPDESC:You cannot hear TEMPBONUS:ANYPC|COMBAT|INITIATIVE|-4
Energy Drained VISIBLE:NO SOURCEPAGE:srdconditionsummary TEMPDESC:You have gained one or more negative levels TEMPBONUS:ANYPC|SAVE|Fortitude,Reflex,Will|-1*%CHOICE TEMPBONUS:ANYPC|COMBAT|TOHIT|-1*%CHOICE TEMPBONUS:ANYPC|HP|CURRENTMAX|-5*(%CHOICE) TEMPBONUS:ANYPC|SKILL|TYPE=Strength,TYPE=Dexterity,TYPE=Constitution,TYPE=Intelligence,TYPE=Wisdom,TYPE=Charisma|-1*%CHOICE TEMPVALUE:MIN=1|MAX=20|TITLE=Negative Levels
Entangled VISIBLE:NO SOURCEPAGE:srdconditionsummary TEMPDESC:You are ensnared TEMPBONUS:ANYPC|COMBAT|TOHIT|-2 TEMPBONUS:ANYPC|STAT|DEX|-4
Exhausted VISIBLE:NO SOURCEPAGE:srdconditionsummary TEMPDESC:You are exhausted TEMPBONUS:ANYPC|STAT|DEX,STR|-6
Fatigued VISIBLE:NO SOURCEPAGE:srdconditionsummary TEMPDESC:You are fatigued TEMPBONUS:ANYPC|STAT|DEX,STR|-2
Frightened VISIBLE:NO SOURCEPAGE:srdconditionsummary TEMPDESC:You are frightened TEMPBONUS:ANYPC|SAVE|Fortitude,Reflex,Will|-2|TYPE=Morale TEMPBONUS:ANYPC|COMBAT|TOHIT|-2|TYPE=Morale TEMPBONUS:ANYPC|SKILL|TYPE=Strength,TYPE=Dexterity,TYPE=Constitution,TYPE=Intelligence,TYPE=Wisdom,TYPE=Charisma|-2|TYPE=Morale
Invisible VISIBLE:NO SOURCEPAGE:srdconditionsummary TEMPDESC:You are invisible, you gain a +2 bonus on attack rolls against sighted opponents, and ignore your opponents' Dexterity bonuses to AC (if any) TEMPBONUS:ANYPC|COMBAT|TOHIT|2|TYPE=Invisibility
Panicked VISIBLE:NO SOURCEPAGE:srdconditionsummary TEMPDESC:You are panicked and must drop anything you hold and flee at top speed from the source of your fear TEMPBONUS:ANYPC|SAVE|Fortitude,Reflex,Will|-2|TYPE=Morale TEMPBONUS:ANYPC|SKILL|TYPE=Strength,TYPE=Dexterity,TYPE=Constitution,TYPE=Intelligence,TYPE=Wisdom,TYPE=Charisma|-2
Prone VISIBLE:NO SOURCEPAGE:srdconditionsummary TEMPDESC:You are on the ground TEMPBONUS:ANYPC|COMBAT|TOHIT.MELEE|-4
Shaken VISIBLE:NO SOURCEPAGE:srdconditionsummary TEMPDESC:You are shaken TEMPBONUS:ANYPC|SAVE|Fortitude,Reflex,Will|-2|TYPE=Morale TEMPBONUS:ANYPC|COMBAT|TOHIT|-2 TEMPBONUS:ANYPC|SKILL|TYPE=Strength,TYPE=Dexterity,TYPE=Constitution,TYPE=Intelligence,TYPE=Wisdom,TYPE=Charisma|-2
Stunned VISIBLE:NO SOURCEPAGE:srdconditionsummary TEMPDESC:You are stunned, you drop everything held, and cannot take actions TEMPBONUS:ANYPC|COMBAT|AC|-(max(DEX,0))|TYPE=Ability.STACK
###Block: Combat Templates
# Template Name Visible Source Page Temporary effect description Temporary Bonus
Fighting Defensively VISIBLE:NO SOURCEPAGE:SRDCombatActions TEMPDESC:You are fighting defensively when attacking TEMPBONUS:ANYPC|COMBAT|TOHIT|-4 TEMPBONUS:ANYPC|VAR|FightingDefensivelyAC|2+FightingDefensivelyACBonus|TYPE=Temp1 TEMPBONUS:ANYPC|VAR|FightingDefensivelyACBonus|1|TYPE=Temp2|PRESKILL:1,Tumble=5
Total Defense VISIBLE:NO SOURCEPAGE:SRDCombatActions TEMPDESC:You are defending yourself as a standard action TEMPBONUS:ANYPC|VAR|TotalDefenseAC|4+TotalDefenseACBonus|TYPE=Temp1 TEMPBONUS:ANYPC|VAR|TotalDefenseACBonus|2|TYPE=Temp2|PRESKILL:1,Tumble=5
###Block: Awakened Animal
# Template Name Required Race Add Apply Kit Bonus Languages Subrace Main Race Type Race Subtype Add Levels
Awakened Animal PRERACE:1,RACETYPE=Animal,TYPE=Animal ADD:LANGUAGE|TYPE=Spoken KIT:1|Awakened Animal LANGBONUS:TYPE=Spoken SUBRACE:Awakened RACETYPE:Magical Beast RACESUBTYPE:Augmented Animal ADDLEVEL:Animal|2
###Block: Diseases
# Template Name Visible Source Page Temporary effect description Temporary Bonus TEMPVALUE
Disease Damage (Blinding Sickness) VISIBLE:NO SOURCEPAGE:AbilitiesandConditions TEMPDESC:Infection DC 16 (Ingested), Incubation 1d3 days, Damage 1d4 Str (Each time the victim takes 2 or more damage from the disease, he must make another Fortitude save or be permanently blinded), Apply this temporary bonus each day the victim takes damage. TEMPBONUS:ANYPC|STAT|STR|-1*(%CHOICE) TEMPVALUE:MIN=1|MAX=4|TITLE=Stength Damage
Disease Damage (Cackle fever) VISIBLE:NO SOURCEPAGE:AbilitiesandConditions TEMPDESC:Infection DC 16 (Inhaled), Incubation 1 day, Damage 1d6 Wis, Apply this temporary bonus each day the victim takes damage. TEMPBONUS:ANYPC|STAT|WIS|-1*(%CHOICE) TEMPVALUE:MIN=1|MAX=6|TITLE=Wisdom Damage
Disease Damage (Demon fever) VISIBLE:NO SOURCEPAGE:AbilitiesandConditions TEMPDESC:Infection DC 18 (Injury), Incubation 1 day, Damage 1d6 Con (When damaged, character must succeed on another saving throw or 1 point of damage is permanent drain instead), Apply this temporary bonus each day the victim takes damage. TEMPBONUS:ANYPC|STAT|CON|-1*(%CHOICE) TEMPVALUE:MIN=1|MAX=6|TITLE=Constitution Damage
Disease Damage (Devil chills) VISIBLE:NO SOURCEPAGE:AbilitiesandConditions TEMPDESC:Infection DC 14 (Injury), Incubation 1d4 days, Damage 1d4 Str (The victim must make three successful Fortitude saving throws in a row to recover from devil chills), Apply this temporary bonus each day the victim takes damage. TEMPBONUS:ANYPC|STAT|STR|-1*(%CHOICE) TEMPVALUE:MIN=1|MAX=4|TITLE=Stength Damage
Disease Damage (Filth fever/Dex Damage) VISIBLE:NO SOURCEPAGE:AbilitiesandConditions TEMPDESC:Infection DC 12 (Injury), Incubation 1d3 days, Damage 1d3 Dex, 1d3 Con, Apply this temporary bonus for the dexterity damage each day the victim takes damage. TEMPBONUS:ANYPC|STAT|DEX|-1*(%CHOICE) TEMPVALUE:MIN=1|MAX=3|TITLE=Dexterity Damage
Disease Damage (Filth fever/Con Damage) VISIBLE:NO SOURCEPAGE:AbilitiesandConditions TEMPDESC:Infection DC 12 (Injury), Incubation 1d3 days, Damage 1d3 Dex, 1d3 Con, Apply this temporary bonus for the constitution damage each day the victim takes damage. TEMPBONUS:ANYPC|STAT|Con|-1*(%CHOICE) TEMPVALUE:MIN=1|MAX=3|TITLE=Constitution Damage
Disease Damage (Mindfire) VISIBLE:NO SOURCEPAGE:AbilitiesandConditions TEMPDESC:Infection DC 12 (Inhaled), Incubation 1 day, Damage 1d4 Int, Apply this temporary bonus each day the victim takes damage. TEMPBONUS:ANYPC|STAT|INT|-1*(%CHOICE) TEMPVALUE:MIN=1|MAX=4|TITLE=Intelligence Damage
Disease Damage (Mummy rot) VISIBLE:NO SOURCEPAGE:AbilitiesandConditions TEMPDESC:Infection DC 20 (Contact), Incubation 1 day, Damage 1d6 Con (Successful saves do not allow the character to recover, Only magical healing can save the character), Apply this temporary bonus each day the victim takes damage. TEMPBONUS:ANYPC|STAT|CON|-1*(%CHOICE) TEMPVALUE:MIN=1|MAX=6|TITLE=Constitution Damage
Disease Damage (Red ache) VISIBLE:NO SOURCEPAGE:AbilitiesandConditions TEMPDESC:Infection DC 15 (Injury), Incubation 1d3 days, Damage 1d6 Str, Apply this temporary bonus each day the victim takes damage. TEMPBONUS:ANYPC|STAT|STR|-1*(%CHOICE) TEMPVALUE:MIN=1|MAX=6|TITLE=Stength Damage
Disease Damage (Shakes) VISIBLE:NO SOURCEPAGE:AbilitiesandConditions TEMPDESC:Infection DC 13 (Contact), Incubation 1 day, Damage 1d8 Dex, Apply this temporary bonus each day the victim takes damage. TEMPBONUS:ANYPC|STAT|DEX|-1*(%CHOICE) TEMPVALUE:MIN=1|MAX=8|TITLE=Dexterity Damage
Disease Damage (Slimy doom) VISIBLE:NO SOURCEPAGE:AbilitiesandConditions TEMPDESC:Infection DC 14 (Contact), Incubation 1 day, Damage 1d4 Con (When damaged, character must succeed on another saving throw or 1 point of damage is permanent drain instead), Apply this temporary bonus each day the victim takes damage. TEMPBONUS:ANYPC|STAT|STR|-1*(%CHOICE) TEMPVALUE:MIN=1|MAX=4|TITLE=Constitution Damage
###Block: Fractional Hit Die Adjustments for Monster classes
# Template Name Hit Dice Size Visible
Half Hitdie HITDIE:%/2|CLASS.TYPE=Monster VISIBLE:NO
Quarter Hitdie HITDIE:%/4|CLASS.TYPE=Monster VISIBLE:NO
Eighth Hitdie HITDIE:%/8|CLASS.TYPE=Monster VISIBLE:NO
###Block: Missing in the 3e main set
# Template Name Visible Source Page Ability
Fey VISIBLE:NO SOURCEPAGE:TypesSubtypesAbilities
Cold VISIBLE:NO SOURCEPAGE:TypesSubtypesAbilities ABILITY:Special Ability|AUTOMATIC|Immunity To Cold|Vulnerability To Fire
Evil VISIBLE:NO SOURCEPAGE:TypesSubtypesAbilities ABILITY:Special Ability|AUTOMATIC|Evil Traits
Fire VISIBLE:NO SOURCEPAGE:TypesSubtypesAbilities ABILITY:Special Ability|AUTOMATIC|Immunity To Fire|Vulnerability To Cold
###Block: Inherent ability bonuses
# Template Name Visible Template Source Page Stat bonus
Inherent Ability Bonus (Strength) VISIBLE:DISPLAY TEMPLATE:CHOOSE:Inherent Strength Bonus +1|Inherent Strength Bonus +2|Inherent Strength Bonus +3|Inherent Strength Bonus +4|Inherent Strength Bonus +5 SOURCEPAGE:p.370
Inherent Ability Bonus (Dexterity) VISIBLE:DISPLAY TEMPLATE:CHOOSE:Inherent Dexterity Bonus +1|Inherent Dexterity Bonus +2|Inherent Dexterity Bonus +3|Inherent Dexterity Bonus +4|Inherent Dexterity Bonus +5 SOURCEPAGE:p.370
Inherent Ability Bonus (Constitution) VISIBLE:DISPLAY TEMPLATE:CHOOSE:Inherent Constitution Bonus +1|Inherent Constitution Bonus +2|Inherent Constitution Bonus +3|Inherent Constitution Bonus +4|Inherent Constitution Bonus +5 SOURCEPAGE:p.370
Inherent Ability Bonus (Intelligence) VISIBLE:DISPLAY TEMPLATE:CHOOSE:Inherent Intelligence Bonus +1|Inherent Intelligence Bonus +2|Inherent Intelligence Bonus +3|Inherent Intelligence Bonus +4|Inherent Intelligence Bonus +5 SOURCEPAGE:p.370
Inherent Ability Bonus (Wisdom) VISIBLE:DISPLAY TEMPLATE:CHOOSE:Inherent Wisdom Bonus +1|Inherent Wisdom Bonus +2|Inherent Wisdom Bonus +3|Inherent Wisdom Bonus +4|Inherent Wisdom Bonus +5 SOURCEPAGE:p.370
Inherent Ability Bonus (Charisma) VISIBLE:DISPLAY TEMPLATE:CHOOSE:Inherent Charisma Bonus +1|Inherent Charisma Bonus +2|Inherent Charisma Bonus +3|Inherent Charisma Bonus +4|Inherent Charisma Bonus +5 SOURCEPAGE:p.370
# Strength
Inherent Strength Bonus +1 VISIBLE:NO BONUS:STAT|STR|1|TYPE=Inherent
Inherent Strength Bonus +2 VISIBLE:NO BONUS:STAT|STR|2|TYPE=Inherent
Inherent Strength Bonus +3 VISIBLE:NO BONUS:STAT|STR|3|TYPE=Inherent
Inherent Strength Bonus +4 VISIBLE:NO BONUS:STAT|STR|4|TYPE=Inherent
Inherent Strength Bonus +5 VISIBLE:NO BONUS:STAT|STR|5|TYPE=Inherent
# Dexterity
Inherent Dexterity Bonus +1 VISIBLE:NO BONUS:STAT|DEX|1|TYPE=Inherent
Inherent Dexterity Bonus +2 VISIBLE:NO BONUS:STAT|DEX|2|TYPE=Inherent
Inherent Dexterity Bonus +3 VISIBLE:NO BONUS:STAT|DEX|3|TYPE=Inherent
Inherent Dexterity Bonus +4 VISIBLE:NO BONUS:STAT|DEX|4|TYPE=Inherent
Inherent Dexterity Bonus +5 VISIBLE:NO BONUS:STAT|DEX|5|TYPE=Inherent
# Constitution
Inherent Constitution Bonus +1 VISIBLE:NO BONUS:STAT|CON|1|TYPE=Inherent
Inherent Constitution Bonus +2 VISIBLE:NO BONUS:STAT|CON|2|TYPE=Inherent
Inherent Constitution Bonus +3 VISIBLE:NO BONUS:STAT|CON|3|TYPE=Inherent
Inherent Constitution Bonus +4 VISIBLE:NO BONUS:STAT|CON|4|TYPE=Inherent
Inherent Constitution Bonus +5 VISIBLE:NO BONUS:STAT|CON|5|TYPE=Inherent
# Intelligence
Inherent Intelligence Bonus +1 VISIBLE:NO BONUS:STAT|INT|1|TYPE=Inherent
Inherent Intelligence Bonus +2 VISIBLE:NO BONUS:STAT|INT|2|TYPE=Inherent
Inherent Intelligence Bonus +3 VISIBLE:NO BONUS:STAT|INT|3|TYPE=Inherent
Inherent Intelligence Bonus +4 VISIBLE:NO BONUS:STAT|INT|4|TYPE=Inherent
Inherent Intelligence Bonus +5 VISIBLE:NO BONUS:STAT|INT|5|TYPE=Inherent
# Wisdom
Inherent Wisdom Bonus +1 VISIBLE:NO BONUS:STAT|WIS|1|TYPE=Inherent
Inherent Wisdom Bonus +2 VISIBLE:NO BONUS:STAT|WIS|2|TYPE=Inherent
Inherent Wisdom Bonus +3 VISIBLE:NO BONUS:STAT|WIS|3|TYPE=Inherent
Inherent Wisdom Bonus +4 VISIBLE:NO BONUS:STAT|WIS|4|TYPE=Inherent
Inherent Wisdom Bonus +5 VISIBLE:NO BONUS:STAT|WIS|5|TYPE=Inherent
# Wisdom
Inherent Charisma Bonus +1 VISIBLE:NO BONUS:STAT|CHA|1|TYPE=Inherent
Inherent Charisma Bonus +2 VISIBLE:NO BONUS:STAT|CHA|2|TYPE=Inherent
Inherent Charisma Bonus +3 VISIBLE:NO BONUS:STAT|CHA|3|TYPE=Inherent
Inherent Charisma Bonus +4 VISIBLE:NO BONUS:STAT|CHA|4|TYPE=Inherent
Inherent Charisma Bonus +5 VISIBLE:NO BONUS:STAT|CHA|5|TYPE=Inherent
#
# End
#
| 412 | 0.840539 | 1 | 0.840539 | game-dev | MEDIA | 0.955387 | game-dev | 0.742858 | 1 | 0.742858 |
DaFuqs/Spectrum | 1,721 | src/main/java/de/dafuqs/spectrum/mixin/EndermanEntityMixin.java | package de.dafuqs.spectrum.mixin;
import de.dafuqs.spectrum.*;
import de.dafuqs.spectrum.registries.*;
import net.minecraft.server.level.*;
import net.minecraft.util.*;
import net.minecraft.world.entity.monster.*;
import net.minecraft.world.level.*;
import net.minecraft.world.level.block.state.*;
import org.jetbrains.annotations.*;
import org.spongepowered.asm.mixin.*;
import org.spongepowered.asm.mixin.injection.*;
import org.spongepowered.asm.mixin.injection.callback.*;
@Mixin(EnderMan.class)
public abstract class EndermanEntityMixin {
@Unique
private final BlockState carriedBlockState = SpectrumBlocks.RADIATING_ENDER.defaultBlockState();
@Shadow
@Nullable
public abstract BlockState getCarriedBlock();
@Inject(at = @At("TAIL"), method = "<init>")
private void init(CallbackInfo info) {
EnderMan endermanEntity = ((EnderMan) (Object) this);
Level world = endermanEntity.getCommandSenderWorld();
if (world instanceof ServerLevel) {
RandomSource random = world.random;
float chance;
if (world.dimension().equals(Level.END)) {
chance = SpectrumCommon.CONFIG.EndermanHoldingEnderTreasureInEndChance;
} else {
chance = SpectrumCommon.CONFIG.EndermanHoldingEnderTreasureChance;
}
if (random.nextFloat() < chance) {
if (endermanEntity.getCarriedBlock() == null) {
endermanEntity.setCarriedBlock(carriedBlockState);
}
}
}
}
@Inject(at = @At("RETURN"), method = "requiresCustomPersistence", cancellable = true)
public void cannotDespawn(CallbackInfoReturnable<Boolean> cir) {
if (cir.getReturnValue() && this.getCarriedBlock() != null && this.getCarriedBlock().is(SpectrumBlocks.RADIATING_ENDER)) {
cir.setReturnValue(false);
}
}
}
| 412 | 0.900092 | 1 | 0.900092 | game-dev | MEDIA | 0.97932 | game-dev | 0.941647 | 1 | 0.941647 |
3arthqu4ke/3arthh4ck | 22,008 | src/main/java/me/earth/earthhack/impl/modules/client/hud/HUD.java | package me.earth.earthhack.impl.modules.client.hud;
import com.mojang.realmsclient.gui.ChatFormatting;
import me.earth.earthhack.api.module.Module;
import me.earth.earthhack.api.module.util.Category;
import me.earth.earthhack.api.setting.Complexity;
import me.earth.earthhack.api.setting.Setting;
import me.earth.earthhack.api.setting.settings.*;
import me.earth.earthhack.impl.Earthhack;
import me.earth.earthhack.impl.managers.Managers;
import me.earth.earthhack.impl.managers.render.TextRenderer;
import me.earth.earthhack.impl.modules.client.hud.arraylist.ArrayEntry;
import me.earth.earthhack.impl.modules.client.hud.modes.HudRainbow;
import me.earth.earthhack.impl.modules.client.hud.modes.Modules;
import me.earth.earthhack.impl.modules.client.hud.modes.PotionColor;
import me.earth.earthhack.impl.modules.client.hud.modes.Potions;
import me.earth.earthhack.impl.util.client.ModuleUtil;
import me.earth.earthhack.impl.util.math.MathUtil;
import me.earth.earthhack.impl.util.math.rotation.RotationUtil;
import me.earth.earthhack.impl.util.minecraft.DamageUtil;
import me.earth.earthhack.impl.util.minecraft.InventoryUtil;
import me.earth.earthhack.impl.util.network.ServerUtil;
import me.earth.earthhack.impl.util.render.ColorHelper;
import me.earth.earthhack.impl.util.render.ColorUtil;
import me.earth.earthhack.impl.util.text.ChatUtil;
import me.earth.earthhack.impl.util.text.TextColor;
import me.earth.earthhack.pingbypass.modules.PbModule;
import net.minecraft.block.material.Material;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.RenderItem;
import net.minecraft.client.resources.I18n;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.init.Items;
import net.minecraft.init.MobEffects;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import org.lwjgl.opengl.GL11;
import java.awt.*;
import java.time.DateTimeException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;
// TODO: REWRITE?
public class HUD extends Module {
public static final TextRenderer RENDERER = Managers.TEXT;
protected final Setting<HudRainbow> colorMode =
register(new EnumSetting<>("Rainbow", HudRainbow.None));
protected final Setting<Color> color =
register(new ColorSetting("Color", Color.WHITE));
protected final Setting<Boolean> logo =
register(new BooleanSetting("Logo", true));
protected final Setting<String> logoText =
register(new StringSetting("LogoText", "3arthh4ck"));
protected final Setting<Boolean> coordinates =
register(new BooleanSetting("Coordinates", true));
protected final Setting<Boolean> armor =
register(new BooleanSetting("Armor", true));
protected final Setting<Boolean> totems =
register(new BooleanSetting("Totems", false));
protected final Setting<Integer> totemsYOffset =
register(new NumberSetting<>("Totems-Y-Offset", 0, -10, 10));
protected final Setting<Integer> totemsXOffset =
register(new NumberSetting<>("Totems-X-Offset", 0, -10, 10));
protected final Setting<Modules> renderModules =
register(new EnumSetting<>("Modules", Modules.Length));
protected final Setting<Potions> potions =
register(new EnumSetting<>("Potions", Potions.Move));
protected final Setting<PotionColor> potionColor =
register(new EnumSetting<>("PotionColor", PotionColor.Normal));
protected final Setting<Boolean> shadow =
register(new BooleanSetting("Shadow", true));
protected final Setting<Boolean> ping =
register(new BooleanSetting("Ping", false));
protected final Setting<Boolean> speed =
register(new BooleanSetting("Speed", false));
protected final Setting<Boolean> fps =
register(new BooleanSetting("FPS", false));
protected final Setting<Boolean> tps =
register(new BooleanSetting("TPS", false));
protected final Setting<Boolean> currentTps =
register(new BooleanSetting("CurrentTps", true));
protected final Setting<Boolean> animations =
register(new BooleanSetting("Animations", true));
protected final Setting<Boolean> serverBrand =
register(new BooleanSetting("ServerBrand", false));
protected final Setting<Boolean> time =
register(new BooleanSetting("Time", false));
protected final Setting<String> timeFormat =
register(new StringSetting("TimeFormat", "hh:mm:ss"));
protected final Setting<Integer> textOffset =
register(new NumberSetting<>("Offset", 2, 0, 10))
.setComplexity(Complexity.Expert);
protected final List<Map.Entry<String, Module>> modules = new ArrayList<>();
protected final Map<Module, ArrayEntry> arrayEntries = new HashMap<>();
protected final Map<Module, ArrayEntry> removeEntries = new HashMap<>();
protected DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm:ss");
protected ScaledResolution resolution = new ScaledResolution(mc);
protected int width;
protected int height;
protected float animationY = 0;
private final Map<Potion, Color> potionColorMap = new HashMap<>();
public HUD() {
super("HUD", Category.Client);
this.listeners.add(new ListenerRender(this));
this.listeners.add(new ListenerPostKey(this));
this.setData(new HUDData(this));
potionColorMap.put(MobEffects.SPEED, new Color(124, 175, 198));
potionColorMap.put(MobEffects.SLOWNESS, new Color(90, 108, 129));
potionColorMap.put(MobEffects.HASTE, new Color(217, 192, 67));
potionColorMap.put(MobEffects.MINING_FATIGUE, new Color(74, 66, 23));
potionColorMap.put(MobEffects.STRENGTH, new Color(147, 36, 35));
potionColorMap.put(MobEffects.INSTANT_HEALTH, new Color(67, 10, 9));
potionColorMap.put(MobEffects.INSTANT_DAMAGE, new Color(67, 10, 9));
potionColorMap.put(MobEffects.JUMP_BOOST, new Color(34, 255, 76));
potionColorMap.put(MobEffects.NAUSEA, new Color(85, 29, 74));
potionColorMap.put(MobEffects.REGENERATION, new Color(205, 92, 171));
potionColorMap.put(MobEffects.RESISTANCE, new Color(153, 69, 58));
potionColorMap.put(MobEffects.FIRE_RESISTANCE, new Color(228, 154, 58));
potionColorMap.put(MobEffects.WATER_BREATHING, new Color(46, 82, 153));
potionColorMap.put(MobEffects.INVISIBILITY, new Color(127, 131, 146));
potionColorMap.put(MobEffects.BLINDNESS, new Color(31, 31, 35));
potionColorMap.put(MobEffects.NIGHT_VISION, new Color(31, 31, 161));
potionColorMap.put(MobEffects.HUNGER, new Color(88, 118, 83));
potionColorMap.put(MobEffects.WEAKNESS, new Color(72, 77, 72));
potionColorMap.put(MobEffects.POISON, new Color(78, 147, 49));
potionColorMap.put(MobEffects.WITHER, new Color(53, 42, 39));
potionColorMap.put(MobEffects.HEALTH_BOOST, new Color(248, 125, 35));
potionColorMap.put(MobEffects.ABSORPTION, new Color(37, 82, 165));
potionColorMap.put(MobEffects.SATURATION, new Color(248, 36, 35));
potionColorMap.put(MobEffects.GLOWING, new Color(148, 160, 97));
potionColorMap.put(MobEffects.LEVITATION, new Color(206, 255, 255));
potionColorMap.put(MobEffects.LUCK, new Color(51, 153, 0));
potionColorMap.put(MobEffects.UNLUCK, new Color(192, 164, 77));
timeFormat.addObserver(e -> {
if (!e.isCancelled()) {
try {
formatter = DateTimeFormatter.ofPattern(e.getValue());
} catch (IllegalArgumentException iae) {
ChatUtil.sendMessageScheduled(TextColor.RED + "Invalid DateTimeFormat: " + TextColor.WHITE + e.getValue());
formatter = DateTimeFormatter.ofPattern("hh:mm:ss");
}
}
});
}
public int getArmorY() {
int y;
if (mc.player.isInsideOfMaterial(Material.WATER)
&& mc.player.getAir() > 0
&& !mc.player.capabilities.isCreativeMode) {
y = 65;
} else if (mc.player.getRidingEntity() != null
&& !mc.player.capabilities.isCreativeMode) {
if (mc.player.getRidingEntity()
instanceof EntityLivingBase) {
EntityLivingBase entity =
(EntityLivingBase) mc.player.getRidingEntity();
y = (int) (45
+ Math.ceil((entity.getMaxHealth()
- 1.0F)
/ 20.0F)
* 10);
} else {
y = 45;
}
} else if (mc.player.capabilities.isCreativeMode) {
y = mc.player.isRidingHorse() ? 45 : 38;
} else {
y = 55;
}
return y;
}
protected void renderLogo() {
if (logo.getValue()) {
renderText(logoText.getValue() + " - " + Earthhack.VERSION, 2, 2);
}
}
protected void renderModules() {
int offset = 0;
EntityPlayerSP player;
if (serverBrand.getValue() && (player = mc.player) != null) {
String serverBrand = "ServerBrand " + TextColor.GRAY + player.getServerBrand();
renderText(serverBrand, width - 2 - RENDERER.getStringWidth(serverBrand), height - 2 - RENDERER.getStringHeightI() - offset - animationY);
offset += RENDERER.getStringHeightI() + textOffset.getValue();
}
if (potions.getValue() == Potions.Text) {
final ArrayList<Potion> sorted = new ArrayList<>();
for (final Potion potion : Potion.REGISTRY) {
if (potion != null) {
if (mc.player.isPotionActive(potion)) {
sorted.add(potion);
}
}
}
sorted.sort(Comparator.comparingDouble(potion -> -RENDERER.getStringWidth(I18n.format(potion.getName()) + (mc.player.getActivePotionEffect(potion).getAmplifier() > 0 ? " " + (mc.player.getActivePotionEffect(potion).getAmplifier() + 1) : "") + ChatFormatting.GRAY + " " + Potion.getPotionDurationString(Objects.requireNonNull(mc.player.getActivePotionEffect(potion)), 1.0F))));
for (final Potion potion : sorted) {
final PotionEffect effect = mc.player.getActivePotionEffect(potion);
if (effect != null) {
final String label = I18n.format(potion.getName()) + (effect.getAmplifier() > 0 ? " " + (effect.getAmplifier() + 1) : "") + ChatFormatting.GRAY + " " + Potion.getPotionDurationString(effect, 1.0F);
GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
final int x = width - 2 - RENDERER.getStringWidth(label);
renderPotionText(label, x, height - 2 - RENDERER.getStringHeightI() - offset - animationY, effect.getPotion());
offset += RENDERER.getStringHeightI() + textOffset.getValue();
}
}
}
if (speed.getValue()) {
String text = "Speed " + TextColor.GRAY + MathUtil.round(Managers.SPEED.getSpeed(), 2) + " km/h";
renderText(text, width - 2 - RENDERER.getStringWidth(text), height - 2 - RENDERER.getStringHeightI() - offset - animationY);
offset += RENDERER.getStringHeightI() + textOffset.getValue();
}
if (tps.getValue()) {
String tps = "TPS " + TextColor.GRAY + MathUtil.round(Managers.TPS.getTps(), 2);
if (currentTps.getValue())
{
tps += TextColor.WHITE + " [" + TextColor.GRAY + MathUtil.round(Managers.TPS.getCurrentTps(), 2) + TextColor.WHITE + "]";
}
renderText(tps, width - 2 - RENDERER.getStringWidth(tps), height - 2 - RENDERER.getStringHeightI() - offset - animationY);
offset += RENDERER.getStringHeightI() + textOffset.getValue();
}
if (time.getValue()) {
LocalDateTime time = LocalDateTime.now();
String text;
try {
text = "Time " + TextColor.GRAY + formatter.format(time);
} catch (DateTimeException e) {
ModuleUtil.sendMessageWithAquaModule(this, TextColor.RED + "Can not render time: " + e.getMessage(), "time");
text = "Time " + TextColor.GRAY + TextColor.RED + "Invalid";
}
renderText(text, width - 2 - RENDERER.getStringWidth(text), height - 2 - RENDERER.getStringHeightI() - offset - animationY);
offset += RENDERER.getStringHeightI() + textOffset.getValue();
}
if (fps.getValue()) {
String fps = "FPS " + TextColor.GRAY + Minecraft.getDebugFPS();
renderText(fps, width - 2 - RENDERER.getStringWidth(fps), height - 2 - RENDERER.getStringHeightI() - offset - animationY);
offset += RENDERER.getStringHeightI() + textOffset.getValue();
}
if (ping.getValue()) {
String ping = "Ping " + TextColor.GRAY + ServerUtil.getPing();
renderText(ping, width - 2 - RENDERER.getStringWidth(ping), height - 2 - RENDERER.getStringHeightI() - offset - animationY);
}
if (coordinates.getValue()) {
final long x = Math.round(mc.player.posX);
final long y = Math.round(mc.player.posY);
final long z = Math.round(mc.player.posZ);
final String coords = mc.player.dimension == -1 ? String.format(ChatFormatting.PREFIX_CODE + "7%s " + ChatFormatting.PREFIX_CODE + "f[%s]" + ChatFormatting.PREFIX_CODE + "8, " + ChatFormatting.PREFIX_CODE + "7%s" + ChatFormatting.PREFIX_CODE + "8, " + ChatFormatting.PREFIX_CODE + "7%s " + ChatFormatting.PREFIX_CODE + "f[%s]", x, x * 8, y, z, z * 8) : (mc.player.dimension == 0 ? String.format(ChatFormatting.PREFIX_CODE + "f%s " + ChatFormatting.PREFIX_CODE + "7[%s]" + ChatFormatting.PREFIX_CODE + "8, " + ChatFormatting.PREFIX_CODE + "f%s" + ChatFormatting.PREFIX_CODE + "8, " + ChatFormatting.PREFIX_CODE + "f%s " + ChatFormatting.PREFIX_CODE + "7[%s]",
x,
x / 8,
y,
z,
z / 8) : String.format(ChatFormatting.PREFIX_CODE + "f%s" + ChatFormatting.PREFIX_CODE + "8, " + ChatFormatting.PREFIX_CODE + "f%s" + ChatFormatting.PREFIX_CODE + "8, " + ChatFormatting.PREFIX_CODE + "f%s", x, y, z));
renderText(coords, 2, height - 2 - RENDERER.getStringHeightI() - animationY);
final String dir = RotationUtil.getDirection4D(false);
renderText(dir, 2, height - 3 - RENDERER.getStringHeightI() * 2 - animationY);
}
if (totems.getValue()) {
RenderItem itemRender = mc.getRenderItem();
int width = resolution.getScaledWidth();
int height = resolution.getScaledHeight();
int totems = InventoryUtil.getCount(Items.TOTEM_OF_UNDYING);
if (totems > 0) {
int x = width / 2 - (totemsXOffset.getValue()) - 7;
int y = height - (totemsYOffset.getValue()) - getArmorY();
itemRender.zLevel = 200.0f;
itemRender.renderItemAndEffectIntoGUI(mc.player, new ItemStack(Items.TOTEM_OF_UNDYING), x, y);
itemRender.zLevel = 0.0f;
GlStateManager.disableDepth();
String text = String.valueOf(totems);
renderText(text, x + 17 - RENDERER.getStringWidth(text), y + 9);
GlStateManager.enableDepth();
}
}
renderArmor();
if (renderModules.getValue() != Modules.None) {
boolean move = potions.getValue() == Potions.Move && !mc.player.getActivePotionEffects().isEmpty();
int j = move ? 2 : 0;
int o = move ? 5 : 2;
int moduleOffset = Managers.TEXT.getStringHeightI() + textOffset.getValue();
if (animations.getValue()) {
for (Map.Entry<String, Module> module : modules) {
if (isArrayMember(module.getValue()))
continue;
getArrayEntries().put(module.getValue(), new ArrayEntry(module.getValue()));
if (!(module.getValue() instanceof PbModule)) {
getArrayEntries()
.entrySet()
.removeIf(m -> m.getKey() instanceof PbModule
&& Objects.equals(
((PbModule) m.getKey()).getModule(),
module.getValue()));
}
}
Map<Module, ArrayEntry> arrayEntriesSorted;
if (renderModules.getValue() == Modules.Length) {
arrayEntriesSorted = getArrayEntries().entrySet().stream().sorted(Comparator.comparingDouble(entry -> Managers.TEXT.getStringWidth(ModuleUtil.getHudName(entry.getKey())) * -1)).collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(e1, e2) -> e1,
LinkedHashMap::new));
} else {
arrayEntriesSorted = getArrayEntries().entrySet().stream().sorted(Comparator.comparing(entry -> ModuleUtil.getHudName(entry.getKey()))).collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(e1, e2) -> e1,
LinkedHashMap::new));
}
for (ArrayEntry arrayEntry : arrayEntriesSorted.values()) {
arrayEntry.drawArrayEntry(width - 2, o + j * moduleOffset);
j++;
}
getRemoveEntries().forEach((key, value) -> getArrayEntries().remove(key));
getRemoveEntries().clear();
} else {
for (Map.Entry<String, Module> module : modules) {
renderText(module.getKey(), width - 2 - RENDERER.getStringWidth(module.getKey()), o + j * moduleOffset);
j++;
}
}
}
}
private void renderArmor() {
if (armor.getValue()) {
GL11.glColor4f(1.f, 1.f, 1.f, 1.f);
int x = 15;
RenderHelper.enableGUIStandardItemLighting();
for (int i = 3; i >= 0; i--) {
ItemStack stack = mc.player.inventory.armorInventory.get(i);
if (!stack.isEmpty()) {
int y = getArmorY();
final float percent = DamageUtil.getPercent(stack) / 100.0f;
GlStateManager.pushMatrix();
GlStateManager.scale(0.625F, 0.625F, 0.625F);
GlStateManager.disableDepth();
Managers.TEXT.drawStringWithShadow(
((int) (percent * 100.0f)) + "%", (((width >> 1) + x + 1) * 1.6F), (height - y - 3) * 1.6F, ColorHelper.toColor(percent * 120.0f, 100.0f, 50.0f, 1.0f).getRGB());
GlStateManager.enableDepth();
GlStateManager.scale(1.0f, 1.0f, 1.0f);
GlStateManager.popMatrix();
GlStateManager.pushMatrix();
mc.getRenderItem()
.renderItemIntoGUI(stack,
width / 2 + x,
height - y);
mc.getRenderItem()
.renderItemOverlays(mc.fontRenderer,
stack,
width / 2 + x,
height - y);
GlStateManager.popMatrix();
x += 18;
}
}
RenderHelper.disableStandardItemLighting();
}
}
public void renderText(String text, float x, float y) {
String colorCode = colorMode.getValue().getColor();
RENDERER.drawStringWithShadow(colorCode + text,
x,
y,
colorMode.getValue() == HudRainbow.None
? color.getValue().getRGB()
: (colorMode.getValue() == HudRainbow.Static ? (ColorUtil.staticRainbow((y + 1) * 0.89f, color.getValue())) : 0xffffffff));
}
public void renderPotionText(String text, float x, float y, Potion potion) {
String colorCode = potionColor.getValue() == PotionColor.Normal ? "" : colorMode.getValue().getColor();
RENDERER.drawStringWithShadow(colorCode + text,
x,
y,
potionColor.getValue() == PotionColor.Normal ? potionColorMap.get(potion).getRGB() : (
colorMode.getValue() == HudRainbow.None
? color.getValue().getRGB()
: (colorMode.getValue() == HudRainbow.Static ? (ColorUtil.staticRainbow((y + 1) * 0.89f, color.getValue())) : 0xffffffff)));
}
public Map<Module, ArrayEntry> getArrayEntries() {
return arrayEntries;
}
public Map<Module, ArrayEntry> getRemoveEntries() {
return removeEntries;
}
protected boolean isArrayMember(Module module) {
return getArrayEntries().containsKey(module)
|| module instanceof PbModule
&& getArrayEntries().containsKey(((PbModule) module)
.getModule());
}
}
| 412 | 0.811646 | 1 | 0.811646 | game-dev | MEDIA | 0.99421 | game-dev | 0.980609 | 1 | 0.980609 |
MirzaBeig/Wave-Simulator | 4,740 | Assets/Mirza Beig/Wave Simulator/Scripts/WaveSimulatorRigidbody.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WaveSimulatorRigidbody : MonoBehaviour
{
Rigidbody rigidbody;
public WaveSimulator waveSimulator;
public Texture2D analyzePixels;
[Space]
public float inputRadius = 10.0f;
public float collisionForce = 0.1f;
void Start()
{
rigidbody = GetComponent<Rigidbody>();
analyzePixels = new Texture2D(32, 32, TextureFormat.RGBA64, false, true);
}
void FixedUpdate()
{
rigidbody.WakeUp();
}
void LateUpdate()
{
//Graphics.CopyTexture(waveSimulator.GetTexture(), 0, 0, 8, 8, 32, 32, currenttexture, 0, 0, 0, 0);
}
void OnCollisionEnter(Collision collision)
{
foreach (ContactPoint contact in collision.contacts)
{
Vector3 contactPoint = contact.point;
Vector3 contactNormal = contact.normal;
Ray ray = new()
{
origin = contactPoint + (contactNormal * 0.1f),
direction = -contactNormal
};
if (collision.collider.Raycast(ray, out RaycastHit hit, 0.2f))
{
RenderTexture renderTexture = waveSimulator.GetTexture();
RenderTexture.active = renderTexture;
Vector2 collisionPixelCoord = hit.textureCoord * waveSimulator.size;
analyzePixels.ReadPixels(new Rect(collisionPixelCoord.x, collisionPixelCoord.y, 1, 1), 0, 0, false);
RenderTexture.active = null;
Color colour = analyzePixels.GetPixel(0, 0);
float waveHeight = colour.g;
//Vector3 waveVelocity = new(colour.b, 0.0f, colour.a);
float waveHeightAbs = Mathf.Abs(waveHeight);
if (waveHeightAbs > 0.001f)
{
//print(waveHeightAbs);
//rigidbody.AddForceAtPosition(waveVelocity, contactPoint, ForceMode.VelocityChange);
}
waveSimulator.AddInput(collisionPixelCoord, inputRadius * (collisionForce * collision.relativeVelocity.magnitude));
}
}
}
//void OnCollisionStay(Collision collision)
//{
// foreach (ContactPoint contact in collision.contacts)
// {
// Vector3 contactPoint = contact.point;
// Vector3 contactNormal = contact.normal;
// Ray ray = new()
// {
// origin = contactPoint + (contactNormal * 0.1f),
// direction = -contactNormal
// };
// if (collision.collider.Raycast(ray, out RaycastHit hit, 0.2f))
// {
// RenderTexture renderTexture = waveSimulator.GetTexture();
// RenderTexture.active = renderTexture;
// Vector2 collisionPixelCoord = hit.textureCoord * waveSimulator.size;
// // Read 4 pixels around the contact point
// Texture2D analyzePixels = new Texture2D(2, 2, TextureFormat.RGBA32, false);
// analyzePixels.ReadPixels(new Rect(collisionPixelCoord.x - 0.5f, collisionPixelCoord.y - 0.5f, 2, 2), 0, 0, false);
// analyzePixels.Apply();
// RenderTexture.active = null;
// // Calculate normals based on 4 pixels wave height
// Color topLeft = analyzePixels.GetPixel(0, 1);
// Color topRight = analyzePixels.GetPixel(1, 1);
// Color bottomLeft = analyzePixels.GetPixel(0, 0);
// Color bottomRight = analyzePixels.GetPixel(-1, 0);
// float heightLeft = (topLeft.g + bottomLeft.g) * 0.5f;
// float heightRight = (topRight.g + bottomRight.g) * 0.5f;
// float heightTop = (topLeft.g + topRight.g) * 0.5f;
// float heightBottom = (bottomLeft.g + bottomRight.g) * 0.5f;
// Vector3 calculatedNormal = new Vector3(heightLeft - heightRight, 2.0f, heightBottom - heightTop).normalized;
// // Determine force direction and magnitude based on the wave height and normal
// float waveHeight = (topLeft.g + topRight.g + bottomLeft.g + bottomRight.g) * 0.25f;
// Vector3 waveVelocity = calculatedNormal * waveHeight;
// float waveHeightAbs = Mathf.Abs(waveHeight);
// print(calculatedNormal);
// if (waveHeightAbs > 0.001f)
// {
// rigidbody.AddForceAtPosition(waveVelocity, contactPoint, ForceMode.VelocityChange);
// }
// //waveSimulator.AddInput(collisionPixelCoord, inputRadius);
// }
// }
//}
}
| 412 | 0.905048 | 1 | 0.905048 | game-dev | MEDIA | 0.93377 | game-dev,graphics-rendering | 0.982703 | 1 | 0.982703 |
FrozenBlock/WilderWild | 82,607 | src/main/java/net/frozenblock/wilderwild/datagen/tag/WWBlockTagProvider.java | /*
* Copyright 2025 FrozenBlock
* This file is part of Wilder Wild.
*
* This program is free software; you can modify it under
* the terms of version 1 of the FrozenBlock Modding Oasis License
* as published by FrozenBlock Modding Oasis.
*
* 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
* FrozenBlock Modding Oasis License for more details.
*
* You should have received a copy of the FrozenBlock Modding Oasis License
* along with this program; if not, see <https://github.com/FrozenBlock/Licenses>.
*/
package net.frozenblock.wilderwild.datagen.tag;
import java.util.concurrent.CompletableFuture;
import net.fabricmc.fabric.api.datagen.v1.FabricDataOutput;
import net.fabricmc.fabric.api.datagen.v1.provider.FabricTagProvider;
import net.fabricmc.fabric.api.tag.convention.v2.ConventionalBlockTags;
import net.frozenblock.lib.tag.api.FrozenBlockTags;
import net.frozenblock.wilderwild.registry.WWBlocks;
import net.frozenblock.wilderwild.tag.WWBlockTags;
import net.minecraft.core.HolderLookup;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.BlockTags;
import net.minecraft.tags.TagKey;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import org.jetbrains.annotations.NotNull;
public final class WWBlockTagProvider extends FabricTagProvider.BlockTagProvider {
public WWBlockTagProvider(@NotNull FabricDataOutput output, @NotNull CompletableFuture<HolderLookup.Provider> registries) {
super(output, registries);
}
@Override
protected void addTags(@NotNull HolderLookup.Provider arg) {
this.generateSounds();
this.generateCompat();
this.generateLib();
this.generateFeatures();
this.generateDeepDark();
this.generateHollowedAndTermites();
this.generateTags();
this.generateMinecraft();
this.generateWoods();
}
@NotNull
private TagKey<Block> getTag(String id) {
return TagKey.create(this.registryKey, ResourceLocation.parse(id));
}
private void generateCompat() {
this.getOrCreateTagBuilder(ConventionalBlockTags.CHESTS)
.add(WWBlocks.STONE_CHEST);
this.getOrCreateTagBuilder(ConventionalBlockTags.STRIPPED_LOGS)
.add(WWBlocks.STRIPPED_BAOBAB_LOG)
.add(WWBlocks.STRIPPED_WILLOW_LOG)
.add(WWBlocks.STRIPPED_CYPRESS_LOG)
.add(WWBlocks.STRIPPED_PALM_LOG)
.add(WWBlocks.STRIPPED_MAPLE_LOG)
.addOptionalTag(WWBlockTags.STRIPPED_HOLLOWED_LOGS);
}
private void generateLib() {
this.getOrCreateTagBuilder(FrozenBlockTags.DRIPSTONE_CAN_DRIP_ON)
.add(Blocks.DIRT)
.add(WWBlocks.SCORCHED_SAND, WWBlocks.SCORCHED_RED_SAND);
}
private void generateFeatures() {
this.getOrCreateTagBuilder(WWBlockTags.STONE_TRANSITION_REPLACEABLE)
.add(Blocks.GRASS_BLOCK, Blocks.DIRT, Blocks.MUD)
.add(Blocks.SAND);
this.getOrCreateTagBuilder(WWBlockTags.STONE_TRANSITION_PLACEABLE)
.add(Blocks.STONE);
this.getOrCreateTagBuilder(WWBlockTags.SMALL_SAND_TRANSITION_REPLACEABLE)
.add(Blocks.GRASS_BLOCK, Blocks.DIRT, Blocks.MUD);
this.getOrCreateTagBuilder(WWBlockTags.GRAVEL_TRANSITION_REPLACEABLE)
.add(Blocks.GRASS_BLOCK, Blocks.DIRT, Blocks.MUD)
.add(Blocks.SAND)
.add(Blocks.STONE);
this.getOrCreateTagBuilder(WWBlockTags.GRAVEL_TRANSITION_PLACEABLE)
.add(Blocks.GRAVEL);
this.getOrCreateTagBuilder(WWBlockTags.SAND_TRANSITION_REPLACEABLE)
.add(Blocks.GRASS_BLOCK, Blocks.DIRT, Blocks.MUD)
.add(Blocks.GRAVEL)
.add(Blocks.STONE);
this.getOrCreateTagBuilder(WWBlockTags.SAND_TRANSITION_PLACEABLE)
.add(Blocks.SAND);
this.getOrCreateTagBuilder(WWBlockTags.RED_SAND_TRANSITION_REPLACEABLE)
.add(Blocks.GRASS_BLOCK, Blocks.MUD)
.add(Blocks.GRAVEL)
.add(Blocks.SAND)
.addOptionalTag(BlockTags.BASE_STONE_OVERWORLD);
this.getOrCreateTagBuilder(WWBlockTags.RED_SAND_TRANSITION_PLACEABLE)
.add(Blocks.RED_SAND)
.addOptionalTag(BlockTags.TERRACOTTA);
this.getOrCreateTagBuilder(WWBlockTags.MUD_TRANSITION_REPLACEABLE)
.add(Blocks.GRASS_BLOCK, Blocks.DIRT)
.add(Blocks.CLAY)
.add(Blocks.SAND);
this.getOrCreateTagBuilder(WWBlockTags.MUD_TRANSITION_PLACEABLE)
.add(Blocks.MUD, Blocks.MUDDY_MANGROVE_ROOTS);
this.getOrCreateTagBuilder(WWBlockTags.MUD_PATH_REPLACEABLE)
.add(Blocks.GRASS_BLOCK, Blocks.DIRT)
.add(Blocks.CLAY)
.add(Blocks.SAND);
this.getOrCreateTagBuilder(WWBlockTags.COARSE_PATH_REPLACEABLE)
.add(Blocks.GRASS_BLOCK, Blocks.DIRT)
.add(Blocks.PODZOL);
this.getOrCreateTagBuilder(WWBlockTags.COARSE_CLEARING_REPLACEABLE)
.add(Blocks.GRASS_BLOCK, Blocks.DIRT)
.add(Blocks.PODZOL)
.add(Blocks.GRAVEL);
this.getOrCreateTagBuilder(WWBlockTags.ROOTED_DIRT_PATH_REPLACEABLE)
.add(Blocks.GRAVEL)
.add(Blocks.COARSE_DIRT);
this.getOrCreateTagBuilder(WWBlockTags.UNDER_WATER_SAND_PATH_REPLACEABLE)
.add(Blocks.GRASS_BLOCK, Blocks.DIRT)
.add(Blocks.GRAVEL);
this.getOrCreateTagBuilder(WWBlockTags.UNDER_WATER_GRAVEL_PATH_REPLACEABLE)
.add(Blocks.GRASS_BLOCK, Blocks.DIRT)
.add(Blocks.STONE);
this.getOrCreateTagBuilder(WWBlockTags.UNDER_WATER_CLAY_PATH_REPLACEABLE)
.add(Blocks.GRASS_BLOCK, Blocks.DIRT)
.add(Blocks.GRAVEL)
.add(Blocks.STONE);
this.getOrCreateTagBuilder(WWBlockTags.BEACH_CLAY_PATH_REPLACEABLE)
.add(Blocks.SAND);
this.getOrCreateTagBuilder(WWBlockTags.RIVER_GRAVEL_PATH_REPLACEABLE)
.add(Blocks.SAND);
this.getOrCreateTagBuilder(WWBlockTags.SAND_PATH_REPLACEABLE)
.add(Blocks.GRASS_BLOCK, Blocks.DIRT)
.add(Blocks.GRAVEL)
.addOptionalTag(BlockTags.BASE_STONE_OVERWORLD);
this.getOrCreateTagBuilder(WWBlockTags.GRAVEL_PATH_REPLACEABLE)
.add(Blocks.GRASS_BLOCK, Blocks.DIRT, Blocks.COARSE_DIRT)
.addOptionalTag(BlockTags.BASE_STONE_OVERWORLD);
this.getOrCreateTagBuilder(WWBlockTags.GRAVEL_CLEARING_REPLACEABLE)
.add(Blocks.GRASS_BLOCK, Blocks.DIRT, Blocks.COARSE_DIRT)
.addOptionalTag(BlockTags.BASE_STONE_OVERWORLD);
this.getOrCreateTagBuilder(WWBlockTags.STONE_PATH_REPLACEABLE)
.add(Blocks.GRASS_BLOCK, Blocks.DIRT)
.addOptionalTag(BlockTags.SAND);
this.getOrCreateTagBuilder(WWBlockTags.PACKED_MUD_PATH_REPLACEABLE)
.add(Blocks.GRASS_BLOCK, Blocks.DIRT, Blocks.COARSE_DIRT);
this.getOrCreateTagBuilder(WWBlockTags.MOSS_PATH_REPLACEABLE)
.add(Blocks.GRASS_BLOCK)
.add(Blocks.PODZOL);
this.getOrCreateTagBuilder(WWBlockTags.OCEAN_MOSS_REPLACEABLE)
.add(Blocks.GRAVEL)
.addOptionalTag(BlockTags.SAND);
this.getOrCreateTagBuilder(WWBlockTags.SANDSTONE_PATH_REPLACEABLE)
.add(Blocks.SAND);
this.getOrCreateTagBuilder(WWBlockTags.SMALL_COARSE_DIRT_PATH_REPLACEABLE)
.add(Blocks.RED_SAND);
this.getOrCreateTagBuilder(WWBlockTags.PACKED_MUD_PATH_BADLANDS_REPLACEABLE)
.add(Blocks.RED_SAND, Blocks.RED_SANDSTONE)
.addOptionalTag(BlockTags.TERRACOTTA);
this.getOrCreateTagBuilder(WWBlockTags.POLLEN_FEATURE_PLACEABLE)
.add(Blocks.GRASS_BLOCK)
.addOptionalTag(BlockTags.LEAVES)
.addOptionalTag(BlockTags.OVERWORLD_NATURAL_LOGS);
this.getOrCreateTagBuilder(WWBlockTags.AUBURN_CREEPING_MOSS_FEATURE_PLACEABLE)
.add(Blocks.PRISMARINE)
.add(Blocks.PRISMARINE_BRICKS)
.add(Blocks.DARK_PRISMARINE)
.add(Blocks.SEA_LANTERN)
.add(Blocks.CLAY)
.add(Blocks.GRAVEL)
.addOptionalTag(BlockTags.DIRT)
.addOptionalTag(BlockTags.STONE_BRICKS)
.addOptionalTag(BlockTags.LOGS)
.addOptionalTag(BlockTags.PLANKS)
.addOptionalTag(BlockTags.SLABS)
.addOptionalTag(BlockTags.STAIRS)
.addOptionalTag(BlockTags.DOORS)
.addOptionalTag(BlockTags.TRAPDOORS)
.addOptionalTag(BlockTags.LEAVES)
.addOptionalTag(BlockTags.BASE_STONE_OVERWORLD)
.addOptionalTag(BlockTags.BASE_STONE_NETHER);
this.getOrCreateTagBuilder(WWBlockTags.BARNACLES_FEATURE_PLACEABLE)
.add(Blocks.PRISMARINE)
.add(Blocks.PRISMARINE_BRICKS)
.add(Blocks.DARK_PRISMARINE)
.add(Blocks.SEA_LANTERN)
.add(Blocks.CLAY)
.add(Blocks.GRAVEL)
.addOptionalTag(BlockTags.DIRT)
.addOptionalTag(BlockTags.STONE_BRICKS)
.addOptionalTag(BlockTags.LOGS)
.addOptionalTag(BlockTags.PLANKS)
.addOptionalTag(BlockTags.SLABS)
.addOptionalTag(BlockTags.STAIRS)
.addOptionalTag(BlockTags.DOORS)
.addOptionalTag(BlockTags.TRAPDOORS)
.addOptionalTag(BlockTags.BASE_STONE_OVERWORLD);
this.getOrCreateTagBuilder(WWBlockTags.BARNACLES_FEATURE_PLACEABLE_STRUCTURE)
.add(Blocks.PRISMARINE)
.add(Blocks.PRISMARINE_BRICKS)
.add(Blocks.DARK_PRISMARINE)
.add(Blocks.SEA_LANTERN)
.addOptionalTag(BlockTags.STONE_BRICKS)
.addOptionalTag(BlockTags.LOGS)
.addOptionalTag(BlockTags.PLANKS)
.addOptionalTag(BlockTags.SLABS)
.addOptionalTag(BlockTags.STAIRS)
.addOptionalTag(BlockTags.DOORS)
.addOptionalTag(BlockTags.TRAPDOORS);
this.getOrCreateTagBuilder(WWBlockTags.SEA_ANEMONE_FEATURE_CANNOT_PLACE)
.add(Blocks.MOSS_BLOCK);
this.getOrCreateTagBuilder(WWBlockTags.TERMITE_DISK_REPLACEABLE)
.addOptionalTag(BlockTags.DIRT)
.addOptionalTag(BlockTags.SAND)
.addOptionalTag(BlockTags.BASE_STONE_OVERWORLD);
this.getOrCreateTagBuilder(WWBlockTags.TERMITE_DISK_BLOCKS)
.add(Blocks.COARSE_DIRT)
.add(Blocks.PACKED_MUD);
this.getOrCreateTagBuilder(WWBlockTags.BLUE_NEMATOCYST_FEATURE_PLACEABLE)
.add(Blocks.CLAY)
.add(Blocks.DRIPSTONE_BLOCK)
.add(Blocks.CALCITE)
.add(WWBlocks.BLUE_PEARLESCENT_MESOGLEA)
.addOptionalTag(BlockTags.BASE_STONE_OVERWORLD);
this.getOrCreateTagBuilder(WWBlockTags.PURPLE_NEMATOCYST_FEATURE_PLACEABLE)
.add(Blocks.CLAY)
.add(Blocks.DRIPSTONE_BLOCK)
.add(Blocks.CALCITE)
.add(WWBlocks.PURPLE_PEARLESCENT_MESOGLEA)
.addOptionalTag(BlockTags.BASE_STONE_OVERWORLD);
this.getOrCreateTagBuilder(WWBlockTags.SHELF_FUNGI_FEATURE_PLACEABLE)
.add(Blocks.MUSHROOM_STEM)
.addOptionalTag(BlockTags.OVERWORLD_NATURAL_LOGS);
this.getOrCreateTagBuilder(WWBlockTags.SHELF_FUNGI_FEATURE_PLACEABLE_NETHER)
.addOptionalTag(BlockTags.CRIMSON_STEMS)
.addOptionalTag(BlockTags.WARPED_STEMS);
this.getOrCreateTagBuilder(WWBlockTags.SCORCHED_SAND_FEATURE_INNER_REPLACEABLE)
.add(Blocks.SAND, WWBlocks.SCORCHED_SAND);
this.getOrCreateTagBuilder(WWBlockTags.SCORCHED_SAND_FEATURE_REPLACEABLE)
.add(Blocks.SAND);
this.getOrCreateTagBuilder(WWBlockTags.RED_SCORCHED_SAND_FEATURE_INNER_REPLACEABLE)
.add(Blocks.RED_SAND, WWBlocks.SCORCHED_RED_SAND);
this.getOrCreateTagBuilder(WWBlockTags.RED_SCORCHED_SAND_FEATURE_REPLACEABLE)
.add(Blocks.RED_SAND);
this.getOrCreateTagBuilder(WWBlockTags.CAVE_ICE_REPLACEABLE)
.add(Blocks.GRAVEL)
.addOptionalTag(BlockTags.DIRT)
.addOptionalTag(BlockTags.BASE_STONE_OVERWORLD)
.add(Blocks.SNOW_BLOCK)
.add(Blocks.SNOW);
this.getOrCreateTagBuilder(WWBlockTags.CAVE_FRAGILE_ICE_REPLACEABLE)
.addOptionalTag(BlockTags.ICE)
.addOptionalTag(WWBlockTags.CAVE_ICE_REPLACEABLE);
this.getOrCreateTagBuilder(WWBlockTags.DIORITE_ICE_REPLACEABLE)
.add(Blocks.GRAVEL)
.addOptionalTag(BlockTags.DIRT)
.addOptionalTag(BlockTags.BASE_STONE_OVERWORLD)
.add(Blocks.SNOW_BLOCK)
.add(Blocks.SNOW)
.add(Blocks.ICE)
.add(Blocks.BLUE_ICE)
.add(Blocks.PACKED_ICE);
this.getOrCreateTagBuilder(WWBlockTags.MESOGLEA_PATH_REPLACEABLE)
.add(Blocks.CLAY)
.add(Blocks.DRIPSTONE_BLOCK)
.add(Blocks.CALCITE)
.addOptionalTag(BlockTags.BASE_STONE_OVERWORLD);
this.getOrCreateTagBuilder(WWBlockTags.MAGMA_REPLACEABLE)
.add(Blocks.GRAVEL)
.addOptionalTag(BlockTags.DIRT)
.addOptionalTag(BlockTags.BASE_STONE_OVERWORLD);
this.getOrCreateTagBuilder(WWBlockTags.NETHER_GEYSER_REPLACEABLE)
.addOptionalTag(BlockTags.BASE_STONE_NETHER);
this.getOrCreateTagBuilder(WWBlockTags.OASIS_PATH_REPLACEABLE)
.add(Blocks.SAND)
.add(Blocks.SANDSTONE);
this.getOrCreateTagBuilder(WWBlockTags.COARSE_DIRT_DISK_REPLACEABLE)
.addOptionalTag(BlockTags.SAND)
.add(Blocks.GRASS_BLOCK, Blocks.DIRT)
.add(Blocks.CLAY)
.add(Blocks.PODZOL);
this.getOrCreateTagBuilder(WWBlockTags.RIVER_POOL_REPLACEABLE)
.addOptionalTag(BlockTags.SAND)
.addOptionalTag(BlockTags.DIRT)
.add(Blocks.GRAVEL)
.add(Blocks.CLAY);
this.getOrCreateTagBuilder(WWBlockTags.FALLEN_TREE_PLACEABLE)
.addOptionalTag(BlockTags.BASE_STONE_OVERWORLD)
.addOptionalTag(BlockTags.SAND)
.addOptionalTag(BlockTags.DIRT)
.add(Blocks.GRAVEL)
.add(Blocks.CLAY)
.add(Blocks.MOSS_BLOCK)
.add(Blocks.PACKED_MUD)
.add(Blocks.SNOW)
.add(WWBlocks.AUBURN_MOSS_BLOCK);
this.getOrCreateTagBuilder(WWBlockTags.PACKED_MUD_REPLACEABLE)
.add(Blocks.STONE)
.add(Blocks.DIRT)
.add(Blocks.SANDSTONE);
this.getOrCreateTagBuilder(WWBlockTags.SMALL_SPONGE_GROWS_ON)
.addOptionalTag(BlockTags.BASE_STONE_OVERWORLD)
.addOptionalTag(BlockTags.SAND)
.add(Blocks.GRAVEL)
.add(Blocks.SPONGE)
.add(Blocks.CLAY)
.add(Blocks.MOSS_BLOCK)
.add(WWBlocks.AUBURN_MOSS_BLOCK)
.addOptionalTag(WWBlockTags.MESOGLEA);
this.getOrCreateTagBuilder(WWBlockTags.BASIN_REPLACEABLE)
.add(Blocks.GRASS_BLOCK, Blocks.COARSE_DIRT)
.add(Blocks.PODZOL)
.add(Blocks.MOSS_BLOCK)
.add(WWBlocks.AUBURN_MOSS_BLOCK);
this.getOrCreateTagBuilder(WWBlockTags.HYDROTHERMAL_VENT_REPLACEABLE)
.add(Blocks.CLAY)
.add(Blocks.GRAVEL)
.addOptionalTag(BlockTags.DIRT)
.addOptionalTag(BlockTags.SAND)
.addOptionalTag(BlockTags.BASE_STONE_OVERWORLD);
this.getOrCreateTagBuilder(WWBlockTags.CATTAIL_FEATURE_PLACEABLE)
.addOptionalTag(BlockTags.DIRT)
.addOptionalTag(BlockTags.SAND)
.add(Blocks.CLAY);
this.getOrCreateTagBuilder(WWBlockTags.CATTAIL_FEATURE_MUD_PLACEABLE)
.add(Blocks.MUD);
this.getOrCreateTagBuilder(WWBlockTags.BUSH_MAY_PLACE_ON_FEATURE_NO_SAND)
.addOptionalTag(BlockTags.TERRACOTTA)
.addOptionalTag(BlockTags.DIRT);
this.getOrCreateTagBuilder(WWBlockTags.SAND_POOL_REPLACEABLE)
.add(Blocks.SAND);
}
private void generateTags() {
this.getOrCreateTagBuilder(WWBlockTags.MESOGLEA)
.add(WWBlocks.BLUE_MESOGLEA)
.add(WWBlocks.BLUE_PEARLESCENT_MESOGLEA)
.add(WWBlocks.LIME_MESOGLEA)
.add(WWBlocks.PINK_MESOGLEA)
.add(WWBlocks.PURPLE_PEARLESCENT_MESOGLEA)
.add(WWBlocks.RED_MESOGLEA)
.add(WWBlocks.YELLOW_MESOGLEA);
this.getOrCreateTagBuilder(WWBlockTags.NEMATOCYSTS)
.add(WWBlocks.BLUE_NEMATOCYST)
.add(WWBlocks.BLUE_PEARLESCENT_NEMATOCYST)
.add(WWBlocks.LIME_NEMATOCYST)
.add(WWBlocks.PINK_NEMATOCYST)
.add(WWBlocks.PURPLE_PEARLESCENT_NEMATOCYST)
.add(WWBlocks.RED_NEMATOCYST)
.add(WWBlocks.YELLOW_NEMATOCYST);
this.getOrCreateTagBuilder(WWBlockTags.FROGLIGHT_GOOP)
.add(WWBlocks.PEARLESCENT_FROGLIGHT_GOOP)
.add(WWBlocks.PEARLESCENT_FROGLIGHT_GOOP_BODY)
.add(WWBlocks.VERDANT_FROGLIGHT_GOOP)
.add(WWBlocks.VERDANT_FROGLIGHT_GOOP_BODY)
.add(WWBlocks.OCHRE_FROGLIGHT_GOOP)
.add(WWBlocks.OCHRE_FROGLIGHT_GOOP_BODY);
this.getOrCreateTagBuilder(WWBlockTags.ICICLE_FALLS_FROM)
.add(Blocks.ICE, Blocks.PACKED_ICE, Blocks.BLUE_ICE, WWBlocks.FRAGILE_ICE);
this.getOrCreateTagBuilder(WWBlockTags.ICICLE_GROWS_WHEN_UNDER)
.add(Blocks.ICE, Blocks.PACKED_ICE, Blocks.BLUE_ICE, WWBlocks.FRAGILE_ICE);
this.getOrCreateTagBuilder(WWBlockTags.STOPS_TUMBLEWEED)
.add(Blocks.MUD, Blocks.MUDDY_MANGROVE_ROOTS)
.add(Blocks.SLIME_BLOCK)
.add(Blocks.IRON_BARS)
.add(Blocks.HONEY_BLOCK);
this.getOrCreateTagBuilder(WWBlockTags.SPLITS_COCONUT)
.addOptionalTag(BlockTags.MINEABLE_WITH_PICKAXE)
.addOptionalTag(BlockTags.BASE_STONE_OVERWORLD)
.addOptionalTag(BlockTags.BASE_STONE_NETHER)
.addOptionalTag(BlockTags.DRAGON_IMMUNE)
.addOptionalTag(BlockTags.WITHER_IMMUNE)
.addOptionalTag(BlockTags.LOGS);
this.getOrCreateTagBuilder(WWBlockTags.FIREFLY_HIDEABLE_BLOCKS)
.add(Blocks.SHORT_GRASS, Blocks.TALL_GRASS)
.add(Blocks.FERN, Blocks.LARGE_FERN)
.add(WWBlocks.FROZEN_SHORT_GRASS, WWBlocks.FROZEN_TALL_GRASS)
.add(WWBlocks.FROZEN_FERN, WWBlocks.FROZEN_LARGE_FERN)
.add(Blocks.PEONY)
.add(Blocks.ROSE_BUSH)
.add(Blocks.DEAD_BUSH)
.add(WWBlocks.CATTAIL)
.add(WWBlocks.MILKWEED)
.add(WWBlocks.BUSH)
.addOptionalTag(BlockTags.SMALL_FLOWERS);
this.getOrCreateTagBuilder(WWBlockTags.CRAB_HIDEABLE)
.addOptionalTag(BlockTags.DIRT)
.addOptionalTag(BlockTags.SAND)
.add(Blocks.CLAY)
.add(Blocks.GRAVEL);
this.getOrCreateTagBuilder(WWBlockTags.OSTRICH_BEAK_BURYABLE)
.addOptionalTag(BlockTags.MINEABLE_WITH_SHOVEL)
.addOptionalTag(BlockTags.MINEABLE_WITH_HOE)
.addOptionalTag(BlockTags.WOOL);
this.getOrCreateTagBuilder(WWBlockTags.PENGUIN_IGNORE_FRICTION)
.addOptionalTag(BlockTags.ICE);
this.getOrCreateTagBuilder(WWBlockTags.PENGUINS_SPAWNABLE_ON)
.add(Blocks.ICE)
.add(Blocks.SNOW_BLOCK)
.add(Blocks.SAND)
.add(Blocks.GRAVEL)
.addOptionalTag(BlockTags.BASE_STONE_OVERWORLD)
.addOptionalTag(BlockTags.ANIMALS_SPAWNABLE_ON);
this.getOrCreateTagBuilder(FrozenBlockTags.BLOWING_CAN_PASS_THROUGH)
.addOptionalTag(WWBlockTags.MESOGLEA);
this.getOrCreateTagBuilder(WWBlockTags.NO_LIGHTNING_BLOCK_PARTICLES)
.add(Blocks.LIGHTNING_ROD);
this.getOrCreateTagBuilder(WWBlockTags.NO_LIGHTNING_SMOKE_PARTICLES)
.add(Blocks.LIGHTNING_ROD);
this.getOrCreateTagBuilder(ConventionalBlockTags.GLASS_BLOCKS)
.add(WWBlocks.ECHO_GLASS);
this.getOrCreateTagBuilder(WWBlockTags.BUSH_MAY_PLACE_ON)
.addOptionalTag(BlockTags.DEAD_BUSH_MAY_PLACE_ON);
this.getOrCreateTagBuilder(WWBlockTags.MYCELIUM_GROWTH_REPLACEABLE)
.add(Blocks.SHORT_GRASS)
.add(Blocks.FERN);
this.getOrCreateTagBuilder(WWBlockTags.RED_MOSS_REPLACEABLE)
.addOptionalTag(BlockTags.MOSS_REPLACEABLE)
.addOptionalTag(BlockTags.SAND)
.add(Blocks.CLAY)
.add(Blocks.GRAVEL);
this.getOrCreateTagBuilder(WWBlockTags.SNOW_GENERATION_CAN_SEARCH_THROUGH)
.add(Blocks.LADDER)
.add(WWBlocks.ICICLE)
.addOptionalTag(BlockTags.LEAVES)
.addOptionalTag(BlockTags.WALLS)
.addOptionalTag(BlockTags.FENCE_GATES)
.addOptionalTag(BlockTags.FENCES);
}
private void generateDeepDark() {
this.getOrCreateTagBuilder(WWBlockTags.ANCIENT_CITY_BLOCKS)
.add(Blocks.COBBLED_DEEPSLATE, Blocks.COBBLED_DEEPSLATE_STAIRS, Blocks.COBBLED_DEEPSLATE_SLAB, Blocks.COBBLED_DEEPSLATE_WALL)
.add(Blocks.POLISHED_DEEPSLATE, Blocks.POLISHED_DEEPSLATE_STAIRS, Blocks.POLISHED_DEEPSLATE_SLAB, Blocks.POLISHED_DEEPSLATE_WALL)
.add(Blocks.DEEPSLATE_BRICKS, Blocks.DEEPSLATE_BRICK_STAIRS, Blocks.DEEPSLATE_BRICK_SLAB, Blocks.DEEPSLATE_BRICK_WALL)
.add(Blocks.CRACKED_DEEPSLATE_BRICKS)
.add(Blocks.DEEPSLATE_TILES, Blocks.DEEPSLATE_TILE_STAIRS)
.add(Blocks.CHISELED_DEEPSLATE)
.add(Blocks.REINFORCED_DEEPSLATE)
.add(Blocks.POLISHED_BASALT, Blocks.SMOOTH_BASALT)
.add(Blocks.DARK_OAK_LOG, Blocks.DARK_OAK_PLANKS, Blocks.DARK_OAK_FENCE)
.add(Blocks.LIGHT_BLUE_CARPET, Blocks.BLUE_CARPET)
.add(Blocks.LIGHT_BLUE_WOOL, Blocks.GRAY_WOOL)
.add(Blocks.CHEST, WWBlocks.STONE_CHEST)
.add(Blocks.LADDER)
.add(Blocks.CANDLE, Blocks.WHITE_CANDLE)
.add(Blocks.SOUL_LANTERN, Blocks.SOUL_FIRE)
.add(Blocks.SOUL_SAND);
this.getOrCreateTagBuilder(WWBlockTags.SCULK_SLAB_REPLACEABLE)
.add(Blocks.STONE_SLAB, Blocks.GRANITE_SLAB, Blocks.DIORITE_SLAB, Blocks.ANDESITE_SLAB, Blocks.BLACKSTONE_SLAB, WWBlocks.GABBRO_SLAB);
this.getOrCreateTagBuilder(WWBlockTags.SCULK_SLAB_REPLACEABLE_WORLDGEN)
.add(Blocks.COBBLED_DEEPSLATE_SLAB, Blocks.POLISHED_DEEPSLATE_SLAB, Blocks.DEEPSLATE_BRICK_SLAB, Blocks.DEEPSLATE_TILE_SLAB)
.addOptionalTag(WWBlockTags.SCULK_SLAB_REPLACEABLE);
this.getOrCreateTagBuilder(WWBlockTags.SCULK_STAIR_REPLACEABLE)
.add(Blocks.STONE_STAIRS, Blocks.GRANITE_STAIRS, Blocks.DIORITE_STAIRS, Blocks.ANDESITE_STAIRS, Blocks.BLACKSTONE_STAIRS, WWBlocks.GABBRO_STAIRS);
this.getOrCreateTagBuilder(WWBlockTags.SCULK_STAIR_REPLACEABLE_WORLDGEN)
.add(Blocks.COBBLED_DEEPSLATE_STAIRS, Blocks.POLISHED_DEEPSLATE_STAIRS, Blocks.DEEPSLATE_BRICK_STAIRS, Blocks.DEEPSLATE_TILE_STAIRS)
.addOptionalTag(WWBlockTags.SCULK_STAIR_REPLACEABLE);
this.getOrCreateTagBuilder(WWBlockTags.SCULK_WALL_REPLACEABLE)
.add(Blocks.COBBLESTONE_WALL, Blocks.GRANITE_WALL, Blocks.DIORITE_WALL, Blocks.ANDESITE_WALL, Blocks.BLACKSTONE_WALL, WWBlocks.GABBRO_WALL);
this.getOrCreateTagBuilder(WWBlockTags.SCULK_WALL_REPLACEABLE_WORLDGEN)
.add(Blocks.COBBLED_DEEPSLATE_WALL, Blocks.POLISHED_DEEPSLATE_WALL, Blocks.DEEPSLATE_BRICK_WALL, Blocks.DEEPSLATE_TILE_WALL)
.addOptionalTag(WWBlockTags.SCULK_WALL_REPLACEABLE);
this.getOrCreateTagBuilder(BlockTags.OCCLUDES_VIBRATION_SIGNALS)
.add(WWBlocks.ECHO_GLASS);
}
private void generateHollowedAndTermites() {
this.getOrCreateTagBuilder(WWBlockTags.HOLLOWED_ACACIA_LOGS)
.add(WWBlocks.HOLLOWED_ACACIA_LOG, WWBlocks.STRIPPED_HOLLOWED_ACACIA_LOG);
this.getOrCreateTagBuilder(WWBlockTags.HOLLOWED_BIRCH_LOGS)
.add(WWBlocks.HOLLOWED_BIRCH_LOG, WWBlocks.STRIPPED_HOLLOWED_BIRCH_LOG);
this.getOrCreateTagBuilder(WWBlockTags.HOLLOWED_CHERRY_LOGS)
.add(WWBlocks.HOLLOWED_CHERRY_LOG, WWBlocks.STRIPPED_HOLLOWED_CHERRY_LOG);
this.getOrCreateTagBuilder(WWBlockTags.HOLLOWED_CRIMSON_STEMS)
.add(WWBlocks.HOLLOWED_CRIMSON_STEM, WWBlocks.STRIPPED_HOLLOWED_CRIMSON_STEM);
this.getOrCreateTagBuilder(WWBlockTags.HOLLOWED_DARK_OAK_LOGS)
.add(WWBlocks.HOLLOWED_DARK_OAK_LOG, WWBlocks.STRIPPED_HOLLOWED_DARK_OAK_LOG);
this.getOrCreateTagBuilder(WWBlockTags.HOLLOWED_JUNGLE_LOGS)
.add(WWBlocks.HOLLOWED_JUNGLE_LOG, WWBlocks.STRIPPED_HOLLOWED_JUNGLE_LOG);
this.getOrCreateTagBuilder(WWBlockTags.HOLLOWED_MANGROVE_LOGS)
.add(WWBlocks.HOLLOWED_MANGROVE_LOG, WWBlocks.STRIPPED_HOLLOWED_MANGROVE_LOG);
this.getOrCreateTagBuilder(WWBlockTags.HOLLOWED_OAK_LOGS)
.add(WWBlocks.HOLLOWED_OAK_LOG, WWBlocks.STRIPPED_HOLLOWED_OAK_LOG);
this.getOrCreateTagBuilder(WWBlockTags.HOLLOWED_SPRUCE_LOGS)
.add(WWBlocks.HOLLOWED_SPRUCE_LOG, WWBlocks.STRIPPED_HOLLOWED_SPRUCE_LOG);
this.getOrCreateTagBuilder(WWBlockTags.HOLLOWED_WARPED_STEMS)
.add(WWBlocks.HOLLOWED_WARPED_STEM, WWBlocks.STRIPPED_HOLLOWED_WARPED_STEM);
this.getOrCreateTagBuilder(WWBlockTags.HOLLOWED_BAOBAB_LOGS)
.add(WWBlocks.HOLLOWED_BAOBAB_LOG, WWBlocks.STRIPPED_HOLLOWED_BAOBAB_LOG);
this.getOrCreateTagBuilder(WWBlockTags.HOLLOWED_WILLOW_LOGS)
.add(WWBlocks.HOLLOWED_WILLOW_LOG, WWBlocks.STRIPPED_HOLLOWED_WILLOW_LOG);
this.getOrCreateTagBuilder(WWBlockTags.HOLLOWED_CYPRESS_LOGS)
.add(WWBlocks.HOLLOWED_CYPRESS_LOG, WWBlocks.STRIPPED_HOLLOWED_CYPRESS_LOG);
this.getOrCreateTagBuilder(WWBlockTags.HOLLOWED_PALM_LOGS)
.add(WWBlocks.HOLLOWED_PALM_LOG, WWBlocks.STRIPPED_HOLLOWED_PALM_LOG);
this.getOrCreateTagBuilder(WWBlockTags.HOLLOWED_MAPLE_LOGS)
.add(WWBlocks.HOLLOWED_MAPLE_LOG, WWBlocks.STRIPPED_HOLLOWED_MAPLE_LOG);
this.getOrCreateTagBuilder(WWBlockTags.HOLLOWED_LOGS_THAT_BURN)
.addOptionalTag(WWBlockTags.HOLLOWED_ACACIA_LOGS)
.addOptionalTag(WWBlockTags.HOLLOWED_BIRCH_LOGS)
.addOptionalTag(WWBlockTags.HOLLOWED_CHERRY_LOGS)
.addOptionalTag(WWBlockTags.HOLLOWED_CRIMSON_STEMS)
.addOptionalTag(WWBlockTags.HOLLOWED_DARK_OAK_LOGS)
.addOptionalTag(WWBlockTags.HOLLOWED_JUNGLE_LOGS)
.addOptionalTag(WWBlockTags.HOLLOWED_MANGROVE_LOGS)
.addOptionalTag(WWBlockTags.HOLLOWED_OAK_LOGS)
.addOptionalTag(WWBlockTags.HOLLOWED_SPRUCE_LOGS)
.addOptionalTag(WWBlockTags.HOLLOWED_WARPED_STEMS)
.addOptionalTag(WWBlockTags.HOLLOWED_BAOBAB_LOGS)
.addOptionalTag(WWBlockTags.HOLLOWED_WILLOW_LOGS)
.addOptionalTag(WWBlockTags.HOLLOWED_CYPRESS_LOGS)
.addOptionalTag(WWBlockTags.HOLLOWED_PALM_LOGS)
.addOptionalTag(WWBlockTags.HOLLOWED_MAPLE_LOGS);
this.getOrCreateTagBuilder(WWBlockTags.HOLLOWED_LOGS_DONT_BURN)
.addOptionalTag(WWBlockTags.HOLLOWED_CRIMSON_STEMS)
.addOptionalTag(WWBlockTags.HOLLOWED_WARPED_STEMS);
this.getOrCreateTagBuilder(WWBlockTags.HOLLOWED_LOGS)
.addOptionalTag(WWBlockTags.HOLLOWED_LOGS_THAT_BURN)
.addOptionalTag(WWBlockTags.HOLLOWED_LOGS_DONT_BURN);
this.getOrCreateTagBuilder(WWBlockTags.STRIPPED_HOLLOWED_LOGS_THAT_BURN)
.add(WWBlocks.STRIPPED_HOLLOWED_ACACIA_LOG)
.add(WWBlocks.STRIPPED_HOLLOWED_BIRCH_LOG)
.add(WWBlocks.STRIPPED_HOLLOWED_CHERRY_LOG)
.add(WWBlocks.STRIPPED_HOLLOWED_DARK_OAK_LOG)
.add(WWBlocks.STRIPPED_HOLLOWED_JUNGLE_LOG)
.add(WWBlocks.STRIPPED_HOLLOWED_MANGROVE_LOG)
.add(WWBlocks.STRIPPED_HOLLOWED_OAK_LOG)
.add(WWBlocks.STRIPPED_HOLLOWED_SPRUCE_LOG)
.add(WWBlocks.STRIPPED_HOLLOWED_BAOBAB_LOG)
.add(WWBlocks.STRIPPED_HOLLOWED_WILLOW_LOG)
.add(WWBlocks.STRIPPED_HOLLOWED_CYPRESS_LOG)
.add(WWBlocks.STRIPPED_HOLLOWED_PALM_LOG)
.add(WWBlocks.STRIPPED_HOLLOWED_MAPLE_LOG);
this.getOrCreateTagBuilder(WWBlockTags.STRIPPED_HOLLOWED_LOGS_DONT_BURN)
.add(WWBlocks.STRIPPED_HOLLOWED_CRIMSON_STEM)
.add(WWBlocks.STRIPPED_HOLLOWED_WARPED_STEM);
this.getOrCreateTagBuilder(WWBlockTags.STRIPPED_HOLLOWED_LOGS)
.addOptionalTag(WWBlockTags.STRIPPED_HOLLOWED_LOGS_THAT_BURN)
.addOptionalTag(WWBlockTags.STRIPPED_HOLLOWED_LOGS_DONT_BURN);
this.getOrCreateTagBuilder(WWBlockTags.BLOCKS_TERMITE)
.addOptionalTag(ConventionalBlockTags.GLASS_BLOCKS)
.addOptionalTag(ConventionalBlockTags.GLASS_PANES);
this.getOrCreateTagBuilder(WWBlockTags.KILLS_TERMITE)
.add(Blocks.WATER, Blocks.WATER_CAULDRON)
.add(Blocks.LAVA, Blocks.LAVA_CAULDRON)
.add(Blocks.POWDER_SNOW, Blocks.POWDER_SNOW_CAULDRON)
.add(Blocks.CRIMSON_ROOTS, Blocks.NETHER_SPROUTS)
.add(Blocks.CRIMSON_PLANKS, Blocks.WARPED_PLANKS)
.add(Blocks.WEEPING_VINES, Blocks.WEEPING_VINES_PLANT)
.add(Blocks.TWISTING_VINES, Blocks.TWISTING_VINES_PLANT)
.add(Blocks.CRIMSON_SLAB, Blocks.WARPED_SLAB)
.add(Blocks.CRIMSON_PRESSURE_PLATE, Blocks.WARPED_PRESSURE_PLATE)
.add(Blocks.CRIMSON_FENCE, Blocks.WARPED_FENCE)
.add(Blocks.CRIMSON_TRAPDOOR, Blocks.WARPED_TRAPDOOR)
.add(Blocks.CRIMSON_FENCE_GATE, Blocks.WARPED_FENCE_GATE)
.add(Blocks.CRIMSON_STAIRS, Blocks.WARPED_STAIRS)
.add(Blocks.CRIMSON_BUTTON, Blocks.WARPED_BUTTON)
.add(Blocks.CRIMSON_DOOR, Blocks.WARPED_DOOR)
.add(Blocks.CRIMSON_SIGN, Blocks.WARPED_SIGN)
.add(Blocks.CRIMSON_WALL_SIGN, Blocks.WARPED_WALL_SIGN)
.add(Blocks.CRIMSON_HANGING_SIGN, Blocks.WARPED_HANGING_SIGN)
.add(Blocks.CRIMSON_WALL_HANGING_SIGN, Blocks.WARPED_WALL_HANGING_SIGN)
.add(Blocks.CRIMSON_STEM, Blocks.WARPED_STEM)
.add(Blocks.STRIPPED_CRIMSON_STEM, Blocks.STRIPPED_WARPED_STEM)
.add(Blocks.STRIPPED_CRIMSON_HYPHAE, Blocks.STRIPPED_WARPED_HYPHAE)
.add(Blocks.CRIMSON_NYLIUM, Blocks.WARPED_NYLIUM)
.add(Blocks.CRIMSON_FUNGUS, Blocks.WARPED_FUNGUS)
.add(Blocks.NETHER_WART_BLOCK, Blocks.WARPED_WART_BLOCK)
.add(Blocks.NETHER_WART)
.add(Blocks.REDSTONE_WIRE, Blocks.REDSTONE_BLOCK, Blocks.REDSTONE_TORCH, Blocks.REDSTONE_WALL_TORCH)
.add(WWBlocks.HOLLOWED_CRIMSON_STEM, WWBlocks.HOLLOWED_WARPED_STEM)
.add(WWBlocks.STRIPPED_HOLLOWED_CRIMSON_STEM, WWBlocks.STRIPPED_HOLLOWED_WARPED_STEM)
.addOptionalTag(BlockTags.WARPED_STEMS)
.addOptionalTag(BlockTags.CRIMSON_STEMS);
}
private void generateMinecraft() {
this.getOrCreateTagBuilder(BlockTags.MINEABLE_WITH_AXE)
.add(Blocks.CACTUS)
.add(Blocks.SWEET_BERRY_BUSH)
.addOptionalTag(WWBlockTags.HOLLOWED_LOGS)
.add(WWBlocks.TUMBLEWEED, WWBlocks.TUMBLEWEED_PLANT)
.add(WWBlocks.PRICKLY_PEAR_CACTUS)
.add(WWBlocks.MYCELIUM_GROWTH)
.add(WWBlocks.BROWN_SHELF_FUNGI, WWBlocks.RED_SHELF_FUNGI)
.add(WWBlocks.CRIMSON_SHELF_FUNGI, WWBlocks.WARPED_SHELF_FUNGI)
.add(WWBlocks.CLOVERS)
.add(WWBlocks.FROZEN_SHORT_GRASS, WWBlocks.FROZEN_TALL_GRASS)
.add(WWBlocks.FROZEN_FERN, WWBlocks.FROZEN_LARGE_FERN)
.add(WWBlocks.BARNACLES);
this.getOrCreateTagBuilder(BlockTags.MINEABLE_WITH_HOE)
.add(Blocks.SWEET_BERRY_BUSH)
.add(WWBlocks.OSSEOUS_SCULK)
.add(WWBlocks.SCULK_SLAB, WWBlocks.SCULK_STAIRS, WWBlocks.SCULK_WALL)
.add(WWBlocks.HANGING_TENDRIL)
.add(WWBlocks.BAOBAB_LEAVES)
.add(WWBlocks.WILLOW_LEAVES)
.add(WWBlocks.CYPRESS_LEAVES)
.add(WWBlocks.PALM_FRONDS)
.add(WWBlocks.YELLOW_MAPLE_LEAVES)
.add(WWBlocks.ORANGE_MAPLE_LEAVES)
.add(WWBlocks.RED_MAPLE_LEAVES)
.add(WWBlocks.TUMBLEWEED_PLANT)
.add(WWBlocks.TUMBLEWEED)
.add(WWBlocks.PRICKLY_PEAR_CACTUS)
.add(WWBlocks.SPONGE_BUD)
.add(WWBlocks.BARNACLES)
.add(WWBlocks.WILDFLOWERS)
.add(WWBlocks.PHLOX)
.add(WWBlocks.LANTANAS)
.add(WWBlocks.AUBURN_MOSS_BLOCK)
.add(WWBlocks.AUBURN_MOSS_CARPET)
.add(WWBlocks.AUBURN_CREEPING_MOSS)
.addOptionalTag(WWBlockTags.FROGLIGHT_GOOP);
this.getOrCreateTagBuilder(BlockTags.MINEABLE_WITH_PICKAXE)
.add(WWBlocks.STONE_CHEST)
.add(WWBlocks.NULL_BLOCK)
.add(WWBlocks.DISPLAY_LANTERN)
.add(WWBlocks.SCORCHED_SAND, WWBlocks.SCORCHED_RED_SAND)
.add(WWBlocks.CHISELED_MUD_BRICKS)
.add(WWBlocks.CRACKED_MUD_BRICKS)
.add(WWBlocks.MOSSY_MUD_BRICKS, WWBlocks.MOSSY_MUD_BRICK_STAIRS, WWBlocks.MOSSY_MUD_BRICK_SLAB, WWBlocks.MOSSY_MUD_BRICK_WALL)
.add(WWBlocks.GABBRO)
.add(WWBlocks.GEYSER)
.add(WWBlocks.GABBRO_STAIRS, WWBlocks.GABBRO_SLAB, WWBlocks.GABBRO_WALL)
.add(WWBlocks.POLISHED_GABBRO, WWBlocks.POLISHED_GABBRO_STAIRS, WWBlocks.POLISHED_GABBRO_SLAB, WWBlocks.POLISHED_GABBRO_WALL)
.add(WWBlocks.CHISELED_GABBRO_BRICKS)
.add(WWBlocks.GABBRO_BRICKS)
.add(WWBlocks.CRACKED_GABBRO_BRICKS)
.add(WWBlocks.GABBRO_BRICK_STAIRS, WWBlocks.GABBRO_BRICK_SLAB, WWBlocks.GABBRO_BRICK_WALL)
.add(WWBlocks.MOSSY_GABBRO_BRICKS, WWBlocks.MOSSY_GABBRO_BRICK_STAIRS, WWBlocks.MOSSY_GABBRO_BRICK_SLAB, WWBlocks.MOSSY_GABBRO_BRICK_WALL)
.add(WWBlocks.FRAGILE_ICE)
.add(WWBlocks.ICICLE)
.add(WWBlocks.BARNACLES);
this.getOrCreateTagBuilder(BlockTags.MINEABLE_WITH_SHOVEL)
.add(WWBlocks.SCORCHED_SAND, WWBlocks.SCORCHED_RED_SAND)
.add(WWBlocks.TERMITE_MOUND)
.add(WWBlocks.PLANKTON)
.addOptionalTag(WWBlockTags.MESOGLEA);
this.getOrCreateTagBuilder(BlockTags.SWORD_EFFICIENT)
.add(WWBlocks.BUSH)
.add(WWBlocks.TUMBLEWEED, WWBlocks.TUMBLEWEED_PLANT)
.add(WWBlocks.MILKWEED)
.add(WWBlocks.DATURA)
.add(WWBlocks.CATTAIL)
.add(WWBlocks.FLOWERING_LILY_PAD)
.add(WWBlocks.ALGAE)
.add(WWBlocks.PLANKTON)
.add(WWBlocks.BROWN_SHELF_FUNGI)
.add(WWBlocks.RED_SHELF_FUNGI)
.add(WWBlocks.CRIMSON_SHELF_FUNGI)
.add(WWBlocks.WARPED_SHELF_FUNGI)
.add(WWBlocks.SPONGE_BUD)
.add(WWBlocks.BARNACLES)
.add(WWBlocks.PRICKLY_PEAR_CACTUS)
.add(WWBlocks.MYCELIUM_GROWTH)
.add(WWBlocks.WILDFLOWERS)
.add(WWBlocks.PHLOX)
.add(WWBlocks.LANTANAS)
.add(WWBlocks.CLOVERS)
.add(WWBlocks.FROZEN_SHORT_GRASS, WWBlocks.FROZEN_TALL_GRASS)
.add(WWBlocks.FROZEN_FERN, WWBlocks.FROZEN_LARGE_FERN)
.add(WWBlocks.AUBURN_MOSS_CARPET)
.add(WWBlocks.AUBURN_CREEPING_MOSS)
.addOptionalTag(WWBlockTags.NEMATOCYSTS)
.addOptionalTag(WWBlockTags.FROGLIGHT_GOOP);
this.getOrCreateTagBuilder(BlockTags.SAND)
.add(WWBlocks.SCORCHED_SAND, WWBlocks.SCORCHED_RED_SAND);
this.getOrCreateTagBuilder(BlockTags.DIRT)
.add(WWBlocks.AUBURN_MOSS_BLOCK);
this.getOrCreateTagBuilder(BlockTags.SNIFFER_DIGGABLE_BLOCK)
.add(WWBlocks.AUBURN_MOSS_BLOCK);
this.getOrCreateTagBuilder(BlockTags.NEEDS_STONE_TOOL)
.add(WWBlocks.GABBRO)
.add(WWBlocks.GEYSER)
.add(WWBlocks.GABBRO_STAIRS, WWBlocks.GABBRO_SLAB, WWBlocks.GABBRO_WALL)
.add(WWBlocks.POLISHED_GABBRO, WWBlocks.POLISHED_GABBRO_STAIRS, WWBlocks.POLISHED_GABBRO_SLAB, WWBlocks.POLISHED_GABBRO_WALL)
.add(WWBlocks.CHISELED_GABBRO_BRICKS)
.add(WWBlocks.GABBRO_BRICKS)
.add(WWBlocks.CRACKED_GABBRO_BRICKS)
.add(WWBlocks.GABBRO_BRICK_STAIRS, WWBlocks.GABBRO_BRICK_SLAB, WWBlocks.GABBRO_BRICK_WALL)
.add(WWBlocks.MOSSY_GABBRO_BRICKS, WWBlocks.MOSSY_GABBRO_BRICK_STAIRS, WWBlocks.MOSSY_GABBRO_BRICK_SLAB, WWBlocks.MOSSY_GABBRO_BRICK_WALL);
this.getOrCreateTagBuilder(BlockTags.BASE_STONE_OVERWORLD)
.add(WWBlocks.GABBRO);
this.getOrCreateTagBuilder(BlockTags.DEEPSLATE_ORE_REPLACEABLES)
.add(WWBlocks.GABBRO);
this.getOrCreateTagBuilder(BlockTags.STAIRS)
.add(WWBlocks.SCULK_STAIRS)
.add(WWBlocks.MOSSY_MUD_BRICK_STAIRS)
.add(WWBlocks.GABBRO_STAIRS)
.add(WWBlocks.POLISHED_GABBRO_STAIRS)
.add(WWBlocks.GABBRO_BRICK_STAIRS)
.add(WWBlocks.MOSSY_GABBRO_BRICK_STAIRS);
this.getOrCreateTagBuilder(BlockTags.SLABS)
.add(WWBlocks.SCULK_SLAB)
.add(WWBlocks.MOSSY_MUD_BRICK_SLAB)
.add(WWBlocks.GABBRO_SLAB)
.add(WWBlocks.POLISHED_GABBRO_SLAB)
.add(WWBlocks.GABBRO_BRICK_SLAB)
.add(WWBlocks.MOSSY_GABBRO_BRICK_SLAB);
this.getOrCreateTagBuilder(BlockTags.WALLS)
.add(WWBlocks.SCULK_WALL)
.add(WWBlocks.MOSSY_MUD_BRICK_WALL)
.add(WWBlocks.GABBRO_WALL)
.add(WWBlocks.POLISHED_GABBRO_WALL)
.add(WWBlocks.GABBRO_BRICK_WALL)
.add(WWBlocks.MOSSY_GABBRO_BRICK_WALL);
this.getOrCreateTagBuilder(BlockTags.CLIMBABLE)
.addOptionalTag(WWBlockTags.FROGLIGHT_GOOP);
this.getOrCreateTagBuilder(BlockTags.INSIDE_STEP_SOUND_BLOCKS)
.add(Blocks.COBWEB)
.add(Blocks.LILY_PAD)
.add(WWBlocks.FLOWERING_LILY_PAD)
.add(WWBlocks.ALGAE)
.add(WWBlocks.PLANKTON)
.add(WWBlocks.TUMBLEWEED_PLANT)
.add(WWBlocks.SPONGE_BUD)
.add(WWBlocks.BARNACLES)
.add(WWBlocks.PRICKLY_PEAR_CACTUS)
.add(WWBlocks.POLLEN)
.add(WWBlocks.WILDFLOWERS)
.add(WWBlocks.PHLOX)
.add(WWBlocks.LANTANAS);
this.getOrCreateTagBuilder(BlockTags.REPLACEABLE)
.add(WWBlocks.MYCELIUM_GROWTH)
.addOptionalTag(WWBlockTags.LEAF_LITTERS);
this.getOrCreateTagBuilder(BlockTags.GEODE_INVALID_BLOCKS)
.add(WWBlocks.FRAGILE_ICE);
this.getOrCreateTagBuilder(BlockTags.SNOW_LAYER_CANNOT_SURVIVE_ON)
.add(WWBlocks.FRAGILE_ICE);
this.getOrCreateTagBuilder(BlockTags.ICE)
.add(WWBlocks.FRAGILE_ICE);
this.getOrCreateTagBuilder(BlockTags.REPLACEABLE_BY_TREES)
.add(WWBlocks.MYCELIUM_GROWTH)
.add(WWBlocks.DATURA)
.add(WWBlocks.CATTAIL)
.add(WWBlocks.MILKWEED)
.add(WWBlocks.BUSH)
.add(WWBlocks.POLLEN)
.add(WWBlocks.BARNACLES)
.add(WWBlocks.WILDFLOWERS)
.add(WWBlocks.PHLOX)
.add(WWBlocks.LANTANAS)
.add(WWBlocks.CLOVERS)
.add(WWBlocks.FROZEN_SHORT_GRASS, WWBlocks.FROZEN_TALL_GRASS)
.add(WWBlocks.FROZEN_FERN, WWBlocks.FROZEN_LARGE_FERN)
.add(WWBlocks.SEA_ANEMONE)
.add(WWBlocks.SEA_WHIP)
.add(WWBlocks.TUBE_WORMS)
.addOptionalTag(WWBlockTags.LEAF_LITTERS);
this.getOrCreateTagBuilder(BlockTags.COMBINATION_STEP_SOUND_BLOCKS)
.addOptionalTag(WWBlockTags.LEAF_LITTERS)
.add(WWBlocks.POLLEN)
.add(WWBlocks.BARNACLES)
.add(WWBlocks.AUBURN_MOSS_CARPET)
.add(WWBlocks.AUBURN_CREEPING_MOSS);
this.getOrCreateTagBuilder(BlockTags.FLOWER_POTS)
.add(WWBlocks.POTTED_BAOBAB_NUT)
.add(WWBlocks.POTTED_WILLOW_SAPLING)
.add(WWBlocks.POTTED_CYPRESS_SAPLING)
.add(WWBlocks.POTTED_COCONUT)
.add(WWBlocks.POTTED_MAPLE_SAPLING)
.add(WWBlocks.POTTED_BUSH)
.add(WWBlocks.POTTED_BIG_DRIPLEAF)
.add(WWBlocks.POTTED_SMALL_DRIPLEAF)
.add(WWBlocks.POTTED_SHORT_GRASS)
.add(WWBlocks.POTTED_MYCELIUM_GROWTH)
.add(WWBlocks.POTTED_TUMBLEWEED)
.add(WWBlocks.POTTED_TUMBLEWEED_PLANT)
.add(WWBlocks.POTTED_PRICKLY_PEAR)
.add(WWBlocks.POTTED_CARNATION)
.add(WWBlocks.POTTED_MARIGOLD)
.add(WWBlocks.POTTED_SEEDING_DANDELION)
.add(WWBlocks.POTTED_PASQUEFLOWER)
.add(WWBlocks.POTTED_RED_HIBISCUS)
.add(WWBlocks.POTTED_YELLOW_HIBISCUS)
.add(WWBlocks.POTTED_WHITE_HIBISCUS)
.add(WWBlocks.POTTED_PINK_HIBISCUS)
.add(WWBlocks.POTTED_PURPLE_HIBISCUS)
.add(WWBlocks.POTTED_PINK_PETALS)
.add(WWBlocks.POTTED_WILDFLOWERS)
.add(WWBlocks.POTTED_PHLOX)
.add(WWBlocks.POTTED_LANTANAS)
.add(WWBlocks.POTTED_FROZEN_SHORT_GRASS)
.add(WWBlocks.POTTED_FROZEN_FERN);
this.getOrCreateTagBuilder(BlockTags.FLOWERS)
.add(WWBlocks.POLLEN)
.add(WWBlocks.WILDFLOWERS)
.add(WWBlocks.PHLOX)
.add(WWBlocks.LANTANAS);
this.getOrCreateTagBuilder(BlockTags.SMALL_FLOWERS)
.add(WWBlocks.CARNATION)
.add(WWBlocks.MARIGOLD)
.add(WWBlocks.SEEDING_DANDELION)
.add(WWBlocks.PASQUEFLOWER)
.add(WWBlocks.RED_HIBISCUS)
.add(WWBlocks.YELLOW_HIBISCUS)
.add(WWBlocks.WHITE_HIBISCUS)
.add(WWBlocks.PINK_HIBISCUS)
.add(WWBlocks.PURPLE_HIBISCUS)
.add(WWBlocks.FLOWERING_LILY_PAD);
this.getOrCreateTagBuilder(BlockTags.TALL_FLOWERS)
.add(WWBlocks.DATURA)
.add(WWBlocks.CATTAIL)
.add(WWBlocks.MILKWEED);
this.getOrCreateTagBuilder(BlockTags.FROG_PREFER_JUMP_TO)
.add(WWBlocks.FLOWERING_LILY_PAD);
this.getOrCreateTagBuilder(BlockTags.BIG_DRIPLEAF_PLACEABLE)
.addOptionalTag(WWBlockTags.MESOGLEA);
this.getOrCreateTagBuilder(BlockTags.SMALL_DRIPLEAF_PLACEABLE)
.addOptionalTag(WWBlockTags.MESOGLEA);
this.getOrCreateTagBuilder(BlockTags.MANGROVE_ROOTS_CAN_GROW_THROUGH)
.add(WWBlocks.ALGAE)
.add(WWBlocks.PLANKTON)
.add(WWBlocks.AUBURN_MOSS_CARPET)
.add(WWBlocks.AUBURN_CREEPING_MOSS);
this.getOrCreateTagBuilder(BlockTags.GUARDED_BY_PIGLINS)
.add(WWBlocks.STONE_CHEST);
this.getOrCreateTagBuilder(BlockTags.IMPERMEABLE)
.add(WWBlocks.ECHO_GLASS)
.addOptionalTag(WWBlockTags.MESOGLEA);
this.getOrCreateTagBuilder(BlockTags.FEATURES_CANNOT_REPLACE)
.add(WWBlocks.STONE_CHEST);
this.getOrCreateTagBuilder(BlockTags.SCULK_REPLACEABLE_WORLD_GEN)
.addOptionalTag(WWBlockTags.SCULK_SLAB_REPLACEABLE_WORLDGEN)
.addOptionalTag(WWBlockTags.SCULK_STAIR_REPLACEABLE_WORLDGEN)
.addOptionalTag(WWBlockTags.SCULK_WALL_REPLACEABLE_WORLDGEN);
}
private void generateWoods() {
this.getOrCreateTagBuilder(BlockTags.OVERWORLD_NATURAL_LOGS)
.add(WWBlocks.BAOBAB_LOG)
.add(WWBlocks.WILLOW_LOG)
.add(WWBlocks.CYPRESS_LOG)
.add(WWBlocks.PALM_LOG)
.add(WWBlocks.MAPLE_LOG);
this.getOrCreateTagBuilder(BlockTags.ACACIA_LOGS)
.addOptionalTag(WWBlockTags.HOLLOWED_ACACIA_LOGS);
this.getOrCreateTagBuilder(BlockTags.BIRCH_LOGS)
.addOptionalTag(WWBlockTags.HOLLOWED_BIRCH_LOGS);
this.getOrCreateTagBuilder(BlockTags.CHERRY_LOGS)
.addOptionalTag(WWBlockTags.HOLLOWED_CHERRY_LOGS);
this.getOrCreateTagBuilder(BlockTags.CRIMSON_STEMS)
.addOptionalTag(WWBlockTags.HOLLOWED_CRIMSON_STEMS);
this.getOrCreateTagBuilder(BlockTags.DARK_OAK_LOGS)
.addOptionalTag(WWBlockTags.HOLLOWED_DARK_OAK_LOGS);
this.getOrCreateTagBuilder(BlockTags.JUNGLE_LOGS)
.addOptionalTag(WWBlockTags.HOLLOWED_JUNGLE_LOGS);
this.getOrCreateTagBuilder(BlockTags.ACACIA_LOGS)
.addOptionalTag(WWBlockTags.HOLLOWED_ACACIA_LOGS);
this.getOrCreateTagBuilder(BlockTags.MANGROVE_LOGS)
.addOptionalTag(WWBlockTags.HOLLOWED_MANGROVE_LOGS);
this.getOrCreateTagBuilder(BlockTags.OAK_LOGS)
.addOptionalTag(WWBlockTags.HOLLOWED_OAK_LOGS);
this.getOrCreateTagBuilder(BlockTags.ACACIA_LOGS)
.addOptionalTag(WWBlockTags.HOLLOWED_ACACIA_LOGS);
this.getOrCreateTagBuilder(BlockTags.SPRUCE_LOGS)
.addOptionalTag(WWBlockTags.HOLLOWED_SPRUCE_LOGS);
this.getOrCreateTagBuilder(BlockTags.WARPED_STEMS)
.addOptionalTag(WWBlockTags.HOLLOWED_WARPED_STEMS);
this.getOrCreateTagBuilder(WWBlockTags.LEAF_LITTER_CANNOT_SURVIVE_ON)
.add(Blocks.BARRIER)
.addOptionalTag(BlockTags.LEAVES);
this.getOrCreateTagBuilder(WWBlockTags.LEAF_LITTER_CAN_SURVIVE_ON)
.add(Blocks.HONEY_BLOCK)
.add(Blocks.SOUL_SAND)
.add(Blocks.MUD);
this.getOrCreateTagBuilder(WWBlockTags.BAOBAB_LOGS)
.add(WWBlocks.BAOBAB_LOG, WWBlocks.STRIPPED_BAOBAB_LOG)
.add(WWBlocks.BAOBAB_WOOD, WWBlocks.STRIPPED_BAOBAB_WOOD)
.addOptionalTag(WWBlockTags.HOLLOWED_BAOBAB_LOGS);
this.getOrCreateTagBuilder(WWBlockTags.WILLOW_LOGS)
.add(WWBlocks.WILLOW_LOG, WWBlocks.STRIPPED_WILLOW_LOG)
.add(WWBlocks.WILLOW_WOOD, WWBlocks.STRIPPED_WILLOW_WOOD)
.addOptionalTag(WWBlockTags.HOLLOWED_WILLOW_LOGS);
this.getOrCreateTagBuilder(WWBlockTags.CYPRESS_LOGS)
.add(WWBlocks.CYPRESS_LOG, WWBlocks.STRIPPED_CYPRESS_LOG)
.add(WWBlocks.CYPRESS_WOOD, WWBlocks.STRIPPED_CYPRESS_WOOD)
.addOptionalTag(WWBlockTags.HOLLOWED_CYPRESS_LOGS);
this.getOrCreateTagBuilder(WWBlockTags.PALM_LOGS)
.add(WWBlocks.PALM_LOG, WWBlocks.STRIPPED_PALM_LOG)
.add(WWBlocks.PALM_WOOD, WWBlocks.STRIPPED_PALM_WOOD)
.addOptionalTag(WWBlockTags.HOLLOWED_PALM_LOGS);
this.getOrCreateTagBuilder(WWBlockTags.MAPLE_LOGS)
.add(WWBlocks.MAPLE_LOG, WWBlocks.STRIPPED_MAPLE_LOG)
.add(WWBlocks.MAPLE_WOOD, WWBlocks.STRIPPED_MAPLE_WOOD)
.addOptionalTag(WWBlockTags.HOLLOWED_MAPLE_LOGS);
this.getOrCreateTagBuilder(BlockTags.LOGS)
.addOptionalTag(WWBlockTags.BAOBAB_LOGS)
.addOptionalTag(WWBlockTags.WILLOW_LOGS)
.addOptionalTag(WWBlockTags.CYPRESS_LOGS)
.addOptionalTag(WWBlockTags.PALM_LOGS)
.addOptionalTag(WWBlockTags.MAPLE_LOGS)
.addOptionalTag(WWBlockTags.HOLLOWED_LOGS);
this.getOrCreateTagBuilder(BlockTags.LOGS_THAT_BURN)
.addOptionalTag(WWBlockTags.BAOBAB_LOGS)
.addOptionalTag(WWBlockTags.WILLOW_LOGS)
.addOptionalTag(WWBlockTags.CYPRESS_LOGS)
.addOptionalTag(WWBlockTags.PALM_LOGS)
.addOptionalTag(WWBlockTags.MAPLE_LOGS)
.addOptionalTag(WWBlockTags.HOLLOWED_LOGS_THAT_BURN);
this.getOrCreateTagBuilder(WWBlockTags.WILLOW_ROOTS_CAN_GROW_THROUGH)
.add(Blocks.MUDDY_MANGROVE_ROOTS)
.add(Blocks.MANGROVE_ROOTS)
.add(Blocks.MOSS_CARPET)
.add(Blocks.VINE)
.add(Blocks.SNOW)
.add(Blocks.RED_MUSHROOM)
.add(Blocks.BROWN_MUSHROOM)
.add(WWBlocks.ALGAE)
.add(WWBlocks.PLANKTON)
.add(WWBlocks.AUBURN_MOSS_CARPET)
.add(WWBlocks.AUBURN_CREEPING_MOSS)
.addOptionalTag(BlockTags.SMALL_FLOWERS);
this.getOrCreateTagBuilder(BlockTags.LEAVES)
.add(WWBlocks.BAOBAB_LEAVES)
.add(WWBlocks.WILLOW_LEAVES)
.add(WWBlocks.CYPRESS_LEAVES)
.add(WWBlocks.PALM_FRONDS)
.add(WWBlocks.YELLOW_MAPLE_LEAVES)
.add(WWBlocks.ORANGE_MAPLE_LEAVES)
.add(WWBlocks.RED_MAPLE_LEAVES);
this.getOrCreateTagBuilder(WWBlockTags.LEAF_LITTERS)
.add(WWBlocks.YELLOW_MAPLE_LEAF_LITTER)
.add(WWBlocks.ORANGE_MAPLE_LEAF_LITTER)
.add(WWBlocks.RED_MAPLE_LEAF_LITTER);
this.getOrCreateTagBuilder(BlockTags.PLANKS)
.add(WWBlocks.BAOBAB_PLANKS)
.add(WWBlocks.WILLOW_PLANKS)
.add(WWBlocks.CYPRESS_PLANKS)
.add(WWBlocks.PALM_PLANKS)
.add(WWBlocks.MAPLE_PLANKS);
this.getOrCreateTagBuilder(BlockTags.SAPLINGS)
.add(WWBlocks.BAOBAB_NUT)
.add(WWBlocks.WILLOW_SAPLING)
.add(WWBlocks.CYPRESS_SAPLING)
.add(WWBlocks.COCONUT)
.add(WWBlocks.MAPLE_SAPLING);
this.getOrCreateTagBuilder(BlockTags.STANDING_SIGNS)
.add(WWBlocks.BAOBAB_SIGN)
.add(WWBlocks.WILLOW_SIGN)
.add(WWBlocks.CYPRESS_SIGN)
.add(WWBlocks.PALM_SIGN)
.add(WWBlocks.MAPLE_SIGN);
this.getOrCreateTagBuilder(BlockTags.WALL_SIGNS)
.add(WWBlocks.BAOBAB_WALL_SIGN)
.add(WWBlocks.WILLOW_WALL_SIGN)
.add(WWBlocks.CYPRESS_WALL_SIGN)
.add(WWBlocks.PALM_WALL_SIGN)
.add(WWBlocks.MAPLE_WALL_SIGN);
this.getOrCreateTagBuilder(BlockTags.CEILING_HANGING_SIGNS)
.add(WWBlocks.BAOBAB_HANGING_SIGN)
.add(WWBlocks.WILLOW_HANGING_SIGN)
.add(WWBlocks.CYPRESS_HANGING_SIGN)
.add(WWBlocks.PALM_HANGING_SIGN)
.add(WWBlocks.MAPLE_HANGING_SIGN);
this.getOrCreateTagBuilder(BlockTags.WALL_HANGING_SIGNS)
.add(WWBlocks.BAOBAB_WALL_HANGING_SIGN)
.add(WWBlocks.WILLOW_WALL_HANGING_SIGN)
.add(WWBlocks.CYPRESS_WALL_HANGING_SIGN)
.add(WWBlocks.PALM_WALL_HANGING_SIGN)
.add(WWBlocks.MAPLE_WALL_HANGING_SIGN);
this.getOrCreateTagBuilder(BlockTags.WOODEN_BUTTONS)
.add(WWBlocks.BAOBAB_BUTTON)
.add(WWBlocks.WILLOW_BUTTON)
.add(WWBlocks.CYPRESS_BUTTON)
.add(WWBlocks.PALM_BUTTON)
.add(WWBlocks.MAPLE_BUTTON);
this.getOrCreateTagBuilder(BlockTags.WOODEN_DOORS)
.add(WWBlocks.BAOBAB_DOOR)
.add(WWBlocks.WILLOW_DOOR)
.add(WWBlocks.CYPRESS_DOOR)
.add(WWBlocks.PALM_DOOR)
.add(WWBlocks.MAPLE_DOOR);
this.getOrCreateTagBuilder(BlockTags.WOODEN_FENCES)
.add(WWBlocks.BAOBAB_FENCE)
.add(WWBlocks.WILLOW_FENCE)
.add(WWBlocks.CYPRESS_FENCE)
.add(WWBlocks.PALM_FENCE)
.add(WWBlocks.MAPLE_FENCE);
this.getOrCreateTagBuilder(BlockTags.FENCE_GATES)
.add(WWBlocks.BAOBAB_FENCE_GATE)
.add(WWBlocks.WILLOW_FENCE_GATE)
.add(WWBlocks.CYPRESS_FENCE_GATE)
.add(WWBlocks.PALM_FENCE_GATE)
.add(WWBlocks.MAPLE_FENCE_GATE);
this.getOrCreateTagBuilder(BlockTags.WOODEN_PRESSURE_PLATES)
.add(WWBlocks.BAOBAB_PRESSURE_PLATE)
.add(WWBlocks.WILLOW_PRESSURE_PLATE)
.add(WWBlocks.CYPRESS_PRESSURE_PLATE)
.add(WWBlocks.PALM_PRESSURE_PLATE)
.add(WWBlocks.MAPLE_PRESSURE_PLATE);
this.getOrCreateTagBuilder(BlockTags.WOODEN_SLABS)
.add(WWBlocks.BAOBAB_SLAB)
.add(WWBlocks.WILLOW_SLAB)
.add(WWBlocks.CYPRESS_SLAB)
.add(WWBlocks.PALM_SLAB)
.add(WWBlocks.MAPLE_SLAB);
this.getOrCreateTagBuilder(BlockTags.WOODEN_STAIRS)
.add(WWBlocks.BAOBAB_STAIRS)
.add(WWBlocks.WILLOW_STAIRS)
.add(WWBlocks.CYPRESS_STAIRS)
.add(WWBlocks.PALM_STAIRS)
.add(WWBlocks.MAPLE_STAIRS);
this.getOrCreateTagBuilder(BlockTags.WOODEN_TRAPDOORS)
.add(WWBlocks.BAOBAB_TRAPDOOR)
.add(WWBlocks.WILLOW_TRAPDOOR)
.add(WWBlocks.CYPRESS_TRAPDOOR)
.add(WWBlocks.PALM_TRAPDOOR)
.add(WWBlocks.MAPLE_TRAPDOOR);
}
private void generateSounds() {
this.getOrCreateTagBuilder(WWBlockTags.SOUND_AUBURN_MOSS_CARPET)
.add(WWBlocks.AUBURN_MOSS_CARPET, WWBlocks.AUBURN_CREEPING_MOSS);
this.getOrCreateTagBuilder(WWBlockTags.SOUND_AUBURN_MOSS)
.add(WWBlocks.AUBURN_MOSS_BLOCK);
this.getOrCreateTagBuilder(WWBlockTags.SOUND_COCONUT)
.add(WWBlocks.COCONUT)
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit", "coconut"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit", "young_coconut"));
this.getOrCreateTagBuilder(WWBlockTags.SOUND_MAGMA_BLOCK)
.add(Blocks.MAGMA_BLOCK);
this.getOrCreateTagBuilder(WWBlockTags.SOUND_WITHER_ROSE)
.add(Blocks.WITHER_ROSE);
this.getOrCreateTagBuilder(WWBlockTags.SOUND_SUGAR_CANE)
.add(Blocks.SUGAR_CANE);
this.getOrCreateTagBuilder(WWBlockTags.SOUND_REINFORCED_DEEPSLATE)
.add(Blocks.REINFORCED_DEEPSLATE);
this.getOrCreateTagBuilder(WWBlockTags.SOUND_PODZOL)
.add(Blocks.PODZOL);
this.getOrCreateTagBuilder(WWBlockTags.SOUND_DEAD_BUSH)
.add(Blocks.DEAD_BUSH);
this.getOrCreateTagBuilder(WWBlockTags.SOUND_CLAY)
.add(Blocks.CLAY);
this.getOrCreateTagBuilder(WWBlockTags.SOUND_GRAVEL)
.add(Blocks.GRAVEL);
this.getOrCreateTagBuilder(WWBlockTags.SOUND_MELON)
.add(Blocks.PUMPKIN, Blocks.CARVED_PUMPKIN, Blocks.JACK_O_LANTERN)
.add(Blocks.MELON);
this.getOrCreateTagBuilder(WWBlockTags.SOUND_MELON_STEM)
.add(Blocks.MELON_STEM, Blocks.PUMPKIN_STEM)
.add(Blocks.ATTACHED_MELON_STEM, Blocks.ATTACHED_PUMPKIN_STEM);
this.getOrCreateTagBuilder(WWBlockTags.SOUND_LILY_PAD)
.add(Blocks.LILY_PAD, WWBlocks.FLOWERING_LILY_PAD);
this.getOrCreateTagBuilder(WWBlockTags.SOUND_SANDSTONE)
.addOptionalTag(ConventionalBlockTags.SANDSTONE_BLOCKS);
this.getOrCreateTagBuilder(WWBlockTags.SOUND_MUSHROOM_BLOCK)
.add(Blocks.RED_MUSHROOM_BLOCK, Blocks.BROWN_MUSHROOM_BLOCK)
.add(Blocks.MUSHROOM_STEM)
.addOptional(ResourceLocation.fromNamespaceAndPath("betterend", "mossy_glowshroom_cap"))
.addOptional(ResourceLocation.fromNamespaceAndPath("betterend", "mossy_glowshroom_fur"))
.addOptional(ResourceLocation.fromNamespaceAndPath("betterend", "jellyshroom_cap_purple"))
.addOptional(ResourceLocation.fromNamespaceAndPath("betternether", "red_large_mushroom"))
.addOptional(ResourceLocation.fromNamespaceAndPath("betternether", "brown_large_mushroom"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "glowshroom_block"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","shitake_mushroom_block"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","blue_bioshroom"));
this.getOrCreateTagBuilder(WWBlockTags.SOUND_MUSHROOM)
.add(Blocks.RED_MUSHROOM, Blocks.BROWN_MUSHROOM)
.addOptional(ResourceLocation.fromNamespaceAndPath("betterend", "mossy_glowshroom_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("betterend", "small_jellyshroom"))
.addOptional(ResourceLocation.fromNamespaceAndPath("betterend", "bolux_mushroom"))
.addOptional(ResourceLocation.fromNamespaceAndPath("betternether", "lucis_mushroom"))
.addOptional(ResourceLocation.fromNamespaceAndPath("betternether", "wall_mushroom_red"))
.addOptional(ResourceLocation.fromNamespaceAndPath("betternether", "wall_mushroom_brown"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "glowshroom"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","shitake_mushroom"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","brown_wall_mushroom"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","mycotoxic_mushrooms"));
this.getOrCreateTagBuilder(WWBlockTags.SOUND_FROSTED_ICE)
.add(Blocks.FROSTED_ICE, WWBlocks.FRAGILE_ICE);
this.getOrCreateTagBuilder(WWBlockTags.SOUND_ICE)
.add(Blocks.ICE, Blocks.PACKED_ICE, Blocks.BLUE_ICE)
.add(WWBlocks.ICICLE);
this.getOrCreateTagBuilder(WWBlockTags.SOUND_COARSE_DIRT)
.add(Blocks.COARSE_DIRT)
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","sandy_soil"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","peat_coarse_dirt"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","silt_coarse_dirt"));
this.getOrCreateTagBuilder(WWBlockTags.SOUND_CACTUS)
.add(Blocks.CACTUS, WWBlocks.PRICKLY_PEAR_CACTUS)
.addOptional(ResourceLocation.fromNamespaceAndPath("betternether", "barrel_cactus"))
.addOptional(ResourceLocation.fromNamespaceAndPath("betternether", "nether_cactus"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","aureate_succulent"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","drowsy_succulent"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","foamy_succulent"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","imperial_succulent"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","ornate_succulent"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","regal_succulent"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","sage_succulent"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","orange_maple_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","white_wisteria_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","larch_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","barrel_cactus"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","saguaro_cactus"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","saguaro_cactus_corner"))
.addOptional(ResourceLocation.fromNamespaceAndPath("terrestria","tiny_cactus"))
.addOptional(ResourceLocation.fromNamespaceAndPath("terrestria","saguaro_cactus_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("terrestria","saguaro_cactus"));
this.getOrCreateTagBuilder(WWBlockTags.SOUND_SAPLING)
.add(Blocks.ACACIA_SAPLING)
.add(Blocks.BIRCH_SAPLING)
.add(Blocks.DARK_OAK_SAPLING)
.add(Blocks.JUNGLE_SAPLING)
.add(Blocks.MANGROVE_PROPAGULE)
.add(Blocks.OAK_SAPLING)
.add(Blocks.SPRUCE_SAPLING)
.add(WWBlocks.WILLOW_SAPLING)
.add(WWBlocks.CYPRESS_SAPLING)
.add(WWBlocks.PALM_FRONDS)
.add(WWBlocks.MAPLE_SAPLING)
.add(WWBlocks.BUSH)
.addOptional(ResourceLocation.fromNamespaceAndPath("betterend", "pythadendron_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("betterend", "lacugrove_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("betterend", "dragon_tree_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("betterend", "tenanea_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("betterend", "helix_tree_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("betterend", "umbrella_tree_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("betterend", "lucernia_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "cypress_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "dead_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "empyreal_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "fir_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "flowering_oak_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "hellbark_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "jacaranda_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "magic_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "mahogany_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "orange_maple_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "palm_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "pine_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "rainbow_birch_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "red_maple_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "redwood_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "snowblossom_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "umbran_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "willow_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "yellow_maple_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("blockus","white_oak_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("excessive_building","ancient_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("excessive_building","gloom_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","saxaul_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","fir_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","cedar_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","pink_wisteria_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","blue_wisteria_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","olive_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","joshua_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","orange_maple_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","white_wisteria_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","larch_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","mahogany_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","redwood_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","purple_wisteria_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","aspen_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","red_maple_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","cypress_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","willow_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","sugi_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","yellow_maple_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","palo_verde_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","ghaf_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","silverbush"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","apple_oak_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","ashen_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","bamboo_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","blackwood_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","blue_magnolia_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","brimwood_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","cobalt_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","cypress_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","dead_pine_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","dead_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","enchanted_birch_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","eucalyptus_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","flowering_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","golden_larch_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","joshua_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","kapok_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","larch_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","magnolia_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","mauve_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","maple_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","mauve_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","orange_maple_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","palm_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","pine_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","pink_magnolia_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","red_maple_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","redwood_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","silver_birch_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","small_oak_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","socotra_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","white_magnolia_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","willow_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("terrestria","bryce_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("terrestria","cypress_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("terrestria","dark_japanese_maple_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("terrestria","hemlock_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("terrestria","japanese_maple_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("terrestria","japanese_maple_shrub_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("terrestria","jungle_palm_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("terrestria","rainbow_eucalyptus_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("terrestria","redwood_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("terrestria","rubber_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("terrestria","sakura_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("terrestria","willow_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("terrestria","yucca_palm_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("traverse","brown_autumnal_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("traverse","fir_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("traverse","orange_autumnal_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("traverse","red_autumnal_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("traverse","yellow_autumnal_sapling"));
this.getOrCreateTagBuilder(WWBlockTags.SOUND_CONIFER_LEAVES)
.add(Blocks.SPRUCE_LEAVES)
.add(WWBlocks.CYPRESS_LEAVES)
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "cypress_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "fir_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "pine_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "redwood_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "umbran_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","fir_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","joshua_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","frosty_fir_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","saxaul_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","cedar_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","larch_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","redwood_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","frosty_redwood_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","cypress_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","sugi_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","pine_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","dead_pine_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","cypress_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","redwood_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","eucalyptus_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","joshua_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("terrestria","cypress_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("terrestria","rainbow_eucalyptus_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("terrestria","redwood_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("terrestria","hemlock_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("traverse","fir_leaves"));
this.getOrCreateTagBuilder(WWBlockTags.SOUND_LEAVES)
.add(Blocks.ACACIA_LEAVES)
.add(Blocks.BIRCH_LEAVES)
.add(Blocks.DARK_OAK_LEAVES)
.add(Blocks.JUNGLE_LEAVES)
.add(Blocks.MANGROVE_LEAVES)
.add(Blocks.OAK_LEAVES)
.add(WWBlocks.BAOBAB_LEAVES)
.add(WWBlocks.WILLOW_LEAVES)
.add(WWBlocks.PALM_FRONDS)
.addOptional(ResourceLocation.fromNamespaceAndPath("betterend", "pythadendron_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("betterend", "lacugrove_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("betterend", "dragon_tree_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("betterend", "tenanea_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("betterend", "helix_tree_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("betterend", "lucernia_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("betterend", "lucernia_outer_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("betterend", "glowing_pillar_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("betterend", "cave_bush"))
.addOptional(ResourceLocation.fromNamespaceAndPath("betterend", "end_lotus_leaf"))
.addOptional(ResourceLocation.fromNamespaceAndPath("betternether", "willow_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("betternether", "rubeus_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("betternether", "anchor_tree_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("betternether", "nether_sakura_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "bramble_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "dead_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "empyreal_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "flowering_oak_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "hellbark_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "jacaranda_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "magic_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "mahogany_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "null_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "orange_maple_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "palm_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "rainbow_birch_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "red_maple_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "snowblossom_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "willow_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "yellow_maple_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("blockus","white_oak_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("excessive_building","ancient_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("excessive_building","gloom_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","part_pink_wisteria_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","yellow_aspen_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","part_white_wisteria_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","wisteria_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","part_purple_wisteria_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","pink_wisteria_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","blue_wisteria_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","olive_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","orange_maple_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","white_wisteria_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","mahogany_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","purple_wisteria_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","aspen_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","red_maple_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","coconut_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","willow_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","yellow_maple_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","palo_verde_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","part_blue_wisteria_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","ghaf_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","apple_oak_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","ashen_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","bamboo_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","baobab_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","blackwood_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","blue_magnolia_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","brimwood_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","dead_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","enchanted_birch_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","flowering_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","golden_larch_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","kapok_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","larch_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","magnolia_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","maple_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","mauve_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","orange_maple_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","palm_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","pink_magnolia_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","red_maple_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","silver_birch_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","small_oak_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","socotra_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","white_magnolia_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","willow_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("techreborn","rubber_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("terrestria","dark_japanese_maple_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("terrestria","japanese_maple_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("terrestria","japanese_maple_shrub_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("terrestria","jungle_palm_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("terrestria","rubber_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("terrestria","sakura_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("terrestria","willow_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("terrestria","yucca_palm_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("traverse","brown_autumnal_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("traverse","orange_autumnal_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("traverse","red_autumnal_leaves"))
.addOptional(ResourceLocation.fromNamespaceAndPath("traverse","yellow_autumnal_leaves"));
this.getOrCreateTagBuilder(WWBlockTags.SOUND_GRASS)
.add(Blocks.SHORT_GRASS)
.add(Blocks.TALL_GRASS)
.add(Blocks.FERN)
.add(Blocks.LARGE_FERN)
.add(WWBlocks.CLOVERS);
this.getOrCreateTagBuilder(WWBlockTags.SOUND_FROZEN_GRASS)
.add(WWBlocks.FROZEN_SHORT_GRASS)
.add(WWBlocks.FROZEN_TALL_GRASS)
.add(WWBlocks.FROZEN_FERN)
.add(WWBlocks.FROZEN_LARGE_FERN);
this.getOrCreateTagBuilder(WWBlockTags.SOUND_FLOWER)
.add(Blocks.DANDELION)
.add(Blocks.POPPY)
.add(Blocks.BLUE_ORCHID)
.add(Blocks.ALLIUM)
.add(Blocks.AZURE_BLUET)
.add(Blocks.ORANGE_TULIP)
.add(Blocks.PINK_TULIP)
.add(Blocks.RED_TULIP)
.add(Blocks.WHITE_TULIP)
.add(Blocks.OXEYE_DAISY)
.add(Blocks.CORNFLOWER)
.add(Blocks.LILY_OF_THE_VALLEY)
.add(WWBlocks.SEEDING_DANDELION)
.add(WWBlocks.CARNATION)
.add(WWBlocks.MARIGOLD)
.add(WWBlocks.PASQUEFLOWER)
.add(WWBlocks.RED_HIBISCUS)
.add(WWBlocks.PINK_HIBISCUS)
.add(WWBlocks.YELLOW_HIBISCUS)
.add(WWBlocks.WHITE_HIBISCUS)
.add(WWBlocks.PURPLE_HIBISCUS)
.add(WWBlocks.DATURA)
.add(WWBlocks.MILKWEED)
.add(Blocks.SUNFLOWER)
.add(Blocks.ROSE_BUSH)
.add(Blocks.PEONY)
.add(Blocks.LILAC)
.add(Blocks.TORCHFLOWER)
.add(WWBlocks.WILDFLOWERS)
.add(WWBlocks.PHLOX)
.add(WWBlocks.LANTANAS)
.addOptional(ResourceLocation.fromNamespaceAndPath("trailiertales", "cyan_rose"))
.addOptional(ResourceLocation.fromNamespaceAndPath("trailiertales", "manedrop"))
.addOptional(ResourceLocation.fromNamespaceAndPath("betterend", "hydralux_petal_block"))
.addOptional(ResourceLocation.fromNamespaceAndPath("betterend", "end_lotus_flower"))
.addOptional(ResourceLocation.fromNamespaceAndPath("betterend", "tenanea_flowers"))
.addOptional(ResourceLocation.fromNamespaceAndPath("betternether", "soul_lily"))
.addOptional(ResourceLocation.fromNamespaceAndPath("betternether", "soul_lily_sapling"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "white_petals"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "wildflower"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "rose"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "violet"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "lavendar"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "white_lavendar"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "orange_cosmos"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "pink_daffodil"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "pink_hibiscus"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "waterlily"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "glowflower"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "wilted_lily"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "burning_blossom"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "endbloom"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "tall_lavendar"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "tall_white_lavendar"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "blue_hydrangea"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "goldenrod"))
.addOptional(ResourceLocation.fromNamespaceAndPath("biomesoplenty", "icy_iris"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","anemone"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","begonia"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","black_iris"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","bleeding_heart"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","blue_bulbs"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","blue_iris"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","bluebell"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","carnation"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","dwarf_blossoms"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","foxglove"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","gardenia"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","hibiscus"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","iris"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","lavender"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","lotus_flower"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","marigold"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","protea"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","purple_heather"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","red_bearberries"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","red_heather"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","ruby_blossoms"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","snapdragon"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","tiger_lily"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","white_heather"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","yellow_wildflower"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","purple_wildflower"))
.addOptional(ResourceLocation.fromNamespaceAndPath("natures_spirit","black_iris"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","cactus_flower"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","tassel"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","day_lily"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","aster"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","bleeding_heart"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","blue_lupine"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","daisy"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","dorcel"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","felicia_daisy"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","fireweed"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","hibiscus"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","mallow"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","hyssop"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","pink_lupine"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","poppy_bush"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","salmon_poppy_bush"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","purple_lupine"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","red_lupine"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","waratah"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","tsubaki"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","white_trillium"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","wilting_trillium"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","yellow_lupine"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","red_snowbelle"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","orange_snowbelle"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","yellow_snowbelle"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","lime_snowbelle"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","green_snowbelle"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","cyan_snowbelle"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","light_blue_snowbelle"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","blue_snowbelle"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","purple_snowbelle"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","magenta_snowbelle"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","pink_snowbelle"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","brown_snowbelle"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","white_snowbelle"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","light_gray_snowbelle"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","gray_snowbelle"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","black_snowbelle"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","hyacinth_flowers"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","orange_coneflower"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","purple_coneflower"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","blue_magnolia_flowers"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","pink_magnolia_flowers"))
.addOptional(ResourceLocation.fromNamespaceAndPath("regions_unexplored","white_magnolia_flowers"))
.addOptional(ResourceLocation.fromNamespaceAndPath("terrestria","indian_paintbrush"))
.addOptional(ResourceLocation.fromNamespaceAndPath("terrestria","monsteras"));
}
}
| 412 | 0.851559 | 1 | 0.851559 | game-dev | MEDIA | 0.978432 | game-dev | 0.544138 | 1 | 0.544138 |
rfhits/Computer-Organization-BUAA-2020 | 1,413 | 0-Pre_Study/3-Verilog与ISE/counting-1.v | `timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 20:19:32 09/28/2020
// Design Name:
// Module Name: counting
// Project Name:
// Target Devices:
// Tool versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
`define S0 2'b00
`define S1 2'b01
`define S2 2'b10
`define S3 2'b11
module counting(
input [1:0] num,
input clk,
output ans
);
reg [1:0]state;
initial begin
state = `S0;
end
always@(posedge clk)
begin
case(state)
`S0 : begin
if (num == 1) begin
state <= `S1;
end
else begin
end
end
`S1 : begin
if (num ==1) begin
state <= `S1;
end
else if(num==2) begin
state <= `S2;
end
else begin
state <= `S0;
end
end
`S2: begin
if (num ==1) begin
state <=`S1;
end
else if(num==2)begin
state <=`S0;
end
else begin
state <=`S0;
end
end
`S3 : begin
if(num==1) begin
state <=`S1;
end
else if(num==2) begin
state <=`S0;
end
else begin
state <=`S3;
end
end
endcase
end
assign ans=(state==`S3)? 1:0;
endmodule
| 412 | 0.726786 | 1 | 0.726786 | game-dev | MEDIA | 0.296539 | game-dev | 0.993614 | 1 | 0.993614 |
Project-Tactics/Project-Tactics | 1,992 | src/Apps/Samples/States/DemoPhysicsState.cpp | #include "DemoPhysicsState.h"
#include <Engine/Scene/SceneSystem.h>
#include <Libs/Ecs/Component/MeshComponent.h>
#include <Libs/Ecs/Component/TransformComponent.h>
#include <Libs/Input/InputSystem.h>
#include <Libs/Utility/Random.h>
namespace tactics {
DemoPhysicsState::DemoPhysicsState(ServiceLocator& serviceLocator) : SampleState(serviceLocator) {}
FsmAction DemoPhysicsState::enter() {
auto& inputSystem = getService<InputSystem>();
inputSystem.assignInputMap("PhysicsDemo");
auto& sceneSystem = getService<SceneSystem>();
sceneSystem.createEntity("Camera"_id, "defaultCamera"_id);
sceneSystem.createEntity("Plane"_id, "defaultPlane"_id);
for (auto i = 0; i < 100; ++i) {
auto entity = sceneSystem.createEntity(HashId("Cube_" + std::to_string(i)), "defaultCube"_id);
entity.updateComponent<component::Transform>([i](component::Transform& transform) {
transform.setPosition(Random::range3D(-10.f, 10.f) + glm::vec3{0, 10, 0});
transform.setRotation(Random::random3D() * 90.f);
});
auto& mesh = entity.getComponent<component::Mesh>();
mesh.materials[0]->set("u_Color", glm::vec4(Random::random3D(), 1.0f));
}
return FsmAction::none();
}
void DemoPhysicsState::exit() {
auto& inputSystem = getService<InputSystem>();
inputSystem.unassignInputMap("PhysicsDemo");
}
FsmAction DemoPhysicsState::update() {
auto& inputSystem = getService<InputSystem>();
if (inputSystem.checkAction("exitFromState")) {
return FsmAction::transition("exit"_id);
}
if (inputSystem.checkAction("resetRigidBodies")) {
auto& sceneSystem = getService<SceneSystem>();
for (auto i = 0; i < 100; ++i) {
auto entity = sceneSystem.getEntityByName(HashId("Cube_" + std::to_string(i)));
entity.updateComponent<component::Transform>([i](component::Transform& transform) {
transform.setPosition(Random::range3D(-5.f, 5.f) + glm::vec3{0, 10, 0});
transform.setRotation(Random::random3D() * 90.f);
});
}
}
return FsmAction::none();
}
} // namespace tactics
| 412 | 0.79955 | 1 | 0.79955 | game-dev | MEDIA | 0.858653 | game-dev | 0.885151 | 1 | 0.885151 |
Panda381/CH32LibSDK | 5,788 | Babyboy/Games/TDungeon/src/externBitmaps.cpp |
// -----------------------------------------
// BabyBoy adaptation: Miroslav Nemecek 2025
// -----------------------------------------
#include "../include.h"
//#pragma once
//#include <Arduino.h>
//#include "dungeonTypes.h"
/*
// monsters
extern const uint8_t joey[] PROGMEM;
extern const uint8_t beholder[] PROGMEM;
extern const uint8_t rat[] PROGMEM;
// objects
extern const uint8_t newBars[] PROGMEM;
extern const uint8_t door[] PROGMEM;
extern const uint8_t leverLeft[] PROGMEM;
extern const uint8_t leverRight[] PROGMEM;
extern const uint8_t chestClosed[] PROGMEM;
extern const uint8_t chestOpen[] PROGMEM;
extern const uint8_t fountain[] PROGMEM;
extern const uint8_t statusPanel[] PROGMEM;
extern const uint8_t compass[] PROGMEM;
// walls
extern const unsigned char smallFrontWall_D1[] PROGMEM;
extern const unsigned char smallFrontWall_D2 [] PROGMEM;
extern const unsigned char smallFrontWall_D3 [] PROGMEM;
extern const unsigned char leftRightWalls_D0[] PROGMEM;
extern const unsigned char leftRightWalls_D1[] PROGMEM;
extern const unsigned char leftRightWalls_D2[] PROGMEM;
extern const unsigned char leftRightWalls_D3[] PROGMEM;
extern const unsigned char outerLeftRightWalls_D2 [] PROGMEM;
extern const unsigned char outerLeftRightWalls_D3 [] PROGMEM;
*/
// list of possible non wall objects (i.e. monsters, doors, ...) (10 bytes per object)
const NON_WALL_OBJECT objectList [11] PROGMEM = {
// itemType , width, verticalOffsetBits, heightBits, lineOffset, scalingThreshold, bitmapData
{ SKELETON , 28, 2 * 8, 5 * 8, 56, { 1, 2, 5 }, joey }, // 0
{ BEHOLDER , 32, 0 * 8, 7 * 8, 64, { 1, 2, 5 }, beholder }, // 1
{ BARS , 28, 1 * 8, 6 * 8, 56, { 1, 2, 5 }, newBars }, // 2
{ DOOR , 32, 1 * 8, 7 * 8, 64, { 1, 3, 12 }, door }, // 3
{ LVR_LEFT , 16, 3 * 8, 1 * 8, 32, { 1, 2, 8 }, leverLeft }, // 4
{ LVR_RIGHT , 16, 3 * 8, 1 * 8, 32, { 1, 2, 8 }, leverRight }, // 5
{ CLOSED_CHEST, 24, 4 * 8, 3 * 8, 48, { 1, 3, 99 }, chestClosed }, // 6
{ MIMIC , 24, 4 * 8, 3 * 8, 48, { 1, 3, 99 }, chestClosed }, // 7
{ OPEN_CHEST , 24, 4 * 8, 3 * 8, 48, { 1, 3, 99 }, chestOpen }, // 8
{ FOUNTAIN , 12, 4 * 8, 3 * 8, 24, { 1, 2, 99 }, fountain }, // 9
{ RAT , 20, 5 * 8, 2 * 8, 40, { 1, 2, 99 }, rat }, // 10
};
// array of conditions for wall display (9 bytes per row)
// 'WALL & ~FLAG_SOLID' means all walls, fake or not...
// CAUTION: The entries must be ordered from min. distance(0) to max. distance (3)
// Otherwise display errors will occur
const SIMPLE_WALL_INFO arrayOfWallInfo[] PROGMEM = {
// *wallBitmap , startX, endX, posStartEndY, distance, l/r offset,relPos, width
// distance 0
{ leftRightWalls_D0 , 0 , 3 , 0x07 , 0 , -1 , 0 , 8 }, // 0
{ leftRightWalls_D0 , 92 , 95 , 0x07 , 0 , +1 , 4 , 8 }, // 1
// distance 1
{ smallFrontWall_D1 , 0 , 3 , 0x07 , 1 , -1 , 84 , 88 }, // 2
{ smallFrontWall_D1 , 4 , 91 , 0x07 , 1 , 0 , 0 , 88 }, // 3
{ smallFrontWall_D1 , 92 , 95 , 0x07 , 1 , +1 , 0 , 88 }, // 4
{ leftRightWalls_D1 , 4 , 25 , 0x07 , 1 , -1 , 0 , 44 }, // 5
{ leftRightWalls_D1 , 70 , 91 , 0x07 , 1 , +1 , 22 , 44 }, // 6
// distance 2
{ smallFrontWall_D2 , 0 , 25 , 0x25 , 2 , -1 , 18 , 44 }, // 7
{ smallFrontWall_D2 , 26 , 69 , 0x25 , 2 , 0 , 0 , 44 }, // 8
{ smallFrontWall_D2 , 70 , 95 , 0x25 , 2 , +1 , 0 , 44 }, // 9
{ leftRightWalls_D2 , 26 , 36 , 0x25 , 2 , -1 , 0 , 22 }, // 10
{ leftRightWalls_D2 , 59 , 69 , 0x25 , 2 , +1 , 11 , 22 }, // 11
{ outerLeftRightWalls_D2 , 0 , 14 , 0x25 , 2 , -2 , 0 , 30 }, // 12
{ outerLeftRightWalls_D2 , 81 , 95 , 0x25 , 2 , +2 , 15 , 30 }, // 13
// distance 3
{ smallFrontWall_D3 , 0 , 14 , 0x34 , 3 , -2 , 7 , 22 }, // 14
{ smallFrontWall_D3 , 15 , 36 , 0x34 , 3 , -1 , 0 , 22 }, // 15
{ smallFrontWall_D3 , 37 , 58 , 0x34 , 3 , 0 , 0 , 22 }, // 16
{ smallFrontWall_D3 , 59 , 80 , 0x34 , 3 , +1 , 0 , 22 }, // 17
{ smallFrontWall_D3 , 81 , 95 , 0x34 , 3 , +2 , 0 , 22 }, // 18
{ leftRightWalls_D3 , 37 , 41 , 0x34 , 3 , -1 , 0 , 10 }, // 19
{ leftRightWalls_D3 , 54 , 58 , 0x34 , 3 , +1 , 5 , 10 }, // 20
{ outerLeftRightWalls_D3 , 15 , 29 , 0x34 , 3 , -2 , 0 , 30 }, // 21
{ outerLeftRightWalls_D3 , 66 , 80 , 0x34 , 3 , +2 , 15 , 30 }, // 22
{ NULL , 0 , 0 , 0x00 , 0 , 0 , 0 , 0 }, // 7 unused bytes.. how can I save those?
};
| 412 | 0.833007 | 1 | 0.833007 | game-dev | MEDIA | 0.599248 | game-dev,graphics-rendering | 0.699718 | 1 | 0.699718 |
jswigart/omni-bot | 8,112 | GameInterfaces/Q4/src/mpgame/ai/Monster_TurretFlying.cpp |
#include "../../idlib/precompiled.h"
#pragma hdrstop
#include "../Game_local.h"
class rvMonsterTurretFlying : public idAI {
public:
CLASS_PROTOTYPE( rvMonsterTurretFlying );
rvMonsterTurretFlying ( void );
void InitSpawnArgsVariables( void );
void Spawn ( void );
void Save ( idSaveGame *savefile ) const;
void Restore ( idRestoreGame *savefile );
virtual bool Pain ( idEntity *inflictor, idEntity *attacker, int damage, const idVec3 &dir, int location );
virtual bool CheckActions ( void );
protected:
stateResult_t State_Combat ( const stateParms_t& parms );
stateResult_t State_Fall ( const stateParms_t& parms );
stateResult_t State_Killed ( const stateParms_t& parms );
stateResult_t State_Torso_Idle ( const stateParms_t& parms );
stateResult_t State_Legs_Idle ( const stateParms_t& parms );
stateResult_t State_Torso_BlasterAttack ( const stateParms_t& parms );
int shieldHealth;
int maxShots;
int minShots;
int shots;
private:
rvAIAction actionBlasterAttack;
CLASS_STATES_PROTOTYPE ( rvMonsterTurretFlying );
};
CLASS_DECLARATION( idAI, rvMonsterTurretFlying )
END_CLASS
/*
================
rvMonsterTurretFlying::rvMonsterTurretFlying
================
*/
rvMonsterTurretFlying::rvMonsterTurretFlying ( ) {
shieldHealth = spawnArgs.GetInt ( "shieldHealth" );
}
void rvMonsterTurretFlying::InitSpawnArgsVariables( void )
{
maxShots = spawnArgs.GetInt ( "maxShots", "1" );
minShots = spawnArgs.GetInt ( "minShots", "1" );
}
/*
================
rvMonsterTurretFlying::Spawn
================
*/
void rvMonsterTurretFlying::Spawn ( void ) {
shieldHealth = spawnArgs.GetInt ( "shieldHealth" );
InitSpawnArgsVariables();
shots = 0;
actionBlasterAttack.Init ( spawnArgs, "action_blasterAttack", "Torso_BlasterAttack", AIACTIONF_ATTACK );
//don't take damage until we open up
fl.takedamage = false;
}
/*
================
rvMonsterTurretFlying::CheckActions
================
*/
bool rvMonsterTurretFlying::CheckActions ( void ) {
// Attacks
if ( PerformAction ( &actionBlasterAttack, (checkAction_t)&idAI::CheckAction_RangedAttack, &actionTimerRangedAttack ) ) {
return true;
}
return idAI::CheckActions ( );
}
/*
================
rvMonsterTurretFlying::Pain
================
*/
bool rvMonsterTurretFlying::Pain ( idEntity *inflictor, idEntity *attacker, int damage, const idVec3 &dir, int location ) {
// Handle the shield effects
if ( shieldHealth > 0 ) {
shieldHealth -= damage;
if ( shieldHealth <= 0 ) {
PlayEffect ( "fx_shieldBreak", GetPhysics()->GetOrigin(), (-GetPhysics()->GetGravityNormal()).ToMat3() );
} else {
PlayEffect ( "fx_shieldHit", GetPhysics()->GetOrigin(), (-GetPhysics()->GetGravityNormal()).ToMat3() );
}
}
return idAI::Pain ( inflictor, attacker, damage, dir, location );
}
/*
================
rvMonsterTurretFlying::Save
================
*/
void rvMonsterTurretFlying::Save( idSaveGame *savefile ) const {
savefile->WriteInt ( shieldHealth );
savefile->WriteInt ( shots );
actionBlasterAttack.Save ( savefile ) ;
}
/*
================
rvMonsterTurretFlying::Restore
================
*/
void rvMonsterTurretFlying::Restore( idRestoreGame *savefile ) {
savefile->ReadInt ( shieldHealth );
savefile->ReadInt ( shots );
actionBlasterAttack.Restore ( savefile ) ;
InitSpawnArgsVariables();
}
/*
===============================================================================
States
===============================================================================
*/
CLASS_STATES_DECLARATION ( rvMonsterTurretFlying )
STATE ( "State_Combat", rvMonsterTurretFlying::State_Combat )
STATE ( "State_Fall", rvMonsterTurretFlying::State_Fall )
STATE ( "State_Killed", rvMonsterTurretFlying::State_Killed )
STATE ( "Torso_Idle", rvMonsterTurretFlying::State_Torso_Idle )
STATE ( "Legs_Idle", rvMonsterTurretFlying::State_Legs_Idle )
STATE ( "Torso_BlasterAttack", rvMonsterTurretFlying::State_Torso_BlasterAttack )
END_CLASS_STATES
/*
================
rvMonsterTurretFlying::State_Combat
================
*/
stateResult_t rvMonsterTurretFlying::State_Combat ( const stateParms_t& parms ) {
// Special handling for not being on the ground
if ( !move.fl.onGround ) {
PostState ( "State_Fall", 0 );
return SRESULT_DONE;
}
// Keep the enemy status up to date
if ( !enemy.ent || enemy.fl.dead ) {
enemy.fl.dead = false;
CheckForEnemy ( true );
}
// try moving, if there was no movement run then just try and action instead
UpdateAction ( );
return SRESULT_WAIT;
}
/*
================
rvMonsterTurretFlying::State_Fall
================
*/
stateResult_t rvMonsterTurretFlying::State_Fall ( const stateParms_t& parms ) {
enum {
STAGE_INIT, // Initialize fall stage
STAGE_WAITIMPACT, // Wait for the drop turret to hit the ground
STAGE_IMPACT, // Handle drop turret impact
STAGE_WAITOPEN, // Wait for drop turret to open up
STAGE_OPENED, // Drop turret opened and ready for combat
};
switch ( parms.stage ) {
case STAGE_INIT:
StopMove ( MOVE_STATUS_DONE );
StartSound ( "snd_falling", SND_CHANNEL_VOICE, 0, false, NULL );
PlayEffect ( "fx_droptrail", animator.GetJointHandle ( "origin" ), true );
PlayCycle ( ANIMCHANNEL_TORSO, "idle_closed", 0 );
return SRESULT_STAGE(STAGE_WAITIMPACT);
case STAGE_WAITIMPACT:
if ( move.fl.onGround ) {
return SRESULT_STAGE(STAGE_IMPACT);
}
return SRESULT_WAIT;
case STAGE_IMPACT:
StopSound ( SND_CHANNEL_VOICE, false );
StopEffect ( "fx_droptrail" );
PlayEffect ( "fx_landing", GetPhysics()->GetOrigin(), (-GetPhysics()->GetGravityNormal()).ToMat3() );
PlayAnim ( ANIMCHANNEL_TORSO, "open", 2 );
return SRESULT_STAGE ( STAGE_WAITOPEN );
case STAGE_WAITOPEN:
if ( AnimDone ( ANIMCHANNEL_TORSO, 0 ) ) {
return SRESULT_STAGE ( STAGE_OPENED );
}
return SRESULT_WAIT;
case STAGE_OPENED:
// Activate shield
fl.takedamage = true;
health += shieldHealth;
PlayEffect ( "fx_shieldOpen", GetPhysics()->GetOrigin(), (-GetPhysics()->GetGravityNormal()).ToMat3() );
SetAnimState ( ANIMCHANNEL_TORSO, "Torso_Idle", 2 );
PostState ( "State_Combat" );
return SRESULT_DONE;
}
return SRESULT_ERROR;
}
/*
================
rvMonsterTurretFlying::State_Killed
================
*/
stateResult_t rvMonsterTurretFlying::State_Killed ( const stateParms_t& parms ) {
gameLocal.PlayEffect ( spawnArgs, "fx_death", GetPhysics()->GetOrigin(), (-GetPhysics()->GetGravityNormal()).ToMat3() );
gameLocal.ProjectDecal( GetPhysics()->GetOrigin(), GetPhysics()->GetGravity(), 128.0f, true, 96.0f, "textures/decals/genericdamage" );
return idAI::State_Killed ( parms );
}
/*
================
rvMonsterTurretFlying::State_Torso_Idle
================
*/
stateResult_t rvMonsterTurretFlying::State_Torso_Idle ( const stateParms_t& parms ) {
if ( move.fl.onGround ) {
IdleAnim ( ANIMCHANNEL_TORSO, "idle_open", parms.blendFrames );
} else {
IdleAnim ( ANIMCHANNEL_TORSO, "idle_closed", parms.blendFrames );
}
return SRESULT_DONE;
}
/*
================
rvMonsterTurretFlying::State_Legs_Idle
================
*/
stateResult_t rvMonsterTurretFlying::State_Legs_Idle ( const stateParms_t& parms ) {
return SRESULT_DONE;
}
/*
================
rvMonsterTurretFlying::State_Torso_BlasterAttack
================
*/
stateResult_t rvMonsterTurretFlying::State_Torso_BlasterAttack ( const stateParms_t& parms ) {
enum {
STAGE_INIT,
STAGE_FIRE,
STAGE_WAIT,
};
switch ( parms.stage ) {
case STAGE_INIT:
DisableAnimState ( ANIMCHANNEL_LEGS );
shots = (minShots + gameLocal.random.RandomInt(maxShots-minShots+1)) * combat.aggressiveScale;
return SRESULT_STAGE ( STAGE_FIRE );
case STAGE_FIRE:
PlayAnim ( ANIMCHANNEL_TORSO, (shots&1)?"range_attack_top":"range_attack_bottom", 2 );
return SRESULT_STAGE ( STAGE_WAIT );
case STAGE_WAIT:
if ( AnimDone ( ANIMCHANNEL_TORSO, 2 ) ) {
if ( --shots <= 0 ) {
return SRESULT_DONE;
}
return SRESULT_STAGE ( STAGE_FIRE );
}
return SRESULT_WAIT;
}
return SRESULT_ERROR;
}
| 412 | 0.996237 | 1 | 0.996237 | game-dev | MEDIA | 0.995433 | game-dev | 0.997711 | 1 | 0.997711 |
flutter/website | 2,481 | examples/cookbook/animation/animated_container/lib/main.dart | import 'dart:math';
import 'package:flutter/material.dart';
void main() => runApp(const AnimatedContainerApp());
class AnimatedContainerApp extends StatefulWidget {
const AnimatedContainerApp({super.key});
@override
State<AnimatedContainerApp> createState() => _AnimatedContainerAppState();
}
class _AnimatedContainerAppState extends State<AnimatedContainerApp> {
// Define the various properties with default values. Update these properties
// when the user taps a FloatingActionButton.
double _width = 50;
double _height = 50;
Color _color = Colors.green;
BorderRadiusGeometry _borderRadius = BorderRadius.circular(8);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('AnimatedContainer Demo')),
body: Center(
// #docregion AnimatedContainer
child: AnimatedContainer(
// Use the properties stored in the State class.
width: _width,
height: _height,
decoration: BoxDecoration(
color: _color,
borderRadius: _borderRadius,
),
// Define how long the animation should take.
duration: const Duration(seconds: 1),
// Provide an optional curve to make the animation feel smoother.
curve: Curves.fastOutSlowIn,
),
// #enddocregion AnimatedContainer
),
// #docregion FAB
floatingActionButton: FloatingActionButton(
// When the user taps the button
onPressed: () {
// Use setState to rebuild the widget with new values.
setState(() {
// Create a random number generator.
final random = Random();
// Generate a random width and height.
_width = random.nextInt(300).toDouble();
_height = random.nextInt(300).toDouble();
// Generate a random color.
_color = Color.fromRGBO(
random.nextInt(256),
random.nextInt(256),
random.nextInt(256),
1,
);
// Generate a random border radius.
_borderRadius = BorderRadius.circular(
random.nextInt(100).toDouble(),
);
});
},
child: const Icon(Icons.play_arrow),
),
// #enddocregion FAB
),
);
}
}
| 412 | 0.510702 | 1 | 0.510702 | game-dev | MEDIA | 0.377849 | game-dev | 0.9174 | 1 | 0.9174 |
Skitttyy/shoreline-client | 1,107 | src/main/java/net/shoreline/client/impl/command/LeaveCommand.java | package net.shoreline.client.impl.command;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import net.minecraft.client.gui.screen.TitleScreen;
import net.minecraft.command.CommandSource;
import net.shoreline.client.api.command.Command;
import net.shoreline.client.mixin.accessor.AccessorMinecraftClient;
import net.shoreline.client.util.chat.ChatUtil;
public class LeaveCommand extends Command
{
public LeaveCommand()
{
super("Leave", "Leaves the game without disconnecting from the server", literal("leave"));
}
@Override
public void buildCommand(LiteralArgumentBuilder<CommandSource> builder)
{
builder.executes(c ->
{
if (mc.isInSingleplayer())
{
ChatUtil.error("Not connected to a server!");
return 0;
}
mc.getNetworkHandler().unloadWorld();
mc.world = null;
mc.player = null;
((AccessorMinecraftClient) mc).hookSetWorld(null);
mc.setScreenAndRender(new TitleScreen());
return 1;
});
}
}
| 412 | 0.893814 | 1 | 0.893814 | game-dev | MEDIA | 0.848409 | game-dev,networking | 0.843541 | 1 | 0.843541 |
Armourers-Workshop/Armourers-Workshop | 3,852 | common/src/main/java/moe/plushie/armourers_workshop/core/data/EntityDataStorage.java | package moe.plushie.armourers_workshop.core.data;
import moe.plushie.armourers_workshop.core.capability.SkinWardrobe;
import moe.plushie.armourers_workshop.core.capability.SkinWardrobeJS;
import moe.plushie.armourers_workshop.core.client.other.BlockEntityRenderData;
import moe.plushie.armourers_workshop.core.client.other.EntityRenderData;
import moe.plushie.armourers_workshop.core.skin.molang.thirdparty.bind.EntityVariableStorageImpl;
import moe.plushie.armourers_workshop.core.utils.LazyOptional;
import moe.plushie.armourers_workshop.init.ModCapabilities;
import moe.plushie.armourers_workshop.init.environment.EnvironmentExecutor;
import moe.plushie.armourers_workshop.init.environment.EnvironmentType;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.block.entity.BlockEntity;
import java.util.Optional;
public class EntityDataStorage {
public static EntityImpl of(Entity entity) {
return DataContainer.of(entity, EntityImpl::new);
}
public static BlockEntityImpl of(BlockEntity entity) {
return DataContainer.of(entity, BlockEntityImpl::new);
}
public static class EntityImpl {
protected final LazyOptional<SkinWardrobe> wardrobe;
protected final LazyOptional<SkinWardrobeJS> wardrobeJS;
protected final LazyOptional<EntityRenderData> renderData;
protected final LazyOptional<EntityAnimationState> animationState;
protected final LazyOptional<EntityVariableStorageImpl> variableStorage;
public EntityImpl(Entity entity) {
this.wardrobe = LazyOptional.of(() -> ModCapabilities.ENTITY_WARDROBE.get().get(entity));
this.wardrobeJS = LazyOptional.of(() -> wardrobe.resolve().map(SkinWardrobeJS::new));
this.renderData = LazyOptional.of(() -> EnvironmentExecutor.callOn(EnvironmentType.CLIENT, () -> () -> new EntityRenderData(entity)));
this.animationState = LazyOptional.ofNullable(EntityAnimationState::new);
this.variableStorage = LazyOptional.ofNullable(EntityVariableStorageImpl::new);
}
public Optional<SkinWardrobe> wardrobe() {
return wardrobe.resolve();
}
public Optional<SkinWardrobeJS> wardrobeJS() {
return wardrobeJS.resolve();
}
public Optional<EntityAnimationState> animationState() {
return animationState.resolve();
}
@Environment(EnvType.CLIENT)
public Optional<EntityRenderData> renderData() {
return renderData.resolve();
}
public Optional<EntityVariableStorageImpl> variableStorage() {
return variableStorage.resolve();
}
}
public static class BlockEntityImpl {
protected final LazyOptional<BlockEntityRenderData> renderData;
protected final LazyOptional<BlockEntityAnimationState> animationState;
protected final LazyOptional<EntityVariableStorageImpl> variableStorage;
public BlockEntityImpl(BlockEntity entity) {
this.renderData = LazyOptional.of(() -> EnvironmentExecutor.callOn(EnvironmentType.CLIENT, () -> () -> new BlockEntityRenderData(entity)));
this.animationState = LazyOptional.ofNullable(BlockEntityAnimationState::new);
this.variableStorage = LazyOptional.ofNullable(EntityVariableStorageImpl::new);
}
public Optional<BlockEntityAnimationState> animationState() {
return animationState.resolve();
}
@Environment(EnvType.CLIENT)
public Optional<BlockEntityRenderData> renderData() {
return renderData.resolve();
}
public Optional<EntityVariableStorageImpl> variableStorage() {
return variableStorage.resolve();
}
}
}
| 412 | 0.639223 | 1 | 0.639223 | game-dev | MEDIA | 0.901238 | game-dev | 0.817236 | 1 | 0.817236 |
pmret/papermario | 13,448 | src/battle/area/mac/actor/lee_bombette.inc.c | #define NAMESPACE A(bombette_lee)
extern EvtScript N(EVS_Init);
extern EvtScript N(EVS_Idle);
extern EvtScript N(EVS_TakeTurn);
extern EvtScript N(EVS_HandleEvent);
extern EvtScript N(EVS_HandlePhase);
s32 N(DefaultAnims)[] = {
STATUS_KEY_NORMAL, ANIM_BattleBombette_Idle,
STATUS_KEY_STONE, ANIM_BattleBombette_Still,
STATUS_KEY_SLEEP, ANIM_BattleBombette_Still,
STATUS_KEY_POISON, ANIM_BattleBombette_Idle,
STATUS_KEY_STOP, ANIM_BattleBombette_Still,
STATUS_KEY_STATIC, ANIM_BattleBombette_Idle,
STATUS_KEY_PARALYZE, ANIM_BattleBombette_Still,
STATUS_KEY_DIZZY, ANIM_BattleBombette_Injured,
STATUS_KEY_FEAR, ANIM_BattleBombette_Injured,
STATUS_END,
};
s32 N(DefenseTable)[] = {
ELEMENT_NORMAL, 0,
ELEMENT_END,
};
s32 N(StatusTable)[] = {
STATUS_KEY_NORMAL, 0,
STATUS_KEY_DEFAULT, 0,
STATUS_KEY_SLEEP, 60,
STATUS_KEY_POISON, 0,
STATUS_KEY_FROZEN, 0,
STATUS_KEY_DIZZY, 75,
STATUS_KEY_FEAR, 0,
STATUS_KEY_STATIC, 0,
STATUS_KEY_PARALYZE, 75,
STATUS_KEY_SHRINK, 80,
STATUS_KEY_STOP, 90,
STATUS_TURN_MOD_DEFAULT, 0,
STATUS_TURN_MOD_SLEEP, -1,
STATUS_TURN_MOD_POISON, 0,
STATUS_TURN_MOD_FROZEN, 0,
STATUS_TURN_MOD_DIZZY, -1,
STATUS_TURN_MOD_FEAR, 0,
STATUS_TURN_MOD_STATIC, 0,
STATUS_TURN_MOD_PARALYZE, 0,
STATUS_TURN_MOD_SHRINK, 0,
STATUS_TURN_MOD_STOP, -1,
STATUS_END,
};
ActorPartBlueprint N(ActorParts)[] = {
{
.flags = ACTOR_PART_FLAG_PRIMARY_TARGET,
.index = PRT_MAIN,
.posOffset = { 0, 0, 0 },
.targetOffset = { 0, 22 },
.opacity = 255,
.idleAnimations = N(DefaultAnims),
.defenseTable = N(DefenseTable),
.eventFlags = ACTOR_EVENT_FLAGS_NONE,
.elementImmunityFlags = 0,
.projectileTargetOffset = { -2, -7 },
},
};
ActorBlueprint NAMESPACE = {
.flags = 0,
.type = ACTOR_TYPE_LEE_BOMBETTE,
.level = ACTOR_LEVEL_LEE_BOMBETTE,
.maxHP = 20,
.partCount = ARRAY_COUNT(N(ActorParts)),
.partsData = N(ActorParts),
.initScript = &N(EVS_Init),
.statusTable = N(StatusTable),
.escapeChance = 100,
.airLiftChance = 0,
.hurricaneChance = 0,
.spookChance = 0,
.upAndAwayChance = 0,
.spinSmashReq = 0,
.powerBounceChance = 90,
.coinReward = 0,
.size = { 30, 28 },
.healthBarOffset = { 0, 0 },
.statusIconOffset = { -10, 20 },
.statusTextOffset = { 10, 20 },
};
EvtScript N(EVS_Init) = {
Call(BindTakeTurn, ACTOR_SELF, Ref(N(EVS_TakeTurn)))
Call(BindIdle, ACTOR_SELF, Ref(N(EVS_Idle)))
Call(BindHandleEvent, ACTOR_SELF, Ref(N(EVS_HandleEvent)))
Call(BindHandlePhase, ACTOR_SELF, Ref(N(EVS_HandlePhase)))
Call(SetActorVar, ACTOR_SELF, AVAR_FormDuration, 1)
Return
End
};
EvtScript N(EVS_Idle) = {
Return
End
};
EvtScript N(EVS_HandleEvent) = {
Call(UseIdleAnimation, ACTOR_SELF, false)
Call(EnableIdleScript, ACTOR_SELF, IDLE_SCRIPT_DISABLE)
Call(GetLastEvent, ACTOR_SELF, LVar0)
Switch(LVar0)
CaseOrEq(EVENT_HIT_COMBO)
CaseOrEq(EVENT_HIT)
SetConst(LVar0, PRT_MAIN)
SetConst(LVar1, ANIM_BattleBombette_Hurt)
ExecWait(EVS_Enemy_Hit)
EndCaseGroup
CaseEq(EVENT_BURN_HIT)
SetConst(LVar0, PRT_MAIN)
SetConst(LVar1, ANIM_BattleBombette_BurnHurt)
SetConst(LVar2, ANIM_BattleBombette_BurnStill)
ExecWait(EVS_Enemy_BurnHit)
CaseEq(EVENT_BURN_DEATH)
SetConst(LVar0, PRT_MAIN)
SetConst(LVar1, ANIM_BattleBombette_BurnHurt)
SetConst(LVar2, ANIM_BattleBombette_BurnStill)
ExecWait(EVS_Enemy_BurnHit)
ExecWait(A(EVS_Lee_RemoveParentActor))
SetConst(LVar0, PRT_MAIN)
SetConst(LVar1, ANIM_BattleBombette_BurnStill)
ExecWait(EVS_Enemy_Death)
Return
CaseEq(EVENT_SPIN_SMASH_HIT)
SetConst(LVar0, PRT_MAIN)
SetConst(LVar1, ANIM_BattleBombette_Hurt)
ExecWait(EVS_Enemy_SpinSmashHit)
CaseEq(EVENT_SPIN_SMASH_DEATH)
ExecWait(A(EVS_Lee_RemoveParentActor))
SetConst(LVar0, PRT_MAIN)
SetConst(LVar1, ANIM_BattleBombette_Hurt)
ExecWait(EVS_Enemy_SpinSmashHit)
SetConst(LVar0, PRT_MAIN)
SetConst(LVar1, ANIM_BattleBombette_Hurt)
ExecWait(EVS_Enemy_Death)
Return
CaseEq(EVENT_SHOCK_HIT)
SetConst(LVar0, PRT_MAIN)
SetConst(LVar1, ANIM_BattleBombette_Hurt)
Set(LVar2, 15)
ExecWait(A(EVS_Lee_ShockKnockback))
Call(SetAnimation, ACTOR_SELF, PRT_MAIN, ANIM_BattleBombette_Run)
Call(SetGoalToHome, ACTOR_SELF)
Call(SetActorSpeed, ACTOR_SELF, Float(5.0))
Call(RunToGoal, ACTOR_SELF, 0, false)
CaseEq(EVENT_SHOCK_DEATH)
ExecWait(A(EVS_Lee_RemoveParentActor))
SetConst(LVar0, PRT_MAIN)
SetConst(LVar1, ANIM_BattleBombette_Hurt)
Set(LVar2, 15)
ExecWait(A(EVS_Lee_ShockKnockback))
SetConst(LVar0, PRT_MAIN)
SetConst(LVar1, ANIM_BattleBombette_BurnStill)
ExecWait(EVS_Enemy_Death)
Return
CaseOrEq(EVENT_ZERO_DAMAGE)
CaseOrEq(EVENT_IMMUNE)
CaseOrEq(EVENT_AIR_LIFT_FAILED)
SetConst(LVar0, PRT_MAIN)
SetConst(LVar1, ANIM_BattleBombette_Idle)
ExecWait(EVS_Enemy_NoDamageHit)
EndCaseGroup
CaseEq(EVENT_DEATH)
ExecWait(A(EVS_Lee_RemoveParentActor))
SetConst(LVar0, PRT_MAIN)
SetConst(LVar1, ANIM_BattleBombette_Hurt)
ExecWait(EVS_Enemy_Hit)
Wait(10)
SetConst(LVar0, PRT_MAIN)
SetConst(LVar1, ANIM_BattleBombette_Hurt)
ExecWait(EVS_Enemy_Death)
Return
CaseEq(EVENT_RECOVER_STATUS)
SetConst(LVar0, PRT_MAIN)
SetConst(LVar1, ANIM_BattleBombette_Idle)
ExecWait(EVS_Enemy_Recover)
CaseEq(EVENT_SCARE_AWAY)
SetConst(LVar0, PRT_MAIN)
SetConst(LVar1, ANIM_BattleBombette_Run)
SetConst(LVar2, ANIM_BattleBombette_Hurt)
ExecWait(EVS_Enemy_ScareAway)
Return
CaseEq(EVENT_BEGIN_AIR_LIFT)
SetConst(LVar0, PRT_MAIN)
SetConst(LVar1, ANIM_BattleBombette_Run)
ExecWait(EVS_Enemy_AirLift)
CaseEq(EVENT_BLOW_AWAY)
SetConst(LVar0, PRT_MAIN)
SetConst(LVar1, ANIM_BattleBombette_Hurt)
ExecWait(EVS_Enemy_BlowAway)
Return
CaseDefault
EndSwitch
Call(EnableIdleScript, ACTOR_SELF, IDLE_SCRIPT_ENABLE)
Call(UseIdleAnimation, ACTOR_SELF, true)
Return
End
};
#include "common/UnkActorPosFunc.inc.c"
EvtScript N(EVS_TakeTurn) = {
Call(UseIdleAnimation, ACTOR_SELF, false)
Call(EnableIdleScript, ACTOR_SELF, IDLE_SCRIPT_DISABLE)
Wait(10)
Call(UseBattleCamPreset, BTL_CAM_ENEMY_APPROACH)
Call(BattleCamTargetActor, ACTOR_SELF)
Call(SetTargetActor, ACTOR_SELF, ACTOR_PLAYER)
Call(SetGoalToTarget, ACTOR_SELF)
Call(AddGoalPos, ACTOR_SELF, 40, 0, 0)
Call(MoveBattleCamOver, 30)
Call(SetAnimation, ACTOR_SELF, PRT_MAIN, ANIM_BattleBombette_Run)
Call(RunToGoal, ACTOR_SELF, 30, false)
Call(SetAnimation, ACTOR_SELF, PRT_MAIN, ANIM_BattleBombette_Idle)
Call(SetAnimation, ACTOR_SELF, PRT_MAIN, ANIM_BattleBombette_Brace)
Wait(15)
Call(SetActorSounds, ACTOR_SELF, ACTOR_SOUND_WALK, SOUND_NONE, SOUND_NONE)
Call(PlaySoundAtActor, ACTOR_SELF, SOUND_BOMBETTE_BODY_SLAM)
Call(EnemyTestTarget, ACTOR_SELF, LVar0, 0, 0, 1, BS_FLAGS1_INCLUDE_POWER_UPS)
Switch(LVar0)
CaseOrEq(HIT_RESULT_MISS)
CaseOrEq(HIT_RESULT_LUCKY)
Set(LVarA, LVar0)
Call(SetGoalToTarget, ACTOR_SELF)
Call(AddGoalPos, ACTOR_SELF, -10, 0, 0)
Call(SetAnimation, ACTOR_SELF, PRT_MAIN, ANIM_BattleBombette_BodySlam)
Call(RunToGoal, ACTOR_SELF, 5, false)
Call(SetAnimation, ACTOR_SELF, PRT_MAIN, ANIM_BattleBombette_Idle)
Thread
Call(SetActorRotationOffset, ACTOR_SELF, 0, 15, 0)
Set(LVar0, 0)
Loop(10)
Add(LVar0, 72)
Call(SetActorRotation, ACTOR_SELF, 0, 0, LVar0)
Wait(1)
EndLoop
Call(SetActorRotationOffset, ACTOR_SELF, 0, 0, 0)
EndThread
Call(AddGoalPos, ACTOR_SELF, -60, 0, 0)
Call(RunToGoal, ACTOR_SELF, 10, false)
Call(SetAnimation, ACTOR_SELF, PRT_MAIN, ANIM_BattleBombette_Idle)
Thread
Call(N(UnkActorPosFunc))
EndThread
IfEq(LVarA, HIT_RESULT_LUCKY)
Call(EnemyTestTarget, ACTOR_SELF, LVar0, DAMAGE_TYPE_TRIGGER_LUCKY, 0, 0, 0)
EndIf
Wait(20)
Call(UseBattleCamPreset, BTL_CAM_DEFAULT)
Call(YieldTurn)
Call(SetAnimation, ACTOR_SELF, PRT_MAIN, ANIM_BattleBombette_Run)
Call(SetGoalToHome, ACTOR_SELF)
Call(SetActorSpeed, ACTOR_SELF, Float(5.0))
Call(RunToGoal, ACTOR_SELF, 0, false)
Call(EnableIdleScript, ACTOR_SELF, IDLE_SCRIPT_ENABLE)
Call(UseIdleAnimation, ACTOR_SELF, true)
Return
EndCaseGroup
EndSwitch
Set(LVarA, LVar0)
Call(SetGoalToTarget, ACTOR_SELF)
Call(SetAnimation, ACTOR_SELF, PRT_MAIN, ANIM_BattleBombette_BodySlam)
Call(RunToGoal, ACTOR_SELF, 4, false)
Call(GetActorVar, ACTOR_SELF, AVAR_Copy_PartnerLevel, LVar9)
Switch(LVar9)
CaseEq(PARTNER_RANK_NORMAL)
Wait(2)
Call(EnemyDamageTarget, ACTOR_SELF, LVar0, 0, 0, 0, 2, BS_FLAGS1_TRIGGER_EVENTS)
CaseEq(PARTNER_RANK_SUPER)
Wait(2)
Call(EnemyDamageTarget, ACTOR_SELF, LVar0, 0, 0, 0, 3, BS_FLAGS1_TRIGGER_EVENTS)
CaseEq(PARTNER_RANK_ULTRA)
Wait(2)
Call(EnemyDamageTarget, ACTOR_SELF, LVar0, 0, 0, 0, 5, BS_FLAGS1_TRIGGER_EVENTS)
EndSwitch
Switch(LVar0)
CaseOrEq(HIT_RESULT_HIT)
CaseOrEq(HIT_RESULT_NO_DAMAGE)
Call(SetAnimation, ACTOR_SELF, PRT_MAIN, ANIM_BattleBombette_Idle)
Call(UseBattleCamPreset, BTL_CAM_DEFAULT)
Call(MoveBattleCamOver, 8)
Call(SetAnimation, ACTOR_SELF, PRT_MAIN, ANIM_BattleBombette_Backfire2)
Call(GetGoalPos, ACTOR_SELF, LVar0, LVar1, LVar2)
Add(LVar0, 40)
Set(LVar1, 0)
Call(SetActorJumpGravity, ACTOR_SELF, Float(1.4))
Call(SetGoalPos, ACTOR_SELF, LVar0, LVar1, LVar2)
Call(JumpToGoal, ACTOR_SELF, 20, false, true, false)
Call(SetAnimation, ACTOR_SELF, PRT_MAIN, ANIM_BattleBombette_Backfire1)
Wait(1)
Call(SetAnimation, ACTOR_SELF, PRT_MAIN, ANIM_BattleBombette_Backfire2)
Add(LVar0, 40)
Call(SetGoalPos, ACTOR_SELF, LVar0, LVar1, LVar2)
Call(JumpToGoal, ACTOR_SELF, 8, false, true, false)
Call(SetAnimation, ACTOR_SELF, PRT_MAIN, ANIM_BattleBombette_Backfire1)
Wait(1)
Call(SetAnimation, ACTOR_SELF, PRT_MAIN, ANIM_BattleBombette_Backfire2)
Add(LVar0, 20)
Call(SetGoalPos, ACTOR_SELF, LVar0, LVar1, LVar2)
Call(JumpToGoal, ACTOR_SELF, 6, false, true, false)
Call(SetAnimation, ACTOR_SELF, PRT_MAIN, ANIM_BattleBombette_Backfire1)
Wait(1)
Call(SetAnimation, ACTOR_SELF, PRT_MAIN, ANIM_BattleBombette_Backfire2)
Add(LVar0, 10)
Call(SetGoalPos, ACTOR_SELF, LVar0, LVar1, LVar2)
Call(JumpToGoal, ACTOR_SELF, 4, false, true, false)
Call(SetAnimation, ACTOR_SELF, PRT_MAIN, ANIM_BattleBombette_Backfire1)
Wait(1)
Call(SetAnimation, ACTOR_SELF, PRT_MAIN, ANIM_BattleBombette_Idle)
Wait(8)
Call(YieldTurn)
Call(SetAnimation, ACTOR_SELF, PRT_MAIN, ANIM_BattleBombette_Run)
Call(SetGoalToHome, ACTOR_SELF)
Call(SetActorSpeed, ACTOR_SELF, Float(5.0))
Call(RunToGoal, ACTOR_SELF, 0, false)
EndCaseGroup
EndSwitch
Call(EnableIdleScript, ACTOR_SELF, IDLE_SCRIPT_ENABLE)
Call(UseIdleAnimation, ACTOR_SELF, true)
Return
End
};
EvtScript N(EVS_HandlePhase) = {
Call(GetBattlePhase, LVar0)
Switch(LVar0)
CaseEq(PHASE_ENEMY_BEGIN)
Call(GetActorVar, ACTOR_SELF, AVAR_FormDuration, LVar0)
IfGt(LVar0, 0)
Sub(LVar0, 1)
Call(SetActorVar, ACTOR_SELF, AVAR_FormDuration, LVar0)
BreakSwitch
EndIf
SetConst(LVar0, PRT_MAIN)
SetConst(LVar1, ANIM_BattleBombette_Hurt)
ExecWait(A(EVS_Lee_LoseDisguise))
Return
EndSwitch
Return
End
};
Formation A(LeeBombetteFormation) = {
ACTOR_BY_POS(NAMESPACE, A(Lee_SummonPos), 0)
};
| 412 | 0.87574 | 1 | 0.87574 | game-dev | MEDIA | 0.996548 | game-dev | 0.940177 | 1 | 0.940177 |
bergerhealer/MyWorlds | 8,133 | src/main/java/com/bergerkiller/bukkit/mw/AsyncHandler.java | package com.bergerkiller.bukkit.mw;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.concurrent.CompletableFuture;
import java.util.logging.Level;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import com.bergerkiller.bukkit.common.AsyncTask;
import com.bergerkiller.bukkit.common.utils.CommonUtil;
public class AsyncHandler {
public static CompletableFuture<Boolean> reset(final CommandSender sender, String worldname, WorldRegenerateOptions options) {
final WorldConfig worldConfig = WorldConfig.get(worldname);
if (worldConfig.isLoaded()) {
CommonUtil.sendMessage(sender, ChatColor.RED + "Can not reset chunk data of a loaded world!");
return CompletableFuture.completedFuture(Boolean.FALSE);
}
final CompletableFuture<Boolean> future = new CompletableFuture<>();
new AsyncTask("World reset thread") {
public void run() {
future.complete(worldConfig.regenerateWorldData(options));
}
}.start();
return future.thenApplyAsync(success -> {
if (success) {
CommonUtil.sendMessage(sender, ChatColor.GREEN + "World '" + worldConfig.worldname + "' chunk data has been reset!");
} else {
CommonUtil.sendMessage(sender, ChatColor.RED + "Failed to (completely) reset the world chunk data!");
}
return success;
}, CommonUtil.getMainThreadExecutor());
}
public static void delete(final CommandSender sender, String worldname) {
final WorldConfig worldConfig = WorldConfig.get(worldname);
if (worldConfig.isLoaded()) {
CommonUtil.sendMessage(sender, ChatColor.RED + "Can not delete a loaded world!");
return;
}
WorldConfig.remove(worldConfig.worldname);
new AsyncTask("World deletion thread") {
public void run() {
if (worldConfig.deleteWorld()) {
CommonUtil.sendMessage(sender, ChatColor.GREEN + "World '" + worldConfig.worldname + "' has been removed!");
} else {
CommonUtil.sendMessage(sender, ChatColor.RED + "Failed to (completely) remove the world!");
}
}
}.start();
}
public static void copy(final CommandSender sender, final String oldworld, final String newworld) {
final WorldConfig oldconfig = WorldConfig.get(oldworld);
final WorldConfig newconfig = WorldConfig.get(newworld);
new AsyncTask("World copy thread") {
public void run() {
if (oldconfig.copyTo(newconfig)) {
CommonUtil.sendMessage(sender, ChatColor.GREEN + "World '" + oldworld + "' has been copied as '" + newworld + "'!");
} else {
CommonUtil.sendMessage(sender, ChatColor.RED + "Failed to copy world to '" + newworld + "'!");
}
}
}.start();
}
public static void repair(final CommandSender sender, final String worldname, final long seed) {
final WorldConfig config = WorldConfig.get(worldname);
if (config.isLoaded()) {
CommonUtil.sendMessage(sender, ChatColor.RED + "Can not repair a loaded world!");
return;
}
new AsyncTask("World repair thread") {
public void run() {
boolean hasMadeFixes = false;
if (config.isBroken()) {
if (config.resetData(seed)) {
hasMadeFixes = true;
CommonUtil.sendMessage(sender, ChatColor.YELLOW + "Level.dat regenerated using seed: " + seed);
} else {
CommonUtil.sendMessage(sender, ChatColor.RED + "Failed to repair world '" + worldname + "': could not fix level.dat!");
return;
}
}
//Fix chunks
int fixedfilecount = 0;
int totalfixes = 0;
int totalremoves = 0;
int totaldelfailures = 0;
int totalaccessfailures = 0;
try {
File regionfolder = config.getRegionFolder();
if (regionfolder != null) {
//Generate backup folder
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy_hh-mm-ss");
File backupfolder = new File(regionfolder + File.separator + "backup_" + sdf.format(cal.getTime()));
String[] regionfiles = regionfolder.list();
int i = 1;
for (String listedFile : regionfiles) {
if (listedFile.toLowerCase().endsWith(".mca")) {
CommonUtil.sendMessage(sender, ChatColor.YELLOW + "Scanning and repairing file " + i + "/" + regionfiles.length);
int fixcount = WorldManager.repairRegion(new File(regionfolder + File.separator + listedFile), backupfolder);
if (fixcount == -1) {
totalremoves++;
fixedfilecount++;
} else if (fixcount == -2) {
totalaccessfailures++;
} else if (fixcount == -3) {
totaldelfailures++;
} else if (fixcount > 0) {
totalfixes += fixcount;
fixedfilecount++;
}
}
i++;
}
if (totalfixes > 0 || totalremoves > 0 || fixedfilecount > 0) {
CommonUtil.sendMessage(sender, ChatColor.YELLOW + "Fixed " + totalfixes + " chunk(s) and removed " + totalremoves + " file(s)!");
CommonUtil.sendMessage(sender, ChatColor.YELLOW.toString() + fixedfilecount + " File(s) are affected!");
if (fixedfilecount > 0) {
CommonUtil.sendMessage(sender, ChatColor.YELLOW + "A backup of these files can be found in '" + backupfolder + "'");
}
hasMadeFixes = true;
} else {
CommonUtil.sendMessage(sender, ChatColor.YELLOW + "No chunk or region file errors have been detected");
}
if (totalaccessfailures > 0) {
CommonUtil.sendMessage(sender, ChatColor.YELLOW.toString() + totalaccessfailures + " File(s) were inaccessible (OK-status unknown).");
}
if (totaldelfailures > 0) {
CommonUtil.sendMessage(sender, ChatColor.YELLOW.toString() + totaldelfailures + " Unrecoverable file(s) could not be removed.");
}
} else {
CommonUtil.sendMessage(sender, ChatColor.RED + "Region folder not found, no regions edited.");
}
} catch (Throwable t) {
//We did nothing...
MyWorlds.plugin.getLogger().log(Level.SEVERE, "Unhandled error trying to repair world", t);
CommonUtil.sendMessage(sender, ChatColor.RED + "Error while repairing: " + t.getMessage());
}
if (hasMadeFixes) {
CommonUtil.sendMessage(sender, ChatColor.GREEN + "World: '" + worldname + "' has been repaired!");
} else {
CommonUtil.sendMessage(sender, ChatColor.GREEN + "World: '" + worldname + "' contained no errors, no fixes have been performed!");
}
}
}.start();
}
}
| 412 | 0.860527 | 1 | 0.860527 | game-dev | MEDIA | 0.73548 | game-dev,networking | 0.930592 | 1 | 0.930592 |
Nautilus-Institute/finals-2025 | 22,419 | nautro/src/game.zig | const std = @import("std");
const cards = @import("cards.zig");
const util = @import("util.zig");
const ge = @import("ge.zig");
var game_instances: ?std.AutoHashMap(u64, *GameInstance) = null;
pub var global_allocator: ?std.mem.Allocator = null;
pub var card_manager: ?cards.CardManager = null;
pub fn init(allocator: std.mem.Allocator) !void {
game_instances = std.AutoHashMap(u64, *GameInstance).init(allocator);
global_allocator = allocator;
card_manager = cards.CardManager{
.allocator = allocator,
.card_collection = std.ArrayList(*cards.Card).init(allocator),
};
try card_manager.?.load_all_base_cards();
}
var uuid_counter: u64 = 0;
var game_instances_lock = std.Thread.RwLock.DefaultRwLock{};
//noinline
fn create_allocator() std.mem.Allocator {
var ga = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = ga.allocator();
return allocator;
}
//noinline
fn lock_game_instances() void {
util.lock(&game_instances_lock);
}
//noinline
fn unlock_game_instances() void {
util.unlock(&game_instances_lock);
}
//noinline
fn put_game_instance(uuid: u64, game_instance: *GameInstance) !void {
try game_instances.?.put(uuid, game_instance);
}
//noinline
fn get_game_instance(uuid: u64) !?*GameInstance {
util.rlock(&game_instances_lock);
defer util.runlock(&game_instances_lock);
return game_instances.?.get(uuid);
}
pub const max_num_resources: comptime_int = @intFromEnum(cards.ResourceType.undefined);
pub const PlayedCard = struct {
card: *cards.Card,
activations: u64,
};
pub const GameState = struct {
epoch: u64,
escape: u64,
sets_left: u64,
discards_left: u64,
hand: std.ArrayList(*cards.Card),
resources: [max_num_resources]cards.ResourceStat,
num_resource_entries: usize,
remaining_deck: std.ArrayList(*cards.Card),
persistent_cards: std.ArrayList(*cards.Card),
hand_size: usize,
max_set_size: usize,
ready_for_next_stage: bool,
//noinline
pub fn update_resources(self: *GameState, resources: []cards.ResourceStat) void {
var i: usize = 0;
var j: usize = 0;
while (i < max_num_resources and j < resources.len) : (j += 1) {
const input_resource = resources[j];
if (input_resource.type == .none or input_resource.value == 0 and input_resource.type != .energy) {
continue;
}
self.resources[i] = input_resource;
i += 1;
}
self.num_resource_entries = i;
}
//noinline
pub fn next_level(self: *GameState, energy: u64, result: *CardProcessResult) void {
var remaining_energy = energy;
_ = result;
while (remaining_energy > self.escape) {
remaining_energy -= self.escape;
self.epoch += 1;
self.escape *= 2;
self.sets_left = 4;
self.discards_left = 3;
self.hand_size += 1;
// TODO add pack to be opened
if (self.epoch > 32) {
break;
}
}
self.ready_for_next_stage = true;
// maybe safe? energy should always be first
self.resources[0].value = remaining_energy;
self.clear_deck();
self.clear_hand();
}
//noinline
pub fn clear_deck(self: *GameState) void {
self.remaining_deck.clearAndFree();
}
//noinline
pub fn reset_deck(self: *GameState, deck: []*cards.Card) void {
self.clear_deck();
self.clear_hand();
for (deck) |card| {
try self.add_to_deck(card);
}
self.shuffle_deck();
try self.refill_hand();
}
//noinline
fn append_card_to_hand(self: *GameState, card: *cards.Card) !void {
try self.hand.append(card);
}
//noinline
fn get_card_index(self: *GameState, card: *cards.Card) ?usize {
for (0..self.hand.items.len) |i| {
if (self.hand.items[i] == card) {
return i;
}
}
return null;
}
//noinline
fn remove_card_index_from_hand(self: *GameState, i: usize) void {
_ = self.hand.orderedRemove(i);
}
//noinline
pub fn remove_card_from_hand(self: *GameState, card: *cards.Card) bool {
const i = self.get_card_index(card);
if (i != null) {
self.remove_card_index_from_hand(i.?);
return true;
}
return false;
}
//noinline
pub fn remove_cards_from_hand(self: *GameState, card_set: []PlayedCard) void {
for (card_set) |card_info| {
_ = self.remove_card_from_hand(card_info.card);
}
}
//noinline
pub fn get_resource_value(self: *GameState, resource_type: cards.ResourceType) u64 {
for (0..self.num_resource_entries) |i| {
if (self.resources[i].type == resource_type) {
return self.resources[i].value;
}
}
return 0;
}
//noinline
pub fn pop_card_from_deck(self: *GameState) ?*cards.Card {
return self.remaining_deck.pop();
}
//noinline
pub fn add_to_deck(self: *GameState, card: *cards.Card) !void {
try self.remaining_deck.append(card);
}
//noinline
pub fn init_from_deck(self: *GameState, deck: []*cards.Card) !void {
self.clear_deck();
self.clear_hand();
for (deck) |card| {
try self.add_to_deck(card);
}
}
//noinline
pub fn shuffle_deck(self: *GameState) void {
if (self.remaining_deck.items.len == 0) {
return;
}
var prng = std.Random.DefaultPrng.init(self.epoch + uuid_counter);
const rand = prng.random();
for (0..100) |_| {
const i = rand.intRangeAtMost(usize, 0, self.remaining_deck.items.len - 1);
const j = rand.intRangeAtMost(usize, 0, self.remaining_deck.items.len - 1);
const temp = self.remaining_deck.items[i];
self.remaining_deck.items[i] = self.remaining_deck.items[j];
self.remaining_deck.items[j] = temp;
}
//self.remaining_deck.shuffle(self.allocator);
}
//noinline
pub fn clear_hand(self: *GameState) void {
self.hand.clearAndFree();
}
//noinline
pub fn refill_hand(self: *GameState) !void {
while (self.hand.items.len < self.hand_size and self.remaining_deck.items.len > 0) {
const card = self.pop_card_from_deck();
if (card != null) {
try self.append_card_to_hand(card.?);
} else {
break;
}
}
}
//noinline
pub fn add_persistent_card(self: *GameState, card: *cards.Card) !void {
try self.persistent_cards.append(card);
}
//noinline
pub fn remove_persistent_card(self: *GameState, card: *cards.Card) bool {
for (0..self.persistent_cards.items.len) |i| {
if (self.persistent_cards.items[i] == card) {
self.persistent_cards.orderedRemove(i);
return true;
}
}
return false;
}
};
pub const SetResources = struct {
resources: [max_num_resources]cards.ResourceStat,
//noinline
fn init(self: *SetResources) void {
for (0..max_num_resources) |i| {
self.resources[i] = cards.ResourceStat{
.type = cards.ResourceType.from_int(i),
.value = 0,
};
}
}
//noinline
pub fn set_base_resources(self: *SetResources, resources: []cards.ResourceStat) void {
for (0..resources.len) |i| {
const resource_num = resources[i].type.to_int();
self.resources[resource_num] = resources[i];
}
}
//noinline
pub fn get_resource(self: *SetResources, resource_type: cards.ResourceType) cards.ResourceStat {
const resource_num = resource_type.to_int();
return self.resources[resource_num];
}
//noinline
pub fn consume_resource(self: *SetResources, resource: cards.ResourceStat) bool {
const resource_num = resource.type.to_int();
const req_value = resource.value;
if (req_value > self.resources[resource_num].value) {
return false;
}
const before = self.resources[resource_num].value;
self.resources[resource_num].value -= req_value;
std.log.info("consume_resource: {s} {d} -> {d}", .{ @tagName(resource.type), before, self.resources[resource_num].value });
return true;
}
//noinline
pub fn consume_resource_max(self: *SetResources, resource: cards.ResourceStat, max_applies: u64) u64 {
const resource_num = resource.type.to_int();
const resource_value = self.resources[resource_num].value;
const req_value = resource.value;
if (req_value > resource_value) {
return 0;
}
var num_applies = resource_value / req_value;
if (max_applies > 0 and num_applies > max_applies) {
num_applies = max_applies;
}
self.resources[resource_num].value -= num_applies * req_value;
std.log.info("consume_resource: {s} {d} -> {d}", .{ @tagName(resource.type), resource_value, self.resources[resource_num].value });
return num_applies;
}
//noinline
pub fn consume_resource_value(self: *SetResources, resource_type: cards.ResourceType, value: u32) bool {
const resource_num = resource_type.to_int();
if (value > self.resources[resource_num].value) {
return false;
}
const before = self.resources[resource_num].value;
self.resources[resource_num].value -= value;
std.log.info("consume_resource: {s} {d} -> {d}", .{ @tagName(resource_type), before, self.resources[resource_num].value });
return true;
}
//noinline
pub fn add_resource(self: *SetResources, resource: cards.ResourceStat) void {
const resource_num = resource.type.to_int();
const before = self.resources[resource_num].value;
self.resources[resource_num].value += resource.value;
std.log.info("add_resource: {s} {d} -> {d}", .{ @tagName(resource.type), before, self.resources[resource_num].value });
}
//noinline
pub fn add_resource_value(self: *SetResources, resource_type: cards.ResourceType, value: u64) void {
const resource_num = resource_type.to_int();
const before = self.resources[resource_num].value;
self.resources[resource_num].value += value;
std.log.info("add_resource: {s} {d} -> {d}", .{ @tagName(resource_type), before, self.resources[resource_num].value });
}
};
pub const CardProcessResult = struct {
failed_on: usize,
success: bool,
failed_reason: ?[]const u8,
reward: ?[]const u8,
win: bool,
//noinline
pub fn to_json(self: *const CardProcessResult, allocator: std.mem.Allocator) ![]u8 {
var json_response = std.ArrayList(u8).init(allocator);
try std.json.stringify(self, .{}, json_response.writer());
return json_response.items;
}
};
pub const GameInstance = struct {
allocator: std.mem.Allocator,
engine_id: u64,
sandbox_mode: bool,
lock: *std.Thread.RwLock.DefaultRwLock,
uuid: u64,
deck: std.ArrayList(*cards.Card),
game_state: ?GameState,
//noinline
fn create_uninitialized(allocator: std.mem.Allocator) !*GameInstance {
return try allocator.create(GameInstance);
}
//noinline
pub fn take_lock(self: *GameInstance) void {
util.lock(self.lock);
}
//noinline
pub fn release_lock(self: *GameInstance) void {
util.unlock(self.lock);
}
//noinline
pub fn add_to_deck(self: *GameInstance, card: *cards.Card) !void {
try self.deck.append(card);
}
//noinline
pub fn clear_deck(self: *GameInstance) void {
self.deck.clearAndFree();
}
//noinline
pub fn make_deck_from_ids(self: *GameInstance, card_ids: []u64) !void {
self.clear_deck();
for (card_ids) |card_id| {
const card = try card_manager.?.get_card_by_uuid(card_id);
try self.add_to_deck(card);
}
}
//noinline
pub fn init_ptr(self: *GameInstance, allocator: std.mem.Allocator, uuid: u64) !void {
const locker = try allocator.create(std.Thread.RwLock.DefaultRwLock);
locker.* = std.Thread.RwLock.DefaultRwLock{};
self.allocator = allocator;
self.lock = locker;
self.uuid = uuid;
self.deck = std.ArrayList(*cards.Card).init(allocator);
self.sandbox_mode = false;
self.game_state = GameState{
.epoch = 1,
.escape = 5,
.sets_left = 4,
.discards_left = 3,
.hand = std.ArrayList(*cards.Card).init(allocator),
.resources = [_]cards.ResourceStat{.{ .type = .none, .value = 0 }} ** max_num_resources,
.num_resource_entries = 1,
.remaining_deck = std.ArrayList(*cards.Card).init(allocator),
.hand_size = 10,
.max_set_size = 5,
.ready_for_next_stage = true,
.persistent_cards = std.ArrayList(*cards.Card).init(allocator),
};
self.game_state.?.resources[0] = cards.ResourceStat{
.type = .energy,
.value = 1,
};
self.game_state.?.resources[1] = cards.ResourceStat{
.type = .water,
.value = 2,
};
self.game_state.?.resources[2] = cards.ResourceStat{
.type = .food,
.value = 2,
};
self.game_state.?.resources[3] = cards.ResourceStat{
.type = .tool,
.value = 2,
};
self.game_state.?.resources[4] = cards.ResourceStat{
.type = .knowledge,
.value = 1,
};
self.game_state.?.resources[5] = cards.ResourceStat{
.type = .stone,
.value = 1,
};
self.game_state.?.num_resource_entries = 6;
try self.create_basic_deck();
}
//noinline
pub fn add_card_to_deck_by_name(self: *GameInstance, name: []const u8) !void {
const card = try card_manager.?.get_card_by_name(name);
try self.add_to_deck(card);
}
//noinline
pub fn create_basic_deck(self: *GameInstance) !void {
// BASIC RESOURCE EXTRACTION (multiple food sources for reliability)
try self.add_card_to_deck_by_name("Foraging");
try self.add_card_to_deck_by_name("Fishing");
try self.add_card_to_deck_by_name("Scavenging");
try self.add_card_to_deck_by_name("Stone Quarry");
try self.add_card_to_deck_by_name("Spring Water");
try self.add_card_to_deck_by_name("Stone Gathering"); // backup stone source
// TOOL CREATION & EARLY PROCESSING
try self.add_card_to_deck_by_name("Tool Making");
try self.add_card_to_deck_by_name("Stone Working");
try self.add_card_to_deck_by_name("Composite Tools"); // multi-input efficiency
// ENERGY GENERATION (multiple paths)
try self.add_card_to_deck_by_name("Fire Making");
try self.add_card_to_deck_by_name("Food Preparation");
try self.add_card_to_deck_by_name("Cooked Meals"); // efficient multi-input
try self.add_card_to_deck_by_name("Manual Labor"); // food→energy alternative
// FOOD AMPLIFICATION
try self.add_card_to_deck_by_name("Hunting"); // tools→food
try self.add_card_to_deck_by_name("Farming"); // water→food scaling
try self.add_card_to_deck_by_name("Herding"); // food→more food
// KNOWLEDGE & SKILL DEVELOPMENT
try self.add_card_to_deck_by_name("Observation"); // tools→knowledge
try self.add_card_to_deck_by_name("Teaching"); // knowledge multiplication
try self.add_card_to_deck_by_name("Cave Paintings"); // alternative knowledge
}
//noinline
pub fn continue_new_epoch(self: *GameInstance) !void {
if (!self.game_state.?.ready_for_next_stage) {
return;
}
self.game_state.?.ready_for_next_stage = false;
// Just setup the deck and hand
try self.game_state.?.init_from_deck(self.deck.items);
self.game_state.?.shuffle_deck();
try self.game_state.?.refill_hand();
}
//noinline
pub fn create_new_game(engine_id: u64) !*GameInstance {
lock_game_instances();
defer unlock_game_instances();
uuid_counter += 1;
const allocator = global_allocator.?;
const game_instance = try create_uninitialized(allocator);
game_instance.engine_id = engine_id;
try game_instance.init_ptr(allocator, uuid_counter);
try put_game_instance(uuid_counter, game_instance);
//util.lock(game_instance.lock);
return game_instance;
}
//noinline
pub fn get(uuid: u64) !?*GameInstance {
return try get_game_instance(uuid);
}
//noinline
pub fn deinit(self: *GameInstance) void {
self.allocator.free(self.deck);
}
//noinline
pub fn get_card_by_uuid(self: *GameInstance, uuid: u64) !*cards.Card {
for (self.deck.items) |card| {
if (card.uuid == uuid) {
return card;
}
}
return cards.CardError.CardNotFound;
}
//noinline
pub fn discard_cards(self: *GameInstance, set: []PlayedCard) !void {
self.take_lock();
defer self.release_lock();
if (self.game_state.?.discards_left == 0) {
return;
}
for (set) |card| {
const removed = self.game_state.?.remove_card_from_hand(card.card);
if (removed) {
try self.game_state.?.add_to_deck(card.card);
}
}
self.game_state.?.shuffle_deck();
try self.game_state.?.refill_hand();
self.game_state.?.discards_left -= 1;
}
//noinline
pub fn process_set(self: *GameInstance, set: []PlayedCard, result: *CardProcessResult) !void {
self.take_lock();
defer self.release_lock();
if (self.game_state.?.sets_left == 0) {
result.failed_on = 0;
result.success = false;
result.failed_reason = "GAME OVER";
return;
}
if (set.len > self.game_state.?.max_set_size) {
result.failed_on = 0;
result.success = false;
result.failed_reason = "Set size exceeds max set size";
return;
}
var set_resources = SetResources{ .resources = undefined };
set_resources.init();
set_resources.set_base_resources(self.game_state.?.resources[0..self.game_state.?.num_resource_entries]);
for (0..set.len) |i| {
const card = set[i];
std.log.info("process_set card: {s} {d}", .{ card.card.name, card.activations });
try self.process_card(i, &set_resources, card, result);
if (!result.success) {
return;
}
}
self.game_state.?.sets_left -= 1;
// Update the left over resources
self.game_state.?.update_resources(set_resources.resources[0..]);
if (self.game_state.?.sets_left == 0) {
self.game_state.?.clear_hand();
} else {
// Remove played cards from hand
self.game_state.?.remove_cards_from_hand(set);
try self.game_state.?.refill_hand();
}
const energy = self.game_state.?.get_resource_value(cards.ResourceType.energy);
if (energy > self.game_state.?.escape) {
// WIN
result.win = true;
// Change level
self.game_state.?.next_level(energy, result);
if (self.game_state.?.epoch > 32) {
if (self.sandbox_mode == false) {
const flag_str = try util.read_all_of_file(self.allocator, "/flag");
result.reward = flag_str;
} else {
result.reward = "You won sandbox mode, now win the game for real!";
}
}
}
}
//noinline
pub fn process_card(self: *GameInstance, i: usize, resources: *SetResources, card_info: PlayedCard, result: *CardProcessResult) !void {
// Stage 1: Consume resources
const card = card_info.card;
const played_activations = card_info.activations;
std.log.info("process_card incoming: {s} {d}", .{ card.name, played_activations });
var num_applies: u64 = 1;
var max_activations = card.max_activations;
if (played_activations > 0 and (max_activations == 0 or played_activations < max_activations)) {
max_activations = played_activations;
}
if (max_activations > 0) {
num_applies = max_activations;
}
if (card.consumes.type != .none and card.consumes.value > 0) {
num_applies = resources.consume_resource_max(card.consumes, max_activations);
}
std.log.info("========= process_card: {s} {d} {d} {d}", .{ @tagName(card.consumes.type), max_activations, played_activations, num_applies });
if (num_applies == 0) {
result.failed_on = i;
result.success = false;
result.failed_reason = "Not enough resources to activate card";
return;
}
// Stage 2: Execute card bytecode
if (card.code != null or self.game_state.?.persistent_cards.items.len > 0) {
const engine = ge.get_engine(self.engine_id);
//_ = engine;
const is_ok = try engine.run(&self.game_state.?, resources, card, num_applies);
//const is_ok = try engine.run(&self.game_state.?, resources, card, num_applies);
if (!is_ok) {
result.failed_on = i;
result.success = false;
result.failed_reason = "Card failed during ability activation";
return;
}
}
// Stage 3: Produce resources
if (card.produces.type != .none and card.produces.value > 0) {
const resource_value = card.produces.value * num_applies;
resources.add_resource_value(card.produces.type, resource_value);
}
}
};
| 412 | 0.982886 | 1 | 0.982886 | game-dev | MEDIA | 0.822377 | game-dev | 0.983179 | 1 | 0.983179 |
absameen/Animator_Timeline | 2,320 | Animator/Files/Classes/AMRotationAction.cs | using UnityEngine;
using System.Collections;
[System.Serializable]
public class AMRotationAction : AMAction {
//public int type = 0; // 0 = Rotate To, 1 = Look At
public int endFrame;
public Transform obj;
public Quaternion startRotation;
public Quaternion endRotation;
public override string ToString (int codeLanguage, int frameRate)
{
if(endFrame == -1) return null;
string s;
if(codeLanguage == 0) {
// c#
s = "AMTween.RotateTo (obj.gameObject, AMTween.Hash (\"delay\", "+getWaitTime(frameRate,0f)+"f, \"time\", "+getTime(frameRate)+"f, ";
s += "\"rotation\", new Vector3("+endRotation.eulerAngles.x+"f, "+endRotation.eulerAngles.y+"f, "+endRotation.eulerAngles.z+"f), ";
s += getEaseString(codeLanguage)+"));";
} else {
// js
s = "AMTween.RotateTo (obj.gameObject, {\"delay\": "+getWaitTime(frameRate,0f)+", \"time\": "+getTime(frameRate)+", ";
s += "\"rotation\": Vector3("+endRotation.eulerAngles.x+", "+endRotation.eulerAngles.y+", "+endRotation.eulerAngles.z+"), ";
s += getEaseString(codeLanguage)+"});";
}
return s;
}
public override int getNumberOfFrames() {
return endFrame-startFrame;
}
public float getTime(int frameRate) {
return (float)getNumberOfFrames()/(float)frameRate;
}
public override void execute(int frameRate, float delay) {
if(!obj) return;
if(endFrame == -1) return;
if(hasCustomEase()) AMTween.RotateTo (obj.gameObject,AMTween.Hash ("delay",getWaitTime(frameRate, delay),"time",getTime(frameRate),"rotation",endRotation.eulerAngles,"easecurve",easeCurve));
else AMTween.RotateTo (obj.gameObject,AMTween.Hash ("delay",getWaitTime(frameRate, delay),"time",getTime(frameRate),"rotation",endRotation.eulerAngles,"easetype",(AMTween.EaseType)easeType));
}
public Quaternion getStartQuaternion() {
return startRotation;
}
public Quaternion getEndQuaternion() {
return endRotation;
}
public override AnimatorTimeline.JSONAction getJSONAction (int frameRate)
{
if(!obj || endFrame == -1) return null;
AnimatorTimeline.JSONAction a = new AnimatorTimeline.JSONAction();
a.go = obj.gameObject.name;
a.method = "rotateto";
a.delay = getWaitTime(frameRate, 0f);
a.time = getTime(frameRate);
setupJSONActionEase(a);
// set rotation
a.setPath(new Vector3[]{endRotation.eulerAngles});
return a;
}
}
| 412 | 0.740852 | 1 | 0.740852 | game-dev | MEDIA | 0.37683 | game-dev | 0.551547 | 1 | 0.551547 |
micronaut-projects/micronaut-core | 1,520 | inject-kotlin/src/test/kotlin/io/micronaut/kotlin/processing/inject/configproperties/MyConfig.kt | package io.micronaut.kotlin.processing.inject.configproperties
import io.micronaut.context.annotation.ConfigurationProperties
import io.micronaut.core.convert.format.ReadableBytes
import java.net.URL
import java.util.Optional
@ConfigurationProperties("foo.bar")
class MyConfig {
var port: Int = 0
var defaultValue: Int = 9999
var stringList: List<String>? = null
var intList: List<Int>? = null
var urlList: List<URL>? = null
var urlList2: List<URL>? = null
var emptyList: List<URL>? = null
var flags: Map<String,Int>? = null
var url: Optional<URL>? = null
var anotherUrl: Optional<URL> = Optional.empty()
var inner: Inner? = null
protected var defaultPort: Int = 9999
protected var anotherPort: Int? = null
var innerVals: List<InnerVal>? = null
@ReadableBytes
var maxSize: Int = 0
var map: Map<String, Map<String, Value>> = mapOf()
class Value {
var property: Int = 0
var property2: Value2? = null
constructor()
constructor(property: Int, property2: Value2) {
this.property = property
this.property2 = property2
}
}
class Value2 {
var property: Int = 0
constructor()
constructor(property: Int) {
this.property = property
}
}
@ConfigurationProperties("inner")
class Inner {
var enabled = false
fun isEnabled() = enabled
}
}
class InnerVal {
var expireUnsignedSeconds: Int? = null
}
| 412 | 0.900311 | 1 | 0.900311 | game-dev | MEDIA | 0.249913 | game-dev | 0.709574 | 1 | 0.709574 |
panaversity/learn-modern-ai-python | 1,561 | 11_python_crash_course/python_crash_course_book_code_with_typing/solution_files/chapter_14/ex_14_5_high_score/ship.py | import pygame
from pygame.sprite import Sprite
class Ship(Sprite):
"""A class to manage the ship."""
def __init__(self, ai_game):
"""Initialize the ship and set its starting position."""
super().__init__()
self.screen = ai_game.screen
self.settings = ai_game.settings
self.screen_rect = ai_game.screen.get_rect()
# Load the ship image and get its rect.
self.image = pygame.image.load('images/ship.bmp')
self.rect = self.image.get_rect()
# Start each new ship at the bottom center of the screen.
self.rect.midbottom = self.screen_rect.midbottom
# Store a decimal value for the ship's horizontal position.
self.x = float(self.rect.x)
# Movement flags
self.moving_right = False
self.moving_left = False
def update(self):
"""Update the ship's position based on movement flags."""
# Update the ship's x value, not the rect.
if self.moving_right and self.rect.right < self.screen_rect.right:
self.x += self.settings.ship_speed
if self.moving_left and self.rect.left > 0:
self.x -= self.settings.ship_speed
# Update rect object from self.x.
self.rect.x = self.x
def blitme(self):
"""Draw the ship at its current location."""
self.screen.blit(self.image, self.rect)
def center_ship(self):
"""Center the ship on the screen."""
self.rect.midbottom = self.screen_rect.midbottom
self.x = float(self.rect.x)
| 412 | 0.573649 | 1 | 0.573649 | game-dev | MEDIA | 0.798973 | game-dev | 0.860243 | 1 | 0.860243 |
gkursi/Pulse-client | 1,920 | src/main/java/xyz/qweru/pulse/client/render/ui/gui/screens/ConfigScreen.java | package xyz.qweru.pulse.client.render.ui.gui.screens;
import xyz.qweru.pulse.client.PulseClient;
import xyz.qweru.pulse.client.managers.impl.ModuleManager;
import xyz.qweru.pulse.client.render.renderer.Pulse2D;
import xyz.qweru.pulse.client.render.ui.gui.PulseScreen;
import xyz.qweru.pulse.client.render.ui.gui.WidgetGroup;
import xyz.qweru.pulse.client.render.ui.gui.widgets.CategoryBackgroundWidget;
import xyz.qweru.pulse.client.render.ui.gui.widgets.CategoryTitleWidget;
import xyz.qweru.pulse.client.render.ui.gui.widgets.ModuleWidget;
import xyz.qweru.pulse.client.systems.modules.Category;
import xyz.qweru.pulse.client.systems.modules.ClientModule;
import java.util.List;
public class ConfigScreen extends PulseScreen {
public ConfigScreen() {
super("setting screen");
}
@Override
protected void init() {
super.init();
Category category = Category.SETTING;
List<ClientModule> modules = ModuleManager.INSTANCE.getModulesByCategory(category);
float cellW = 82;
float cellH = 13;
float totalH = cellH;
for (ClientModule ignored : modules) {
totalH += cellH;
}
float x = (width - cellW) / 2;
float y = (height - totalH) / 2;
WidgetGroup group = new WidgetGroup(true);
CategoryBackgroundWidget bw = new CategoryBackgroundWidget(x, y, cellW, cellH);
group.add(bw);
group.add(new CategoryTitleWidget(x, y, cellW, cellH, category));
y += cellH + Pulse2D.borderWidth;
for (ClientModule clientModule : modules) {
group.add(new ModuleWidget(x, y, cellW, cellH, clientModule));
y += cellH;
}
y += 1;
bw.resizeTo(y);
widgetList.add(group);
}
@Override
public void close() {
this.client.setScreen(PulseClient.INSTANCE.windowManager.getItemByClass(MainScreen.class));
}
}
| 412 | 0.765093 | 1 | 0.765093 | game-dev | MEDIA | 0.723196 | game-dev | 0.600418 | 1 | 0.600418 |
egordorichev/BurningKnight | 3,425 | BurningKnight/entity/creature/mob/desert/Maggot.cs | using System;
using BurningKnight.entity.component;
using BurningKnight.entity.creature.mob.prefabs;
using BurningKnight.entity.projectile;
using BurningKnight.state;
using BurningKnight.util;
using Lens.util;
using Lens.util.tween;
using Microsoft.Xna.Framework;
namespace BurningKnight.entity.creature.mob.desert {
public class Maggot : WallWalker {
private const float TargetDistance = 4f;
private const float Speed = 30f;
protected override void SetStats() {
base.SetStats();
AddComponent(new WallAnimationComponent("maggot"));
SetMaxHp(1);
Depth = Layers.Creature + 1;
}
#region Maggot States
public class IdleState : WallWalker.IdleState {
private bool stop;
public override void DoLogic(float dt) {
base.DoLogic(dt);
if (Self.Target == null) {
ResetVelocity();
return;
}
if (mx == 0) {
if (Math.Abs(Self.DxTo(Self.Target)) <= TargetDistance) {
ResetVelocity();
Become<FireState>();
return;
}
var left = Self.CenterX > Self.Target.CenterX;
if (Self.Left != left) {
InvertVelocity();
stop = false;
} else {
vx = Self.Left ? -1 : 1;
vy = 0;
}
} else {
if (Math.Abs(Self.DyTo(Self.Target)) <= TargetDistance) {
ResetVelocity();
Become<FireState>();
return;
}
var left = Self.CenterY > Self.Target.CenterY;
if (Self.Left != left) {
InvertVelocity();
stop = false;
} else {
vx = 0;
vy = Self.Left ? -1 : 1;
}
}
if (stop) {
vx = 0;
vy = 0;
}
velocity = new Vector2(vx * Speed, vy * Speed);
}
public override void Flip() {
ResetVelocity();
stop = true;
}
}
public class FireState : SmartState<Maggot> {
private bool shot;
public override void Init() {
base.Init();
Self.T = 0;
Self.GetComponent<RectBodyComponent>().Velocity = Vector2.Zero;
Self.GetComponent<WallAnimationComponent>().SetAutoStop(true);
}
public override void Destroy() {
base.Destroy();
Self.GetComponent<WallAnimationComponent>().SetAutoStop(false);
}
public override void Update(float dt) {
base.Update(dt);
if (!shot && Self.GetComponent<WallAnimationComponent>().Animation.Paused) {
if (Self.Target == null) {
Become<IdleState>();
return;
}
shot = true;
var a = Self.GetComponent<WallAnimationComponent>();
Self.GetComponent<AudioEmitterComponent>().EmitRandomized("mob_fire_wall");
var angle = Self.Direction.ToAngle();
var builder = new ProjectileBuilder(Self, "small") {
LightRadius = 30
};
if (Run.Depth > 4 || Run.Loop > 0) {
builder.RemoveFlags(ProjectileFlags.Reflectable, ProjectileFlags.BreakableByMelee);
builder.Scale *= 1.5f;
}
builder.AddFlags(ProjectileFlags.FlyOverStones);
var projectile = builder.Shoot(angle, 5f).Build();
projectile.Center += MathUtils.CreateVector(angle, 4);
a.Scale.X = 1.8f;
a.Scale.Y = 0.2f;
Tween.To(1, a.Scale.X, x => a.Scale.X = x, 0.4f);
Tween.To(1, a.Scale.Y, x => a.Scale.Y = x, 0.4f).OnEnd = () => { Become<IdleState>(); };
}
}
}
#endregion
protected override Type GetIdleState() {
return typeof(IdleState);
}
public override void Update(float dt) {
base.Update(dt);
T += dt;
}
}
} | 412 | 0.894594 | 1 | 0.894594 | game-dev | MEDIA | 0.994397 | game-dev | 0.987446 | 1 | 0.987446 |
TheSnidr/SMF-Open-Source | 20,025 | scripts/rig_load_fbx/rig_load_fbx.gml | /// @description rig_load_fbx(fname)
/// @param fname
function rig_load_fbx() {
/*
Loads an .fbx model into SMF
*/
/*
var fname, meshNum, i, vertNum, vertPosBuff, triNum, triVertIndices, norBuff, uvBuff, vertInd, vx, vy, vz, nx, ny, nz, u, v;
fname = argument0;
var meshNum = ImportModelAndSplitMeshes(fname);
if meshNum <= 0{show_debug_message("Failed to load model " + string(fname)); exit;}
show_debug_message("Loading FBX file " + string(fname) + " into SMF");
/*
Load the nodes from the FBX
Nodes may already have been transformed, and as such, they can not be used directly to create the bind pose.
Each node stores its position and rotation within the parent node, meaning they have to be hierarchichally
multiplied together to create the world orientation
*/
/*
fbxNodeNum = GetNumNodes();
nodeBuff = buffer_create(80 * fbxNodeNum, buffer_grow, 8);
GetNodes(buffer_get_address(nodeBuff));
averageBoneLength = 0;
for (var i = 0; i < fbxNodeNum; i ++)
{
//The index of this node's parent
fbxNodeParent[i] = buffer_read(nodeBuff, buffer_f64);
//Translation
tx = buffer_read(nodeBuff, buffer_f64);
ty = buffer_read(nodeBuff, buffer_f64);
tz = buffer_read(nodeBuff, buffer_f64);
//Rotation
rx = buffer_read(nodeBuff, buffer_f64);
ry = buffer_read(nodeBuff, buffer_f64);
rz = buffer_read(nodeBuff, buffer_f64);
//Scaling
sx = buffer_read(nodeBuff, buffer_f64);
sy = buffer_read(nodeBuff, buffer_f64);
sz = buffer_read(nodeBuff, buffer_f64);
fbxNodeT[i] = [tx, ty, tz];
fbxNodeR[i] = [rx, ry, rz];
fbxNodeS[i] = [sx, sy, sz];
fbxNodeLength[i] = point_distance_3d(0, 0, 0, tx / sx, ty / sy, tz / sz);
averageBoneLength += fbxNodeLength[i];
fbxNodeChildren[i] = -1;
fbxNodeChildNum[i] = 0;
if fbxNodeParent[i] >= 0{
fbxNodeChildren[fbxNodeParent[i], fbxNodeChildNum[fbxNodeParent[i]]++] = i;}
}
buffer_delete(nodeBuff);
averageBoneLength /= fbxNodeNum;
//Append all leaf bones
for (var i = 0; i < fbxNodeNum; i ++)
{
if fbxNodeChildNum[i] > 0{continue;}
fbxNodeInd = array_length(fbxNodeLength);
fbxNodeChildren[i, fbxNodeChildNum[i]++] = fbxNodeInd;
fbxNodeParent[fbxNodeInd] = i;
fbxNodeLength[fbxNodeInd] = fbxNodeLength[i];
fbxNodeChildren[fbxNodeInd] = -1;
fbxNodeChildNum[fbxNodeInd] = 0;
fbxNodeT[fbxNodeInd] = [fbxNodeLength[i], 0, 0];
fbxNodeR[fbxNodeInd] = [0, 0, 0];
fbxNodeS[fbxNodeInd] = [1, 1, 1];
}
//Lists used for indexing bones
boneMatList = ds_list_create();
boneIndList = ds_list_create();
boneMap = ds_map_create();
boneWeightPriority = ds_priority_create();
for (var i = 0; i < meshNum; i ++)
{
//Get number of vertices and their positions
vertNum = GetMeshNumVertices(i);
vertPosBuff = buffer_create(vertNum * 24, buffer_grow, 8);
GetMeshVertexPositions(i, buffer_get_address(vertPosBuff));
//Get number of triangles and their vertex indices
triNum = GetMeshNumTriangles(i);
triVertIndices = buffer_create(triNum * 12, buffer_grow, 4);
GetMeshTriangleVertexIndices(i, buffer_get_address(triVertIndices));
//Get number of normals and their vectors
norNum = GetMeshTriangleNormalsSize(i);
norPerVert = norNum / triNum / 9;
norBuff = buffer_create(max(1, norNum) * 8, buffer_grow, 8);
GetMeshTriangleNormals(i, buffer_get_address(norBuff));
//Get UVs
uvNum = GetMeshTriangleUVsSize(i);
uvPerVert = uvNum / triNum / 6;
uvBuff = buffer_create(max(1, uvNum) * 8, buffer_grow, 8);
GetMeshTriangleUVs(i, buffer_get_address(uvBuff));
//Create a buffer for bone indices and weights
bonePerVertBuff = buffer_create(vertNum * 8 * 4, buffer_grow, 4); //Four indices + four weights per vert, buffer_f32
/*
Load the skins of this mesh
A skin is basically the part of the rig that affects this mesh. Usually, each skin stores the entire rig
*/
/*
skinNum = GetMeshNumSkins(i);
for (var j = 0; j < skinNum; j ++)
{
for (var n = 0; n < fbxNodeNum; n ++){ //Reset the child counter
fbxNodeChildCounter[n] = 0;}
//Load the bones of this skin
boneNum = GetMeshSkinNumBones(i, j);
boneBuff = buffer_create(boneNum * 88, buffer_grow, 8);
GetMeshSkinBoneData(i, j, buffer_get_address(boneBuff));
for (var k = 0; k < boneNum; k ++)
{
//The index of the parent node of this bone
parentNode = buffer_read(boneBuff, buffer_f64);
//The number of vertices affected by this bone
boneVertNum = buffer_read(boneBuff, buffer_f64);
//Translation of this bone in world space
tx = buffer_read(boneBuff, buffer_f64);
ty = buffer_read(boneBuff, buffer_f64);
tz = buffer_read(boneBuff, buffer_f64);
//Rotation of this bone in world space
rx = buffer_read(boneBuff, buffer_f64);
ry = buffer_read(boneBuff, buffer_f64);
rz = buffer_read(boneBuff, buffer_f64);
//Scaling of this bone in world space
sx = buffer_read(boneBuff, buffer_f64);
sy = buffer_read(boneBuff, buffer_f64);
sz = buffer_read(boneBuff, buffer_f64);
//Create the bone's world matrix. Note that this is tail-oriented, meaning it omits the end bones. SMF is head-oriented, so it needs to be converted later
boneMat = matrix_multiply(matrix_build(ty / sy, tx / sx, tz / sz, ry, rx, rz, 1, 1, 1), matrix_build(0, 0, 0, 0, 90, -90, 1, 1, 1));
//Find the index of the node of this bone
fbxNodeIndex = -1;
if fbxNodeChildCounter[parentNode] < fbxNodeChildNum[parentNode]{
fbxNodeIndex = fbxNodeChildren[parentNode, fbxNodeChildCounter[parentNode]++];}
boneIndex = ds_list_find_index(boneIndList, fbxNodeIndex)
//If this bone hasn't been added before
if boneIndex < 0
{
boneIndex = ds_grid_height(RigBoneGrid);
boneParent[boneIndex] = ds_list_find_index(boneIndList, parentNode);
ds_grid_resize(RigBoneGrid, BoneGridValues, boneIndex + 1);
//Loop through all bones and see if a bone has been added at this position before
delta = fbxNodeLength[fbxNodeIndex] / 1000;
var A = boneIndex;
while A--{
testMat = boneMatList[| A];
if abs(boneMat[SMF_X] - testMat[SMF_X]) > delta or abs(boneMat[SMF_Y] - testMat[SMF_Y]) > delta or abs(boneMat[SMF_Z] - testMat[SMF_Z]) > delta{
continue;}
if boneParent[boneIndex] < 0{boneParent[boneIndex] = A;}
break;}
//If this detached bone has not been added before
if A < 0
{
grandParent = ds_list_find_index(boneIndList, fbxNodeParent[parentNode]);
parentMat = boneMatList[| max(0, grandParent)];
if !is_array(parentMat){parentMat = matrix_build_identity();}
//The grandparent is the tip of the "parent bone"
//Now we're comparing the bone to its grandparent. If they do not equal, create an additional detached bone.
if grandParent < 0 or abs(boneMat[SMF_X] - parentMat[SMF_X]) > delta or abs(boneMat[SMF_Y] - parentMat[SMF_Y]) > delta or abs(boneMat[SMF_Z] - parentMat[SMF_Z]) > delta
{
boneParent[boneIndex] = max(0, grandParent+1);
//Create the bone's orientation from the relation between the node's orientation and its parent
RigBoneGrid[# BoneDQ, boneIndex] = dq_create(0, 0, 0, 0, boneMat[SMF_X], boneMat[SMF_Y], boneMat[SMF_Z]);
RigBoneGrid[# BoneAttach, boneIndex] = false; //Detached
RigBoneGrid[# BoneParent, boneIndex] = boneParent[boneIndex];
boneIndList[| boneIndex] = parentNode;
boneMatList[| boneIndex] = array_create(16);
array_copy(boneMatList[| boneIndex], 0, boneMat, 0, 16);
boneIndex ++;
boneParent[boneIndex] = max(boneIndex - 1, 0);
ds_grid_resize(RigBoneGrid, BoneGridValues, boneIndex + 1);
}
}
//The bind pose puts each bone at the position of the parent and pointing at the child
//SMF puts the bone at the child's position. This piece of code makes sure the bone ends up at the right position
boneMat[SMF_X] += fbxNodeLength[fbxNodeIndex] * boneMat[SMF_XTO];
boneMat[SMF_Y] += fbxNodeLength[fbxNodeIndex] * boneMat[SMF_YTO];
boneMat[SMF_Z] += fbxNodeLength[fbxNodeIndex] * boneMat[SMF_ZTO];
boneIndList[| boneIndex] = fbxNodeIndex;
boneMatList[| boneIndex] = array_create(16);
array_copy(boneMatList[| boneIndex], 0, boneMat, 0, 16);
RigBoneGrid[# BoneDQ, boneIndex] = dq_create_from_matrix(boneMat);
RigBoneGrid[# BoneParent, boneIndex] = boneParent[boneIndex];
RigBoneGrid[# BoneAttach, boneIndex] = true;
RigBoneGrid[# BoneLength, boneIndex] = fbxNodeLength[fbxNodeIndex];
}
//Apply the bone indices and weights to the affected vertices
if boneVertNum > 0
{
boneVerts = buffer_create(boneVertNum * 16, buffer_grow, 8);
GetMeshSkinBoneVertexData(i, j, k, buffer_get_address(boneVerts));
for (var h = 0; h < boneVertNum; h ++)
{
vert = buffer_read(boneVerts, buffer_f64);
weight = buffer_read(boneVerts, buffer_f64);
var sum = 0;
var text = "";
ds_priority_clear(boneWeightPriority);
ds_priority_add(boneWeightPriority, boneIndex, weight);
buffer_seek(bonePerVertBuff, buffer_seek_start, vert * 8 * 4);
for (var l = 0; l < 4; l ++){
boneInd[l] = buffer_read(bonePerVertBuff, buffer_f32);}
for (var l = 0; l < 4; l ++){
boneWth[l] = buffer_read(bonePerVertBuff, buffer_f32);
ds_priority_add(boneWeightPriority, boneInd[l], boneWth[l]);}
for (var l = 0; l < 4; l ++){
boneWth[l] = ds_priority_find_priority(boneWeightPriority, ds_priority_find_max(boneWeightPriority));
boneInd[l] = ds_priority_delete_max(boneWeightPriority);}
buffer_seek(bonePerVertBuff, buffer_seek_start, vert * 8 * 4);
for (var l = 0; l < 4; l ++){
buffer_write(bonePerVertBuff, buffer_f32, boneInd[l]);}
for (var l = 0; l < 4; l ++){
buffer_write(bonePerVertBuff, buffer_f32, boneWth[l]);}
}
buffer_delete(boneVerts);
}
}
buffer_delete(boneBuff);
}
/*
Generate a buffer that will later be converted to vertex buffer
*/
/*
mBuff[i] = buffer_create(triNum * 3 * SMF_format_bytes, buffer_fixed, 1);
repeat triNum * 3
{
vertInd = buffer_read(triVertIndices, buffer_s32);
buffer_seek(vertPosBuff, buffer_seek_start, vertInd * 24);
buffer_seek(bonePerVertBuff, buffer_seek_start, vertInd * 8 * 4);
vx = buffer_read(vertPosBuff, buffer_f64);
vy = buffer_read(vertPosBuff, buffer_f64);
vz = buffer_read(vertPosBuff, buffer_f64);
nx = 0; ny = 0; nz = 0;
u = 0; v = 0;
if norPerVert >= 1{
nx = buffer_read(norBuff, buffer_f64);
ny = buffer_read(norBuff, buffer_f64);
nz = buffer_read(norBuff, buffer_f64);
repeat (norPerVert - 1) * 3{
buffer_read(norBuff, buffer_f64);}}
if uvPerVert >= 1{
u = buffer_read(uvBuff, buffer_f64);
v = 1 - buffer_read(uvBuff, buffer_f64);
repeat (uvPerVert - 1) * 2{
buffer_read(uvBuff, buffer_f64);}}
buffer_write(mBuff[i], buffer_f32, -vx);
buffer_write(mBuff[i], buffer_f32, vy);
buffer_write(mBuff[i], buffer_f32, vz);
buffer_write(mBuff[i], buffer_f32, -nx);
buffer_write(mBuff[i], buffer_f32, ny);
buffer_write(mBuff[i], buffer_f32, nz);
buffer_write(mBuff[i], buffer_f32, u);
buffer_write(mBuff[i], buffer_f32, v);
repeat 4{buffer_write(mBuff[i], buffer_u8, 255);}
repeat 4{
b = 0;
if ds_list_size(RigBindPose) > 0{
b = RigBindPoseMappingList[| buffer_read(bonePerVertBuff, buffer_f32)];}
buffer_write(mBuff[i], buffer_u8, b);}
var sum = 0;
for (var j = 0; j < 4; j ++){
wth[j] = buffer_read(bonePerVertBuff, buffer_f32);
sum += wth[j];}
if sum == 0{wth[0] = 1; sum = 1}
wth = [1, 0, 0, 0]; sum = 1;
for (var j = 0; j < 4; j ++){buffer_write(mBuff[i], buffer_u8, 255 * wth[j] / sum);}
}
buffer_delete(vertPosBuff);
buffer_delete(triVertIndices);
buffer_delete(norBuff);
buffer_delete(uvBuff);
buffer_delete(bonePerVertBuff);
}
//rig_create_sample_static();
//rig_update_skeleton();
/*
Load animations
*/
/*
var animNum = GetNumAnims();
for (var i = 0; i < animNum; i ++)
{
var timelineMap = ds_map_create();
var numCurves = GetAnimNumCurves(i);
totalTime = 0;
//Index the "animation curves" by their time stamps
for (var j = 0; j < numCurves; j ++)
{
localFrame = ds_list_create();
var numKeyframes = GetAnimCurveNumKeyframes(i, j);
var keyframeBuff = buffer_create((2 + 4 * numKeyframes) * 8, buffer_grow, 8);
GetAnimCurveData(i, j, buffer_get_address(keyframeBuff));
nodeIndex = buffer_read(keyframeBuff, buffer_f64);
curveType = buffer_read(keyframeBuff, buffer_f64) - 1; //1 = translation, 2 = rotation, 3 = scaling
for (var k = 0; k < numKeyframes; k ++)
{
time = buffer_read(keyframeBuff, buffer_f64);
totalTime = max(totalTime, time);
_x = buffer_read(keyframeBuff, buffer_f64);
_y = buffer_read(keyframeBuff, buffer_f64);
_z = buffer_read(keyframeBuff, buffer_f64);
var transformBoneGrid = timelineMap[? time];
if is_undefined(transformBoneGrid){
transformBoneGrid = ds_grid_create(fbxNodeNum, 3);
timelineMap[? time] = transformBoneGrid;}
transformBoneGrid[# nodeIndex, curveType] = [_x, _y, _z];
}
buffer_delete(keyframeBuff)
}
AnimName[i] = GetAnimName(i);
var boneList = ds_list_create();
var timeList = ds_list_create();
AnimKeyframeBones[i] = boneList; //Bonelist stores a list of the transformations for each bone
AnimKeyframeTime[i] = timeList; //Timelist stores the time of the given keyframe
//Sort the frames into a list
var frameList = ds_list_create();
while ds_map_size(timelineMap){
//Find the timestamp of this frame
var keyframeTime = ds_map_find_first(timelineMap);
var time = 9999999;
while !is_undefined(keyframeTime){
time = min(keyframeTime, time);
keyframeTime = ds_map_find_next(timelineMap, keyframeTime);}
ds_list_add(timeList, time / totalTime);
ds_list_add(frameList, timelineMap[? time]);
ds_map_delete(timelineMap, time);}
var keyframeNum = ds_list_size(frameList);
for (var j = 0; j < keyframeNum; j ++)
{
transformBoneGrid = frameList[| j];
time = timeList[| j];
var localFrame = ds_list_create();
boneList[| j] = localFrame;
for (var n = 0; n < fbxNodeNum; n ++)
{
var keyframeT = transformBoneGrid[# n, 0];
var keyframeR = transformBoneGrid[# n, 1];
var keyframeS = transformBoneGrid[# n, 2];
if !is_array(keyframeT){ //If this bone does not have a curve in this keyframe, look for the nearest keyframe both backwards and forwards in time, and interpolate between them
prevKeyframeT = -1;
nextKeyframeT = -1;
keyframeT = fbxNodeT[n];
//Check backwards in time
for (var k = j-1; k >= 0; k --){
prevTime = timeList[| k];
prevTransformBoneGrid = frameList[| k];
prevKeyframeT = prevTransformBoneGrid[# n, 0];
if is_array(prevKeyframeT){keyframeT = prevKeyframeT; break;}}
//Check forwards in time
for (var k = j+1; k < keyframeNum; k ++){
nextTime = timeList[| k];
nextTransformBoneGrid = frameList[| k];
nextKeyframeT = nextTransformBoneGrid[# n, 0];
if is_array(nextKeyframeT){keyframeT = array_lerp(fbxNodeT[n], nextKeyframeT, time / nextTime); break;}}
//Compare the two, and if both exist, interpolate between them
if is_array(prevKeyframeT) and is_array(nextKeyframeT){
dt = nextTime - prevTime;
amount = 0;
if dt > 0{
amount = (time - nextTime) / dt;}
keyframeT = array_lerp(prevKeyframeT, nextKeyframeT, amount);}
else {keyframeT = fbxNodeT[n];}}
if !is_array(keyframeR){ //If this bone does not have a curve in this keyframe, look for the nearest keyframe both backwards and forwards in time, and interpolate between them
prevKeyframeR = -1;
nextKeyframeR = -1;
keyframeR = fbxNodeR[n];
//Check backwards in time
for (var k = j-1; k >= 0; k --){
prevTime = timeList[| k];
prevTransformBoneGrid = frameList[| k];
prevKeyframeR = prevTransformBoneGrid[# n, 1];
if is_array(prevKeyframeT){keyframeR = prevKeyframeR; break;}}
//Check forwards in time
for (var k = j+1; k < keyframeNum; k ++){
nextTime = timeList[| k];
nextTransformBoneGrid = frameList[| k];
nextKeyframeR = nextTransformBoneGrid[# n, 1];
if is_array(nextKeyframeR){keyframeR = array_lerp(fbxNodeR[n], nextKeyframeR, time / nextTime); break;}}
//Compare the two, and if both exist, interpolate between them
if is_array(prevKeyframeR) and is_array(nextKeyframeR){
dt = nextTime - prevTime;
amount = 0;
if dt > 0{
amount = (time - nextTime) / dt;}
keyframeR = array_lerp(prevKeyframeR, nextKeyframeR, amount);}}
keyframeNodeLocalMat[n] = matrix_build(keyframeT[1], keyframeT[0], keyframeT[2], keyframeR[1], keyframeR[0], keyframeR[2], 1, 1, 1);
if fbxNodeParent[n] >= 0{
keyframeNodeWorldMat[n] = matrix_multiply(keyframeNodeLocalMat[n], keyframeNodeWorldMat[fbxNodeParent[n]]);}
else{
keyframeNodeWorldMat[n] = keyframeNodeLocalMat[n];}
keyframeNodeWorldDQ[n] = dq_create_from_matrix(matrix_multiply(keyframeNodeWorldMat[n], matrix_build(0, 0, 0, 0, 90, -90, 1, 1, 1)));
if i == 0
{
TESTANIMATIONMATARRAY[j, n] = keyframeNodeWorldMat[n];
}
}
//Now I've constructed the world positions of all the bones in the keyframe. These are stored in keyframeNodeWorldMat.
//Compare these to the bindpose, and trace back to the delta local dual quat
//Start by generating a sample for the entire skeleton
for (var n = 0; n < ds_grid_height(RigBoneGrid); n ++)
{
var smfNodeInd = n;
var fbxNodeInd = boneIndList[| smfNodeInd];
boneBindDQ = RigBoneGrid[# BoneDQ, smfNodeInd];
var fbxParentNode = fbxNodeParent[fbxNodeInd];
boneWorldMat = keyframeNodeWorldMat[fbxParentNode];
boneWorldMat[SMF_X] += boneWorldMat[SMF_XTO] * fbxNodeLength[fbxNodeInd];
boneWorldMat[SMF_Y] += boneWorldMat[SMF_YTO] * fbxNodeLength[fbxNodeInd];
boneWorldMat[SMF_Z] += boneWorldMat[SMF_ZTO] * fbxNodeLength[fbxNodeInd];
boneWorldDQ = dq_create_from_matrix(boneWorldMat);
//This is the sample for the entire smf node hierarchy
deltaWorldDQ[smfNodeInd] = dq_multiply(boneWorldDQ, dq_get_conjugate(boneBindDQ));
}
//Then figure out the local changes in orientation
for (var n = 0; n < ds_grid_height(RigBoneGrid); n ++)
{
var smfNodeInd = n;
var smfNodeParent = RigBoneGrid[# BoneParent, smfNodeInd];
var smfNodeWorldDQ = dq_multiply(deltaWorldDQ[smfNodeInd], RigBoneGrid[# BoneDQ, smfNodeInd]);
var smfParentWorldDQ = dq_multiply(deltaWorldDQ[smfNodeParent], RigBoneGrid[# BoneDQ, smfNodeParent]);
var keyframeLocalDQ = dq_multiply(dq_get_conjugate(smfParentWorldDQ), smfNodeWorldDQ);
var bindLocalDQ = dq_multiply(dq_get_conjugate(RigBoneGrid[# BoneDQ, smfNodeParent]), RigBoneGrid[# BoneDQ, smfNodeInd]);
var Q = dq_normalize(dq_multiply(dq_get_conjugate(bindLocalDQ), keyframeLocalDQ));
localFrame[| n] = Q;
}
}
ds_map_destroy(timelineMap);
}
for (var i = 0; i < meshNum; i ++)
{
modelBufferList[i] = mBuff[i];
animationModelList[i] = vertex_create_buffer_from_buffer(mBuff[i], SMF_format);
modelVisible[i] = true;
RigVertsPerPointList[i] = ds_list_create();
RigFaceList[i] = ds_list_create();
skinSelectionList[i] = ds_list_create();
RigNormalMapFactor[i] = 0.5;
RigHeightMapDepth[i] = 0;
editorNormalIndex[i] = "NomDefault";
editorTextureIndex[i] = "TexDefault";
editorMaterialIndex[i] = "Default material";
if GetMeshNumMaterials(i) > 0
{
if GetMeshMaterialNumTextures(i, 0) > 0
{
fname = filename_name(GetMeshMaterialTextureFilename(i, 0, 0));
editorTextureIndex[i] = fname;
if is_undefined(editorTextureMap[? fname]){
editorTextureMap[? fname] = sprite_duplicate(editorTextureMap[? "TexDefault"]);}
}
}
}
smf_model_flip_triangles(edtModelIndex);
/* end rig_load_fbx */
}
| 412 | 0.913008 | 1 | 0.913008 | game-dev | MEDIA | 0.403319 | game-dev | 0.866567 | 1 | 0.866567 |
wolfetplayer/RealRTCW | 59,663 | sdk/rtcw-bspc-custom/src/botai/ai_dmnet.c | /*
===========================================================================
Return to Castle Wolfenstein single player GPL Source Code
Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company.
This file is part of the Return to Castle Wolfenstein single player GPL Source Code (RTCW SP Source Code).
RTCW SP Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
RTCW SP Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with RTCW SP Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the RTCW SP Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the RTCW SP Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
/*****************************************************************************
* name: ai_dmnet.c
*
* desc: Quake3 bot AI
*
*
*****************************************************************************/
#include "../game/g_local.h"
#include "../game/botlib.h"
#include "../game/be_aas.h"
#include "../game/be_ea.h"
#include "../game/be_ai_char.h"
#include "../game/be_ai_chat.h"
#include "../game/be_ai_gen.h"
#include "../game/be_ai_goal.h"
#include "../game/be_ai_move.h"
#include "../game/be_ai_weap.h"
#include "../botai/botai.h"
//
#include "ai_main.h"
#include "ai_dmq3.h"
#include "ai_chat.h"
#include "ai_cmd.h"
#include "ai_dmnet.h"
//data file headers
#include "chars.h" //characteristics
#include "inv.h" //indexes into the inventory
#include "syn.h" //synonyms
#include "match.h" //string matching types and vars
//goal flag, see be_ai_goal.h for the other GFL_*
#define GFL_AIR 16
int numnodeswitches;
char nodeswitch[MAX_NODESWITCHES + 1][144];
#define LOOKAHEAD_DISTANCE 300
/*
==================
BotResetNodeSwitches
==================
*/
void BotResetNodeSwitches( void ) {
numnodeswitches = 0;
}
/*
==================
BotDumpNodeSwitches
==================
*/
void BotDumpNodeSwitches( bot_state_t *bs ) {
int i;
char netname[MAX_NETNAME];
ClientName( bs->client, netname, sizeof( netname ) );
BotAI_Print( PRT_MESSAGE, "%s at %1.1f switched more than %d AI nodes\n", netname, trap_AAS_Time(), MAX_NODESWITCHES );
for ( i = 0; i < numnodeswitches; i++ ) {
BotAI_Print( PRT_MESSAGE, nodeswitch[i] );
}
BotAI_Print( PRT_FATAL, "" );
}
/*
==================
BotRecordNodeSwitch
==================
*/
void BotRecordNodeSwitch( bot_state_t *bs, char *node, char *str ) {
char netname[MAX_NETNAME];
ClientName( bs->client, netname, sizeof( netname ) );
Com_sprintf( nodeswitch[numnodeswitches], 144, "%s at %2.1f entered %s: %s\n", netname, trap_AAS_Time(), node, str );
#ifdef DEBUG
if ( 0 ) {
BotAI_Print( PRT_MESSAGE, nodeswitch[numnodeswitches] );
}
#endif //DEBUG
numnodeswitches++;
}
/*
==================
BotGetAirGoal
==================
*/
int BotGetAirGoal( bot_state_t *bs, bot_goal_t *goal ) {
bsp_trace_t bsptrace;
vec3_t end, mins = {-15, -15, -2}, maxs = {15, 15, 2};
int areanum;
//trace up until we hit solid
VectorCopy( bs->origin, end );
end[2] += 1000;
BotAI_Trace( &bsptrace, bs->origin, mins, maxs, end, bs->entitynum, CONTENTS_SOLID | CONTENTS_PLAYERCLIP );
//trace down until we hit water
VectorCopy( bsptrace.endpos, end );
BotAI_Trace( &bsptrace, end, mins, maxs, bs->origin, bs->entitynum, CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA );
//if we found the water surface
if ( bsptrace.fraction > 0 ) {
areanum = BotPointAreaNum( bsptrace.endpos );
if ( areanum ) {
VectorCopy( bsptrace.endpos, goal->origin );
goal->origin[2] -= 2;
goal->areanum = areanum;
goal->mins[0] = -15;
goal->mins[1] = -15;
goal->mins[2] = -1;
goal->maxs[0] = 15;
goal->maxs[1] = 15;
goal->maxs[2] = 1;
goal->flags = GFL_AIR;
goal->number = 0;
goal->iteminfo = 0;
goal->entitynum = 0;
return qtrue;
}
}
return qfalse;
}
/*
==================
BotGoForAir
==================
*/
int BotGoForAir( bot_state_t *bs, int tfl, bot_goal_t *ltg, float range ) {
bot_goal_t goal;
//if the bot needs air
if ( bs->lastair_time < trap_AAS_Time() - 6 ) {
//
#ifdef DEBUG
//BotAI_Print(PRT_MESSAGE, "going for air\n");
#endif //DEBUG
//if we can find an air goal
if ( BotGetAirGoal( bs, &goal ) ) {
trap_BotPushGoal( bs->gs, &goal );
return qtrue;
} else {
//get a nearby goal outside the water
while ( trap_BotChooseNBGItem( bs->gs, bs->origin, bs->inventory, tfl, ltg, range ) ) {
trap_BotGetTopGoal( bs->gs, &goal );
//if the goal is not in water
if ( !( trap_AAS_PointContents( goal.origin ) & ( CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA ) ) ) {
return qtrue;
}
trap_BotPopGoal( bs->gs );
}
trap_BotResetAvoidGoals( bs->gs );
}
}
return qfalse;
}
/*
==================
BotNearbyGoal
==================
*/
int BotNearbyGoal( bot_state_t *bs, int tfl, bot_goal_t *ltg, float range ) {
int ret;
if ( BotGoForAir( bs, tfl, ltg, range ) ) {
return qtrue;
}
//
ret = trap_BotChooseNBGItem( bs->gs, bs->origin, bs->inventory, tfl, ltg, range );
/*
if (ret)
{
char buf[128];
//get the goal at the top of the stack
trap_BotGetTopGoal(bs->gs, &goal);
trap_BotGoalName(goal.number, buf, sizeof(buf));
BotAI_Print(PRT_MESSAGE, "%1.1f: new nearby goal %s\n", trap_AAS_Time(), buf);
}
*/
return ret;
}
/*
==================
BotReachedGoal
==================
*/
int BotReachedGoal( bot_state_t *bs, bot_goal_t *goal ) {
if ( goal->flags & GFL_ITEM ) {
//if touching the goal
if ( trap_BotTouchingGoal( bs->origin, goal ) ) {
return qtrue;
}
//if the goal isn't there
if ( trap_BotItemGoalInVisButNotVisible( bs->entitynum, bs->eye, bs->viewangles, goal ) ) {
return qtrue;
}
//if in the goal area and below or above the goal and not swimming
if ( bs->areanum == goal->areanum ) {
if ( bs->origin[0] > goal->origin[0] + goal->mins[0] && bs->origin[0] < goal->origin[0] + goal->maxs[0] ) {
if ( bs->origin[1] > goal->origin[1] + goal->mins[1] && bs->origin[1] < goal->origin[1] + goal->maxs[1] ) {
if ( !trap_AAS_Swimming( bs->origin ) ) {
return qtrue;
}
}
}
}
} else if ( goal->flags & GFL_AIR ) {
//if touching the goal
if ( trap_BotTouchingGoal( bs->origin, goal ) ) {
return qtrue;
}
//if the bot got air
if ( bs->lastair_time > trap_AAS_Time() - 1 ) {
return qtrue;
}
} else {
//if touching the goal
if ( trap_BotTouchingGoal( bs->origin, goal ) ) {
return qtrue;
}
}
return qfalse;
}
/*
==================
BotGetItemLongTermGoal
==================
*/
int BotGetItemLongTermGoal( bot_state_t *bs, int tfl, bot_goal_t *goal ) {
//if the bot has no goal
if ( !trap_BotGetTopGoal( bs->gs, goal ) ) {
//BotAI_Print(PRT_MESSAGE, "no ltg on stack\n");
bs->ltg_time = 0;
}
//if the bot touches the current goal
else if ( BotReachedGoal( bs, goal ) ) {
BotChooseWeapon( bs );
bs->ltg_time = 0;
}
//if it is time to find a new long term goal
if ( bs->ltg_time < trap_AAS_Time() ) {
//pop the current goal from the stack
trap_BotPopGoal( bs->gs );
//BotAI_Print(PRT_MESSAGE, "%s: choosing new ltg\n", ClientName(bs->client, netname, sizeof(netname)));
//choose a new goal
//BotAI_Print(PRT_MESSAGE, "%6.1f client %d: BotChooseLTGItem\n", trap_AAS_Time(), bs->client);
if ( trap_BotChooseLTGItem( bs->gs, bs->origin, bs->inventory, tfl ) ) {
/*
char buf[128];
//get the goal at the top of the stack
trap_BotGetTopGoal(bs->gs, goal);
trap_BotGoalName(goal->number, buf, sizeof(buf));
BotAI_Print(PRT_MESSAGE, "%1.1f: new long term goal %s\n", trap_AAS_Time(), buf);
*/
bs->ltg_time = trap_AAS_Time() + 20;
} else { //the bot gets sorta stuck with all the avoid timings, shouldn't happen though
//
#ifdef DEBUG
char netname[128];
BotAI_Print( PRT_MESSAGE, "%s: no valid ltg (probably stuck)\n", ClientName( bs->client, netname, sizeof( netname ) ) );
#endif
//trap_BotDumpAvoidGoals(bs->gs);
//reset the avoid goals and the avoid reach
trap_BotResetAvoidGoals( bs->gs );
trap_BotResetAvoidReach( bs->ms );
}
//get the goal at the top of the stack
return trap_BotGetTopGoal( bs->gs, goal );
}
return qtrue;
}
/*
==================
BotGetLongTermGoal
we could also create a seperate AI node for every long term goal type
however this saves us a lot of code
==================
*/
int BotGetLongTermGoal( bot_state_t *bs, int tfl, int retreat, bot_goal_t *goal ) {
vec3_t target, dir;
char netname[MAX_NETNAME];
char buf[MAX_MESSAGE_SIZE];
int areanum;
float croucher;
aas_entityinfo_t entinfo;
bot_waypoint_t *wp;
if ( bs->ltgtype == LTG_TEAMHELP && !retreat ) {
//check for bot typing status message
if ( bs->teammessage_time && bs->teammessage_time < trap_AAS_Time() ) {
BotAI_BotInitialChat( bs, "help_start", EasyClientName( bs->teammate, netname, sizeof( netname ) ), NULL );
trap_BotEnterChat( bs->cs, bs->client, CHAT_TEAM );
bs->teammessage_time = 0;
}
//if trying to help the team mate for more than a minute
if ( bs->teamgoal_time < trap_AAS_Time() ) {
bs->ltgtype = 0;
}
//if the team mate IS visible for quite some time
if ( bs->teammatevisible_time < trap_AAS_Time() - 10 ) {
bs->ltgtype = 0;
}
//get entity information of the companion
BotEntityInfo( bs->teammate, &entinfo );
//if the team mate is visible
if ( BotEntityVisible( bs->entitynum, bs->eye, bs->viewangles, 360, bs->teammate ) ) {
//if close just stand still there
VectorSubtract( entinfo.origin, bs->origin, dir );
if ( VectorLength( dir ) < 100 ) {
trap_BotResetAvoidReach( bs->ms );
return qfalse;
}
} else {
//last time the bot was NOT visible
bs->teammatevisible_time = trap_AAS_Time();
}
//if the entity information is valid (entity in PVS)
if ( entinfo.valid ) {
areanum = BotPointAreaNum( entinfo.origin );
if ( areanum && trap_AAS_AreaReachability( areanum ) ) {
//update team goal
bs->teamgoal.entitynum = bs->teammate;
bs->teamgoal.areanum = areanum;
VectorCopy( entinfo.origin, bs->teamgoal.origin );
VectorSet( bs->teamgoal.mins, -8, -8, -8 );
VectorSet( bs->teamgoal.maxs, 8, 8, 8 );
}
}
memcpy( goal, &bs->teamgoal, sizeof( bot_goal_t ) );
return qtrue;
}
//if the bot accompanies someone
if ( bs->ltgtype == LTG_TEAMACCOMPANY && !retreat ) {
//check for bot typing status message
if ( bs->teammessage_time && bs->teammessage_time < trap_AAS_Time() ) {
BotAI_BotInitialChat( bs, "accompany_start", EasyClientName( bs->teammate, netname, sizeof( netname ) ), NULL );
trap_BotEnterChat( bs->cs, bs->client, CHAT_TEAM );
bs->teammessage_time = 0;
}
//if accompanying the companion for 3 minutes
if ( bs->teamgoal_time < trap_AAS_Time() ) {
BotAI_BotInitialChat( bs, "accompany_stop", EasyClientName( bs->teammate, netname, sizeof( netname ) ), NULL );
trap_BotEnterChat( bs->cs, bs->client, CHAT_TEAM );
bs->ltgtype = 0;
}
//get entity information of the companion
BotEntityInfo( bs->teammate, &entinfo );
//if the companion is visible
if ( BotEntityVisible( bs->entitynum, bs->eye, bs->viewangles, 360, bs->teammate ) ) {
//update visible time
bs->teammatevisible_time = trap_AAS_Time();
VectorSubtract( entinfo.origin, bs->origin, dir );
if ( VectorLength( dir ) < bs->formation_dist ) {
//check if the bot wants to crouch
//don't crouch if crouched less than 5 seconds ago
if ( bs->attackcrouch_time < trap_AAS_Time() - 5 ) {
croucher = trap_Characteristic_BFloat( bs->character, CHARACTERISTIC_CROUCHER, 0, 1 );
if ( random() < bs->thinktime * croucher ) {
bs->attackcrouch_time = trap_AAS_Time() + 5 + croucher * 15;
}
}
//don't crouch when swimming
if ( trap_AAS_Swimming( bs->origin ) ) {
bs->attackcrouch_time = trap_AAS_Time() - 1;
}
//if not arrived yet or arived some time ago
if ( bs->arrive_time < trap_AAS_Time() - 2 ) {
//if not arrived yet
if ( !bs->arrive_time ) {
trap_EA_Gesture( bs->client );
BotAI_BotInitialChat( bs, "accompany_arrive", EasyClientName( bs->teammate, netname, sizeof( netname ) ), NULL );
trap_BotEnterChat( bs->cs, bs->client, CHAT_TEAM );
bs->arrive_time = trap_AAS_Time();
}
//if the bot wants to crouch
else if ( bs->attackcrouch_time > trap_AAS_Time() ) {
trap_EA_Crouch( bs->client );
}
//else do some model taunts
else if ( random() < bs->thinktime * 0.3 ) {
//do a gesture :)
trap_EA_Gesture( bs->client );
}
}
//if just arrived look at the companion
if ( bs->arrive_time > trap_AAS_Time() - 2 ) {
VectorSubtract( entinfo.origin, bs->origin, dir );
vectoangles( dir, bs->ideal_viewangles );
bs->ideal_viewangles[2] *= 0.5;
}
//else look strategically around for enemies
else if ( random() < bs->thinktime * 0.8 ) {
BotRoamGoal( bs, target );
VectorSubtract( target, bs->origin, dir );
vectoangles( dir, bs->ideal_viewangles );
bs->ideal_viewangles[2] *= 0.5;
}
//check if the bot wants to go for air
if ( BotGoForAir( bs, bs->tfl, &bs->teamgoal, 400 ) ) {
trap_BotResetLastAvoidReach( bs->ms );
//get the goal at the top of the stack
//trap_BotGetTopGoal(bs->gs, &tmpgoal);
//trap_BotGoalName(tmpgoal.number, buf, 144);
//BotAI_Print(PRT_MESSAGE, "new nearby goal %s\n", buf);
//time the bot gets to pick up the nearby goal item
bs->nbg_time = trap_AAS_Time() + 8;
AIEnter_Seek_NBG( bs );
return qfalse;
}
//
trap_BotResetAvoidReach( bs->ms );
return qfalse;
}
}
//if the entity information is valid (entity in PVS)
if ( entinfo.valid ) {
areanum = BotPointAreaNum( entinfo.origin );
if ( areanum && trap_AAS_AreaReachability( areanum ) ) {
//update team goal so bot will accompany
bs->teamgoal.entitynum = bs->teammate;
bs->teamgoal.areanum = areanum;
VectorCopy( entinfo.origin, bs->teamgoal.origin );
VectorSet( bs->teamgoal.mins, -8, -8, -8 );
VectorSet( bs->teamgoal.maxs, 8, 8, 8 );
}
}
//the goal the bot should go for
memcpy( goal, &bs->teamgoal, sizeof( bot_goal_t ) );
//if the companion is NOT visible for too long
if ( bs->teammatevisible_time < trap_AAS_Time() - 60 ) {
BotAI_BotInitialChat( bs, "accompany_cannotfind", EasyClientName( bs->teammate, netname, sizeof( netname ) ), NULL );
trap_BotEnterChat( bs->cs, bs->client, CHAT_TEAM );
bs->ltgtype = 0;
}
return qtrue;
}
//
if ( bs->ltgtype == LTG_DEFENDKEYAREA ) {
if ( trap_AAS_AreaTravelTimeToGoalArea( bs->areanum, bs->origin,
bs->teamgoal.areanum, TFL_DEFAULT ) > bs->defendaway_range ) {
bs->defendaway_time = 0;
}
}
//if defending a key area
if ( bs->ltgtype == LTG_DEFENDKEYAREA && !retreat &&
bs->defendaway_time < trap_AAS_Time() ) {
//check for bot typing status message
if ( bs->teammessage_time && bs->teammessage_time < trap_AAS_Time() ) {
trap_BotGoalName( bs->teamgoal.number, buf, sizeof( buf ) );
BotAI_BotInitialChat( bs, "defend_start", buf, NULL );
trap_BotEnterChat( bs->cs, bs->client, CHAT_TEAM );
bs->teammessage_time = 0;
}
//set the bot goal
memcpy( goal, &bs->teamgoal, sizeof( bot_goal_t ) );
//stop after 2 minutes
if ( bs->teamgoal_time < trap_AAS_Time() ) {
trap_BotGoalName( bs->teamgoal.number, buf, sizeof( buf ) );
BotAI_BotInitialChat( bs, "defend_stop", buf, NULL );
trap_BotEnterChat( bs->cs, bs->client, CHAT_TEAM );
bs->ltgtype = 0;
}
//if very close... go away for some time
VectorSubtract( goal->origin, bs->origin, dir );
if ( VectorLength( dir ) < 70 ) {
trap_BotResetAvoidReach( bs->ms );
bs->defendaway_time = trap_AAS_Time() + 2 + 5 * random();
bs->defendaway_range = 300;
}
return qtrue;
}
//going to kill someone
if ( bs->ltgtype == LTG_KILL && !retreat ) {
//check for bot typing status message
if ( bs->teammessage_time && bs->teammessage_time < trap_AAS_Time() ) {
EasyClientName( bs->teamgoal.entitynum, buf, sizeof( buf ) );
BotAI_BotInitialChat( bs, "kill_start", buf, NULL );
trap_BotEnterChat( bs->cs, bs->client, CHAT_TEAM );
bs->teammessage_time = 0;
}
//
if ( bs->lastkilledplayer == bs->teamgoal.entitynum ) {
EasyClientName( bs->teamgoal.entitynum, buf, sizeof( buf ) );
BotAI_BotInitialChat( bs, "kill_done", buf, NULL );
trap_BotEnterChat( bs->cs, bs->client, CHAT_TEAM );
bs->lastkilledplayer = -1;
bs->ltgtype = 0;
}
//
if ( bs->teamgoal_time < trap_AAS_Time() ) {
bs->ltgtype = 0;
}
//just roam around
return BotGetItemLongTermGoal( bs, tfl, goal );
}
//get an item
if ( bs->ltgtype == LTG_GETITEM && !retreat ) {
//check for bot typing status message
if ( bs->teammessage_time && bs->teammessage_time < trap_AAS_Time() ) {
trap_BotGoalName( bs->teamgoal.number, buf, sizeof( buf ) );
BotAI_BotInitialChat( bs, "getitem_start", buf, NULL );
trap_BotEnterChat( bs->cs, bs->client, CHAT_TEAM );
bs->teammessage_time = 0;
}
//set the bot goal
memcpy( goal, &bs->teamgoal, sizeof( bot_goal_t ) );
//stop after some time
if ( bs->teamgoal_time < trap_AAS_Time() ) {
bs->ltgtype = 0;
}
//
if ( trap_BotItemGoalInVisButNotVisible( bs->entitynum, bs->eye, bs->viewangles, goal ) ) {
trap_BotGoalName( bs->teamgoal.number, buf, sizeof( buf ) );
BotAI_BotInitialChat( bs, "getitem_notthere", buf, NULL );
trap_BotEnterChat( bs->cs, bs->client, CHAT_TEAM );
bs->ltgtype = 0;
} else if ( BotReachedGoal( bs, goal ) ) {
trap_BotGoalName( bs->teamgoal.number, buf, sizeof( buf ) );
BotAI_BotInitialChat( bs, "getitem_gotit", buf, NULL );
trap_BotEnterChat( bs->cs, bs->client, CHAT_TEAM );
bs->ltgtype = 0;
}
return qtrue;
}
//if camping somewhere
if ( ( bs->ltgtype == LTG_CAMP || bs->ltgtype == LTG_CAMPORDER ) && !retreat ) {
//check for bot typing status message
if ( bs->teammessage_time && bs->teammessage_time < trap_AAS_Time() ) {
if ( bs->ltgtype == LTG_CAMPORDER ) {
BotAI_BotInitialChat( bs, "camp_start", EasyClientName( bs->teammate, netname, sizeof( netname ) ), NULL );
trap_BotEnterChat( bs->cs, bs->client, CHAT_TEAM );
}
bs->teammessage_time = 0;
}
//set the bot goal
memcpy( goal, &bs->teamgoal, sizeof( bot_goal_t ) );
//
if ( bs->teamgoal_time < trap_AAS_Time() ) {
if ( bs->ltgtype == LTG_CAMPORDER ) {
BotAI_BotInitialChat( bs, "camp_stop", NULL );
trap_BotEnterChat( bs->cs, bs->client, CHAT_TEAM );
}
bs->ltgtype = 0;
}
//if really near the camp spot
VectorSubtract( goal->origin, bs->origin, dir );
if ( VectorLength( dir ) < 60 ) {
//if not arrived yet
if ( !bs->arrive_time ) {
if ( bs->ltgtype == LTG_CAMPORDER ) {
BotAI_BotInitialChat( bs, "camp_arrive", EasyClientName( bs->teammate, netname, sizeof( netname ) ), NULL );
trap_BotEnterChat( bs->cs, bs->client, CHAT_TEAM );
}
bs->arrive_time = trap_AAS_Time();
}
//look strategically around for enemies
if ( random() < bs->thinktime * 0.8 ) {
BotRoamGoal( bs, target );
VectorSubtract( target, bs->origin, dir );
vectoangles( dir, bs->ideal_viewangles );
bs->ideal_viewangles[2] *= 0.5;
}
//check if the bot wants to crouch
//don't crouch if crouched less than 5 seconds ago
if ( bs->attackcrouch_time < trap_AAS_Time() - 5 ) {
croucher = trap_Characteristic_BFloat( bs->character, CHARACTERISTIC_CROUCHER, 0, 1 );
if ( random() < bs->thinktime * croucher ) {
bs->attackcrouch_time = trap_AAS_Time() + 5 + croucher * 15;
}
}
//if the bot wants to crouch
if ( bs->attackcrouch_time > trap_AAS_Time() ) {
trap_EA_Crouch( bs->client );
}
//don't crouch when swimming
if ( trap_AAS_Swimming( bs->origin ) ) {
bs->attackcrouch_time = trap_AAS_Time() - 1;
}
//make sure the bot is not gonna drown
if ( trap_PointContents( bs->eye,bs->entitynum ) & ( CONTENTS_WATER | CONTENTS_SLIME | CONTENTS_LAVA ) ) {
if ( bs->ltgtype == LTG_CAMPORDER ) {
BotAI_BotInitialChat( bs, "camp_stop", NULL );
trap_BotEnterChat( bs->cs, bs->client, CHAT_TEAM );
}
bs->ltgtype = 0;
}
//
if ( bs->camp_range > 0 ) {
//FIXME: move around a bit
}
//
trap_BotResetAvoidReach( bs->ms );
return qfalse;
}
return qtrue;
}
//patrolling along several waypoints
if ( bs->ltgtype == LTG_PATROL && !retreat ) {
//check for bot typing status message
if ( bs->teammessage_time && bs->teammessage_time < trap_AAS_Time() ) {
strcpy( buf, "" );
for ( wp = bs->patrolpoints; wp; wp = wp->next ) {
strcat( buf, wp->name );
if ( wp->next ) {
strcat( buf, " to " );
}
}
BotAI_BotInitialChat( bs, "patrol_start", buf, NULL );
trap_BotEnterChat( bs->cs, bs->client, CHAT_TEAM );
bs->teammessage_time = 0;
}
//
if ( !bs->curpatrolpoint ) {
bs->ltgtype = 0;
return qfalse;
}
//if the bot touches the current goal
if ( trap_BotTouchingGoal( bs->origin, &bs->curpatrolpoint->goal ) ) {
if ( bs->patrolflags & PATROL_BACK ) {
if ( bs->curpatrolpoint->prev ) {
bs->curpatrolpoint = bs->curpatrolpoint->prev;
} else {
bs->curpatrolpoint = bs->curpatrolpoint->next;
bs->patrolflags &= ~PATROL_BACK;
}
} else {
if ( bs->curpatrolpoint->next ) {
bs->curpatrolpoint = bs->curpatrolpoint->next;
} else {
bs->curpatrolpoint = bs->curpatrolpoint->prev;
bs->patrolflags |= PATROL_BACK;
}
}
}
//stop after 5 minutes
if ( bs->teamgoal_time < trap_AAS_Time() ) {
BotAI_BotInitialChat( bs, "patrol_stop", NULL );
trap_BotEnterChat( bs->cs, bs->client, CHAT_TEAM );
bs->ltgtype = 0;
}
if ( !bs->curpatrolpoint ) {
bs->ltgtype = 0;
return qfalse;
}
memcpy( goal, &bs->curpatrolpoint->goal, sizeof( bot_goal_t ) );
return qtrue;
}
#ifdef CTF
//if going for enemy flag
if ( bs->ltgtype == LTG_GETFLAG ) {
//check for bot typing status message
if ( bs->teammessage_time && bs->teammessage_time < trap_AAS_Time() ) {
BotAI_BotInitialChat( bs, "captureflag_start", NULL );
trap_BotEnterChat( bs->cs, bs->client, CHAT_TEAM );
bs->teammessage_time = 0;
}
//
switch ( BotCTFTeam( bs ) ) {
case CTF_TEAM_RED: *goal = ctf_blueflag; break;
case CTF_TEAM_BLUE: *goal = ctf_redflag; break;
default: bs->ltgtype = 0; return qfalse;
}
//if touching the flag
if ( trap_BotTouchingGoal( bs->origin, goal ) ) {
bs->ltgtype = 0;
}
//stop after 3 minutes
if ( bs->teamgoal_time < trap_AAS_Time() ) {
#ifdef DEBUG
BotAI_Print( PRT_MESSAGE, "%s: I quit getting the flag\n", ClientName( bs->client, netname, sizeof( netname ) ) );
#endif //DEBUG
bs->ltgtype = 0;
}
return qtrue;
}
//if rushing to the base
if ( bs->ltgtype == LTG_RUSHBASE && bs->rushbaseaway_time < trap_AAS_Time() ) {
switch ( BotCTFTeam( bs ) ) {
case CTF_TEAM_RED: *goal = ctf_redflag; break;
case CTF_TEAM_BLUE: *goal = ctf_blueflag; break;
default: bs->ltgtype = 0; return qfalse;
}
//quit rushing after 2 minutes
if ( bs->teamgoal_time < trap_AAS_Time() ) {
bs->ltgtype = 0;
}
//if touching the base flag the bot should loose the enemy flag
if ( trap_BotTouchingGoal( bs->origin, goal ) ) {
//if the bot is still carrying the enemy flag then the
//base flag is gone, now just walk near the base a bit
if ( BotCTFCarryingFlag( bs ) ) {
trap_BotResetAvoidReach( bs->ms );
bs->rushbaseaway_time = trap_AAS_Time() + 5 + 10 * random();
//FIXME: add chat to tell the others to get back the flag
} else {
bs->ltgtype = 0;
}
}
return qtrue;
}
//returning flag
if ( bs->ltgtype == LTG_RETURNFLAG ) {
//check for bot typing status message
if ( bs->teammessage_time && bs->teammessage_time < trap_AAS_Time() ) {
EasyClientName( bs->teamgoal.entitynum, buf, sizeof( buf ) );
BotAI_BotInitialChat( bs, "returnflag_start", buf, NULL );
trap_BotEnterChat( bs->cs, bs->client, CHAT_TEAM );
bs->teammessage_time = 0;
}
//
if ( bs->teamgoal_time < trap_AAS_Time() ) {
bs->ltgtype = 0;
}
//just roam around
return BotGetItemLongTermGoal( bs, tfl, goal );
}
#endif //CTF
//normal goal stuff
return BotGetItemLongTermGoal( bs, tfl, goal );
}
/*
==================
BotLongTermGoal
==================
*/
int BotLongTermGoal( bot_state_t *bs, int tfl, int retreat, bot_goal_t *goal ) {
aas_entityinfo_t entinfo;
char teammate[MAX_MESSAGE_SIZE];
float dist;
int areanum;
vec3_t dir;
//FIXME: also have air long term goals?
//
//if the bot is leading someone and not retreating
if ( bs->lead_time > 0 && !retreat ) {
if ( bs->lead_time < trap_AAS_Time() ) {
//FIXME: add chat to tell the team mate that he/she's on his/her own
bs->lead_time = 0;
return BotGetLongTermGoal( bs, tfl, retreat, goal );
}
//
if ( bs->leadmessage_time < 0 && -bs->leadmessage_time < trap_AAS_Time() ) {
BotAI_BotInitialChat( bs, "followme", EasyClientName( bs->lead_teammate, teammate, sizeof( teammate ) ), NULL );
trap_BotEnterChat( bs->cs, bs->client, CHAT_TEAM );
bs->leadmessage_time = trap_AAS_Time();
}
//get entity information of the companion
BotEntityInfo( bs->lead_teammate, &entinfo );
//
if ( entinfo.valid ) {
areanum = BotPointAreaNum( entinfo.origin );
if ( areanum && trap_AAS_AreaReachability( areanum ) ) {
//update team goal
bs->lead_teamgoal.entitynum = bs->lead_teammate;
bs->lead_teamgoal.areanum = areanum;
VectorCopy( entinfo.origin, bs->lead_teamgoal.origin );
VectorSet( bs->lead_teamgoal.mins, -8, -8, -8 );
VectorSet( bs->lead_teamgoal.maxs, 8, 8, 8 );
}
}
//if the team mate is visible
if ( BotEntityVisible( bs->entitynum, bs->eye, bs->viewangles, 360, bs->lead_teammate ) ) {
bs->leadvisible_time = trap_AAS_Time();
}
//if the team mate is not visible for 1 seconds
if ( bs->leadvisible_time < trap_AAS_Time() - 1 ) {
bs->leadbackup_time = trap_AAS_Time() + 2;
}
//distance towards the team mate
VectorSubtract( bs->origin, bs->lead_teamgoal.origin, dir );
dist = VectorLength( dir );
//if backing up towards the team mate
if ( bs->leadbackup_time > trap_AAS_Time() ) {
if ( bs->leadmessage_time < trap_AAS_Time() - 20 ) {
BotAI_BotInitialChat( bs, "followme", EasyClientName( bs->lead_teammate, teammate, sizeof( teammate ) ), NULL );
trap_BotEnterChat( bs->cs, bs->client, CHAT_TEAM );
bs->leadmessage_time = trap_AAS_Time();
}
//if very close to the team mate
if ( dist < 100 ) {
bs->leadbackup_time = 0;
}
//the bot should go back to the team mate
memcpy( goal, &bs->lead_teamgoal, sizeof( bot_goal_t ) );
return qtrue;
} else {
//if quite distant from the team mate
if ( dist > 500 ) {
if ( bs->leadmessage_time < trap_AAS_Time() - 20 ) {
BotAI_BotInitialChat( bs, "followme", EasyClientName( bs->lead_teammate, teammate, sizeof( teammate ) ), NULL );
trap_BotEnterChat( bs->cs, bs->client, CHAT_TEAM );
bs->leadmessage_time = trap_AAS_Time();
}
//look at the team mate
VectorSubtract( entinfo.origin, bs->origin, dir );
vectoangles( dir, bs->ideal_viewangles );
bs->ideal_viewangles[2] *= 0.5;
//just wait for the team mate
return qfalse;
}
}
}
return BotGetLongTermGoal( bs, tfl, retreat, goal );
}
/*
==================
AIEnter_Intermission
==================
*/
void AIEnter_Intermission( bot_state_t *bs ) {
BotRecordNodeSwitch( bs, "intermission", "" );
//reset the bot state
BotResetState( bs );
//check for end level chat
if ( BotChat_EndLevel( bs ) ) {
trap_BotEnterChat( bs->cs, bs->client, bs->chatto );
}
bs->ainode = AINode_Intermission;
}
/*
==================
AINode_Intermission
==================
*/
int AINode_Intermission( bot_state_t *bs ) {
//if the intermission ended
if ( !BotIntermission( bs ) ) {
if ( BotChat_StartLevel( bs ) ) {
bs->stand_time = trap_AAS_Time() + BotChatTime( bs );
} else {
bs->stand_time = trap_AAS_Time() + 2;
}
AIEnter_Stand( bs );
}
return qtrue;
}
/*
==================
AIEnter_Observer
==================
*/
void AIEnter_Observer( bot_state_t *bs ) {
BotRecordNodeSwitch( bs, "observer", "" );
//reset the bot state
BotResetState( bs );
bs->ainode = AINode_Observer;
}
/*
==================
AINode_Observer
==================
*/
int AINode_Observer( bot_state_t *bs ) {
//if the bot left observer mode
if ( !BotIsObserver( bs ) ) {
AIEnter_Stand( bs );
}
return qtrue;
}
/*
==================
AIEnter_Stand
==================
*/
void AIEnter_Stand( bot_state_t *bs ) {
BotRecordNodeSwitch( bs, "stand", "" );
bs->standfindenemy_time = trap_AAS_Time() + 1;
bs->ainode = AINode_Stand;
}
/*
==================
AINode_Stand
==================
*/
int AINode_Stand( bot_state_t *bs ) {
//if the bot's health decreased
if ( bs->lastframe_health > bs->inventory[INVENTORY_HEALTH] ) {
if ( BotChat_HitTalking( bs ) ) {
bs->standfindenemy_time = trap_AAS_Time() + BotChatTime( bs ) + 0.1;
bs->stand_time = trap_AAS_Time() + BotChatTime( bs ) + 0.1;
}
}
if ( bs->standfindenemy_time < trap_AAS_Time() ) {
if ( BotFindEnemy( bs, -1 ) ) {
AIEnter_Battle_Fight( bs );
return qfalse;
}
bs->standfindenemy_time = trap_AAS_Time() + 1;
}
trap_EA_Talk( bs->client );
if ( bs->stand_time < trap_AAS_Time() ) {
trap_BotEnterChat( bs->cs, bs->client, bs->chatto );
AIEnter_Seek_LTG( bs );
return qfalse;
}
//
return qtrue;
}
/*
==================
AIEnter_Respawn
==================
*/
void AIEnter_Respawn( bot_state_t *bs ) {
BotRecordNodeSwitch( bs, "respawn", "" );
//reset some states
trap_BotResetMoveState( bs->ms );
trap_BotResetGoalState( bs->gs );
trap_BotResetAvoidGoals( bs->gs );
trap_BotResetAvoidReach( bs->ms );
//if the bot wants to chat
if ( BotChat_Death( bs ) ) {
bs->respawn_time = trap_AAS_Time() + BotChatTime( bs );
bs->respawnchat_time = trap_AAS_Time();
} else {
bs->respawn_time = trap_AAS_Time() + 1 + random();
bs->respawnchat_time = 0;
}
//set respawn state
bs->respawn_wait = qfalse;
bs->ainode = AINode_Respawn;
}
/*
==================
AINode_Respawn
==================
*/
int AINode_Respawn( bot_state_t *bs ) {
if ( bs->respawn_wait ) {
if ( !BotIsDead( bs ) ) {
AIEnter_Seek_LTG( bs );
} else {
trap_EA_Respawn( bs->client );
}
} else if ( bs->respawn_time < trap_AAS_Time() ) {
//wait until respawned
bs->respawn_wait = qtrue;
//elementary action respawn
trap_EA_Respawn( bs->client );
//
if ( bs->respawnchat_time ) {
trap_BotEnterChat( bs->cs, bs->client, bs->chatto );
bs->enemy = -1;
}
}
if ( bs->respawnchat_time && bs->respawnchat_time < trap_AAS_Time() - 0.5 ) {
trap_EA_Talk( bs->client );
}
//
return qtrue;
}
/*
==================
AIEnter_Seek_ActivateEntity
==================
*/
void AIEnter_Seek_ActivateEntity( bot_state_t *bs ) {
BotRecordNodeSwitch( bs, "activate entity", "" );
bs->ainode = AINode_Seek_ActivateEntity;
}
/*
==================
AINode_Seek_Activate_Entity
==================
*/
int AINode_Seek_ActivateEntity( bot_state_t *bs ) {
bot_goal_t *goal;
vec3_t target, dir;
bot_moveresult_t moveresult;
if ( BotIsObserver( bs ) ) {
AIEnter_Observer( bs );
return qfalse;
}
//if in the intermission
if ( BotIntermission( bs ) ) {
AIEnter_Intermission( bs );
return qfalse;
}
//respawn if dead
if ( BotIsDead( bs ) ) {
AIEnter_Respawn( bs );
return qfalse;
}
//
bs->tfl = TFL_DEFAULT;
if ( bot_grapple.integer ) {
bs->tfl |= TFL_GRAPPLEHOOK;
}
//if in lava or slime the bot should be able to get out
if ( BotInLava( bs ) ) {
bs->tfl |= TFL_LAVA;
}
if ( BotInSlime( bs ) ) {
bs->tfl |= TFL_SLIME;
}
//map specific code
BotMapScripts( bs );
//no enemy
bs->enemy = -1;
//
goal = &bs->activategoal;
//if the bot has no goal
if ( !goal ) {
bs->activate_time = 0;
}
//if the bot touches the current goal
else if ( trap_BotTouchingGoal( bs->origin, goal ) ) {
BotChooseWeapon( bs );
#ifdef DEBUG
BotAI_Print( PRT_MESSAGE, "touched button or trigger\n" );
#endif //DEBUG
bs->activate_time = 0;
}
//
if ( bs->activate_time < trap_AAS_Time() ) {
AIEnter_Seek_NBG( bs );
return qfalse;
}
//initialize the movement state
BotSetupForMovement( bs );
//move towards the goal
trap_BotMoveToGoal( &moveresult, bs->ms, goal, bs->tfl );
//if the movement failed
if ( moveresult.failure ) {
//reset the avoid reach, otherwise bot is stuck in current area
trap_BotResetAvoidReach( bs->ms );
bs->nbg_time = 0;
}
//check if the bot is blocked
BotAIBlocked( bs, &moveresult, qtrue );
//
if ( moveresult.flags & ( MOVERESULT_MOVEMENTVIEWSET | MOVERESULT_MOVEMENTVIEW | MOVERESULT_SWIMVIEW ) ) {
VectorCopy( moveresult.ideal_viewangles, bs->ideal_viewangles );
}
//if waiting for something
else if ( moveresult.flags & MOVERESULT_WAITING ) {
if ( random() < bs->thinktime * 0.8 ) {
BotRoamGoal( bs, target );
VectorSubtract( target, bs->origin, dir );
vectoangles( dir, bs->ideal_viewangles );
bs->ideal_viewangles[2] *= 0.5;
}
} else if ( !( bs->flags & BFL_IDEALVIEWSET ) ) {
if ( trap_BotMovementViewTarget( bs->ms, goal, bs->tfl, 300, target ) ) {
VectorSubtract( target, bs->origin, dir );
vectoangles( dir, bs->ideal_viewangles );
} else {
//vectoangles(moveresult.movedir, bs->ideal_viewangles);
}
bs->ideal_viewangles[2] *= 0.5;
}
//if the weapon is used for the bot movement
if ( moveresult.flags & MOVERESULT_MOVEMENTWEAPON ) {
bs->weaponnum = moveresult.weapon;
}
//if there is an enemy
if ( BotFindEnemy( bs, -1 ) ) {
if ( BotWantsToRetreat( bs ) ) {
//keep the current long term goal and retreat
AIEnter_Battle_NBG( bs );
} else {
trap_BotResetLastAvoidReach( bs->ms );
//empty the goal stack
trap_BotEmptyGoalStack( bs->gs );
//go fight
AIEnter_Battle_Fight( bs );
}
}
return qtrue;
}
/*
==================
AIEnter_Seek_NBG
==================
*/
void AIEnter_Seek_NBG( bot_state_t *bs ) {
bot_goal_t goal;
char buf[144];
if ( trap_BotGetTopGoal( bs->gs, &goal ) ) {
trap_BotGoalName( goal.number, buf, 144 );
BotRecordNodeSwitch( bs, "seek NBG", buf );
} else {
BotRecordNodeSwitch( bs, "seek NBG", "no goal" );
}
bs->ainode = AINode_Seek_NBG;
}
/*
==================
AINode_Seek_NBG
==================
*/
int AINode_Seek_NBG( bot_state_t *bs ) {
bot_goal_t goal;
vec3_t target, dir;
bot_moveresult_t moveresult;
if ( BotIsObserver( bs ) ) {
AIEnter_Observer( bs );
return qfalse;
}
//if in the intermission
if ( BotIntermission( bs ) ) {
AIEnter_Intermission( bs );
return qfalse;
}
//respawn if dead
if ( BotIsDead( bs ) ) {
AIEnter_Respawn( bs );
return qfalse;
}
//
bs->tfl = TFL_DEFAULT;
if ( bot_grapple.integer ) {
bs->tfl |= TFL_GRAPPLEHOOK;
}
//if in lava or slime the bot should be able to get out
if ( BotInLava( bs ) ) {
bs->tfl |= TFL_LAVA;
}
if ( BotInSlime( bs ) ) {
bs->tfl |= TFL_SLIME;
}
//
if ( BotCanAndWantsToRocketJump( bs ) ) {
bs->tfl |= TFL_ROCKETJUMP;
}
//map specific code
BotMapScripts( bs );
//no enemy
bs->enemy = -1;
//if the bot has no goal
if ( !trap_BotGetTopGoal( bs->gs, &goal ) ) {
bs->nbg_time = 0;
}
//if the bot touches the current goal
else if ( BotReachedGoal( bs, &goal ) ) {
BotChooseWeapon( bs );
bs->nbg_time = 0;
}
//
if ( bs->nbg_time < trap_AAS_Time() ) {
//pop the current goal from the stack
trap_BotPopGoal( bs->gs );
//check for new nearby items right away
//NOTE: we canNOT reset the check_time to zero because it would create an endless loop of node switches
bs->check_time = trap_AAS_Time() + 0.05;
//go back to seek ltg
AIEnter_Seek_LTG( bs );
return qfalse;
}
//initialize the movement state
BotSetupForMovement( bs );
//move towards the goal
trap_BotMoveToGoal( &moveresult, bs->ms, &goal, bs->tfl );
//if the movement failed
if ( moveresult.failure ) {
//reset the avoid reach, otherwise bot is stuck in current area
trap_BotResetAvoidReach( bs->ms );
bs->nbg_time = 0;
}
//check if the bot is blocked
BotAIBlocked( bs, &moveresult, qtrue );
//if the viewangles are used for the movement
if ( moveresult.flags & ( MOVERESULT_MOVEMENTVIEWSET | MOVERESULT_MOVEMENTVIEW | MOVERESULT_SWIMVIEW ) ) {
VectorCopy( moveresult.ideal_viewangles, bs->ideal_viewangles );
}
//if waiting for something
else if ( moveresult.flags & MOVERESULT_WAITING ) {
if ( random() < bs->thinktime * 0.8 ) {
BotRoamGoal( bs, target );
VectorSubtract( target, bs->origin, dir );
vectoangles( dir, bs->ideal_viewangles );
bs->ideal_viewangles[2] *= 0.5;
}
} else if ( !( bs->flags & BFL_IDEALVIEWSET ) ) {
if ( !trap_BotGetSecondGoal( bs->gs, &goal ) ) {
trap_BotGetTopGoal( bs->gs, &goal );
}
if ( trap_BotMovementViewTarget( bs->ms, &goal, bs->tfl, 300, target ) ) {
VectorSubtract( target, bs->origin, dir );
vectoangles( dir, bs->ideal_viewangles );
}
//FIXME: look at cluster portals?
else {vectoangles( moveresult.movedir, bs->ideal_viewangles );}
bs->ideal_viewangles[2] *= 0.5;
}
//if the weapon is used for the bot movement
if ( moveresult.flags & MOVERESULT_MOVEMENTWEAPON ) {
bs->weaponnum = moveresult.weapon;
}
//if there is an enemy
if ( BotFindEnemy( bs, -1 ) ) {
if ( BotWantsToRetreat( bs ) ) {
//keep the current long term goal and retreat
AIEnter_Battle_NBG( bs );
} else {
trap_BotResetLastAvoidReach( bs->ms );
//empty the goal stack
trap_BotEmptyGoalStack( bs->gs );
//go fight
AIEnter_Battle_Fight( bs );
}
}
return qtrue;
}
/*
==================
AIEnter_Seek_LTG
==================
*/
void AIEnter_Seek_LTG( bot_state_t *bs ) {
bot_goal_t goal;
char buf[144];
if ( trap_BotGetTopGoal( bs->gs, &goal ) ) {
trap_BotGoalName( goal.number, buf, 144 );
BotRecordNodeSwitch( bs, "seek LTG", buf );
} else {
BotRecordNodeSwitch( bs, "seek LTG", "no goal" );
}
bs->ainode = AINode_Seek_LTG;
}
/*
==================
AINode_Seek_LTG
==================
*/
int AINode_Seek_LTG( bot_state_t *bs ) {
bot_goal_t goal;
vec3_t target, dir;
bot_moveresult_t moveresult;
int range;
//char buf[128];
//bot_goal_t tmpgoal;
if ( BotIsObserver( bs ) ) {
AIEnter_Observer( bs );
return qfalse;
}
//if in the intermission
if ( BotIntermission( bs ) ) {
AIEnter_Intermission( bs );
return qfalse;
}
//respawn if dead
if ( BotIsDead( bs ) ) {
AIEnter_Respawn( bs );
return qfalse;
}
//
if ( BotChat_Random( bs ) ) {
bs->stand_time = trap_AAS_Time() + BotChatTime( bs );
AIEnter_Stand( bs );
return qfalse;
}
//
bs->tfl = TFL_DEFAULT;
if ( bot_grapple.integer ) {
bs->tfl |= TFL_GRAPPLEHOOK;
}
//if in lava or slime the bot should be able to get out
if ( BotInLava( bs ) ) {
bs->tfl |= TFL_LAVA;
}
if ( BotInSlime( bs ) ) {
bs->tfl |= TFL_SLIME;
}
//
if ( BotCanAndWantsToRocketJump( bs ) ) {
bs->tfl |= TFL_ROCKETJUMP;
}
//map specific code
BotMapScripts( bs );
//no enemy
bs->enemy = -1;
//
if ( bs->killedenemy_time > trap_AAS_Time() - 2 ) {
if ( random() < bs->thinktime * 1 ) {
trap_EA_Gesture( bs->client );
}
}
//if there is an enemy
if ( BotFindEnemy( bs, -1 ) ) {
if ( BotWantsToRetreat( bs ) ) {
//keep the current long term goal and retreat
AIEnter_Battle_Retreat( bs );
return qfalse;
} else {
trap_BotResetLastAvoidReach( bs->ms );
//empty the goal stack
trap_BotEmptyGoalStack( bs->gs );
//go fight
AIEnter_Battle_Fight( bs );
return qfalse;
}
}
#ifdef CTF
if ( gametype == GT_CTF ) {
//decide what to do in CTF mode
BotCTFSeekGoals( bs );
}
#endif //CTF
//get the current long term goal
if ( !BotLongTermGoal( bs, bs->tfl, qfalse, &goal ) ) {
return qtrue;
}
//check for nearby goals periodicly
if ( bs->check_time < trap_AAS_Time() ) {
bs->check_time = trap_AAS_Time() + 0.5;
//check if the bot wants to camp
BotWantsToCamp( bs );
//
if ( bs->ltgtype == LTG_DEFENDKEYAREA ) {
range = 400;
} else { range = 150;}
//
#ifdef CTF
//if carrying a flag the bot shouldn't be distracted too much
if ( BotCTFCarryingFlag( bs ) ) {
range = 50;
}
#endif //CTF
//
if ( BotNearbyGoal( bs, bs->tfl, &goal, range ) ) {
trap_BotResetLastAvoidReach( bs->ms );
//get the goal at the top of the stack
//trap_BotGetTopGoal(bs->gs, &tmpgoal);
//trap_BotGoalName(tmpgoal.number, buf, 144);
//BotAI_Print(PRT_MESSAGE, "new nearby goal %s\n", buf);
//time the bot gets to pick up the nearby goal item
bs->nbg_time = trap_AAS_Time() + 4 + range * 0.01;
AIEnter_Seek_NBG( bs );
return qfalse;
}
}
//initialize the movement state
BotSetupForMovement( bs );
//move towards the goal
trap_BotMoveToGoal( &moveresult, bs->ms, &goal, bs->tfl );
//if the movement failed
if ( moveresult.failure ) {
//reset the avoid reach, otherwise bot is stuck in current area
trap_BotResetAvoidReach( bs->ms );
//BotAI_Print(PRT_MESSAGE, "movement failure %d\n", moveresult.traveltype);
bs->ltg_time = 0;
}
//
BotAIBlocked( bs, &moveresult, qtrue );
//if the viewangles are used for the movement
if ( moveresult.flags & ( MOVERESULT_MOVEMENTVIEWSET | MOVERESULT_MOVEMENTVIEW | MOVERESULT_SWIMVIEW ) ) {
VectorCopy( moveresult.ideal_viewangles, bs->ideal_viewangles );
}
//if waiting for something
else if ( moveresult.flags & MOVERESULT_WAITING ) {
if ( random() < bs->thinktime * 0.8 ) {
BotRoamGoal( bs, target );
VectorSubtract( target, bs->origin, dir );
vectoangles( dir, bs->ideal_viewangles );
bs->ideal_viewangles[2] *= 0.5;
}
} else if ( !( bs->flags & BFL_IDEALVIEWSET ) ) {
if ( trap_BotMovementViewTarget( bs->ms, &goal, bs->tfl, 300, target ) ) {
VectorSubtract( target, bs->origin, dir );
vectoangles( dir, bs->ideal_viewangles );
}
//FIXME: look at cluster portals?
else if ( VectorLength( moveresult.movedir ) ) {
vectoangles( moveresult.movedir, bs->ideal_viewangles );
} else if ( random() < bs->thinktime * 0.8 ) {
BotRoamGoal( bs, target );
VectorSubtract( target, bs->origin, dir );
vectoangles( dir, bs->ideal_viewangles );
bs->ideal_viewangles[2] *= 0.5;
}
bs->ideal_viewangles[2] *= 0.5;
}
//if the weapon is used for the bot movement
if ( moveresult.flags & MOVERESULT_MOVEMENTWEAPON ) {
bs->weaponnum = moveresult.weapon;
}
//
return qtrue;
}
/*
==================
AIEnter_Battle_Fight
==================
*/
void AIEnter_Battle_Fight( bot_state_t *bs ) {
BotRecordNodeSwitch( bs, "battle fight", "" );
trap_BotResetLastAvoidReach( bs->ms );
bs->ainode = AINode_Battle_Fight;
}
/*
==================
AINode_Battle_Fight
==================
*/
int AINode_Battle_Fight( bot_state_t *bs ) {
int areanum;
aas_entityinfo_t entinfo;
bot_moveresult_t moveresult;
if ( BotIsObserver( bs ) ) {
AIEnter_Observer( bs );
return qfalse;
}
//if in the intermission
if ( BotIntermission( bs ) ) {
AIEnter_Intermission( bs );
return qfalse;
}
//respawn if dead
if ( BotIsDead( bs ) ) {
AIEnter_Respawn( bs );
return qfalse;
}
//if no enemy
if ( bs->enemy < 0 ) {
AIEnter_Seek_LTG( bs );
return qfalse;
}
//
BotEntityInfo( bs->enemy, &entinfo );
//if the enemy is dead
if ( bs->enemydeath_time ) {
if ( bs->enemydeath_time < trap_AAS_Time() - 1.5 ) {
bs->enemydeath_time = 0;
if ( bs->enemysuicide ) {
BotChat_EnemySuicide( bs );
}
if ( bs->lastkilledplayer == bs->enemy && BotChat_Kill( bs ) ) {
bs->stand_time = trap_AAS_Time() + BotChatTime( bs );
AIEnter_Stand( bs );
} else {
bs->ltg_time = 0;
AIEnter_Seek_LTG( bs );
}
return qfalse;
}
} else {
if ( EntityIsDead( &entinfo ) ) {
bs->enemydeath_time = trap_AAS_Time();
}
}
//if the enemy is invisible and not shooting the bot looses track easily
if ( EntityIsInvisible( &entinfo ) && !EntityIsShooting( &entinfo ) ) {
if ( random() < 0.2 ) {
AIEnter_Seek_LTG( bs );
return qfalse;
}
}
//update the reachability area and origin if possible
areanum = BotPointAreaNum( entinfo.origin );
if ( areanum && trap_AAS_AreaReachability( areanum ) ) {
VectorCopy( entinfo.origin, bs->lastenemyorigin );
bs->lastenemyareanum = areanum;
}
//update the attack inventory values
BotUpdateBattleInventory( bs, bs->enemy );
//if the bot's health decreased
if ( bs->lastframe_health > bs->inventory[INVENTORY_HEALTH] ) {
if ( BotChat_HitNoDeath( bs ) ) {
bs->stand_time = trap_AAS_Time() + BotChatTime( bs );
AIEnter_Stand( bs );
return qfalse;
}
}
//if the bot hit someone
if ( bs->cur_ps.persistant[PERS_HITS] > bs->lasthitcount ) {
if ( BotChat_HitNoKill( bs ) ) {
bs->stand_time = trap_AAS_Time() + BotChatTime( bs );
AIEnter_Stand( bs );
return qfalse;
}
}
//if the enemy is not visible
if ( !BotEntityVisible( bs->entitynum, bs->eye, bs->viewangles, 360, bs->enemy ) ) {
if ( BotWantsToChase( bs ) ) {
AIEnter_Battle_Chase( bs );
return qfalse;
} else {
AIEnter_Seek_LTG( bs );
return qfalse;
}
}
//use holdable items
BotBattleUseItems( bs );
//
bs->tfl = TFL_DEFAULT;
if ( bot_grapple.integer ) {
bs->tfl |= TFL_GRAPPLEHOOK;
}
//if in lava or slime the bot should be able to get out
if ( BotInLava( bs ) ) {
bs->tfl |= TFL_LAVA;
}
if ( BotInSlime( bs ) ) {
bs->tfl |= TFL_SLIME;
}
//
if ( BotCanAndWantsToRocketJump( bs ) ) {
bs->tfl |= TFL_ROCKETJUMP;
}
//choose the best weapon to fight with
BotChooseWeapon( bs );
//do attack movements
moveresult = BotAttackMove( bs, bs->tfl );
//if the movement failed
if ( moveresult.failure ) {
//reset the avoid reach, otherwise bot is stuck in current area
trap_BotResetAvoidReach( bs->ms );
//BotAI_Print(PRT_MESSAGE, "movement failure %d\n", moveresult.traveltype);
bs->ltg_time = 0;
}
//
BotAIBlocked( bs, &moveresult, qfalse );
//aim at the enemy
BotAimAtEnemy( bs );
//attack the enemy if possible
BotCheckAttack( bs );
//if the bot wants to retreat
if ( BotWantsToRetreat( bs ) ) {
AIEnter_Battle_Retreat( bs );
return qtrue;
}
return qtrue;
}
/*
==================
AIEnter_Battle_Chase
==================
*/
void AIEnter_Battle_Chase( bot_state_t *bs ) {
BotRecordNodeSwitch( bs, "battle chase", "" );
bs->chase_time = trap_AAS_Time();
bs->ainode = AINode_Battle_Chase;
}
/*
==================
AINode_Battle_Chase
==================
*/
int AINode_Battle_Chase( bot_state_t *bs ) {
bot_goal_t goal;
vec3_t target, dir;
bot_moveresult_t moveresult;
float range;
if ( BotIsObserver( bs ) ) {
AIEnter_Observer( bs );
return qfalse;
}
//if in the intermission
if ( BotIntermission( bs ) ) {
AIEnter_Intermission( bs );
return qfalse;
}
//respawn if dead
if ( BotIsDead( bs ) ) {
AIEnter_Respawn( bs );
return qfalse;
}
//if no enemy
if ( bs->enemy < 0 ) {
AIEnter_Seek_LTG( bs );
return qfalse;
}
//if the enemy is visible
if ( BotEntityVisible( bs->entitynum, bs->eye, bs->viewangles, 360, bs->enemy ) ) {
AIEnter_Battle_Fight( bs );
return qfalse;
}
//if there is another enemy
if ( BotFindEnemy( bs, -1 ) ) {
AIEnter_Battle_Fight( bs );
return qfalse;
}
//there is no last enemy area
if ( !bs->lastenemyareanum ) {
AIEnter_Seek_LTG( bs );
return qfalse;
}
//
bs->tfl = TFL_DEFAULT;
if ( bot_grapple.integer ) {
bs->tfl |= TFL_GRAPPLEHOOK;
}
//if in lava or slime the bot should be able to get out
if ( BotInLava( bs ) ) {
bs->tfl |= TFL_LAVA;
}
if ( BotInSlime( bs ) ) {
bs->tfl |= TFL_SLIME;
}
//
if ( BotCanAndWantsToRocketJump( bs ) ) {
bs->tfl |= TFL_ROCKETJUMP;
}
//map specific code
BotMapScripts( bs );
//create the chase goal
goal.entitynum = bs->enemy;
goal.areanum = bs->lastenemyareanum;
VectorCopy( bs->lastenemyorigin, goal.origin );
VectorSet( goal.mins, -8, -8, -8 );
VectorSet( goal.maxs, 8, 8, 8 );
//if the last seen enemy spot is reached the enemy could not be found
if ( trap_BotTouchingGoal( bs->origin, &goal ) ) {
bs->chase_time = 0;
}
//if there's no chase time left
if ( !bs->chase_time || bs->chase_time < trap_AAS_Time() - 10 ) {
AIEnter_Seek_LTG( bs );
return qfalse;
}
//check for nearby goals periodicly
if ( bs->check_time < trap_AAS_Time() ) {
bs->check_time = trap_AAS_Time() + 1;
range = 150;
//
if ( BotNearbyGoal( bs, bs->tfl, &goal, range ) ) {
//the bot gets 5 seconds to pick up the nearby goal item
bs->nbg_time = trap_AAS_Time() + 0.1 * range + 1;
trap_BotResetLastAvoidReach( bs->ms );
AIEnter_Battle_NBG( bs );
return qfalse;
}
}
//
BotUpdateBattleInventory( bs, bs->enemy );
//initialize the movement state
BotSetupForMovement( bs );
//move towards the goal
trap_BotMoveToGoal( &moveresult, bs->ms, &goal, bs->tfl );
//if the movement failed
if ( moveresult.failure ) {
//reset the avoid reach, otherwise bot is stuck in current area
trap_BotResetAvoidReach( bs->ms );
//BotAI_Print(PRT_MESSAGE, "movement failure %d\n", moveresult.traveltype);
bs->ltg_time = 0;
}
//
BotAIBlocked( bs, &moveresult, qfalse );
//
if ( moveresult.flags & ( MOVERESULT_MOVEMENTVIEWSET | MOVERESULT_MOVEMENTVIEW | MOVERESULT_SWIMVIEW ) ) {
VectorCopy( moveresult.ideal_viewangles, bs->ideal_viewangles );
} else if ( !( bs->flags & BFL_IDEALVIEWSET ) ) {
if ( bs->chase_time > trap_AAS_Time() - 2 ) {
BotAimAtEnemy( bs );
} else {
if ( trap_BotMovementViewTarget( bs->ms, &goal, bs->tfl, 300, target ) ) {
VectorSubtract( target, bs->origin, dir );
vectoangles( dir, bs->ideal_viewangles );
} else {
vectoangles( moveresult.movedir, bs->ideal_viewangles );
}
}
bs->ideal_viewangles[2] *= 0.5;
}
//if the weapon is used for the bot movement
if ( moveresult.flags & MOVERESULT_MOVEMENTWEAPON ) {
bs->weaponnum = moveresult.weapon;
}
//if the bot is in the area the enemy was last seen in
if ( bs->areanum == bs->lastenemyareanum ) {
bs->chase_time = 0;
}
//if the bot wants to retreat (the bot could have been damage during the chase)
if ( BotWantsToRetreat( bs ) ) {
AIEnter_Battle_Retreat( bs );
return qtrue;
}
return qtrue;
}
/*
==================
AIEnter_Battle_Retreat
==================
*/
void AIEnter_Battle_Retreat( bot_state_t *bs ) {
BotRecordNodeSwitch( bs, "battle retreat", "" );
bs->ainode = AINode_Battle_Retreat;
}
/*
==================
AINode_Battle_Retreat
==================
*/
int AINode_Battle_Retreat( bot_state_t *bs ) {
bot_goal_t goal;
aas_entityinfo_t entinfo;
bot_moveresult_t moveresult;
vec3_t target, dir;
float attack_skill, range;
int areanum;
if ( BotIsObserver( bs ) ) {
AIEnter_Observer( bs );
return qfalse;
}
//if in the intermission
if ( BotIntermission( bs ) ) {
AIEnter_Intermission( bs );
return qfalse;
}
//respawn if dead
if ( BotIsDead( bs ) ) {
AIEnter_Respawn( bs );
return qfalse;
}
//if no enemy
if ( bs->enemy < 0 ) {
AIEnter_Seek_LTG( bs );
return qfalse;
}
//
BotEntityInfo( bs->enemy, &entinfo );
if ( EntityIsDead( &entinfo ) ) {
AIEnter_Seek_LTG( bs );
return qfalse;
}
//
bs->tfl = TFL_DEFAULT;
if ( bot_grapple.integer ) {
bs->tfl |= TFL_GRAPPLEHOOK;
}
//if in lava or slime the bot should be able to get out
if ( BotInLava( bs ) ) {
bs->tfl |= TFL_LAVA;
}
if ( BotInSlime( bs ) ) {
bs->tfl |= TFL_SLIME;
}
//map specific code
BotMapScripts( bs );
//update the attack inventory values
BotUpdateBattleInventory( bs, bs->enemy );
//if the bot doesn't want to retreat anymore... probably picked up some nice items
if ( BotWantsToChase( bs ) ) {
//empty the goal stack, when chasing, only the enemy is the goal
trap_BotEmptyGoalStack( bs->gs );
//go chase the enemy
AIEnter_Battle_Chase( bs );
return qfalse;
}
//update the last time the enemy was visible
if ( BotEntityVisible( bs->entitynum, bs->eye, bs->viewangles, 360, bs->enemy ) ) {
bs->enemyvisible_time = trap_AAS_Time();
//update the reachability area and origin if possible
areanum = BotPointAreaNum( entinfo.origin );
if ( areanum && trap_AAS_AreaReachability( areanum ) ) {
VectorCopy( entinfo.origin, bs->lastenemyorigin );
bs->lastenemyareanum = areanum;
}
}
//if the enemy is NOT visible for 4 seconds
if ( bs->enemyvisible_time < trap_AAS_Time() - 4 ) {
AIEnter_Seek_LTG( bs );
return qfalse;
}
//else if the enemy is NOT visible
else if ( bs->enemyvisible_time < trap_AAS_Time() ) {
//if there is another enemy
if ( BotFindEnemy( bs, -1 ) ) {
AIEnter_Battle_Fight( bs );
return qfalse;
}
}
//
#ifdef CTF
if ( gametype == GT_CTF ) {
BotCTFRetreatGoals( bs );
}
#endif //CTF
//use holdable items
BotBattleUseItems( bs );
//get the current long term goal while retreating
if ( !BotLongTermGoal( bs, bs->tfl, qtrue, &goal ) ) {
return qtrue;
}
//check for nearby goals periodicly
if ( bs->check_time < trap_AAS_Time() ) {
bs->check_time = trap_AAS_Time() + 1;
range = 150;
#ifdef CTF
//if carrying a flag the bot shouldn't be distracted too much
if ( BotCTFCarryingFlag( bs ) ) {
range = 100;
}
#endif //CTF
//
if ( BotNearbyGoal( bs, bs->tfl, &goal, range ) ) {
trap_BotResetLastAvoidReach( bs->ms );
//time the bot gets to pick up the nearby goal item
bs->nbg_time = trap_AAS_Time() + range / 100 + 1;
AIEnter_Battle_NBG( bs );
return qfalse;
}
}
//initialize the movement state
BotSetupForMovement( bs );
//move towards the goal
trap_BotMoveToGoal( &moveresult, bs->ms, &goal, bs->tfl );
//if the movement failed
if ( moveresult.failure ) {
//reset the avoid reach, otherwise bot is stuck in current area
trap_BotResetAvoidReach( bs->ms );
//BotAI_Print(PRT_MESSAGE, "movement failure %d\n", moveresult.traveltype);
bs->ltg_time = 0;
}
//
BotAIBlocked( bs, &moveresult, qfalse );
//choose the best weapon to fight with
BotChooseWeapon( bs );
//if the view is fixed for the movement
if ( moveresult.flags & ( MOVERESULT_MOVEMENTVIEW
//|MOVERESULT_SWIMVIEW
) ) {
VectorCopy( moveresult.ideal_viewangles, bs->ideal_viewangles );
} else if ( !( moveresult.flags & MOVERESULT_MOVEMENTVIEWSET )
&& !( bs->flags & BFL_IDEALVIEWSET ) ) {
attack_skill = trap_Characteristic_BFloat( bs->character, CHARACTERISTIC_ATTACK_SKILL, 0, 1 );
//if the bot is skilled anough
if ( attack_skill > 0.3 ) {
BotAimAtEnemy( bs );
} else {
if ( trap_BotMovementViewTarget( bs->ms, &goal, bs->tfl, 300, target ) ) {
VectorSubtract( target, bs->origin, dir );
vectoangles( dir, bs->ideal_viewangles );
} else {
vectoangles( moveresult.movedir, bs->ideal_viewangles );
}
bs->ideal_viewangles[2] *= 0.5;
}
}
//if the weapon is used for the bot movement
if ( moveresult.flags & MOVERESULT_MOVEMENTWEAPON ) {
bs->weaponnum = moveresult.weapon;
}
//attack the enemy if possible
BotCheckAttack( bs );
//
return qtrue;
}
/*
==================
AIEnter_Battle_NBG
==================
*/
void AIEnter_Battle_NBG( bot_state_t *bs ) {
BotRecordNodeSwitch( bs, "battle NBG", "" );
bs->ainode = AINode_Battle_NBG;
}
/*
==================
AINode_Battle_NBG
==================
*/
int AINode_Battle_NBG( bot_state_t *bs ) {
int areanum;
bot_goal_t goal;
aas_entityinfo_t entinfo;
bot_moveresult_t moveresult;
float attack_skill;
vec3_t target, dir;
if ( BotIsObserver( bs ) ) {
AIEnter_Observer( bs );
return qfalse;
}
//if in the intermission
if ( BotIntermission( bs ) ) {
AIEnter_Intermission( bs );
return qfalse;
}
//respawn if dead
if ( BotIsDead( bs ) ) {
AIEnter_Respawn( bs );
return qfalse;
}
//if no enemy
if ( bs->enemy < 0 ) {
AIEnter_Seek_NBG( bs );
return qfalse;
}
//
BotEntityInfo( bs->enemy, &entinfo );
if ( EntityIsDead( &entinfo ) ) {
AIEnter_Seek_NBG( bs );
return qfalse;
}
//
bs->tfl = TFL_DEFAULT;
if ( bot_grapple.integer ) {
bs->tfl |= TFL_GRAPPLEHOOK;
}
//if in lava or slime the bot should be able to get out
if ( BotInLava( bs ) ) {
bs->tfl |= TFL_LAVA;
}
if ( BotInSlime( bs ) ) {
bs->tfl |= TFL_SLIME;
}
//
if ( BotCanAndWantsToRocketJump( bs ) ) {
bs->tfl |= TFL_ROCKETJUMP;
}
//map specific code
BotMapScripts( bs );
//update the last time the enemy was visible
if ( BotEntityVisible( bs->entitynum, bs->eye, bs->viewangles, 360, bs->enemy ) ) {
bs->enemyvisible_time = trap_AAS_Time();
//update the reachability area and origin if possible
areanum = BotPointAreaNum( entinfo.origin );
if ( areanum && trap_AAS_AreaReachability( areanum ) ) {
VectorCopy( entinfo.origin, bs->lastenemyorigin );
bs->lastenemyareanum = areanum;
}
}
//if the bot has no goal or touches the current goal
if ( !trap_BotGetTopGoal( bs->gs, &goal ) ) {
bs->nbg_time = 0;
} else if ( trap_BotTouchingGoal( bs->origin, &goal ) ) {
bs->nbg_time = 0;
}
//
if ( bs->nbg_time < trap_AAS_Time() ) {
//pop the current goal from the stack
trap_BotPopGoal( bs->gs );
//if the bot still has a goal
if ( trap_BotGetTopGoal( bs->gs, &goal ) ) {
AIEnter_Battle_Retreat( bs );
} else { AIEnter_Battle_Fight( bs );}
//
return qfalse;
}
//initialize the movement state
BotSetupForMovement( bs );
//move towards the goal
trap_BotMoveToGoal( &moveresult, bs->ms, &goal, bs->tfl );
//if the movement failed
if ( moveresult.failure ) {
//reset the avoid reach, otherwise bot is stuck in current area
trap_BotResetAvoidReach( bs->ms );
//BotAI_Print(PRT_MESSAGE, "movement failure %d\n", moveresult.traveltype);
bs->nbg_time = 0;
}
//
BotAIBlocked( bs, &moveresult, qfalse );
//update the attack inventory values
BotUpdateBattleInventory( bs, bs->enemy );
//choose the best weapon to fight with
BotChooseWeapon( bs );
//if the view is fixed for the movement
if ( moveresult.flags & MOVERESULT_MOVEMENTVIEW ) {
VectorCopy( moveresult.ideal_viewangles, bs->ideal_viewangles );
} else if ( !( moveresult.flags & MOVERESULT_MOVEMENTVIEWSET )
&& !( bs->flags & BFL_IDEALVIEWSET ) ) {
attack_skill = trap_Characteristic_BFloat( bs->character, CHARACTERISTIC_ATTACK_SKILL, 0, 1 );
//if the bot is skilled anough and the enemy is visible
if ( attack_skill > 0.3 ) {
//&& BotEntityVisible(bs->entitynum, bs->eye, bs->viewangles, 360, bs->enemy)
BotAimAtEnemy( bs );
} else {
if ( trap_BotMovementViewTarget( bs->ms, &goal, bs->tfl, 300, target ) ) {
VectorSubtract( target, bs->origin, dir );
vectoangles( dir, bs->ideal_viewangles );
} else {
vectoangles( moveresult.movedir, bs->ideal_viewangles );
}
bs->ideal_viewangles[2] *= 0.5;
}
}
//if the weapon is used for the bot movement
if ( moveresult.flags & MOVERESULT_MOVEMENTWEAPON ) {
bs->weaponnum = moveresult.weapon;
}
//attack the enemy if possible
BotCheckAttack( bs );
//
return qtrue;
}
| 412 | 0.943826 | 1 | 0.943826 | game-dev | MEDIA | 0.81289 | game-dev | 0.986714 | 1 | 0.986714 |
liushijiegame/Fairygui-hybridCLR-YooAsset | 3,455 | Assets/Scripts/Core/Base/EventManager.cs | //------------------------------------------------------------
// Game Framework
// Copyright © 2013-2021 Jiang Yin. All rights reserved.
// Homepage: https://gameframework.cn/
// Feedback: mailto:ellan@gameframework.cn
//------------------------------------------------------------
using System;
using UnityEngine;
namespace GameFramework.Event
{
/// <summary>
/// 事件管理器。
/// </summary>
internal class EventManager : MonoBehaviour, IEventManager
{
private EventPool<GameEventArgs> m_EventPool;
public static EventManager Instance;
private void Awake()
{
if (Instance != null)
{
return;
}
m_EventPool = new EventPool<GameEventArgs>(EventPoolMode.AllowNoHandler | EventPoolMode.AllowMultiHandler);
Instance = this;
DontDestroyOnLoad(this);
}
/// <summary>
/// 获取事件处理函数的数量。
/// </summary>
public int EventHandlerCount => m_EventPool.EventHandlerCount;
/// <summary>
/// 获取事件数量。
/// </summary>
public int EventCount => m_EventPool.EventCount;
/// <summary>
/// 事件管理器轮询。
/// </summary>
private void Update()
{
m_EventPool.Update();
}
/// <summary>
/// 获取事件处理函数的数量。
/// </summary>
/// <param name="id">事件类型编号。</param>
/// <returns>事件处理函数的数量。</returns>
public int Count(int id)
{
return m_EventPool.Count(id);
}
/// <summary>
/// 检查是否存在事件处理函数。
/// </summary>
/// <param name="id">事件类型编号。</param>
/// <param name="handler">要检查的事件处理函数。</param>
/// <returns>是否存在事件处理函数。</returns>
public bool Check(int id, EventHandler<GameEventArgs> handler)
{
return m_EventPool.Check(id, handler);
}
/// <summary>
/// 订阅事件处理函数。
/// </summary>
/// <param name="id">事件类型编号。</param>
/// <param name="handler">要订阅的事件处理函数。</param>
public void Subscribe(int id, EventHandler<GameEventArgs> handler)
{
m_EventPool.Subscribe(id, handler);
}
/// <summary>
/// 取消订阅事件处理函数。
/// </summary>
/// <param name="id">事件类型编号。</param>
/// <param name="handler">要取消订阅的事件处理函数。</param>
public void Unsubscribe(int id, EventHandler<GameEventArgs> handler)
{
m_EventPool.Unsubscribe(id, handler);
}
/// <summary>
/// 设置默认事件处理函数。
/// </summary>
/// <param name="handler">要设置的默认事件处理函数。</param>
public void SetDefaultHandler(EventHandler<GameEventArgs> handler)
{
m_EventPool.SetDefaultHandler(handler);
}
/// <summary>
/// 抛出事件,这个操作是线程安全的,即使不在主线程中抛出,也可保证在主线程中回调事件处理函数,但事件会在抛出后的下一帧分发。
/// </summary>
/// <param name="sender">事件源。</param>
/// <param name="e">事件参数。</param>
public void Fire(object sender, GameEventArgs e)
{
m_EventPool.Fire(sender, e);
}
/// <summary>
/// 抛出事件立即模式,这个操作不是线程安全的,事件会立刻分发。
/// </summary>
/// <param name="sender">事件源。</param>
/// <param name="e">事件参数。</param>
public void FireNow(object sender, GameEventArgs e)
{
m_EventPool.FireNow(sender, e);
}
}
} | 412 | 0.711808 | 1 | 0.711808 | game-dev | MEDIA | 0.888854 | game-dev | 0.839888 | 1 | 0.839888 |
opentibiabr/canary | 1,900 | data-otservbr-global/npc/ferryman_kamil_meluna.lua | local internalNpcName = "Ferryman Kamil"
local npcType = Game.createNpcType("Ferryman Kamil (Meluna)")
local npcConfig = {}
npcConfig.name = internalNpcName
npcConfig.description = internalNpcName
npcConfig.health = 100
npcConfig.maxHealth = npcConfig.health
npcConfig.walkInterval = 2000
npcConfig.walkRadius = 2
npcConfig.outfit = {
lookType = 132,
lookHead = 0,
lookBody = 71,
lookLegs = 76,
lookFeet = 115,
lookAddons = 3,
}
npcConfig.flags = {
floorchange = false,
}
local keywordHandler = KeywordHandler:new()
local npcHandler = NpcHandler:new(keywordHandler)
npcType.onThink = function(npc, interval)
npcHandler:onThink(npc, interval)
end
npcType.onAppear = function(npc, creature)
npcHandler:onAppear(npc, creature)
end
npcType.onDisappear = function(npc, creature)
npcHandler:onDisappear(npc, creature)
end
npcType.onMove = function(npc, creature, fromPosition, toPosition)
npcHandler:onMove(npc, creature, fromPosition, toPosition)
end
npcType.onSay = function(npc, creature, type, message)
npcHandler:onSay(npc, creature, type, message)
end
npcType.onCloseChannel = function(npc, creature)
npcHandler:onCloseChannel(npc, creature)
end
-- Don't forget npcHandler = npcHandler in the parameters. It is required for all StdModule functions!
local travelNode = keywordHandler:addKeyword({ "fibula" }, StdModule.say, { npcHandler = npcHandler, text = "You want me to transport you and your spouse back to {Fibula}?" })
travelNode:addChildKeyword({ "yes" }, StdModule.travel, { npcHandler = npcHandler, premium = false, level = 0, cost = 0, destination = Position(32153, 32457, 7) })
travelNode:addChildKeyword({ "no" }, StdModule.say, { npcHandler = npcHandler, reset = true, text = "You shouldn't miss the experience." })
npcHandler:addModule(FocusModule:new(), npcConfig.name, true, true, true)
-- npcType registering the npcConfig table
npcType:register(npcConfig)
| 412 | 0.896275 | 1 | 0.896275 | game-dev | MEDIA | 0.930901 | game-dev | 0.783728 | 1 | 0.783728 |
FirelandsProject/firelands-cata | 2,559 | src/server/scripts/Kalimdor/BlackfathomDeeps/boss_aku_mai.cpp | /*
* This file is part of the FirelandsCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Affero 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 Affero General Public License for
* more details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptMgr.h"
#include "blackfathom_deeps.h"
#include "ScriptedCreature.h"
enum Spells
{
SPELL_POISON_CLOUD = 3815,
SPELL_FRENZIED_RAGE = 3490
};
enum Events
{
EVENT_POISON_CLOUD = 1,
EVENT_FRENZIED_RAGE
};
class boss_aku_mai : public CreatureScript
{
public:
boss_aku_mai() : CreatureScript("boss_aku_mai") { }
struct boss_aku_maiAI : public BossAI
{
boss_aku_maiAI(Creature* creature) : BossAI(creature, DATA_AKU_MAI)
{
Initialize();
}
void Initialize()
{
IsEnraged = false;
}
void Reset() override
{
Initialize();
_Reset();
}
void JustEngagedWith(Unit* who) override
{
BossAI::JustEngagedWith(who);
events.ScheduleEvent(EVENT_POISON_CLOUD, urand(5000, 9000));
}
void DamageTaken(Unit* /*atacker*/, uint32 &damage) override
{
if (!IsEnraged && me->HealthBelowPctDamaged(30, damage))
{
DoCast(me, SPELL_FRENZIED_RAGE);
IsEnraged = true;
}
}
void ExecuteEvent(uint32 eventId) override
{
switch (eventId)
{
case EVENT_POISON_CLOUD:
DoCastVictim(SPELL_POISON_CLOUD);
events.ScheduleEvent(EVENT_POISON_CLOUD, urand(25000, 50000));
break;
default:
break;
}
}
private:
bool IsEnraged;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetBlackfathomDeepsAI<boss_aku_maiAI>(creature);
}
};
void AddSC_boss_aku_mai()
{
new boss_aku_mai();
}
| 412 | 0.91659 | 1 | 0.91659 | game-dev | MEDIA | 0.955292 | game-dev | 0.831931 | 1 | 0.831931 |
pbghogehoge/kog | 1,430 | Source/CAtkGrpDraw.h | /*
* CAtkGrpDraw.h : 攻撃送り描画
*
*/
#ifndef CATKGRPDRAW_INCLUDED
#define CATKGRPDRAW_INCLUDED "攻撃送り描画 : Version 0.02 : Update 2001/09/25"
/* [更新履歴]
* Version 0.02 : 2001/09/25 : 大幅に変更
* Version 0.01 : 2001/07/28 : 製作開始(〆切間近)
*/
#include "Gian2001.h"
#include "ExAnm.h"
/***** [ 定数 ] *****/
#define AGTASK_MAX 30 // 同時発生可能なタスク数
#define AGTASK_KIND 2 // タスクの種類
#define AGTASK_NORMAL 0x00 // 通常状態(完全にスクリプトに従う)
#define AGTASK_DELETE 0x01 // 消去状態(勝手にフェードがかかる)
#define AGD_LV1 0x01 // レベル1攻撃
#define AGD_LV2 0x02 // レベル2攻撃
#define AGD_BOSS 0x03 // ボスアタック
#define AGD_WON 0x04 // 勝ち
/***** [クラス定義] *****/
class CAtkGrpDraw : public CFixedLList<CAnimeTask, AGTASK_KIND, AGTASK_MAX> {
public:
// 初期化する //
// arg : CharID このプレイヤーのキャラクタID //
// : pRivalAnm 相手プレイヤーのアニメ定義 //
FBOOL Initialize(int CharID, CAtkGrpDraw *pRivalAnm, BOOL Is2PColor);
FVOID Move(void); // 1フレーム動作させる
FVOID Draw(void); // 描画を行う
FBOOL Set(BYTE Level); // 親タスクを生成(以前のタスクにはフェードをかける)
// アニメーションタスクを追加 //
FBOOL SetTask(BYTE *pAddr, CAnimeDef *pAnimeDef, CAnimeTask *pParent);
CAtkGrpDraw(RECT *rcTargetX256, SCENE_ID SceneID); // コンストラクタ
~CAtkGrpDraw(); // デストラクタ
private:
int m_ox; // 画面中心のX座標
int m_oy; // 画面上端のY座標
CAnimeDef *m_pAnimeDef; // アニメーション定義
CAnimeDef *m_pRivalDef; // 相手側のアニメーション定義
SCENE_ID m_SceneID; // どちらの画面か
};
#endif
| 412 | 0.767015 | 1 | 0.767015 | game-dev | MEDIA | 0.754497 | game-dev | 0.503086 | 1 | 0.503086 |
emileb/OpenGames | 13,233 | opengames/src/main/jni/quake2/src/rsrc/m_actor.c | // g_actor.c
#include "g_local.h"
#include "m_actor.h"
#define MAX_ACTOR_NAMES 8
char *actor_names[MAX_ACTOR_NAMES] =
{
"Hellrot",
"Tokay",
"Killme",
"Disruptor",
"Adrianator",
"Rambear",
"Titus",
"Bitterman"
};
mframe_t actor_frames_stand [] =
{
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL,
ai_stand, 0, NULL
};
mmove_t actor_move_stand = {FRAME_stand101, FRAME_stand140, actor_frames_stand, NULL};
void actor_stand (edict_t *self)
{
self->monsterinfo.currentmove = &actor_move_stand;
// randomize on startup
if (level.time < 1.0)
self->s.frame = self->monsterinfo.currentmove->firstframe + (rand() % (self->monsterinfo.currentmove->lastframe - self->monsterinfo.currentmove->firstframe + 1));
}
mframe_t actor_frames_walk [] =
{
ai_walk, 0, NULL,
ai_walk, 6, NULL,
ai_walk, 10, NULL,
ai_walk, 3, NULL,
ai_walk, 2, NULL,
ai_walk, 7, NULL,
ai_walk, 10, NULL,
ai_walk, 1, NULL,
ai_walk, 4, NULL,
ai_walk, 0, NULL,
ai_walk, 0, NULL
};
mmove_t actor_move_walk = {FRAME_walk01, FRAME_walk08, actor_frames_walk, NULL};
void actor_walk (edict_t *self)
{
self->monsterinfo.currentmove = &actor_move_walk;
}
mframe_t actor_frames_run [] =
{
ai_run, 4, NULL,
ai_run, 15, NULL,
ai_run, 15, NULL,
ai_run, 8, NULL,
ai_run, 20, NULL,
ai_run, 15, NULL,
ai_run, 8, NULL,
ai_run, 17, NULL,
ai_run, 12, NULL,
ai_run, -2, NULL,
ai_run, -2, NULL,
ai_run, -1, NULL
};
mmove_t actor_move_run = {FRAME_run02, FRAME_run07, actor_frames_run, NULL};
void actor_run (edict_t *self)
{
if ((level.time < self->pain_debounce_time) && (!self->enemy))
{
if (self->movetarget)
actor_walk(self);
else
actor_stand(self);
return;
}
if (self->monsterinfo.aiflags & AI_STAND_GROUND)
{
actor_stand(self);
return;
}
self->monsterinfo.currentmove = &actor_move_run;
}
mframe_t actor_frames_pain1 [] =
{
ai_move, -5, NULL,
ai_move, 4, NULL,
ai_move, 1, NULL
};
mmove_t actor_move_pain1 = {FRAME_pain101, FRAME_pain103, actor_frames_pain1, actor_run};
mframe_t actor_frames_pain2 [] =
{
ai_move, -4, NULL,
ai_move, 4, NULL,
ai_move, 0, NULL
};
mmove_t actor_move_pain2 = {FRAME_pain201, FRAME_pain203, actor_frames_pain2, actor_run};
mframe_t actor_frames_pain3 [] =
{
ai_move, -1, NULL,
ai_move, 1, NULL,
ai_move, 0, NULL
};
mmove_t actor_move_pain3 = {FRAME_pain301, FRAME_pain303, actor_frames_pain3, actor_run};
mframe_t actor_frames_flipoff [] =
{
ai_turn, 0, NULL,
ai_turn, 0, NULL,
ai_turn, 0, NULL,
ai_turn, 0, NULL,
ai_turn, 0, NULL,
ai_turn, 0, NULL,
ai_turn, 0, NULL,
ai_turn, 0, NULL,
ai_turn, 0, NULL,
ai_turn, 0, NULL,
ai_turn, 0, NULL,
ai_turn, 0, NULL,
ai_turn, 0, NULL,
ai_turn, 0, NULL
};
mmove_t actor_move_flipoff = {FRAME_flip01, FRAME_flip14, actor_frames_flipoff, actor_run};
mframe_t actor_frames_taunt [] =
{
ai_turn, 0, NULL,
ai_turn, 0, NULL,
ai_turn, 0, NULL,
ai_turn, 0, NULL,
ai_turn, 0, NULL,
ai_turn, 0, NULL,
ai_turn, 0, NULL,
ai_turn, 0, NULL,
ai_turn, 0, NULL,
ai_turn, 0, NULL,
ai_turn, 0, NULL,
ai_turn, 0, NULL,
ai_turn, 0, NULL,
ai_turn, 0, NULL,
ai_turn, 0, NULL,
ai_turn, 0, NULL,
ai_turn, 0, NULL
};
mmove_t actor_move_taunt = {FRAME_taunt01, FRAME_taunt17, actor_frames_taunt, actor_run};
char *messages[] =
{
"Watch it",
"#$@*&",
"Idiot",
"Check your targets"
};
void actor_pain (edict_t *self, edict_t *other, float kick, int damage)
{
int n;
if (self->health < (self->max_health / 2))
self->s.skinnum = 1;
if (level.time < self->pain_debounce_time)
return;
self->pain_debounce_time = level.time + 3;
// gi.sound (self, CHAN_VOICE, actor.sound_pain, 1, ATTN_NORM, 0);
if ((other->client) && (random() < 0.4))
{
vec3_t v;
char *name;
VectorSubtract (other->s.origin, self->s.origin, v);
self->ideal_yaw = vectoyaw (v);
if (random() < 0.5)
self->monsterinfo.currentmove = &actor_move_flipoff;
else
self->monsterinfo.currentmove = &actor_move_taunt;
name = actor_names[(self - g_edicts)%MAX_ACTOR_NAMES];
gi.cprintf (other, PRINT_CHAT, "%s: %s!\n", name, messages[rand()%3]);
return;
}
n = rand() % 3;
if (n == 0)
self->monsterinfo.currentmove = &actor_move_pain1;
else if (n == 1)
self->monsterinfo.currentmove = &actor_move_pain2;
else
self->monsterinfo.currentmove = &actor_move_pain3;
}
void actorMachineGun (edict_t *self)
{
vec3_t start, target;
vec3_t forward, right;
AngleVectors (self->s.angles, forward, right, NULL);
G_ProjectSource (self->s.origin, monster_flash_offset[MZ2_ACTOR_MACHINEGUN_1], forward, right, start);
if (self->enemy)
{
if (self->enemy->health > 0)
{
VectorMA (self->enemy->s.origin, -0.2, self->enemy->velocity, target);
target[2] += self->enemy->viewheight;
}
else
{
VectorCopy (self->enemy->absmin, target);
target[2] += (self->enemy->size[2] / 2);
}
VectorSubtract (target, start, forward);
VectorNormalize (forward);
}
else
{
AngleVectors (self->s.angles, forward, NULL, NULL);
}
monster_fire_bullet (self, start, forward, 3, 4, DEFAULT_BULLET_HSPREAD, DEFAULT_BULLET_VSPREAD, MZ2_ACTOR_MACHINEGUN_1);
}
void actor_dead (edict_t *self)
{
VectorSet (self->mins, -16, -16, -24);
VectorSet (self->maxs, 16, 16, -8);
self->movetype = MOVETYPE_TOSS;
self->svflags |= SVF_DEADMONSTER;
self->nextthink = 0;
gi.linkentity (self);
}
mframe_t actor_frames_death1 [] =
{
ai_move, 0, NULL,
ai_move, 0, NULL,
ai_move, -13, NULL,
ai_move, 14, NULL,
ai_move, 3, NULL,
ai_move, -2, NULL,
ai_move, 1, NULL
};
mmove_t actor_move_death1 = {FRAME_death101, FRAME_death107, actor_frames_death1, actor_dead};
mframe_t actor_frames_death2 [] =
{
ai_move, 0, NULL,
ai_move, 7, NULL,
ai_move, -6, NULL,
ai_move, -5, NULL,
ai_move, 1, NULL,
ai_move, 0, NULL,
ai_move, -1, NULL,
ai_move, -2, NULL,
ai_move, -1, NULL,
ai_move, -9, NULL,
ai_move, -13, NULL,
ai_move, -13, NULL,
ai_move, 0, NULL
};
mmove_t actor_move_death2 = {FRAME_death201, FRAME_death213, actor_frames_death2, actor_dead};
void actor_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point)
{
int n;
// check for gib
if (self->health <= -80)
{
// gi.sound (self, CHAN_VOICE, actor.sound_gib, 1, ATTN_NORM, 0);
for (n= 0; n < 2; n++)
ThrowGib (self, "models/objects/gibs/bone/tris.md2", damage, GIB_ORGANIC);
for (n= 0; n < 4; n++)
ThrowGib (self, "models/objects/gibs/sm_meat/tris.md2", damage, GIB_ORGANIC);
ThrowHead (self, "models/objects/gibs/head2/tris.md2", damage, GIB_ORGANIC);
self->deadflag = DEAD_DEAD;
return;
}
if (self->deadflag == DEAD_DEAD)
return;
// regular death
// gi.sound (self, CHAN_VOICE, actor.sound_die, 1, ATTN_NORM, 0);
self->deadflag = DEAD_DEAD;
self->takedamage = DAMAGE_YES;
n = rand() % 2;
if (n == 0)
self->monsterinfo.currentmove = &actor_move_death1;
else
self->monsterinfo.currentmove = &actor_move_death2;
}
void actor_fire (edict_t *self)
{
actorMachineGun (self);
if (level.time >= self->monsterinfo.pausetime)
self->monsterinfo.aiflags &= ~AI_HOLD_FRAME;
else
self->monsterinfo.aiflags |= AI_HOLD_FRAME;
}
mframe_t actor_frames_attack [] =
{
ai_charge, -2, actor_fire,
ai_charge, -2, NULL,
ai_charge, 3, NULL,
ai_charge, 2, NULL
};
mmove_t actor_move_attack = {FRAME_attak01, FRAME_attak04, actor_frames_attack, actor_run};
void actor_attack(edict_t *self)
{
int n;
self->monsterinfo.currentmove = &actor_move_attack;
n = (rand() & 15) + 3 + 7;
self->monsterinfo.pausetime = level.time + n * FRAMETIME;
}
void actor_use (edict_t *self, edict_t *other, edict_t *activator)
{
vec3_t v;
self->goalentity = self->movetarget = G_PickTarget(self->target);
if ((!self->movetarget) || (strcmp(self->movetarget->classname, "target_actor") != 0))
{
gi.dprintf ("%s has bad target %s at %s\n", self->classname, self->target, vtos(self->s.origin));
self->target = NULL;
self->monsterinfo.pausetime = 100000000;
self->monsterinfo.stand (self);
return;
}
VectorSubtract (self->goalentity->s.origin, self->s.origin, v);
self->ideal_yaw = self->s.angles[YAW] = vectoyaw(v);
self->monsterinfo.walk (self);
self->target = NULL;
}
/*QUAKED misc_actor (1 .5 0) (-16 -16 -24) (16 16 32)
*/
void SP_misc_actor (edict_t *self)
{
if (deathmatch->value)
{
G_FreeEdict (self);
return;
}
if (!self->targetname)
{
gi.dprintf("untargeted %s at %s\n", self->classname, vtos(self->s.origin));
G_FreeEdict (self);
return;
}
if (!self->target)
{
gi.dprintf("%s with no target at %s\n", self->classname, vtos(self->s.origin));
G_FreeEdict (self);
return;
}
self->movetype = MOVETYPE_STEP;
self->solid = SOLID_BBOX;
self->s.modelindex = gi.modelindex("players/male/tris.md2");
VectorSet (self->mins, -16, -16, -24);
VectorSet (self->maxs, 16, 16, 32);
if (!self->health)
self->health = 100;
self->mass = 200;
self->pain = actor_pain;
self->die = actor_die;
self->monsterinfo.stand = actor_stand;
self->monsterinfo.walk = actor_walk;
self->monsterinfo.run = actor_run;
self->monsterinfo.attack = actor_attack;
self->monsterinfo.melee = NULL;
self->monsterinfo.sight = NULL;
self->monsterinfo.aiflags |= AI_GOOD_GUY;
gi.linkentity (self);
self->monsterinfo.currentmove = &actor_move_stand;
self->monsterinfo.scale = MODEL_SCALE;
walkmonster_start (self);
// actors always start in a dormant state, they *must* be used to get going
self->use = actor_use;
}
/*QUAKED target_actor (.5 .3 0) (-8 -8 -8) (8 8 8) JUMP SHOOT ATTACK x HOLD BRUTAL
JUMP jump in set direction upon reaching this target
SHOOT take a single shot at the pathtarget
ATTACK attack pathtarget until it or actor is dead
"target" next target_actor
"pathtarget" target of any action to be taken at this point
"wait" amount of time actor should pause at this point
"message" actor will "say" this to the player
for JUMP only:
"speed" speed thrown forward (default 200)
"height" speed thrown upwards (default 200)
*/
void target_actor_touch (edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf)
{
vec3_t v;
if (other->movetarget != self)
return;
if (other->enemy)
return;
other->goalentity = other->movetarget = NULL;
if (self->message)
{
int n;
edict_t *ent;
for (n = 1; n <= game.maxclients; n++)
{
ent = &g_edicts[n];
if (!ent->inuse)
continue;
gi.cprintf (ent, PRINT_CHAT, "%s: %s\n", actor_names[(other - g_edicts)%MAX_ACTOR_NAMES], self->message);
}
}
if (self->spawnflags & 1) //jump
{
other->velocity[0] = self->movedir[0] * self->speed;
other->velocity[1] = self->movedir[1] * self->speed;
if (other->groundentity)
{
other->groundentity = NULL;
other->velocity[2] = self->movedir[2];
gi.sound(other, CHAN_VOICE, gi.soundindex("player/male/jump1.wav"), 1, ATTN_NORM, 0);
}
}
if (self->spawnflags & 2) //shoot
{
}
else if (self->spawnflags & 4) //attack
{
other->enemy = G_PickTarget(self->pathtarget);
if (other->enemy)
{
other->goalentity = other->enemy;
if (self->spawnflags & 32)
other->monsterinfo.aiflags |= AI_BRUTAL;
if (self->spawnflags & 16)
{
other->monsterinfo.aiflags |= AI_STAND_GROUND;
actor_stand (other);
}
else
{
actor_run (other);
}
}
}
if (!(self->spawnflags & 6) && (self->pathtarget))
{
char *savetarget;
savetarget = self->target;
self->target = self->pathtarget;
G_UseTargets (self, other);
self->target = savetarget;
}
other->movetarget = G_PickTarget(self->target);
if (!other->goalentity)
other->goalentity = other->movetarget;
if (!other->movetarget && !other->enemy)
{
other->monsterinfo.pausetime = level.time + 100000000;
other->monsterinfo.stand (other);
}
else if (other->movetarget == other->goalentity)
{
VectorSubtract (other->movetarget->s.origin, other->s.origin, v);
other->ideal_yaw = vectoyaw (v);
}
}
void SP_target_actor (edict_t *self)
{
if (!self->targetname)
gi.dprintf ("%s with no targetname at %s\n", self->classname, vtos(self->s.origin));
self->solid = SOLID_TRIGGER;
self->touch = target_actor_touch;
VectorSet (self->mins, -8, -8, -8);
VectorSet (self->maxs, 8, 8, 8);
self->svflags = SVF_NOCLIENT;
if (self->spawnflags & 1)
{
if (!self->speed)
self->speed = 200;
if (!st.height)
st.height = 200;
if (self->s.angles[YAW] == 0)
self->s.angles[YAW] = 360;
G_SetMovedir (self->s.angles, self->movedir);
self->movedir[2] = st.height;
}
gi.linkentity (self);
}
| 412 | 0.616645 | 1 | 0.616645 | game-dev | MEDIA | 0.982441 | game-dev | 0.947782 | 1 | 0.947782 |
mbaske/grid-sensor | 9,329 | Assets/Scripts/Sensors/Grid/GameObject/Detection/GameObjectSettings.cs | using System.Linq;
using System.Collections.Generic;
using UnityEngine;
using NaughtyAttributes;
namespace MBaske.Sensors.Grid
{
/// <summary>
/// What to detect about a <see cref="DetectableGameObject"/>:
/// <see cref="Position"/> - Transform position
/// <see cref="ClosestPoint"/> - Closest point on collider(s)
/// <see cref="Shape"/> - Set of points matching its shape
/// </summary>
public enum PointDetectionType
{
Position, ClosestPoint, Shape
}
/// <summary>
/// Detection settings for a <see cref="DetectableGameObject"/> type (tag).
/// A <see cref="DetectableGameObject"/> type is defined by its tag. Multiple sensors can
/// use different <see cref="PointDetectionType"/>s, <see cref="PointModifier"/>s and
/// <see cref="Observable"/>s for the same <see cref="DetectableGameObject"/> type.
/// </summary>
[System.Serializable]
public class GameObjectSettings
{
/// <summary>
/// The gameobject's tag.
/// Although marked as hidden, it is displayed as the list item name.
/// </summary>
[HideInInspector]
public string Tag;
/// <summary>
/// Whether this <see cref="DetectableGameObject"/> type is included in sensor observations.
/// Note that changing this after the sensor is created has no effect.
/// </summary>
[Tooltip("Whether this detectable object type is included in sensor observations.")]
public bool Enabled = true;
/// <summary>
/// What to detect about a <see cref="DetectableGameObject"/>.
/// </summary>
[Tooltip("What to detect about the gameobject.")]
public PointDetectionType DetectionType;
// Flag for inspector enable.
private bool UsesShapeDetection => DetectionType == PointDetectionType.Shape;
/// <summary>
/// How to fill space between points for <see cref="PointDetectionType.Shape"/>
/// Note that changing this after the sensor is created has no effect.
/// </summary>
[ShowIf("UsesShapeDetection")]
[AllowNesting]
[Tooltip("How to fill space between points\nfor Detection Type = Shape.")]
public PointModifierType Modifier;
/// <summary>
/// The <see cref="DetectableGameObject"/> the settings are associated with.
///
/// Note that the field refers to a concrete instance (which was dragged
/// onto the inspector field), because the settings object needs to read
/// its tag and observables. However, the settings subsequently apply to
/// ALL <see cref="DetectableGameObject"/> instances sharing the same tag.
/// </summary>
[HideInInspector]
public DetectableGameObject Detectable;
// Copy of original observables created by the DetectableGameObject.
[SerializeField, HideInInspector]
private ObservableCollection m_UserObservables;
// List of user defined + dedicated observables. Items can be
// enabled/disabled and reordered. Determines encoding of observables.
[SerializeField]
[Tooltip("A detectable gameobject requires at least one observable.")]
private List<Observable> m_Observables = new List<Observable>();
[SerializeField, HideInInspector]
private DetectorSpaceType m_DetectorSpaceType;
/// <summary>
/// Creates the <see cref="GameObjectSettings"/> instance.
/// </summary>
/// <param name="detectable"><see cref="DetectableGameObject"/>
/// the <see cref="GameObjectSettings"/> apply to</param>
public GameObjectSettings(DetectableGameObject detectable, DetectorSpaceType detectorSpaceType)
{
Detectable = detectable;
m_DetectorSpaceType = detectorSpaceType;
}
/// <summary>
/// Validates the <see cref="GameObjectSettings"/> instance.
/// </summary>
public void Validate()
{
// Tag might have changed.
Tag = Detectable.Tag;
CheckUserObservablesChanged();
int n = m_Observables.Count;
if (n == 0)
{
// New or emptied settings:
// Will add distance (3D) or one-hot (2D) as default.
AddDedicatedObservable();
}
else
{
CheckDuplicateEntry(n);
}
ValidateDistanceObservableIndex();
}
/// <summary>
/// Enumerates enabled <see cref="Observable"/>s.
/// Will tell the <see cref="Encoder"/> which
/// <see cref="Observable"/>s to query an in what order.
/// </summary>
/// <returns><see cref="Observable"/> enumeration</returns>
public IEnumerable<Observable> GetEnabledObservables()
{
foreach (var obs in m_Observables)
{
if (obs.Enabled)
{
yield return obs;
}
}
}
private void CheckUserObservablesChanged()
{
// Re-initialize in case of code changes.
var current = Detectable.InitObservables();
if (!current.Equals(m_UserObservables))
{
bool hasDistance = HasObservableType(ObservableType.Distance);
bool hasOneHot = HasObservableType(ObservableType.OneHot);
m_UserObservables = current.Copy();
// Overwrite with changed...
m_UserObservables.CopyTo(m_Observables);
// and re-add dedicated.
if (hasDistance)
{
AddDedicatedObservable();
}
if (hasOneHot)
{
AddDedicatedObservable();
}
}
}
// User can press list + for adding dedicated observables
// or for re-adding previously removed user observables.
private void CheckDuplicateEntry(int n)
{
bool HasDuplicate = n > 1 &&
m_Observables[n - 1].Name == m_Observables[n - 2].Name;
if (HasDuplicate)
{
// NOTE RemoveAt(n - 1) must come AFTER 'can add'
// checks, but BEFORE adding new observables.
if (CanAddDistanceObservable())
{
// Replace duplicate with distance.
m_Observables.RemoveAt(n - 1);
AddDedicatedObservable();
}
else if (CanAddUserObservable(out Observable obs))
{
// Replace duplicate with user observable.
m_Observables.RemoveAt(n - 1);
m_Observables.Add(obs);
}
else if (CanAddOneHotObservable())
{
// Replace duplicate with one-hot.
m_Observables.RemoveAt(n - 1);
AddDedicatedObservable();
}
else
{
// Nothing to add.
m_Observables.RemoveAt(n - 1);
}
}
}
private void AddDedicatedObservable()
{
// Distance can only be added to 3D.
if (CanAddDistanceObservable())
{
m_Observables.Insert(0,
new Observable(ObservableType.Distance, Observable.Distance));
// Add one at a time.
return;
}
// One-Hot can be added to 3D and 2D.
if (CanAddOneHotObservable())
{
m_Observables.Add(
new Observable(ObservableType.OneHot, Observable.OneHot));
}
}
private bool CanAddDistanceObservable()
{
return m_DetectorSpaceType == DetectorSpaceType.Sphere &&
!HasObservableType(ObservableType.Distance);
}
private bool CanAddOneHotObservable()
{
return !HasObservableType(ObservableType.OneHot);
}
private bool CanAddUserObservable(out Observable next)
{
if (m_UserObservables.ContainsOtherThan(
m_Observables, out IList <Observable> list))
{
next = list[0];
return true;
}
next = null;
return false;
}
// NOTE Distance always comes first.
// User might have switched entries.
private void ValidateDistanceObservableIndex()
{
int index = m_Observables.FindIndex(
o => o.Type == ObservableType.Distance);
if (index > 0)
{
var obs = m_Observables[index];
m_Observables.RemoveAt(index);
m_Observables.Insert(0, obs);
Debug.LogWarning("Reordering observables: distance needs to come first.");
}
}
private bool HasObservableType(ObservableType type)
{
return m_Observables.Any(o => o.Type == type);
}
}
} | 412 | 0.903225 | 1 | 0.903225 | game-dev | MEDIA | 0.381422 | game-dev | 0.796373 | 1 | 0.796373 |
tempestphp/highlight | 9,306 | src/Themes/TerminalStyle.php | <?php
declare(strict_types=1);
namespace Tempest\Highlight\Themes;
enum TerminalStyle: string
{
case ESC = "\033[";
case RESET = "0m";
case RESET_INTENSITY = "22m";
case RESET_ITALIC = "23m";
case RESET_UNDERLINE = "24m";
case RESET_OVERLINE = "55m";
case RESET_STRIKETHROUGH = "29m";
case RESET_REVERSE_TEXT = "27m";
case RESET_BACKGROUND = "49m";
case RESET_FOREGROUND = "39m";
case VISIBLE = "28m";
case FG_BLACK = "30m";
case FG_DARK_RED = "31m";
case FG_DARK_GREEN = "32m";
case FG_DARK_YELLOW = "33m";
case FG_DARK_BLUE = "34m";
case FG_DARK_MAGENTA = "35m";
case FG_DARK_CYAN = "36m";
case FG_LIGHT_GRAY = "37m";
case FG_GRAY = "90m";
case FG_RED = "91m";
case FG_GREEN = "92m";
case FG_YELLOW = "93m";
case FG_BLUE = "94m";
case FG_MAGENTA = "95m";
case FG_CYAN = "96m";
case FG_WHITE = "97m";
case BG_BLACK = "40m";
case BG_DARK_RED = "41m";
case BG_DARK_GREEN = "42m";
case BG_DARK_YELLOW = "43m";
case BG_DARK_BLUE = "44m";
case BG_DARK_MAGENTA = "45m";
case BG_DARK_CYAN = "46m";
case BG_LIGHT_GRAY = "47m";
case BG_GRAY = "100m";
case BG_RED = "101m";
case BG_GREEN = "102m";
case BG_YELLOW = "103m";
case BG_BLUE = "104m";
case BG_MAGENTA = "105m";
case BG_CYAN = "106m";
case BG_WHITE = "107m";
case BOLD = "1m";
case DIM = "2m";
case ITALIC = "3m";
case UNDERLINE = "4m";
case OVERLINE = "53m";
case HIDDEN = "8m";
case STRIKETHROUGH = "9m";
case REVERSE_TEXT = "7m";
public static function STYLE(self $style, string $text): string
{
return self::ESC->value . $style->value . $text;
}
public static function RESET(string $text = ''): string
{
return $text . self::ESC->value . self::RESET->value;
}
public static function FG_BLACK(string $text = ''): string
{
return self::ESC->value . self::FG_BLACK->value . $text . self::ESC->value . self::RESET->value;
}
public static function FG_DARK_RED(string $text = ''): string
{
return self::ESC->value . self::FG_DARK_RED->value . $text . self::ESC->value . self::RESET->value;
}
public static function FG_DARK_GREEN(string $text = ''): string
{
return self::ESC->value . self::FG_DARK_GREEN->value . $text . self::ESC->value . self::RESET->value;
}
public static function FG_DARK_YELLOW(string $text = ''): string
{
return self::ESC->value . self::FG_DARK_YELLOW->value . $text . self::ESC->value . self::RESET->value;
}
public static function FG_DARK_BLUE(string $text = ''): string
{
return self::ESC->value . self::FG_DARK_BLUE->value . $text . self::ESC->value . self::RESET->value;
}
public static function FG_DARK_MAGENTA(string $text = ''): string
{
return self::ESC->value . self::FG_DARK_MAGENTA->value . $text . self::ESC->value . self::RESET->value;
}
public static function FG_DARK_CYAN(string $text = ''): string
{
return self::ESC->value . self::FG_DARK_CYAN->value . $text . self::ESC->value . self::RESET->value;
}
public static function FG_LIGHT_GRAY(string $text = ''): string
{
return self::ESC->value . self::FG_LIGHT_GRAY->value . $text . self::ESC->value . self::RESET->value;
}
public static function FG_GRAY(string $text = ''): string
{
return self::ESC->value . self::FG_GRAY->value . $text . self::ESC->value . self::RESET->value;
}
public static function FG_RED(string $text = ''): string
{
return self::ESC->value . self::FG_RED->value . $text . self::ESC->value . self::RESET->value;
}
public static function FG_GREEN(string $text = ''): string
{
return self::ESC->value . self::FG_GREEN->value . $text . self::ESC->value . self::RESET->value;
}
public static function FG_YELLOW(string $text = ''): string
{
return self::ESC->value . self::FG_YELLOW->value . $text . self::ESC->value . self::RESET->value;
}
public static function FG_BLUE(string $text = ''): string
{
return self::ESC->value . self::FG_BLUE->value . $text . self::ESC->value . self::RESET->value;
}
public static function FG_MAGENTA(string $text = ''): string
{
return self::ESC->value . self::FG_MAGENTA->value . $text . self::ESC->value . self::RESET->value;
}
public static function FG_CYAN(string $text = ''): string
{
return self::ESC->value . self::FG_CYAN->value . $text . self::ESC->value . self::RESET->value;
}
public static function FG_WHITE(string $text = ''): string
{
return self::ESC->value . self::FG_WHITE->value . $text . self::ESC->value . self::RESET->value;
}
public static function BG_BLACK(string $text = ''): string
{
return self::ESC->value . self::BG_BLACK->value . $text . self::ESC->value . self::RESET->value;
}
public static function BG_DARK_RED(string $text = ''): string
{
return self::ESC->value . self::BG_DARK_RED->value . $text . self::ESC->value . self::RESET->value;
}
public static function BG_DARK_GREEN(string $text = ''): string
{
return self::ESC->value . self::BG_DARK_GREEN->value . $text . self::ESC->value . self::RESET->value;
}
public static function BG_DARK_YELLOW(string $text = ''): string
{
return self::ESC->value . self::BG_DARK_YELLOW->value . $text . self::ESC->value . self::RESET->value;
}
public static function BG_DARK_BLUE(string $text = ''): string
{
return self::ESC->value . self::BG_DARK_BLUE->value . $text . self::ESC->value . self::RESET->value;
}
public static function BG_DARK_MAGENTA(string $text = ''): string
{
return self::ESC->value . self::BG_DARK_MAGENTA->value . $text . self::ESC->value . self::RESET->value;
}
public static function BG_DARK_CYAN(string $text = ''): string
{
return self::ESC->value . self::BG_DARK_CYAN->value . $text . self::ESC->value . self::RESET->value;
}
public static function BG_LIGHT_GRAY(string $text = ''): string
{
return self::ESC->value . self::BG_LIGHT_GRAY->value . $text . self::ESC->value . self::RESET->value;
}
public static function BG_GRAY(string $text = ''): string
{
return self::ESC->value . self::BG_GRAY->value . $text . self::ESC->value . self::RESET->value;
}
public static function BG_RED(string $text = ''): string
{
return self::ESC->value . self::BG_RED->value . $text . self::ESC->value . self::RESET->value;
}
public static function BG_GREEN(string $text = ''): string
{
return self::ESC->value . self::BG_GREEN->value . $text . self::ESC->value . self::RESET->value;
}
public static function BG_YELLOW(string $text = ''): string
{
return self::ESC->value . self::BG_YELLOW->value . $text . self::ESC->value . self::RESET->value;
}
public static function BG_BLUE(string $text = ''): string
{
return self::ESC->value . self::BG_BLUE->value . $text . self::ESC->value . self::RESET->value;
}
public static function BG_MAGENTA(string $text = ''): string
{
return self::ESC->value . self::BG_MAGENTA->value . $text . self::ESC->value . self::RESET->value;
}
public static function BG_CYAN(string $text = ''): string
{
return self::ESC->value . self::BG_CYAN->value . $text . self::ESC->value . self::RESET->value;
}
public static function BG_WHITE(string $text = ''): string
{
return self::ESC->value . self::BG_WHITE->value . $text . self::ESC->value . self::RESET->value;
}
public static function BOLD(string $text = ''): string
{
return self::ESC->value . self::BOLD->value . $text . self::ESC->value . self::RESET_INTENSITY->value;
}
public static function DIM(string $text = ''): string
{
return self::ESC->value . self::DIM->value . $text . self::ESC->value . self::RESET_INTENSITY->value;
}
public static function ITALIC(string $text = ''): string
{
return self::ESC->value . self::ITALIC->value . $text . self::ESC->value . self::RESET_ITALIC->value;
}
public static function UNDERLINE(string $text = ''): string
{
return self::ESC->value . self::UNDERLINE->value . $text . self::ESC->value . self::RESET_UNDERLINE->value;
}
public static function OVERLINE(string $text = ''): string
{
return self::ESC->value . self::OVERLINE->value . $text . self::ESC->value . self::RESET_OVERLINE->value;
}
public static function HIDDEN(string $text = ''): string
{
return self::ESC->value . self::HIDDEN->value . $text . self::ESC->value . self::VISIBLE->value;
}
public static function STRIKETHROUGH(string $text = ''): string
{
return self::ESC->value . self::STRIKETHROUGH->value . $text . self::ESC->value . self::RESET_STRIKETHROUGH->value;
}
public static function REVERSE_TEXT(string $text = ''): string
{
return self::ESC->value . self::REVERSE_TEXT->value . $text . self::ESC->value . self::RESET_REVERSE_TEXT->value;
}
}
| 412 | 0.655226 | 1 | 0.655226 | game-dev | MEDIA | 0.865154 | game-dev | 0.500056 | 1 | 0.500056 |
jinmin527/learning-cuda-trt | 1,741 | tensorrt-basic-1.10-3rd-plugin/TensorRT-main/samples/sampleNMT/model/componentWeights.cpp | /*
* Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "common.h"
#include "componentWeights.h"
#include <string>
namespace nmtSample
{
std::istream& operator>>(std::istream& input, ComponentWeights& value)
{
std::string footerString("trtsamplenmt");
size_t footerSize = sizeof(int32_t) + footerString.size();
char* footer = (char*) malloc(footerSize);
input.seekg(0, std::ios::end);
size_t fileSize = input.tellg();
input.seekg(-footerSize, std::ios::end);
input.read(footer, footerSize);
size_t metaDataCount = ((int32_t*) footer)[0];
std::string str(footer + sizeof(int32_t), footer + footerSize);
ASSERT(footerString.compare(str) == 0);
free(footer);
input.seekg(-(footerSize + metaDataCount * sizeof(int32_t)), std::ios::end);
value.mMetaData.resize(metaDataCount);
size_t metaSize = metaDataCount * sizeof(int32_t);
input.read((char*) (&value.mMetaData[0]), metaSize);
size_t dataSize = fileSize - footerSize - metaSize;
input.seekg(0, input.beg);
value.mWeights.resize(dataSize);
input.read(&value.mWeights[0], dataSize);
return input;
}
} // namespace nmtSample
| 412 | 0.795779 | 1 | 0.795779 | game-dev | MEDIA | 0.286771 | game-dev | 0.516469 | 1 | 0.516469 |
FredTungsten/ScriptPlayer | 3,440 | ScriptPlayer/ScriptPlayer/Generators/GeneratorJob.cs | namespace ScriptPlayer.Generators
{
public abstract class GeneratorJob : IGeneratorJobWithFfmpegSettings
{
public abstract GeneratorEntry Entry { get; }
public abstract void CheckSkip();
public abstract GeneratorResult Process();
public abstract GeneratorEntry CreateEntry();
public abstract void Cancel();
public abstract bool HasIdenticalSettings(GeneratorJob job);
public abstract bool HasIdenticalSettings(FfmpegGeneratorSettings settings);
public abstract string VideoFileName { get; }
public abstract FfmpegGeneratorSettings GetSettings();
}
public interface IGeneratorJobWithFfmpegSettings
{
string VideoFileName { get; }
FfmpegGeneratorSettings GetSettings();
}
public class GeneratorJob<TSettings, TEntry> : GeneratorJob, IGeneratorJobWithFfmpegSettings where TEntry : GeneratorEntry where TSettings : FfmpegGeneratorSettings
{
private readonly TSettings _settings;
private TEntry _entry;
private bool _skip;
private bool _cancelled;
public GeneratorJob(TSettings settings, IGenerator<TSettings, TEntry> generator)
{
_settings = settings;
Generator = generator;
}
public IGenerator<TSettings, TEntry> Generator { get; set; }
public override GeneratorEntry Entry => _entry;
public override void CheckSkip()
{
_skip = Generator.CheckSkip(_settings);
if (!_skip) return;
_entry.Update("Skipped", 1);
_entry.DoneType = JobDoneTypes.Skipped;
_entry.State = JobStates.Done;
}
public override GeneratorResult Process()
{
if (!_skip && !_cancelled)
{
if (_settings.RenameBeforeExecute != null)
{
if(!_settings.RenameBeforeExecute.RenameNow())
return GeneratorResult.Failed();
}
return Generator.Process(_settings, _entry);
}
return GeneratorResult.Failed();
}
public override GeneratorEntry CreateEntry()
{
_entry = Generator.CreateEntry(_settings);
_entry.Job = this;
return _entry;
}
public override void Cancel()
{
if (_cancelled)
return;
_entry.Update("Cancelled", 1);
_entry.DoneType = JobDoneTypes.Cancelled;
_entry.State = JobStates.Done;
_cancelled = true;
Generator.Cancel();
}
public override bool HasIdenticalSettings(GeneratorJob job)
{
if (!(job is IGeneratorJobWithFfmpegSettings jobWithSettings))
return false;
return _settings.IsIdenticalTo(jobWithSettings.GetSettings());
}
public override bool HasIdenticalSettings(FfmpegGeneratorSettings settings)
{
if ((_settings == null) != (settings == null))
return false;
if (_settings == null)
return true;
return _settings.IsIdenticalTo(settings);
}
public override string VideoFileName => _settings.VideoFile;
public override FfmpegGeneratorSettings GetSettings()
{
return _settings;
}
}
} | 412 | 0.771057 | 1 | 0.771057 | game-dev | MEDIA | 0.214523 | game-dev | 0.507968 | 1 | 0.507968 |
mikejsavage/cocainediesel | 27,945 | source/cgame/cg_ents.cpp | /*
Copyright (C) 2002-2003 Victor Luchits
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "cgame/cg_local.h"
#include "qcommon/time.h"
#include "client/audio/api.h"
#include "client/renderer/renderer.h"
#include "client/renderer/text.h"
static void CG_UpdateEntities();
static bool CG_UpdateLinearProjectilePosition( centity_t *cent ) {
constexpr int MIN_DRAWDISTANCE_FIRSTPERSON = 86;
constexpr int MIN_DRAWDISTANCE_THIRDPERSON = 52;
SyncEntityState * state = ¢->current;
if( !state->linearMovement ) {
return false;
}
int64_t serverTime;
if( client_gs.gameState.paused ) {
serverTime = cg.frame.serverTime;
} else {
serverTime = cl.serverTime + cgs.extrapolationTime;
}
// TODO: see if commenting this out fixes non-lerped rockets while spectating
// const cmodel_t * cmodel = CM_TryFindCModel( CM_Client, state->model );
// if( cmodel == NULL ) {
// // add a time offset to counter antilag visualization
// if( !cgs.demoPlaying && cg_projectileAntilagOffset->number > 0.0f &&
// !ISVIEWERENTITY( state->ownerNum ) && ( cgs.playerNum + 1 != cg.predictedPlayerState.POVnum ) ) {
// serverTime += state->linearMovementTimeDelta * cg_projectileAntilagOffset->number;
// }
// }
Vec3 origin;
int moveTime = GS_LinearMovement( state, serverTime, &origin );
state->origin = origin;
if( moveTime < 0 ) {
// when flyTime is negative don't offset it backwards more than PROJECTILE_PRESTEP value
// FIXME: is this still valid?
float maxBackOffset;
if( ISVIEWERENTITY( state->ownerNum ) ) {
maxBackOffset = PROJECTILE_PRESTEP - MIN_DRAWDISTANCE_FIRSTPERSON;
} else {
maxBackOffset = PROJECTILE_PRESTEP - MIN_DRAWDISTANCE_THIRDPERSON;
}
if( Length( state->origin - state->origin2 ) > maxBackOffset ) {
return false;
}
}
return true;
}
static void CG_NewPacketEntityState( SyncEntityState *state ) {
centity_t * cent = &cg_entities[state->number];
cent->prevVelocity = Vec3( 0.0f );
cent->canExtrapolatePrev = false;
if( ISEVENTENTITY( state ) ) {
cent->prev = cent->current;
cent->current = *state;
cent->serverFrame = cg.frame.serverFrame;
cent->velocity = Vec3( 0.0f );
cent->canExtrapolate = false;
} else if( state->linearMovement ) {
if( cent->serverFrame != cg.oldFrame.serverFrame || state->teleported ||
state->linearMovement != cent->current.linearMovement || state->linearMovementTimeStamp != cent->current.linearMovementTimeStamp ) {
cent->prev = *state;
} else {
cent->prev = cent->current;
}
cent->current = *state;
cent->serverFrame = cg.frame.serverFrame;
cent->canExtrapolate = false;
cent->linearProjectileCanDraw = CG_UpdateLinearProjectilePosition( cent );
cent->velocity = cent->current.linearMovementVelocity;
cent->trailOrigin = cent->current.origin;
} else {
// if it moved too much force the teleported bit
if( Abs( cent->current.origin.x - state->origin.x ) > 512
|| Abs( cent->current.origin.y - state->origin.y ) > 512
|| Abs( cent->current.origin.z - state->origin.z ) > 512 ) {
cent->serverFrame = -99;
}
// some data changes will force no lerping
if( state->model != cent->current.model || state->teleported || state->linearMovement != cent->current.linearMovement ) {
cent->serverFrame = -99;
}
if( cent->serverFrame != cg.oldFrame.serverFrame ) {
// wasn't in last update, so initialize some things
// duplicate the current state so lerping doesn't hurt anything
cent->prev = *state;
memset( cent->localEffects, 0, sizeof( cent->localEffects ) );
// Init the animation when new into PVS
if( cg.frame.valid && ( state->type == ET_PLAYER || state->type == ET_CORPSE ) ) {
memset( cent->lastVelocities, 0, sizeof( cent->lastVelocities ) );
memset( cent->lastVelocitiesFrames, 0, sizeof( cent->lastVelocitiesFrames ) );
CG_PModel_ClearEventAnimations( state->number );
memset( &cg_entPModels[state->number].animState, 0, sizeof( cg_entPModels[state->number].animState ) );
}
} else { // shuffle the last state to previous
cent->prev = cent->current;
}
if( cent->serverFrame != cg.oldFrame.serverFrame ) {
cent->microSmooth = 0;
}
cent->current = *state;
cent->trailOrigin = state->origin;
cent->prevVelocity = cent->velocity;
cent->canExtrapolatePrev = cent->canExtrapolate;
cent->canExtrapolate = false;
cent->serverFrame = cg.frame.serverFrame;
// set up velocities for this entity
if( cgs.extrapolationTime &&
( cent->current.type == ET_PLAYER || cent->current.type == ET_CORPSE ) ) {
cent->velocity = cent->current.origin2;
cent->prevVelocity = cent->prev.origin2;
cent->canExtrapolate = cent->canExtrapolatePrev = true;
} else if( cent->prev.origin != cent->current.origin ) {
float snapTime = ( cg.frame.serverTime - cg.oldFrame.serverTime );
if( !snapTime ) {
snapTime = cgs.snapFrameTime;
}
cent->velocity = ( cent->current.origin - cent->prev.origin ) * 1000.0f / snapTime;
} else {
cent->velocity = Vec3( 0.0f );
}
if( ( cent->current.type == ET_GENERIC || cent->current.type == ET_PLAYER
|| cent->current.type == ET_LAUNCHER
|| cent->current.type == ET_CORPSE || cent->current.type == ET_FLASH ) ) {
cent->canExtrapolate = true;
}
}
}
int CG_LostMultiviewPOV() {
int best = client_gs.maxclients;
int index = -1;
int fallback = -1;
for( int i = 0; i < cg.frame.numplayers; i++ ) {
int value = Abs( (int)cg.frame.playerStates[i].playerNum - (int)cg.multiviewPlayerNum );
if( value == best && i > index ) {
continue;
}
if( value < best ) {
if( cg.frame.playerStates[i].pmove.pm_type == PM_SPECTATOR ) {
fallback = i;
continue;
}
best = value;
index = i;
}
}
return index > -1 ? index : fallback;
}
static void CG_SetFramePlayerState( snapshot_t *frame, int index ) {
frame->playerState = frame->playerStates[index];
if( cgs.demoPlaying || cg.frame.multipov ) {
frame->playerState.pmove.pm_flags |= PMF_NO_PREDICTION;
if( frame->playerState.pmove.pm_type != PM_SPECTATOR ) {
frame->playerState.pmove.pm_type = PM_CHASECAM;
}
}
}
static void CG_UpdatePlayerState() {
int index = 0;
if( cg.frame.multipov ) {
// find the playerState containing our current POV, then cycle playerStates
index = -1;
for( int i = 0; i < cg.frame.numplayers; i++ ) {
if( cg.frame.playerStates[i].playerNum < (unsigned)client_gs.maxclients
&& cg.frame.playerStates[i].playerNum == cg.multiviewPlayerNum ) {
index = i;
break;
}
}
// the POV was lost, find the closer one (may go up or down, but who cares)
if( index < 0 || cg.frame.playerStates[index].pmove.pm_type == PM_SPECTATOR ) {
index = CG_LostMultiviewPOV();
}
if( index < 0 ) {
index = 0;
}
}
cg.multiviewPlayerNum = cg.frame.playerStates[index].playerNum;
// set up the playerstates
// current
CG_SetFramePlayerState( &cg.frame, index );
// old
index = -1;
for( int i = 0; i < cg.oldFrame.numplayers; i++ ) {
if( cg.oldFrame.playerStates[i].playerNum == cg.multiviewPlayerNum ) {
index = i;
break;
}
}
// use the current one for old frame too, if correct POV wasn't found
if( index == -1 ) {
cg.oldFrame.playerState = cg.frame.playerState;
} else {
CG_SetFramePlayerState( &cg.oldFrame, index );
}
cg.predictedPlayerState = cg.frame.playerState;
}
/*
* CG_NewFrameSnap
* a new frame snap has been received from the server
*/
bool CG_NewFrameSnap( snapshot_t *frame, snapshot_t *lerpframe ) {
TracyZoneScoped;
Assert( frame );
if( lerpframe ) {
cg.oldFrame = *lerpframe;
} else {
cg.oldFrame = *frame;
}
cg.frame = *frame;
client_gs.gameState = frame->gameState;
cl.map = FindMap( client_gs.gameState.map );
if( cl.map == NULL ) {
Com_Error( "You don't have the map" );
}
if( cg_projectileAntilagOffset->number > 1.0f || cg_projectileAntilagOffset->number < 0.0f ) {
Cvar_ForceSet( "cg_projectileAntilagOffset", cg_projectileAntilagOffset->default_value );
}
CG_UpdatePlayerState();
for( int i = 0; i < frame->numEntities; i++ ) {
CG_NewPacketEntityState( &frame->parsedEntities[ i % ARRAY_COUNT( frame->parsedEntities ) ] );
}
if( !cg.frame.valid ) {
return false;
}
// a new server frame begins now
CG_BuildSolidList( frame );
ResetAnnouncerSpeakers();
CG_UpdateEntities();
CG_CheckPredictionError();
cg.predictFrom = 0; // force the prediction to be restarted from the new snapshot
cg.fireEvents = true;
for( int i = 0; i < cg.frame.numgamecommands; i++ ) {
int target = cg.frame.playerState.POVnum - 1;
if( cg.frame.gamecommands[i].all || cg.frame.gamecommands[i].targets[target >> 3] & ( 1 << ( target & 7 ) ) ) {
CG_GameCommand( cg.frame.gamecommandsData + cg.frame.gamecommands[i].commandOffset );
}
}
CG_FireEvents( true );
return true;
}
void CG_ExtrapolateLinearProjectile( centity_t *cent ) {
cent->linearProjectileCanDraw = CG_UpdateLinearProjectilePosition( cent );
cent->interpolated.origin = cent->current.origin;
cent->interpolated.origin2 = cent->current.origin;
cent->interpolated.scale = cent->current.scale;
cent->interpolated.color = RGBA8( CG_TeamColor( cent->prev.team ) );
AnglesToAxis( cent->current.angles, cent->interpolated.axis );
}
void CG_LerpGenericEnt( centity_t *cent ) {
EulerDegrees3 ent_angles = EulerDegrees3( 0.0f, 0.0f, 0.0f );
if( ISVIEWERENTITY( cent->current.number ) || cg.view.POVent == cent->current.number ) {
ent_angles = cg.predictedPlayerState.viewangles;
} else {
// interpolate angles
ent_angles = LerpAngles( cent->prev.angles, cg.lerpfrac, cent->current.angles );
}
AnglesToAxis( ent_angles, cent->interpolated.axis );
if( ISVIEWERENTITY( cent->current.number ) || cg.view.POVent == cent->current.number ) {
cent->interpolated.origin = cg.predictedPlayerState.pmove.origin;
cent->interpolated.origin2 = cent->interpolated.origin;
} else if( cgs.extrapolationTime && cent->canExtrapolate ) { // extrapolation
Vec3 origin, xorigin1, xorigin2;
float lerpfrac = Clamp01( cg.lerpfrac );
// extrapolation with half-snapshot smoothing
xorigin1 = cent->current.origin + cent->velocity * cg.xerpTime;
if( cg.xerpTime < 0 && cent->canExtrapolatePrev ) {
Vec3 oldPosition = cent->prev.origin + cent->prevVelocity * cg.oldXerpTime;
xorigin1 = Lerp( oldPosition, cg.xerpSmoothFrac, xorigin1 );
}
// extrapolation with full-snapshot smoothing
xorigin2 = cent->current.origin + cent->velocity * cg.xerpTime;
if( cent->canExtrapolatePrev ) {
Vec3 oldPosition = cent->prev.origin + cent->prevVelocity * cg.oldXerpTime;
xorigin2 = Lerp( oldPosition, lerpfrac, xorigin2 );
}
origin = Lerp( xorigin1, 0.5f, xorigin2 );
if( cent->microSmooth == 2 ) {
Vec3 oldsmoothorigin = Lerp( cent->microSmoothOrigin2, 0.65f, cent->microSmoothOrigin );
cent->interpolated.origin = Lerp( origin, 0.5f, oldsmoothorigin );
} else if( cent->microSmooth == 1 ) {
cent->interpolated.origin = Lerp( origin, 0.5f, cent->microSmoothOrigin );
} else {
cent->interpolated.origin = origin;
}
if( cent->microSmooth ) {
cent->microSmoothOrigin2 = Vec3( cent->microSmoothOrigin );
}
cent->microSmoothOrigin = origin;
cent->microSmooth = Min2( 2, cent->microSmooth + 1 );
cent->interpolated.origin2 = cent->interpolated.origin;
} else { // plain interpolation
cent->interpolated.origin = Lerp( cent->prev.origin, cg.lerpfrac, cent->current.origin );
cent->interpolated.origin2 = cent->interpolated.origin;
}
cent->interpolated.scale = Lerp( cent->prev.scale, cg.lerpfrac, cent->current.scale );
cent->interpolated.animating = cent->prev.animating;
cent->interpolated.animation_time = Lerp( cent->prev.animation_time, cg.lerpfrac, cent->current.animation_time );
cent->interpolated.color = RGBA8( CG_TeamColor( cent->prev.team ) );
}
static void DrawEntityModel( centity_t * cent ) {
TracyZoneScoped;
Vec3 scale = cent->interpolated.scale;
if( scale.x == 0.0f || scale.y == 0.0f || scale.z == 0.0f ) {
return;
}
Optional< ModelRenderData > maybe_model = FindModelRenderData( cent->prev.model );
if( !maybe_model.exists ) {
return;
}
ModelRenderData model = maybe_model.value;
TempAllocator temp = cls.frame_arena.temp();
Mat3x4 transform = FromAxisAndOrigin( cent->interpolated.axis, cent->interpolated.origin ) * Mat4Scale( scale );
Vec4 color = sRGBToLinear( cent->interpolated.color );
MatrixPalettes palettes = { };
if( cent->interpolated.animating && model.type == ModelType_GLTF && model.gltf->animations.n > 0 ) { // TODO: this is fragile and we should do something better
Span< Transform > pose = SampleAnimation( &temp, model.gltf, cent->interpolated.animation_time );
palettes = ComputeMatrixPalettes( &temp, model.gltf, pose );
}
else if( cent->current.type == ET_MAPMODEL && model.type == ModelType_GLTF && model.gltf->animations.n > 0 ) {
float t = PositiveMod( ToSeconds( cls.monotonicTime ), model.gltf->animations[ 0 ].duration );
Span< Transform > pose = SampleAnimation( &temp, model.gltf, t );
palettes = ComputeMatrixPalettes( &temp, model.gltf, pose );
}
DrawModelConfig config = { };
config.draw_model.enabled = true;
config.draw_shadows.enabled = true;
if( cent->current.silhouetteColor.a > 0 ) {
if( ( cent->current.effects & EF_TEAM_SILHOUETTE ) == 0 || ISREALSPECTATOR() || cent->current.team == cg.predictedPlayerState.team ) {
config.draw_silhouette.enabled = true;
config.draw_silhouette.silhouette_color = sRGBToLinear( cent->current.silhouetteColor );
}
}
DrawModel( config, model, transform, color, palettes );
}
static void CG_AddPlayerEnt( centity_t *cent ) {
// if set to invisible, skip
if( cent->current.team == Team_None ) { // TODO remove?
return;
}
CG_DrawPlayer( cent );
}
static void CG_LerpLaser( centity_t *cent ) {
cent->interpolated.origin = Lerp( cent->prev.origin, cg.lerpfrac, cent->current.origin );
cent->interpolated.origin2 = Lerp( cent->prev.origin2, cg.lerpfrac, cent->current.origin2 );
}
static void CG_AddLaserEnt( centity_t *cent ) {
DrawBeam( cent->interpolated.origin, cent->interpolated.origin2, cent->current.radius, white.linear, "entities/laser/laser" );
}
static void CG_UpdateLaserbeamEnt( centity_t *cent ) {
centity_t *owner;
if( cg.view.playerPrediction && ISVIEWERENTITY( cent->current.ownerNum ) ) {
return;
}
owner = &cg_entities[cent->current.ownerNum];
if( owner->serverFrame != cg.frame.serverFrame ) {
Com_Error( "CG_UpdateLaserbeamEnt: owner is not in the snapshot\n" );
}
owner->localEffects[LOCALEFFECT_LASERBEAM] = cl.serverTime + 10;
// laser->s.origin is beam start
// laser->s.origin2 is beam end
owner->laserOriginOld = cent->prev.origin;
owner->laserPointOld = cent->prev.origin2;
owner->laserOrigin = cent->current.origin;
owner->laserPoint = cent->current.origin2;
}
static void CG_LerpLaserbeamEnt( centity_t *cent ) {
centity_t *owner = &cg_entities[cent->current.ownerNum];
if( cg.view.playerPrediction && ISVIEWERENTITY( cent->current.ownerNum ) ) {
return;
}
owner->localEffects[LOCALEFFECT_LASERBEAM] = cl.serverTime + 1;
}
void CG_SoundEntityNewState( centity_t *cent ) {
int owner = cent->current.ownerNum;
bool fixed = cent->current.positioned_sound;
if( cent->current.svflags & SVF_BROADCAST ) {
PlaySFX( cent->current.sound );
return;
}
if( owner ) {
if( owner < 0 || owner >= MAX_EDICTS ) {
Com_Printf( "CG_SoundEntityNewState: bad owner number" );
return;
}
if( cg_entities[owner].serverFrame != cg.frame.serverFrame ) {
owner = 0;
}
}
if( !owner ) {
fixed = true;
}
if( fixed ) {
PlaySFX( cent->current.sound, PlaySFXConfigPosition( cent->current.origin ) );
}
else if( ISVIEWERENTITY( owner ) ) {
PlaySFX( cent->current.sound );
}
else {
PlaySFX( cent->current.sound, PlaySFXConfigEntity( owner ) );
}
}
static void CG_LerpSpikes( centity_t * cent ) {
constexpr float retracted = -48;
constexpr float primed = -36;
constexpr float extended = 0;
float position = retracted;
if( cent->current.radius == 1 ) {
position = extended;
}
else if( cent->current.linearMovementTimeStamp != 0 ) {
int64_t delta = Lerp( cg.oldFrame.serverTime, cg.lerpfrac, cg.frame.serverTime ) - cent->current.linearMovementTimeStamp;
if( delta > 0 ) {
// 0-100: jump to primed
// 1000-1050: fully extend
// 1500-2000: retract
if( delta < 1000 ) {
float t = Min2( 1.0f, Unlerp( int64_t( 0 ), delta, int64_t( 100 ) ) );
position = Lerp( retracted, t, primed );
}
else if( delta < 1050 ) {
float t = Min2( 1.0f, Unlerp( int64_t( 1000 ), delta, int64_t( 1050 ) ) );
position = Lerp( primed, t, extended );
}
else {
float t = Max2( 0.0f, Unlerp( int64_t( 1500 ), delta, int64_t( 2000 ) ) );
position = Lerp( extended, t, retracted );
}
}
}
Vec3 up;
AngleVectors( cent->current.angles, NULL, NULL, &up );
AnglesToAxis( cent->current.angles, cent->interpolated.axis );
cent->interpolated.origin = cent->current.origin + up * position;
cent->interpolated.origin2 = cent->interpolated.origin;
}
static void CG_UpdateSpikes( centity_t * cent ) {
if( cent->current.linearMovementTimeStamp == 0 )
return;
int64_t old_delta = cg.oldFrame.serverTime - cent->current.linearMovementTimeStamp;
int64_t delta = cg.frame.serverTime - cent->current.linearMovementTimeStamp;
StringHash sound = EMPTY_HASH;
if( old_delta <= 0 && delta >= 0 ) {
sound = "sounds/spikes/arm";
}
else if( old_delta < 1000 && delta >= 1000 ) {
sound = "sounds/spikes/deploy";
}
else if( old_delta < 1050 && delta >= 1050 ) {
sound = "sounds/spikes/glint";
}
else if( old_delta < 1500 && delta >= 1500 ) {
sound = "sounds/spikes/retract";
}
PlaySFX( sound, PlaySFXConfigEntity( cent->current.number ) );
}
void CG_EntityLoopSound( centity_t * cent, SyncEntityState * state ) {
cent->sound = PlayImmediateSFX( state->sound, cent->sound, PlaySFXConfigEntity( state->number ) );
}
static void PerkIdleSounds( centity_t * cent, SyncEntityState * state ) {
if( state->perk == Perk_Jetpack ) {
cent->playing_idle_sound = PlayImmediateSFX( "perks/jetpack/idle", cent->playing_idle_sound, PlaySFXConfigEntity( cent->current.number ) );
} else if( state->perk == Perk_Wheel ) {
PlaySFXConfig cfg = PlaySFXConfigEntity( cent->current.number );
float speed = Length( cent->velocity.xy() );
cfg.pitch = 0.65f + speed * 0.0015f;
cfg.volume = 0.25f + speed * 0.001f;
cent->playing_idle_sound = PlayImmediateSFX( "perks/wheel/idle", cent->playing_idle_sound, cfg );
}
}
static void DrawEntityTrail( const centity_t * cent, StringHash name ) {
// didn't move
Vec3 vec = cent->interpolated.origin - cent->trailOrigin;
float len = Length( vec );
if( len == 0 )
return;
Vec4 color = Vec4( CG_TeamColorVec4( cent->current.team ).xyz(), 0.5f );
DoVisualEffect( name, cent->interpolated.origin, cent->trailOrigin, 1.0f, color );
DrawTrail( Hash64( cent->current.id.id ), cent->interpolated.origin, 16.0f, color, "simpletrail", Milliseconds( 500 ) );
}
void DrawEntities() {
TracyZoneScoped;
for( int pnum = 0; pnum < cg.frame.numEntities; pnum++ ) {
SyncEntityState * state = &cg.frame.parsedEntities[ pnum % ARRAY_COUNT( cg.frame.parsedEntities ) ];
centity_t * cent = &cg_entities[state->number];
if( cent->current.linearMovement ) {
if( !cent->linearProjectileCanDraw ) {
continue;
}
}
switch( cent->type ) {
case ET_GENERIC:
DrawEntityModel( cent );
CG_EntityLoopSound( cent, state );
break;
case ET_BAZOOKA:
DrawEntityModel( cent );
DrawEntityTrail( cent, "loadout/bazooka/trail" );
DrawDynamicLight( cent->interpolated.origin, CG_TeamColorVec4( cent->current.team ).xyz(), 25600.0f );
CG_EntityLoopSound( cent, state );
break;
case ET_LAUNCHER:
DrawEntityModel( cent );
DrawEntityTrail( cent, "loadout/launcher/trail" );
DrawDynamicLight( cent->interpolated.origin, CG_TeamColorVec4( cent->current.team ).xyz(), 6400.0f );
CG_EntityLoopSound( cent, state );
break;
case ET_FLASH:
DrawEntityModel( cent );
DrawEntityTrail( cent, "loadout/flash/trail" );
DrawDynamicLight( cent->interpolated.origin, CG_TeamColorVec4( cent->current.team ).xyz(), 6400.0f );
CG_EntityLoopSound( cent, state );
break;
case ET_ASSAULT:
DrawEntityModel( cent );
DrawEntityTrail( cent, "loadout/assault/trail" );
DrawDynamicLight( cent->interpolated.origin, CG_TeamColorVec4( cent->current.team ).xyz(), 6400.0f );
CG_EntityLoopSound( cent, state );
break;
case ET_BUBBLE:
DrawEntityModel( cent );
DrawEntityTrail( cent, "loadout/bubble/trail" );
DrawDynamicLight( cent->interpolated.origin, CG_TeamColorVec4( cent->current.team ).xyz(), 6400.0f );
CG_EntityLoopSound( cent, state );
break;
case ET_RIFLE:
DrawEntityModel( cent );
DrawEntityTrail( cent, "loadout/rifle/trail" );
CG_EntityLoopSound( cent, state );
break;
case ET_PISTOL:
//change angle after bounce
if( cent->velocity != Vec3( 0.0f ) ) {
AnglesToAxis( VecToAngles( cent->velocity ), cent->interpolated.axis );
}
DrawEntityModel( cent );
DrawEntityTrail( cent, "loadout/pistol/trail" );
CG_EntityLoopSound( cent, state );
break;
case ET_CROSSBOW:
DrawEntityModel( cent );
DrawEntityTrail( cent, "loadout/crossbow/trail" );
CG_EntityLoopSound( cent, state );
break;
case ET_BLASTER:
DrawEntityTrail( cent, "loadout/blaster/trail" );
DrawDynamicLight( cent->interpolated.origin, CG_TeamColorVec4( cent->current.team ).xyz(), 3200.0f );
CG_EntityLoopSound( cent, state );
break;
case ET_SAWBLADE:
DrawEntityModel( cent );
DrawEntityTrail( cent, EMPTY_HASH );
CG_EntityLoopSound( cent, state );
break;
case ET_STICKY:
DrawEntityModel( cent );
DrawEntityTrail( cent, "loadout/sticky/trail" );
DrawDynamicLight( cent->interpolated.origin, CG_TeamColorVec4( cent->current.team ).xyz(), 6400.0f );
CG_EntityLoopSound( cent, state );
break;
case ET_AXE:
DrawEntityModel( cent );
DrawEntityTrail( cent, "loadout/axe/trail" );
CG_EntityLoopSound( cent, state );
break;
case ET_SHURIKEN:
DrawEntityModel( cent );
DrawEntityTrail( cent, EMPTY_HASH );
CG_EntityLoopSound( cent, state );
break;
case ET_PLAYER:
CG_AddPlayerEnt( cent );
CG_EntityLoopSound( cent, state );
CG_LaserBeamEffect( cent );
CG_JetpackEffect( cent );
PerkIdleSounds( cent, state );
break;
case ET_CORPSE:
CG_AddPlayerEnt( cent );
CG_EntityLoopSound( cent, state );
break;
case ET_GHOST:
break;
case ET_DECAL: {
Quaternion orientation = EulerDegrees3ToQuaternion( cent->current.angles );
DrawDecal( cent->current.origin, orientation, cent->current.scale.x, cent->current.material, sRGBToLinear( cent->current.color ) );
} break;
case ET_LASERBEAM:
break;
case ET_JUMPPAD:
case ET_PAINKILLER_JUMPPAD:
DrawEntityModel( cent );
break;
case ET_EVENT:
case ET_SOUNDEVENT:
break;
case ET_BOMB:
CG_AddBombIndicator( cent );
break;
case ET_BOMB_SITE:
CG_AddBombSiteIndicator( cent );
break;
case ET_LASER: {
CG_AddLaserEnt( cent );
Vec3 start = cent->interpolated.origin;
Vec3 end = cent->interpolated.origin2;
cent->sound = PlayImmediateSFX( state->sound, cent->sound, PlaySFXConfigLineSegment( start, end ) );
} break;
case ET_SPIKES:
DrawEntityModel( cent );
break;
case ET_SPEAKER:
DrawEntityModel( cent );
break;
case ET_CINEMATIC_MAPNAME: {
TempAllocator temp = cls.frame_arena.temp();
Span< const char > big = ToUpperASCII( &temp, cl.map->name );
Draw3DText( cls.fontBoldItalic, 256.0f, big, cent->current.origin, cent->current.angles, white.linear );
} break;
case ET_MAPMODEL:
DrawEntityModel( cent );
break;
default:
Com_Error( "DrawEntities: unknown entity type" );
break;
}
cent->trailOrigin = cent->interpolated.origin;
}
}
/*
* CG_LerpEntities
* Interpolate the entity states positions into the entity_t structs
*/
void CG_LerpEntities() {
TracyZoneScoped;
for( int pnum = 0; pnum < cg.frame.numEntities; pnum++ ) {
const SyncEntityState * state = &cg.frame.parsedEntities[ pnum % ARRAY_COUNT( cg.frame.parsedEntities ) ];
int number = state->number;
centity_t * cent = &cg_entities[ number ];
cent->interpolated = { };
switch( cent->type ) {
case ET_GENERIC:
case ET_JUMPPAD:
case ET_PAINKILLER_JUMPPAD:
case ET_BAZOOKA:
case ET_STICKY:
case ET_ASSAULT:
case ET_BUBBLE:
case ET_LAUNCHER:
case ET_FLASH:
case ET_RIFLE:
case ET_PISTOL:
case ET_CROSSBOW:
case ET_BLASTER:
case ET_SAWBLADE:
case ET_AXE:
case ET_SHURIKEN:
case ET_PLAYER:
case ET_CORPSE:
case ET_GHOST:
case ET_SPEAKER:
case ET_CINEMATIC_MAPNAME:
case ET_BOMB:
case ET_MAPMODEL:
if( state->linearMovement ) {
CG_ExtrapolateLinearProjectile( cent );
} else {
CG_LerpGenericEnt( cent );
}
break;
case ET_DECAL:
break;
case ET_LASERBEAM:
CG_LerpLaserbeamEnt( cent );
break;
case ET_EVENT:
case ET_SOUNDEVENT:
break;
case ET_BOMB_SITE:
break;
case ET_LASER:
CG_LerpLaser( cent );
break;
case ET_SPIKES:
CG_LerpGenericEnt( cent );
CG_LerpSpikes( cent );
break;
default:
Com_Error( "CG_LerpEntities: unknown entity type" );
break;
}
}
}
/*
* CG_UpdateEntities
* Called at receiving a new serverframe. Sets up the model, type, etc to be drawn later on
*/
void CG_UpdateEntities() {
TracyZoneScoped;
for( int pnum = 0; pnum < cg.frame.numEntities; pnum++ ) {
SyncEntityState * state = &cg.frame.parsedEntities[ pnum % ARRAY_COUNT( cg.frame.parsedEntities ) ];
if( cgs.demoPlaying ) {
if( ( state->svflags & SVF_ONLYTEAM ) && cg.predictedPlayerState.team != state->team )
continue;
if( ( ( state->svflags & SVF_ONLYOWNER ) || ( state->svflags & SVF_OWNERANDCHASERS ) ) && checked_cast< int >( cg.predictedPlayerState.POVnum ) != state->ownerNum )
continue;
}
centity_t * cent = &cg_entities[state->number];
cent->type = state->type;
cent->effects = state->effects;
switch( cent->type ) {
case ET_GENERIC:
case ET_BAZOOKA:
case ET_ASSAULT:
case ET_BUBBLE:
case ET_LAUNCHER:
case ET_FLASH:
case ET_RIFLE:
case ET_PISTOL:
case ET_CROSSBOW:
case ET_BLASTER:
case ET_SAWBLADE:
case ET_STICKY:
case ET_RAILALT:
case ET_AXE:
case ET_SHURIKEN:
case ET_CINEMATIC_MAPNAME:
case ET_MAPMODEL:
break;
case ET_PLAYER:
case ET_CORPSE:
CG_UpdatePlayerModelEnt( cent );
break;
case ET_GHOST:
break;
case ET_DECAL:
break;
case ET_LASERBEAM:
CG_UpdateLaserbeamEnt( cent );
break;
case ET_JUMPPAD:
case ET_PAINKILLER_JUMPPAD:
break;
case ET_EVENT:
case ET_SOUNDEVENT:
break;
case ET_BOMB:
case ET_BOMB_SITE:
break;
case ET_LASER:
break;
case ET_SPIKES:
CG_UpdateSpikes( cent );
break;
case ET_SPEAKER:
AddAnnouncerSpeaker( cent );
break;
default:
Com_Error( "CG_UpdateEntities: unknown entity type %i", cent->type );
break;
}
}
}
| 412 | 0.780473 | 1 | 0.780473 | game-dev | MEDIA | 0.840426 | game-dev | 0.662532 | 1 | 0.662532 |
kishanrajput23/Awesome-Python-Projects | 4,253 | Python project for snake game using turtle | # Creating a window screen
wn = turtle.Screen()
wn.title("Snake Game")
wn.bgcolor("blue")
# the width and height can be put as user's choice
wn.setup(width=600, height=600)
wn.tracer(0)
# head of the snake
head = turtle.Turtle()
head.shape("square")
head.color("white")
head.penup()
head.goto(0, # import required modules
import turtle
import time
import random
delay = 0.1
score = 0
high_score = 0
# Creating a window screen
wn = turtle.Screen()
wn.title("Snake Game")
wn.bgcolor("blue")
# the width and height can be put as user's choice
wn.setup(width=600, height=600)
wn.tracer(0)
# head of the snake
head = turtle.Turtle()
head.shape("square")
head.color("white")
head.penup()
head.goto(0, 0)
head.direction = "Stop"
# food in the game
food = turtle.Turtle()
colors = random.choice(['red', 'green', 'black'])
shapes = random.choice(['square', 'triangle', 'circle'])
food.speed(0)
food.shape(shapes)
food.color(colors)
food.penup()
food.goto(0, 100)
pen = turtle.Turtle()
pen.speed(0)
pen.shape("square")
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0, 250)
pen.write("Score : 0 High Score : 0", align="center",
font=("candara", 24, "bold"))
# assigning key directions
def group():
if head.direction != "down":
head.direction = "up"
def godown():
if head.direction != "up":
head.direction = "down"
def goleft():
if head.direction != "right":
head.direction = "left"
def goright():
if head.direction != "left":
head.direction = "right"
def move():
if head.direction == "up":
y = head.ycor()
head.sety(y+20)
if head.direction == "down":
y = head.ycor()
head.sety(y-20)
if head.direction == "left":
x = head.xcor()
head.setx(x-20)
if head.direction == "right":
x = head.xcor()
head.setx(x+20)
wn.listen()
wn.onkeypress(group, "w")
wn.onkeypress(godown, "s")
wn.onkeypress(goleft, "a")
wn.onkeypress(goright, "d")
segments = []
# Main Gameplay
while True:
wn.update()
if head.xcor() > 290 or head.xcor() < -290 or head.ycor() > 290 or head.ycor() < -290:
time.sleep(1)
head.goto(0, 0)
head.direction = "Stop"
colors = random.choice(['red', 'blue', 'green'])
shapes = random.choice(['square', 'circle'])
for segment in segments:
segment.goto(1000, 1000)
segments.clear()
score = 0
delay = 0.1
pen.clear()
pen.write("Score : {} High Score : {} ".format(
score, high_score), align="center", font=("candara", 24, "bold"))
if head.distance(food) < 20:
x = random.randint(-270, 270)
y = random.randint(-270, 270)
food.goto(x, y)
# Adding segment
new_segment = turtle.Turtle()
new_segment.speed(0)
new_segment.shape("square")
new_segment.color("orange") # tail colour
new_segment.penup()
segments.append(new_segment)
delay -= 0.001
score += 10
if score > high_score:
high_score = score
pen.clear()
pen.write("Score : {} High Score : {} ".format(
score, high_score), align="center", font=("candara", 24, "bold"))
# Checking for head collisions with body segments
for index in range(len(segments)-1, 0, -1):
x = segments[index-1].xcor()
y = segments[index-1].ycor()
segments[index].goto(x, y)
if len(segments) > 0:
x = head.xcor()
y = head.ycor()
segments[0].goto(x, y)
move()
for segment in segments:
if segment.distance(head) < 20:
time.sleep(1)
head.goto(0, 0)
head.direction = "stop"
colors = random.choice(['red', 'blue', 'green'])
shapes = random.choice(['square', 'circle'])
for segment in segments:
segment.goto(1000, 1000)
segment.clear()
score = 0
delay = 0.1
pen.clear()
pen.write("Score : {} High Score : {} ".format(
score, high_score), align="center", font=("candara", 24, "bold"))
time.sleep(delay)
wn.mainloop()
| 412 | 0.706921 | 1 | 0.706921 | game-dev | MEDIA | 0.742432 | game-dev | 0.712397 | 1 | 0.712397 |
redot-rex/rex-engine | 50,116 | modules/navigation_3d/3d/godot_navigation_server_3d.cpp | /**************************************************************************/
/* godot_navigation_server_3d.cpp */
/**************************************************************************/
/* This file is part of: */
/* REDOT ENGINE */
/* https://redotengine.org */
/**************************************************************************/
/* Copyright (c) 2024-present Redot Engine contributors */
/* (see REDOT_AUTHORS.md) */
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#include "godot_navigation_server_3d.h"
#include "core/os/mutex.h"
#include "scene/main/node.h"
#include "nav_mesh_generator_3d.h"
using namespace NavigationUtilities;
/// Creates a struct for each function and a function that once called creates
/// an instance of that struct with the submitted parameters.
/// Then, that struct is stored in an array; the `sync` function consume that array.
#define COMMAND_1(F_NAME, T_0, D_0) \
struct MERGE(F_NAME, _command_3d) : public SetCommand3D { \
T_0 d_0; \
MERGE(F_NAME, _command_3d) \
(T_0 p_d_0) : \
d_0(p_d_0) {} \
virtual void exec(GodotNavigationServer3D *server) override { \
server->MERGE(_cmd_, F_NAME)(d_0); \
} \
}; \
void GodotNavigationServer3D::F_NAME(T_0 D_0) { \
auto cmd = memnew(MERGE(F_NAME, _command_3d)( \
D_0)); \
add_command(cmd); \
} \
void GodotNavigationServer3D::MERGE(_cmd_, F_NAME)(T_0 D_0)
#define COMMAND_2(F_NAME, T_0, D_0, T_1, D_1) \
struct MERGE(F_NAME, _command_3d) : public SetCommand3D { \
T_0 d_0; \
T_1 d_1; \
MERGE(F_NAME, _command_3d) \
( \
T_0 p_d_0, \
T_1 p_d_1) : \
d_0(p_d_0), \
d_1(p_d_1) {} \
virtual void exec(GodotNavigationServer3D *server) override { \
server->MERGE(_cmd_, F_NAME)(d_0, d_1); \
} \
}; \
void GodotNavigationServer3D::F_NAME(T_0 D_0, T_1 D_1) { \
auto cmd = memnew(MERGE(F_NAME, _command_3d)( \
D_0, \
D_1)); \
add_command(cmd); \
} \
void GodotNavigationServer3D::MERGE(_cmd_, F_NAME)(T_0 D_0, T_1 D_1)
GodotNavigationServer3D::GodotNavigationServer3D() {}
GodotNavigationServer3D::~GodotNavigationServer3D() {
flush_queries();
}
void GodotNavigationServer3D::add_command(SetCommand3D *command) {
MutexLock lock(commands_mutex);
commands.push_back(command);
}
TypedArray<RID> GodotNavigationServer3D::get_maps() const {
TypedArray<RID> all_map_rids;
LocalVector<RID> maps_owned = map_owner.get_owned_list();
uint32_t map_count = maps_owned.size();
if (map_count) {
all_map_rids.resize(map_count);
for (uint32_t i = 0; i < map_count; i++) {
all_map_rids[i] = maps_owned[i];
}
}
return all_map_rids;
}
RID GodotNavigationServer3D::map_create() {
MutexLock lock(operations_mutex);
RID rid = map_owner.make_rid();
NavMap3D *map = map_owner.get_or_null(rid);
map->set_self(rid);
return rid;
}
COMMAND_2(map_set_active, RID, p_map, bool, p_active) {
NavMap3D *map = map_owner.get_or_null(p_map);
ERR_FAIL_NULL(map);
if (p_active) {
if (!map_is_active(p_map)) {
active_maps.push_back(map);
}
} else {
int map_index = active_maps.find(map);
ERR_FAIL_COND(map_index < 0);
active_maps.remove_at(map_index);
}
}
bool GodotNavigationServer3D::map_is_active(RID p_map) const {
NavMap3D *map = map_owner.get_or_null(p_map);
ERR_FAIL_NULL_V(map, false);
return active_maps.has(map);
}
COMMAND_2(map_set_up, RID, p_map, Vector3, p_up) {
NavMap3D *map = map_owner.get_or_null(p_map);
ERR_FAIL_NULL(map);
map->set_up(p_up);
}
Vector3 GodotNavigationServer3D::map_get_up(RID p_map) const {
const NavMap3D *map = map_owner.get_or_null(p_map);
ERR_FAIL_NULL_V(map, Vector3());
return map->get_up();
}
COMMAND_2(map_set_cell_size, RID, p_map, real_t, p_cell_size) {
NavMap3D *map = map_owner.get_or_null(p_map);
ERR_FAIL_NULL(map);
map->set_cell_size(p_cell_size);
}
real_t GodotNavigationServer3D::map_get_cell_size(RID p_map) const {
const NavMap3D *map = map_owner.get_or_null(p_map);
ERR_FAIL_NULL_V(map, 0);
return map->get_cell_size();
}
COMMAND_2(map_set_cell_height, RID, p_map, real_t, p_cell_height) {
NavMap3D *map = map_owner.get_or_null(p_map);
ERR_FAIL_NULL(map);
map->set_cell_height(p_cell_height);
}
real_t GodotNavigationServer3D::map_get_cell_height(RID p_map) const {
const NavMap3D *map = map_owner.get_or_null(p_map);
ERR_FAIL_NULL_V(map, 0);
return map->get_cell_height();
}
COMMAND_2(map_set_merge_rasterizer_cell_scale, RID, p_map, float, p_value) {
NavMap3D *map = map_owner.get_or_null(p_map);
ERR_FAIL_NULL(map);
map->set_merge_rasterizer_cell_scale(p_value);
}
float GodotNavigationServer3D::map_get_merge_rasterizer_cell_scale(RID p_map) const {
NavMap3D *map = map_owner.get_or_null(p_map);
ERR_FAIL_NULL_V(map, false);
return map->get_merge_rasterizer_cell_scale();
}
COMMAND_2(map_set_use_edge_connections, RID, p_map, bool, p_enabled) {
NavMap3D *map = map_owner.get_or_null(p_map);
ERR_FAIL_NULL(map);
map->set_use_edge_connections(p_enabled);
}
bool GodotNavigationServer3D::map_get_use_edge_connections(RID p_map) const {
NavMap3D *map = map_owner.get_or_null(p_map);
ERR_FAIL_NULL_V(map, false);
return map->get_use_edge_connections();
}
COMMAND_2(map_set_edge_connection_margin, RID, p_map, real_t, p_connection_margin) {
NavMap3D *map = map_owner.get_or_null(p_map);
ERR_FAIL_NULL(map);
map->set_edge_connection_margin(p_connection_margin);
}
real_t GodotNavigationServer3D::map_get_edge_connection_margin(RID p_map) const {
const NavMap3D *map = map_owner.get_or_null(p_map);
ERR_FAIL_NULL_V(map, 0);
return map->get_edge_connection_margin();
}
COMMAND_2(map_set_link_connection_radius, RID, p_map, real_t, p_connection_radius) {
NavMap3D *map = map_owner.get_or_null(p_map);
ERR_FAIL_NULL(map);
map->set_link_connection_radius(p_connection_radius);
}
real_t GodotNavigationServer3D::map_get_link_connection_radius(RID p_map) const {
const NavMap3D *map = map_owner.get_or_null(p_map);
ERR_FAIL_NULL_V(map, 0);
return map->get_link_connection_radius();
}
Vector<Vector3> GodotNavigationServer3D::map_get_path(RID p_map, Vector3 p_origin, Vector3 p_destination, bool p_optimize, uint32_t p_navigation_layers) {
const NavMap3D *map = map_owner.get_or_null(p_map);
ERR_FAIL_NULL_V(map, Vector<Vector3>());
Ref<NavigationPathQueryParameters3D> query_parameters;
query_parameters.instantiate();
query_parameters->set_map(p_map);
query_parameters->set_start_position(p_origin);
query_parameters->set_target_position(p_destination);
query_parameters->set_navigation_layers(p_navigation_layers);
query_parameters->set_pathfinding_algorithm(NavigationPathQueryParameters3D::PathfindingAlgorithm::PATHFINDING_ALGORITHM_ASTAR);
query_parameters->set_path_postprocessing(NavigationPathQueryParameters3D::PathPostProcessing::PATH_POSTPROCESSING_CORRIDORFUNNEL);
if (!p_optimize) {
query_parameters->set_path_postprocessing(NavigationPathQueryParameters3D::PATH_POSTPROCESSING_EDGECENTERED);
}
Ref<NavigationPathQueryResult3D> query_result;
query_result.instantiate();
query_path(query_parameters, query_result);
return query_result->get_path();
}
Vector3 GodotNavigationServer3D::map_get_closest_point_to_segment(RID p_map, const Vector3 &p_from, const Vector3 &p_to, const bool p_use_collision) const {
const NavMap3D *map = map_owner.get_or_null(p_map);
ERR_FAIL_NULL_V(map, Vector3());
return map->get_closest_point_to_segment(p_from, p_to, p_use_collision);
}
Vector3 GodotNavigationServer3D::map_get_closest_point(RID p_map, const Vector3 &p_point) const {
const NavMap3D *map = map_owner.get_or_null(p_map);
ERR_FAIL_NULL_V(map, Vector3());
return map->get_closest_point(p_point);
}
Vector3 GodotNavigationServer3D::map_get_closest_point_normal(RID p_map, const Vector3 &p_point) const {
const NavMap3D *map = map_owner.get_or_null(p_map);
ERR_FAIL_NULL_V(map, Vector3());
return map->get_closest_point_normal(p_point);
}
RID GodotNavigationServer3D::map_get_closest_point_owner(RID p_map, const Vector3 &p_point) const {
const NavMap3D *map = map_owner.get_or_null(p_map);
ERR_FAIL_NULL_V(map, RID());
return map->get_closest_point_owner(p_point);
}
TypedArray<RID> GodotNavigationServer3D::map_get_links(RID p_map) const {
TypedArray<RID> link_rids;
const NavMap3D *map = map_owner.get_or_null(p_map);
ERR_FAIL_NULL_V(map, link_rids);
const LocalVector<NavLink3D *> &links = map->get_links();
link_rids.resize(links.size());
for (uint32_t i = 0; i < links.size(); i++) {
link_rids[i] = links[i]->get_self();
}
return link_rids;
}
TypedArray<RID> GodotNavigationServer3D::map_get_regions(RID p_map) const {
TypedArray<RID> regions_rids;
const NavMap3D *map = map_owner.get_or_null(p_map);
ERR_FAIL_NULL_V(map, regions_rids);
const LocalVector<NavRegion3D *> ®ions = map->get_regions();
regions_rids.resize(regions.size());
for (uint32_t i = 0; i < regions.size(); i++) {
regions_rids[i] = regions[i]->get_self();
}
return regions_rids;
}
TypedArray<RID> GodotNavigationServer3D::map_get_agents(RID p_map) const {
TypedArray<RID> agents_rids;
const NavMap3D *map = map_owner.get_or_null(p_map);
ERR_FAIL_NULL_V(map, agents_rids);
const LocalVector<NavAgent3D *> &agents = map->get_agents();
agents_rids.resize(agents.size());
for (uint32_t i = 0; i < agents.size(); i++) {
agents_rids[i] = agents[i]->get_self();
}
return agents_rids;
}
TypedArray<RID> GodotNavigationServer3D::map_get_obstacles(RID p_map) const {
TypedArray<RID> obstacles_rids;
const NavMap3D *map = map_owner.get_or_null(p_map);
ERR_FAIL_NULL_V(map, obstacles_rids);
const LocalVector<NavObstacle3D *> obstacles = map->get_obstacles();
obstacles_rids.resize(obstacles.size());
for (uint32_t i = 0; i < obstacles.size(); i++) {
obstacles_rids[i] = obstacles[i]->get_self();
}
return obstacles_rids;
}
RID GodotNavigationServer3D::region_get_map(RID p_region) const {
NavRegion3D *region = region_owner.get_or_null(p_region);
ERR_FAIL_NULL_V(region, RID());
if (region->get_map()) {
return region->get_map()->get_self();
}
return RID();
}
RID GodotNavigationServer3D::agent_get_map(RID p_agent) const {
NavAgent3D *agent = agent_owner.get_or_null(p_agent);
ERR_FAIL_NULL_V(agent, RID());
if (agent->get_map()) {
return agent->get_map()->get_self();
}
return RID();
}
COMMAND_2(map_set_use_async_iterations, RID, p_map, bool, p_enabled) {
NavMap3D *map = map_owner.get_or_null(p_map);
ERR_FAIL_NULL(map);
map->set_use_async_iterations(p_enabled);
}
bool GodotNavigationServer3D::map_get_use_async_iterations(RID p_map) const {
const NavMap3D *map = map_owner.get_or_null(p_map);
ERR_FAIL_NULL_V(map, false);
return map->get_use_async_iterations();
}
Vector3 GodotNavigationServer3D::map_get_random_point(RID p_map, uint32_t p_navigation_layers, bool p_uniformly) const {
const NavMap3D *map = map_owner.get_or_null(p_map);
ERR_FAIL_NULL_V(map, Vector3());
return map->get_random_point(p_navigation_layers, p_uniformly);
}
RID GodotNavigationServer3D::region_create() {
MutexLock lock(operations_mutex);
RID rid = region_owner.make_rid();
NavRegion3D *reg = region_owner.get_or_null(rid);
reg->set_self(rid);
return rid;
}
uint32_t GodotNavigationServer3D::region_get_iteration_id(RID p_region) const {
NavRegion3D *region = region_owner.get_or_null(p_region);
ERR_FAIL_NULL_V(region, 0);
return region->get_iteration_id();
}
COMMAND_2(region_set_enabled, RID, p_region, bool, p_enabled) {
NavRegion3D *region = region_owner.get_or_null(p_region);
ERR_FAIL_NULL(region);
region->set_enabled(p_enabled);
}
bool GodotNavigationServer3D::region_get_enabled(RID p_region) const {
const NavRegion3D *region = region_owner.get_or_null(p_region);
ERR_FAIL_NULL_V(region, false);
return region->get_enabled();
}
COMMAND_2(region_set_use_edge_connections, RID, p_region, bool, p_enabled) {
NavRegion3D *region = region_owner.get_or_null(p_region);
ERR_FAIL_NULL(region);
region->set_use_edge_connections(p_enabled);
}
bool GodotNavigationServer3D::region_get_use_edge_connections(RID p_region) const {
NavRegion3D *region = region_owner.get_or_null(p_region);
ERR_FAIL_NULL_V(region, false);
return region->get_use_edge_connections();
}
COMMAND_2(region_set_map, RID, p_region, RID, p_map) {
NavRegion3D *region = region_owner.get_or_null(p_region);
ERR_FAIL_NULL(region);
NavMap3D *map = map_owner.get_or_null(p_map);
region->set_map(map);
}
COMMAND_2(region_set_transform, RID, p_region, Transform3D, p_transform) {
NavRegion3D *region = region_owner.get_or_null(p_region);
ERR_FAIL_NULL(region);
region->set_transform(p_transform);
}
Transform3D GodotNavigationServer3D::region_get_transform(RID p_region) const {
NavRegion3D *region = region_owner.get_or_null(p_region);
ERR_FAIL_NULL_V(region, Transform3D());
return region->get_transform();
}
COMMAND_2(region_set_enter_cost, RID, p_region, real_t, p_enter_cost) {
NavRegion3D *region = region_owner.get_or_null(p_region);
ERR_FAIL_NULL(region);
ERR_FAIL_COND(p_enter_cost < 0.0);
region->set_enter_cost(p_enter_cost);
}
real_t GodotNavigationServer3D::region_get_enter_cost(RID p_region) const {
NavRegion3D *region = region_owner.get_or_null(p_region);
ERR_FAIL_NULL_V(region, 0);
return region->get_enter_cost();
}
COMMAND_2(region_set_travel_cost, RID, p_region, real_t, p_travel_cost) {
NavRegion3D *region = region_owner.get_or_null(p_region);
ERR_FAIL_NULL(region);
ERR_FAIL_COND(p_travel_cost < 0.0);
region->set_travel_cost(p_travel_cost);
}
real_t GodotNavigationServer3D::region_get_travel_cost(RID p_region) const {
NavRegion3D *region = region_owner.get_or_null(p_region);
ERR_FAIL_NULL_V(region, 0);
return region->get_travel_cost();
}
COMMAND_2(region_set_owner_id, RID, p_region, ObjectID, p_owner_id) {
NavRegion3D *region = region_owner.get_or_null(p_region);
ERR_FAIL_NULL(region);
region->set_owner_id(p_owner_id);
}
ObjectID GodotNavigationServer3D::region_get_owner_id(RID p_region) const {
const NavRegion3D *region = region_owner.get_or_null(p_region);
ERR_FAIL_NULL_V(region, ObjectID());
return region->get_owner_id();
}
bool GodotNavigationServer3D::region_owns_point(RID p_region, const Vector3 &p_point) const {
const NavRegion3D *region = region_owner.get_or_null(p_region);
ERR_FAIL_NULL_V(region, false);
if (region->get_map()) {
RID closest_point_owner = map_get_closest_point_owner(region->get_map()->get_self(), p_point);
return closest_point_owner == region->get_self();
}
return false;
}
COMMAND_2(region_set_navigation_layers, RID, p_region, uint32_t, p_navigation_layers) {
NavRegion3D *region = region_owner.get_or_null(p_region);
ERR_FAIL_NULL(region);
region->set_navigation_layers(p_navigation_layers);
}
uint32_t GodotNavigationServer3D::region_get_navigation_layers(RID p_region) const {
NavRegion3D *region = region_owner.get_or_null(p_region);
ERR_FAIL_NULL_V(region, 0);
return region->get_navigation_layers();
}
COMMAND_2(region_set_navigation_mesh, RID, p_region, Ref<NavigationMesh>, p_navigation_mesh) {
NavRegion3D *region = region_owner.get_or_null(p_region);
ERR_FAIL_NULL(region);
region->set_navigation_mesh(p_navigation_mesh);
}
#ifndef DISABLE_DEPRECATED
void GodotNavigationServer3D::region_bake_navigation_mesh(Ref<NavigationMesh> p_navigation_mesh, Node *p_root_node) {
ERR_FAIL_COND(p_navigation_mesh.is_null());
ERR_FAIL_NULL(p_root_node);
WARN_PRINT_ONCE("NavigationServer3D::region_bake_navigation_mesh() is deprecated due to core threading changes. To upgrade existing code, first create a NavigationMeshSourceGeometryData3D resource. Use this resource with method parse_source_geometry_data() to parse the SceneTree for nodes that should contribute to the navigation mesh baking. The SceneTree parsing needs to happen on the main thread. After the parsing is finished use the resource with method bake_from_source_geometry_data() to bake a navigation mesh..");
p_navigation_mesh->clear();
Ref<NavigationMeshSourceGeometryData3D> source_geometry_data;
source_geometry_data.instantiate();
parse_source_geometry_data(p_navigation_mesh, source_geometry_data, p_root_node);
bake_from_source_geometry_data(p_navigation_mesh, source_geometry_data);
}
#endif // DISABLE_DEPRECATED
int GodotNavigationServer3D::region_get_connections_count(RID p_region) const {
NavRegion3D *region = region_owner.get_or_null(p_region);
ERR_FAIL_NULL_V(region, 0);
NavMap3D *map = region->get_map();
if (map) {
return map->get_region_connections_count(region);
}
return 0;
}
Vector3 GodotNavigationServer3D::region_get_connection_pathway_start(RID p_region, int p_connection_id) const {
NavRegion3D *region = region_owner.get_or_null(p_region);
ERR_FAIL_NULL_V(region, Vector3());
NavMap3D *map = region->get_map();
if (map) {
return map->get_region_connection_pathway_start(region, p_connection_id);
}
return Vector3();
}
Vector3 GodotNavigationServer3D::region_get_connection_pathway_end(RID p_region, int p_connection_id) const {
NavRegion3D *region = region_owner.get_or_null(p_region);
ERR_FAIL_NULL_V(region, Vector3());
NavMap3D *map = region->get_map();
if (map) {
return map->get_region_connection_pathway_end(region, p_connection_id);
}
return Vector3();
}
Vector3 GodotNavigationServer3D::region_get_closest_point_to_segment(RID p_region, const Vector3 &p_from, const Vector3 &p_to, bool p_use_collision) const {
const NavRegion3D *region = region_owner.get_or_null(p_region);
ERR_FAIL_NULL_V(region, Vector3());
return region->get_closest_point_to_segment(p_from, p_to, p_use_collision);
}
Vector3 GodotNavigationServer3D::region_get_closest_point(RID p_region, const Vector3 &p_point) const {
const NavRegion3D *region = region_owner.get_or_null(p_region);
ERR_FAIL_NULL_V(region, Vector3());
return region->get_closest_point_info(p_point).point;
}
Vector3 GodotNavigationServer3D::region_get_closest_point_normal(RID p_region, const Vector3 &p_point) const {
const NavRegion3D *region = region_owner.get_or_null(p_region);
ERR_FAIL_NULL_V(region, Vector3());
return region->get_closest_point_info(p_point).normal;
}
Vector3 GodotNavigationServer3D::region_get_random_point(RID p_region, uint32_t p_navigation_layers, bool p_uniformly) const {
const NavRegion3D *region = region_owner.get_or_null(p_region);
ERR_FAIL_NULL_V(region, Vector3());
return region->get_random_point(p_navigation_layers, p_uniformly);
}
AABB GodotNavigationServer3D::region_get_bounds(RID p_region) const {
const NavRegion3D *region = region_owner.get_or_null(p_region);
ERR_FAIL_NULL_V(region, AABB());
return region->get_bounds();
}
RID GodotNavigationServer3D::link_create() {
MutexLock lock(operations_mutex);
RID rid = link_owner.make_rid();
NavLink3D *link = link_owner.get_or_null(rid);
link->set_self(rid);
return rid;
}
COMMAND_2(link_set_map, RID, p_link, RID, p_map) {
NavLink3D *link = link_owner.get_or_null(p_link);
ERR_FAIL_NULL(link);
NavMap3D *map = map_owner.get_or_null(p_map);
link->set_map(map);
}
RID GodotNavigationServer3D::link_get_map(const RID p_link) const {
const NavLink3D *link = link_owner.get_or_null(p_link);
ERR_FAIL_NULL_V(link, RID());
if (link->get_map()) {
return link->get_map()->get_self();
}
return RID();
}
COMMAND_2(link_set_enabled, RID, p_link, bool, p_enabled) {
NavLink3D *link = link_owner.get_or_null(p_link);
ERR_FAIL_NULL(link);
link->set_enabled(p_enabled);
}
bool GodotNavigationServer3D::link_get_enabled(RID p_link) const {
const NavLink3D *link = link_owner.get_or_null(p_link);
ERR_FAIL_NULL_V(link, false);
return link->get_enabled();
}
COMMAND_2(link_set_bidirectional, RID, p_link, bool, p_bidirectional) {
NavLink3D *link = link_owner.get_or_null(p_link);
ERR_FAIL_NULL(link);
link->set_bidirectional(p_bidirectional);
}
bool GodotNavigationServer3D::link_is_bidirectional(RID p_link) const {
const NavLink3D *link = link_owner.get_or_null(p_link);
ERR_FAIL_NULL_V(link, false);
return link->is_bidirectional();
}
COMMAND_2(link_set_navigation_layers, RID, p_link, uint32_t, p_navigation_layers) {
NavLink3D *link = link_owner.get_or_null(p_link);
ERR_FAIL_NULL(link);
link->set_navigation_layers(p_navigation_layers);
}
uint32_t GodotNavigationServer3D::link_get_navigation_layers(const RID p_link) const {
const NavLink3D *link = link_owner.get_or_null(p_link);
ERR_FAIL_NULL_V(link, 0);
return link->get_navigation_layers();
}
COMMAND_2(link_set_start_position, RID, p_link, Vector3, p_position) {
NavLink3D *link = link_owner.get_or_null(p_link);
ERR_FAIL_NULL(link);
link->set_start_position(p_position);
}
Vector3 GodotNavigationServer3D::link_get_start_position(RID p_link) const {
const NavLink3D *link = link_owner.get_or_null(p_link);
ERR_FAIL_NULL_V(link, Vector3());
return link->get_start_position();
}
COMMAND_2(link_set_end_position, RID, p_link, Vector3, p_position) {
NavLink3D *link = link_owner.get_or_null(p_link);
ERR_FAIL_NULL(link);
link->set_end_position(p_position);
}
Vector3 GodotNavigationServer3D::link_get_end_position(RID p_link) const {
const NavLink3D *link = link_owner.get_or_null(p_link);
ERR_FAIL_NULL_V(link, Vector3());
return link->get_end_position();
}
COMMAND_2(link_set_enter_cost, RID, p_link, real_t, p_enter_cost) {
NavLink3D *link = link_owner.get_or_null(p_link);
ERR_FAIL_NULL(link);
link->set_enter_cost(p_enter_cost);
}
real_t GodotNavigationServer3D::link_get_enter_cost(const RID p_link) const {
const NavLink3D *link = link_owner.get_or_null(p_link);
ERR_FAIL_NULL_V(link, 0);
return link->get_enter_cost();
}
COMMAND_2(link_set_travel_cost, RID, p_link, real_t, p_travel_cost) {
NavLink3D *link = link_owner.get_or_null(p_link);
ERR_FAIL_NULL(link);
link->set_travel_cost(p_travel_cost);
}
real_t GodotNavigationServer3D::link_get_travel_cost(const RID p_link) const {
const NavLink3D *link = link_owner.get_or_null(p_link);
ERR_FAIL_NULL_V(link, 0);
return link->get_travel_cost();
}
COMMAND_2(link_set_owner_id, RID, p_link, ObjectID, p_owner_id) {
NavLink3D *link = link_owner.get_or_null(p_link);
ERR_FAIL_NULL(link);
link->set_owner_id(p_owner_id);
}
ObjectID GodotNavigationServer3D::link_get_owner_id(RID p_link) const {
const NavLink3D *link = link_owner.get_or_null(p_link);
ERR_FAIL_NULL_V(link, ObjectID());
return link->get_owner_id();
}
RID GodotNavigationServer3D::agent_create() {
MutexLock lock(operations_mutex);
RID rid = agent_owner.make_rid();
NavAgent3D *agent = agent_owner.get_or_null(rid);
agent->set_self(rid);
return rid;
}
COMMAND_2(agent_set_avoidance_enabled, RID, p_agent, bool, p_enabled) {
NavAgent3D *agent = agent_owner.get_or_null(p_agent);
ERR_FAIL_NULL(agent);
agent->set_avoidance_enabled(p_enabled);
}
bool GodotNavigationServer3D::agent_get_avoidance_enabled(RID p_agent) const {
NavAgent3D *agent = agent_owner.get_or_null(p_agent);
ERR_FAIL_NULL_V(agent, false);
return agent->is_avoidance_enabled();
}
COMMAND_2(agent_set_use_3d_avoidance, RID, p_agent, bool, p_enabled) {
NavAgent3D *agent = agent_owner.get_or_null(p_agent);
ERR_FAIL_NULL(agent);
agent->set_use_3d_avoidance(p_enabled);
}
bool GodotNavigationServer3D::agent_get_use_3d_avoidance(RID p_agent) const {
NavAgent3D *agent = agent_owner.get_or_null(p_agent);
ERR_FAIL_NULL_V(agent, false);
return agent->get_use_3d_avoidance();
}
COMMAND_2(agent_set_map, RID, p_agent, RID, p_map) {
NavAgent3D *agent = agent_owner.get_or_null(p_agent);
ERR_FAIL_NULL(agent);
NavMap3D *map = map_owner.get_or_null(p_map);
agent->set_map(map);
}
COMMAND_2(agent_set_paused, RID, p_agent, bool, p_paused) {
NavAgent3D *agent = agent_owner.get_or_null(p_agent);
ERR_FAIL_NULL(agent);
agent->set_paused(p_paused);
}
bool GodotNavigationServer3D::agent_get_paused(RID p_agent) const {
NavAgent3D *agent = agent_owner.get_or_null(p_agent);
ERR_FAIL_NULL_V(agent, false);
return agent->get_paused();
}
COMMAND_2(agent_set_neighbor_distance, RID, p_agent, real_t, p_distance) {
NavAgent3D *agent = agent_owner.get_or_null(p_agent);
ERR_FAIL_NULL(agent);
agent->set_neighbor_distance(p_distance);
}
real_t GodotNavigationServer3D::agent_get_neighbor_distance(RID p_agent) const {
NavAgent3D *agent = agent_owner.get_or_null(p_agent);
ERR_FAIL_NULL_V(agent, 0);
return agent->get_neighbor_distance();
}
COMMAND_2(agent_set_max_neighbors, RID, p_agent, int, p_count) {
NavAgent3D *agent = agent_owner.get_or_null(p_agent);
ERR_FAIL_NULL(agent);
agent->set_max_neighbors(p_count);
}
int GodotNavigationServer3D::agent_get_max_neighbors(RID p_agent) const {
NavAgent3D *agent = agent_owner.get_or_null(p_agent);
ERR_FAIL_NULL_V(agent, 0);
return agent->get_max_neighbors();
}
COMMAND_2(agent_set_time_horizon_agents, RID, p_agent, real_t, p_time_horizon) {
ERR_FAIL_COND_MSG(p_time_horizon < 0.0, "Time horizon must be positive.");
NavAgent3D *agent = agent_owner.get_or_null(p_agent);
ERR_FAIL_NULL(agent);
agent->set_time_horizon_agents(p_time_horizon);
}
real_t GodotNavigationServer3D::agent_get_time_horizon_agents(RID p_agent) const {
NavAgent3D *agent = agent_owner.get_or_null(p_agent);
ERR_FAIL_NULL_V(agent, 0);
return agent->get_time_horizon_agents();
}
COMMAND_2(agent_set_time_horizon_obstacles, RID, p_agent, real_t, p_time_horizon) {
ERR_FAIL_COND_MSG(p_time_horizon < 0.0, "Time horizon must be positive.");
NavAgent3D *agent = agent_owner.get_or_null(p_agent);
ERR_FAIL_NULL(agent);
agent->set_time_horizon_obstacles(p_time_horizon);
}
real_t GodotNavigationServer3D::agent_get_time_horizon_obstacles(RID p_agent) const {
NavAgent3D *agent = agent_owner.get_or_null(p_agent);
ERR_FAIL_NULL_V(agent, 0);
return agent->get_time_horizon_obstacles();
}
COMMAND_2(agent_set_radius, RID, p_agent, real_t, p_radius) {
ERR_FAIL_COND_MSG(p_radius < 0.0, "Radius must be positive.");
NavAgent3D *agent = agent_owner.get_or_null(p_agent);
ERR_FAIL_NULL(agent);
agent->set_radius(p_radius);
}
real_t GodotNavigationServer3D::agent_get_radius(RID p_agent) const {
NavAgent3D *agent = agent_owner.get_or_null(p_agent);
ERR_FAIL_NULL_V(agent, 0);
return agent->get_radius();
}
COMMAND_2(agent_set_height, RID, p_agent, real_t, p_height) {
ERR_FAIL_COND_MSG(p_height < 0.0, "Height must be positive.");
NavAgent3D *agent = agent_owner.get_or_null(p_agent);
ERR_FAIL_NULL(agent);
agent->set_height(p_height);
}
real_t GodotNavigationServer3D::agent_get_height(RID p_agent) const {
NavAgent3D *agent = agent_owner.get_or_null(p_agent);
ERR_FAIL_NULL_V(agent, 0);
return agent->get_height();
}
COMMAND_2(agent_set_max_speed, RID, p_agent, real_t, p_max_speed) {
ERR_FAIL_COND_MSG(p_max_speed < 0.0, "Max speed must be positive.");
NavAgent3D *agent = agent_owner.get_or_null(p_agent);
ERR_FAIL_NULL(agent);
agent->set_max_speed(p_max_speed);
}
real_t GodotNavigationServer3D::agent_get_max_speed(RID p_agent) const {
NavAgent3D *agent = agent_owner.get_or_null(p_agent);
ERR_FAIL_NULL_V(agent, 0);
return agent->get_max_speed();
}
COMMAND_2(agent_set_velocity, RID, p_agent, Vector3, p_velocity) {
NavAgent3D *agent = agent_owner.get_or_null(p_agent);
ERR_FAIL_NULL(agent);
agent->set_velocity(p_velocity);
}
Vector3 GodotNavigationServer3D::agent_get_velocity(RID p_agent) const {
NavAgent3D *agent = agent_owner.get_or_null(p_agent);
ERR_FAIL_NULL_V(agent, Vector3());
return agent->get_velocity();
}
COMMAND_2(agent_set_velocity_forced, RID, p_agent, Vector3, p_velocity) {
NavAgent3D *agent = agent_owner.get_or_null(p_agent);
ERR_FAIL_NULL(agent);
agent->set_velocity_forced(p_velocity);
}
COMMAND_2(agent_set_position, RID, p_agent, Vector3, p_position) {
NavAgent3D *agent = agent_owner.get_or_null(p_agent);
ERR_FAIL_NULL(agent);
agent->set_position(p_position);
}
Vector3 GodotNavigationServer3D::agent_get_position(RID p_agent) const {
NavAgent3D *agent = agent_owner.get_or_null(p_agent);
ERR_FAIL_NULL_V(agent, Vector3());
return agent->get_position();
}
bool GodotNavigationServer3D::agent_is_map_changed(RID p_agent) const {
NavAgent3D *agent = agent_owner.get_or_null(p_agent);
ERR_FAIL_NULL_V(agent, false);
return agent->is_map_changed();
}
COMMAND_2(agent_set_avoidance_callback, RID, p_agent, Callable, p_callback) {
NavAgent3D *agent = agent_owner.get_or_null(p_agent);
ERR_FAIL_NULL(agent);
agent->set_avoidance_callback(p_callback);
if (agent->get_map()) {
if (p_callback.is_valid()) {
agent->get_map()->set_agent_as_controlled(agent);
} else {
agent->get_map()->remove_agent_as_controlled(agent);
}
}
}
bool GodotNavigationServer3D::agent_has_avoidance_callback(RID p_agent) const {
NavAgent3D *agent = agent_owner.get_or_null(p_agent);
ERR_FAIL_NULL_V(agent, false);
return agent->has_avoidance_callback();
}
COMMAND_2(agent_set_avoidance_layers, RID, p_agent, uint32_t, p_layers) {
NavAgent3D *agent = agent_owner.get_or_null(p_agent);
ERR_FAIL_NULL(agent);
agent->set_avoidance_layers(p_layers);
}
uint32_t GodotNavigationServer3D::agent_get_avoidance_layers(RID p_agent) const {
NavAgent3D *agent = agent_owner.get_or_null(p_agent);
ERR_FAIL_NULL_V(agent, 0);
return agent->get_avoidance_layers();
}
COMMAND_2(agent_set_avoidance_mask, RID, p_agent, uint32_t, p_mask) {
NavAgent3D *agent = agent_owner.get_or_null(p_agent);
ERR_FAIL_NULL(agent);
agent->set_avoidance_mask(p_mask);
}
uint32_t GodotNavigationServer3D::agent_get_avoidance_mask(RID p_agent) const {
NavAgent3D *agent = agent_owner.get_or_null(p_agent);
ERR_FAIL_NULL_V(agent, 0);
return agent->get_avoidance_mask();
}
COMMAND_2(agent_set_avoidance_priority, RID, p_agent, real_t, p_priority) {
ERR_FAIL_COND_MSG(p_priority < 0.0, "Avoidance priority must be between 0.0 and 1.0 inclusive.");
ERR_FAIL_COND_MSG(p_priority > 1.0, "Avoidance priority must be between 0.0 and 1.0 inclusive.");
NavAgent3D *agent = agent_owner.get_or_null(p_agent);
ERR_FAIL_NULL(agent);
agent->set_avoidance_priority(p_priority);
}
real_t GodotNavigationServer3D::agent_get_avoidance_priority(RID p_agent) const {
NavAgent3D *agent = agent_owner.get_or_null(p_agent);
ERR_FAIL_NULL_V(agent, 0);
return agent->get_avoidance_priority();
}
RID GodotNavigationServer3D::obstacle_create() {
MutexLock lock(operations_mutex);
RID rid = obstacle_owner.make_rid();
NavObstacle3D *obstacle = obstacle_owner.get_or_null(rid);
obstacle->set_self(rid);
RID agent_rid = agent_owner.make_rid();
NavAgent3D *agent = agent_owner.get_or_null(agent_rid);
agent->set_self(agent_rid);
obstacle->set_agent(agent);
return rid;
}
COMMAND_2(obstacle_set_avoidance_enabled, RID, p_obstacle, bool, p_enabled) {
NavObstacle3D *obstacle = obstacle_owner.get_or_null(p_obstacle);
ERR_FAIL_NULL(obstacle);
obstacle->set_avoidance_enabled(p_enabled);
}
bool GodotNavigationServer3D::obstacle_get_avoidance_enabled(RID p_obstacle) const {
NavObstacle3D *obstacle = obstacle_owner.get_or_null(p_obstacle);
ERR_FAIL_NULL_V(obstacle, false);
return obstacle->is_avoidance_enabled();
}
COMMAND_2(obstacle_set_use_3d_avoidance, RID, p_obstacle, bool, p_enabled) {
NavObstacle3D *obstacle = obstacle_owner.get_or_null(p_obstacle);
ERR_FAIL_NULL(obstacle);
obstacle->set_use_3d_avoidance(p_enabled);
}
bool GodotNavigationServer3D::obstacle_get_use_3d_avoidance(RID p_obstacle) const {
NavObstacle3D *obstacle = obstacle_owner.get_or_null(p_obstacle);
ERR_FAIL_NULL_V(obstacle, false);
return obstacle->get_use_3d_avoidance();
}
COMMAND_2(obstacle_set_map, RID, p_obstacle, RID, p_map) {
NavObstacle3D *obstacle = obstacle_owner.get_or_null(p_obstacle);
ERR_FAIL_NULL(obstacle);
NavMap3D *map = map_owner.get_or_null(p_map);
obstacle->set_map(map);
}
RID GodotNavigationServer3D::obstacle_get_map(RID p_obstacle) const {
NavObstacle3D *obstacle = obstacle_owner.get_or_null(p_obstacle);
ERR_FAIL_NULL_V(obstacle, RID());
if (obstacle->get_map()) {
return obstacle->get_map()->get_self();
}
return RID();
}
COMMAND_2(obstacle_set_paused, RID, p_obstacle, bool, p_paused) {
NavObstacle3D *obstacle = obstacle_owner.get_or_null(p_obstacle);
ERR_FAIL_NULL(obstacle);
obstacle->set_paused(p_paused);
}
bool GodotNavigationServer3D::obstacle_get_paused(RID p_obstacle) const {
NavObstacle3D *obstacle = obstacle_owner.get_or_null(p_obstacle);
ERR_FAIL_NULL_V(obstacle, false);
return obstacle->get_paused();
}
COMMAND_2(obstacle_set_radius, RID, p_obstacle, real_t, p_radius) {
ERR_FAIL_COND_MSG(p_radius < 0.0, "Radius must be positive.");
NavObstacle3D *obstacle = obstacle_owner.get_or_null(p_obstacle);
ERR_FAIL_NULL(obstacle);
obstacle->set_radius(p_radius);
}
real_t GodotNavigationServer3D::obstacle_get_radius(RID p_obstacle) const {
NavObstacle3D *obstacle = obstacle_owner.get_or_null(p_obstacle);
ERR_FAIL_NULL_V(obstacle, 0);
return obstacle->get_radius();
}
COMMAND_2(obstacle_set_height, RID, p_obstacle, real_t, p_height) {
NavObstacle3D *obstacle = obstacle_owner.get_or_null(p_obstacle);
ERR_FAIL_NULL(obstacle);
obstacle->set_height(p_height);
}
real_t GodotNavigationServer3D::obstacle_get_height(RID p_obstacle) const {
NavObstacle3D *obstacle = obstacle_owner.get_or_null(p_obstacle);
ERR_FAIL_NULL_V(obstacle, 0);
return obstacle->get_height();
}
COMMAND_2(obstacle_set_velocity, RID, p_obstacle, Vector3, p_velocity) {
NavObstacle3D *obstacle = obstacle_owner.get_or_null(p_obstacle);
ERR_FAIL_NULL(obstacle);
obstacle->set_velocity(p_velocity);
}
Vector3 GodotNavigationServer3D::obstacle_get_velocity(RID p_obstacle) const {
NavObstacle3D *obstacle = obstacle_owner.get_or_null(p_obstacle);
ERR_FAIL_NULL_V(obstacle, Vector3());
return obstacle->get_velocity();
}
COMMAND_2(obstacle_set_position, RID, p_obstacle, Vector3, p_position) {
NavObstacle3D *obstacle = obstacle_owner.get_or_null(p_obstacle);
ERR_FAIL_NULL(obstacle);
obstacle->set_position(p_position);
}
Vector3 GodotNavigationServer3D::obstacle_get_position(RID p_obstacle) const {
NavObstacle3D *obstacle = obstacle_owner.get_or_null(p_obstacle);
ERR_FAIL_NULL_V(obstacle, Vector3());
return obstacle->get_position();
}
void GodotNavigationServer3D::obstacle_set_vertices(RID p_obstacle, const Vector<Vector3> &p_vertices) {
NavObstacle3D *obstacle = obstacle_owner.get_or_null(p_obstacle);
ERR_FAIL_NULL(obstacle);
obstacle->set_vertices(p_vertices);
}
Vector<Vector3> GodotNavigationServer3D::obstacle_get_vertices(RID p_obstacle) const {
NavObstacle3D *obstacle = obstacle_owner.get_or_null(p_obstacle);
ERR_FAIL_NULL_V(obstacle, Vector<Vector3>());
return obstacle->get_vertices();
}
COMMAND_2(obstacle_set_avoidance_layers, RID, p_obstacle, uint32_t, p_layers) {
NavObstacle3D *obstacle = obstacle_owner.get_or_null(p_obstacle);
ERR_FAIL_NULL(obstacle);
obstacle->set_avoidance_layers(p_layers);
}
uint32_t GodotNavigationServer3D::obstacle_get_avoidance_layers(RID p_obstacle) const {
NavObstacle3D *obstacle = obstacle_owner.get_or_null(p_obstacle);
ERR_FAIL_NULL_V(obstacle, 0);
return obstacle->get_avoidance_layers();
}
void GodotNavigationServer3D::parse_source_geometry_data(const Ref<NavigationMesh> &p_navigation_mesh, const Ref<NavigationMeshSourceGeometryData3D> &p_source_geometry_data, Node *p_root_node, const Callable &p_callback) {
ERR_FAIL_COND_MSG(!Thread::is_main_thread(), "The SceneTree can only be parsed on the main thread. Call this function from the main thread or use call_deferred().");
ERR_FAIL_COND_MSG(p_navigation_mesh.is_null(), "Invalid navigation mesh.");
ERR_FAIL_NULL_MSG(p_root_node, "No parsing root node specified.");
ERR_FAIL_COND_MSG(!p_root_node->is_inside_tree(), "The root node needs to be inside the SceneTree.");
ERR_FAIL_NULL(NavMeshGenerator3D::get_singleton());
NavMeshGenerator3D::get_singleton()->parse_source_geometry_data(p_navigation_mesh, p_source_geometry_data, p_root_node, p_callback);
}
void GodotNavigationServer3D::bake_from_source_geometry_data(const Ref<NavigationMesh> &p_navigation_mesh, const Ref<NavigationMeshSourceGeometryData3D> &p_source_geometry_data, const Callable &p_callback) {
ERR_FAIL_COND_MSG(p_navigation_mesh.is_null(), "Invalid navigation mesh.");
ERR_FAIL_COND_MSG(p_source_geometry_data.is_null(), "Invalid NavigationMeshSourceGeometryData3D.");
ERR_FAIL_NULL(NavMeshGenerator3D::get_singleton());
NavMeshGenerator3D::get_singleton()->bake_from_source_geometry_data(p_navigation_mesh, p_source_geometry_data, p_callback);
}
void GodotNavigationServer3D::bake_from_source_geometry_data_async(const Ref<NavigationMesh> &p_navigation_mesh, const Ref<NavigationMeshSourceGeometryData3D> &p_source_geometry_data, const Callable &p_callback) {
ERR_FAIL_COND_MSG(p_navigation_mesh.is_null(), "Invalid navigation mesh.");
ERR_FAIL_COND_MSG(p_source_geometry_data.is_null(), "Invalid NavigationMeshSourceGeometryData3D.");
ERR_FAIL_NULL(NavMeshGenerator3D::get_singleton());
NavMeshGenerator3D::get_singleton()->bake_from_source_geometry_data_async(p_navigation_mesh, p_source_geometry_data, p_callback);
}
bool GodotNavigationServer3D::is_baking_navigation_mesh(Ref<NavigationMesh> p_navigation_mesh) const {
return NavMeshGenerator3D::get_singleton()->is_baking(p_navigation_mesh);
}
COMMAND_1(free, RID, p_object) {
if (map_owner.owns(p_object)) {
NavMap3D *map = map_owner.get_or_null(p_object);
// Removes any assigned region
for (NavRegion3D *region : map->get_regions()) {
map->remove_region(region);
region->set_map(nullptr);
}
// Removes any assigned links
for (NavLink3D *link : map->get_links()) {
map->remove_link(link);
link->set_map(nullptr);
}
// Remove any assigned agent
for (NavAgent3D *agent : map->get_agents()) {
map->remove_agent(agent);
agent->set_map(nullptr);
}
// Remove any assigned obstacles
for (NavObstacle3D *obstacle : map->get_obstacles()) {
map->remove_obstacle(obstacle);
obstacle->set_map(nullptr);
}
int map_index = active_maps.find(map);
if (map_index >= 0) {
active_maps.remove_at(map_index);
}
map_owner.free(p_object);
} else if (region_owner.owns(p_object)) {
NavRegion3D *region = region_owner.get_or_null(p_object);
// Removes this region from the map if assigned
if (region->get_map() != nullptr) {
region->get_map()->remove_region(region);
region->set_map(nullptr);
}
region_owner.free(p_object);
} else if (link_owner.owns(p_object)) {
NavLink3D *link = link_owner.get_or_null(p_object);
// Removes this link from the map if assigned
if (link->get_map() != nullptr) {
link->get_map()->remove_link(link);
link->set_map(nullptr);
}
link_owner.free(p_object);
} else if (agent_owner.owns(p_object)) {
internal_free_agent(p_object);
} else if (obstacle_owner.owns(p_object)) {
internal_free_obstacle(p_object);
} else if (geometry_parser_owner.owns(p_object)) {
RWLockWrite write_lock(geometry_parser_rwlock);
NavMeshGeometryParser3D *parser = geometry_parser_owner.get_or_null(p_object);
ERR_FAIL_NULL(parser);
generator_parsers.erase(parser);
NavMeshGenerator3D::get_singleton()->set_generator_parsers(generator_parsers);
geometry_parser_owner.free(parser->self);
} else {
ERR_PRINT("Attempted to free a NavigationServer RID that did not exist (or was already freed).");
}
}
void GodotNavigationServer3D::internal_free_agent(RID p_object) {
NavAgent3D *agent = agent_owner.get_or_null(p_object);
if (agent) {
if (agent->get_map() != nullptr) {
agent->get_map()->remove_agent(agent);
agent->set_map(nullptr);
}
agent_owner.free(p_object);
}
}
void GodotNavigationServer3D::internal_free_obstacle(RID p_object) {
NavObstacle3D *obstacle = obstacle_owner.get_or_null(p_object);
if (obstacle) {
NavAgent3D *obstacle_agent = obstacle->get_agent();
if (obstacle_agent) {
RID _agent_rid = obstacle_agent->get_self();
internal_free_agent(_agent_rid);
obstacle->set_agent(nullptr);
}
if (obstacle->get_map() != nullptr) {
obstacle->get_map()->remove_obstacle(obstacle);
obstacle->set_map(nullptr);
}
obstacle_owner.free(p_object);
}
}
void GodotNavigationServer3D::set_active(bool p_active) {
MutexLock lock(operations_mutex);
active = p_active;
}
void GodotNavigationServer3D::flush_queries() {
MutexLock lock(commands_mutex);
MutexLock lock2(operations_mutex);
for (SetCommand3D *command : commands) {
command->exec(this);
memdelete(command);
}
commands.clear();
}
void GodotNavigationServer3D::map_force_update(RID p_map) {
NavMap3D *map = map_owner.get_or_null(p_map);
ERR_FAIL_NULL(map);
flush_queries();
map->sync();
}
uint32_t GodotNavigationServer3D::map_get_iteration_id(RID p_map) const {
NavMap3D *map = map_owner.get_or_null(p_map);
ERR_FAIL_NULL_V(map, 0);
return map->get_iteration_id();
}
void GodotNavigationServer3D::sync() {
if (navmesh_generator_3d) {
navmesh_generator_3d->sync();
}
}
void GodotNavigationServer3D::process(double p_delta_time) {
// Called for each main loop iteration AFTER node and user script process() and BEFORE RenderingServer sync.
// Will run reliably every rendered frame independent of the physics tick rate.
// Use for things that (only) need to update once per main loop iteration and rendered frame or is visible to the user.
// E.g. (final) sync of objects for this main loop iteration, updating rendered debug visuals, updating debug statistics, ...
sync();
}
void GodotNavigationServer3D::physics_process(double p_delta_time) {
// Called for each physics process step AFTER node and user script physics_process() and BEFORE PhysicsServer sync.
// Will NOT run reliably every rendered frame. If there is no physics step this function will not run.
// Use for physics or step depending calculations and updates where the result affects the next step calculation.
// E.g. anything physics sync related, avoidance simulations, physics space state queries, ...
// If physics process needs to play catchup this function will be called multiple times per frame so it should not hold
// costly updates that are not important outside the stepped calculations to avoid causing a physics performance death spiral.
flush_queries();
if (!active) {
return;
}
int _new_pm_region_count = 0;
int _new_pm_agent_count = 0;
int _new_pm_link_count = 0;
int _new_pm_polygon_count = 0;
int _new_pm_edge_count = 0;
int _new_pm_edge_merge_count = 0;
int _new_pm_edge_connection_count = 0;
int _new_pm_edge_free_count = 0;
int _new_pm_obstacle_count = 0;
MutexLock lock(operations_mutex);
for (uint32_t i(0); i < active_maps.size(); i++) {
active_maps[i]->sync();
active_maps[i]->step(p_delta_time);
active_maps[i]->dispatch_callbacks();
_new_pm_region_count += active_maps[i]->get_pm_region_count();
_new_pm_agent_count += active_maps[i]->get_pm_agent_count();
_new_pm_link_count += active_maps[i]->get_pm_link_count();
_new_pm_polygon_count += active_maps[i]->get_pm_polygon_count();
_new_pm_edge_count += active_maps[i]->get_pm_edge_count();
_new_pm_edge_merge_count += active_maps[i]->get_pm_edge_merge_count();
_new_pm_edge_connection_count += active_maps[i]->get_pm_edge_connection_count();
_new_pm_edge_free_count += active_maps[i]->get_pm_edge_free_count();
_new_pm_obstacle_count += active_maps[i]->get_pm_obstacle_count();
}
pm_region_count = _new_pm_region_count;
pm_agent_count = _new_pm_agent_count;
pm_link_count = _new_pm_link_count;
pm_polygon_count = _new_pm_polygon_count;
pm_edge_count = _new_pm_edge_count;
pm_edge_merge_count = _new_pm_edge_merge_count;
pm_edge_connection_count = _new_pm_edge_connection_count;
pm_edge_free_count = _new_pm_edge_free_count;
pm_obstacle_count = _new_pm_obstacle_count;
}
void GodotNavigationServer3D::init() {
navmesh_generator_3d = memnew(NavMeshGenerator3D);
RWLockRead read_lock(geometry_parser_rwlock);
navmesh_generator_3d->set_generator_parsers(generator_parsers);
}
void GodotNavigationServer3D::finish() {
flush_queries();
if (navmesh_generator_3d) {
navmesh_generator_3d->finish();
memdelete(navmesh_generator_3d);
navmesh_generator_3d = nullptr;
}
}
void GodotNavigationServer3D::query_path(const Ref<NavigationPathQueryParameters3D> &p_query_parameters, Ref<NavigationPathQueryResult3D> p_query_result, const Callable &p_callback) {
ERR_FAIL_COND(p_query_parameters.is_null());
ERR_FAIL_COND(p_query_result.is_null());
NavMap3D *map = map_owner.get_or_null(p_query_parameters->get_map());
ERR_FAIL_NULL(map);
NavMeshQueries3D::map_query_path(map, p_query_parameters, p_query_result, p_callback);
}
RID GodotNavigationServer3D::source_geometry_parser_create() {
RWLockWrite write_lock(geometry_parser_rwlock);
RID rid = geometry_parser_owner.make_rid();
NavMeshGeometryParser3D *parser = geometry_parser_owner.get_or_null(rid);
parser->self = rid;
generator_parsers.push_back(parser);
NavMeshGenerator3D::get_singleton()->set_generator_parsers(generator_parsers);
return rid;
}
void GodotNavigationServer3D::source_geometry_parser_set_callback(RID p_parser, const Callable &p_callback) {
RWLockWrite write_lock(geometry_parser_rwlock);
NavMeshGeometryParser3D *parser = geometry_parser_owner.get_or_null(p_parser);
ERR_FAIL_NULL(parser);
parser->callback = p_callback;
}
Vector<Vector3> GodotNavigationServer3D::simplify_path(const Vector<Vector3> &p_path, real_t p_epsilon) {
if (p_path.size() <= 2) {
return p_path;
}
p_epsilon = MAX(0.0, p_epsilon);
LocalVector<Vector3> source_path;
{
source_path.resize(p_path.size());
const Vector3 *r = p_path.ptr();
for (uint32_t i = 0; i < p_path.size(); i++) {
source_path[i] = r[i];
}
}
LocalVector<uint32_t> simplified_path_indices = NavMeshQueries3D::get_simplified_path_indices(source_path, p_epsilon);
uint32_t index_count = simplified_path_indices.size();
Vector<Vector3> simplified_path;
{
simplified_path.resize(index_count);
Vector3 *w = simplified_path.ptrw();
const Vector3 *r = source_path.ptr();
for (uint32_t i = 0; i < index_count; i++) {
w[i] = r[simplified_path_indices[i]];
}
}
return simplified_path;
}
int GodotNavigationServer3D::get_process_info(ProcessInfo p_info) const {
switch (p_info) {
case INFO_ACTIVE_MAPS: {
return active_maps.size();
} break;
case INFO_REGION_COUNT: {
return pm_region_count;
} break;
case INFO_AGENT_COUNT: {
return pm_agent_count;
} break;
case INFO_LINK_COUNT: {
return pm_link_count;
} break;
case INFO_POLYGON_COUNT: {
return pm_polygon_count;
} break;
case INFO_EDGE_COUNT: {
return pm_edge_count;
} break;
case INFO_EDGE_MERGE_COUNT: {
return pm_edge_merge_count;
} break;
case INFO_EDGE_CONNECTION_COUNT: {
return pm_edge_connection_count;
} break;
case INFO_EDGE_FREE_COUNT: {
return pm_edge_free_count;
} break;
case INFO_OBSTACLE_COUNT: {
return pm_obstacle_count;
} break;
}
return 0;
}
#undef COMMAND_1
#undef COMMAND_2
| 412 | 0.932892 | 1 | 0.932892 | game-dev | MEDIA | 0.953395 | game-dev | 0.767045 | 1 | 0.767045 |
Rinnegatamante/vitaRTCW | 9,540 | mp_code/game/bg_slidemove.c | /*
===========================================================================
Return to Castle Wolfenstein multiplayer GPL Source Code
Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company.
This file is part of the Return to Castle Wolfenstein multiplayer GPL Source Code (RTCW MP Source Code).
RTCW MP Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
RTCW MP Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with RTCW MP Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the RTCW MP Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the RTCW MP 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.
===========================================================================
*/
// bg_slidemove.c -- part of bg_pmove functionality
#include "../qcommon/q_shared.h"
#include "bg_public.h"
#include "bg_local.h"
/*
input: origin, velocity, bounds, groundPlane, trace function
output: origin, velocity, impacts, stairup boolean
*/
/*
==================
PM_SlideMove
Returns qtrue if the velocity was clipped in some way
==================
*/
#define MAX_CLIP_PLANES 5
qboolean PM_SlideMove( qboolean gravity ) {
int bumpcount, numbumps;
vec3_t dir;
float d;
int numplanes;
vec3_t planes[MAX_CLIP_PLANES];
vec3_t primal_velocity;
vec3_t clipVelocity;
int i, j, k;
trace_t trace;
vec3_t end;
float time_left;
float into;
vec3_t endVelocity;
vec3_t endClipVelocity;
numbumps = 4;
VectorCopy( pm->ps->velocity, primal_velocity );
if ( gravity ) {
VectorCopy( pm->ps->velocity, endVelocity );
endVelocity[2] -= pm->ps->gravity * pml.frametime;
pm->ps->velocity[2] = ( pm->ps->velocity[2] + endVelocity[2] ) * 0.5;
primal_velocity[2] = endVelocity[2];
if ( pml.groundPlane ) {
// slide along the ground plane
PM_ClipVelocity( pm->ps->velocity, pml.groundTrace.plane.normal,
pm->ps->velocity, OVERCLIP );
}
}
time_left = pml.frametime;
// never turn against the ground plane
if ( pml.groundPlane ) {
numplanes = 1;
VectorCopy( pml.groundTrace.plane.normal, planes[0] );
} else {
numplanes = 0;
}
// never turn against original velocity
VectorNormalize2( pm->ps->velocity, planes[numplanes] );
numplanes++;
for ( bumpcount = 0 ; bumpcount < numbumps ; bumpcount++ ) {
// calculate position we are trying to move to
VectorMA( pm->ps->origin, time_left, pm->ps->velocity, end );
// see if we can make it there
pm->trace( &trace, pm->ps->origin, pm->mins, pm->maxs, end, pm->ps->clientNum, pm->tracemask );
if ( trace.allsolid ) {
// entity is completely trapped in another solid
pm->ps->velocity[2] = 0; // don't build up falling damage, but allow sideways acceleration
return qtrue;
}
if ( trace.fraction > 0 ) {
// actually covered some distance
VectorCopy( trace.endpos, pm->ps->origin );
}
if ( trace.fraction == 1 ) {
break; // moved the entire distance
}
// save entity for contact
PM_AddTouchEnt( trace.entityNum );
time_left -= time_left * trace.fraction;
if ( numplanes >= MAX_CLIP_PLANES ) {
// this shouldn't really happen
VectorClear( pm->ps->velocity );
return qtrue;
}
//
// if this is the same plane we hit before, nudge velocity
// out along it, which fixes some epsilon issues with
// non-axial planes
//
for ( i = 0 ; i < numplanes ; i++ ) {
if ( DotProduct( trace.plane.normal, planes[i] ) > 0.99 ) {
VectorAdd( trace.plane.normal, pm->ps->velocity, pm->ps->velocity );
break;
}
}
if ( i < numplanes ) {
continue;
}
VectorCopy( trace.plane.normal, planes[numplanes] );
numplanes++;
//
// modify velocity so it parallels all of the clip planes
//
// find a plane that it enters
for ( i = 0 ; i < numplanes ; i++ ) {
into = DotProduct( pm->ps->velocity, planes[i] );
if ( into >= 0.1 ) {
continue; // move doesn't interact with the plane
}
// see how hard we are hitting things
if ( -into > pml.impactSpeed ) {
pml.impactSpeed = -into;
}
// slide along the plane
PM_ClipVelocity( pm->ps->velocity, planes[i], clipVelocity, OVERCLIP );
if ( gravity ) {
// slide along the plane
PM_ClipVelocity( endVelocity, planes[i], endClipVelocity, OVERCLIP );
}
// see if there is a second plane that the new move enters
for ( j = 0 ; j < numplanes ; j++ ) {
if ( j == i ) {
continue;
}
if ( DotProduct( clipVelocity, planes[j] ) >= 0.1 ) {
continue; // move doesn't interact with the plane
}
// try clipping the move to the plane
PM_ClipVelocity( clipVelocity, planes[j], clipVelocity, OVERCLIP );
if ( gravity ) {
PM_ClipVelocity( endClipVelocity, planes[j], endClipVelocity, OVERCLIP );
}
// see if it goes back into the first clip plane
if ( DotProduct( clipVelocity, planes[i] ) >= 0 ) {
continue;
}
// slide the original velocity along the crease
CrossProduct( planes[i], planes[j], dir );
VectorNormalize( dir );
d = DotProduct( dir, pm->ps->velocity );
VectorScale( dir, d, clipVelocity );
if ( gravity ) {
CrossProduct( planes[i], planes[j], dir );
VectorNormalize( dir );
d = DotProduct( dir, endVelocity );
VectorScale( dir, d, endClipVelocity );
}
// see if there is a third plane the the new move enters
for ( k = 0 ; k < numplanes ; k++ ) {
if ( k == i || k == j ) {
continue;
}
if ( DotProduct( clipVelocity, planes[k] ) >= 0.1 ) {
continue; // move doesn't interact with the plane
}
// stop dead at a tripple plane interaction
VectorClear( pm->ps->velocity );
return qtrue;
}
}
// if we have fixed all interactions, try another move
VectorCopy( clipVelocity, pm->ps->velocity );
if ( gravity ) {
VectorCopy( endClipVelocity, endVelocity );
}
break;
}
}
if ( gravity ) {
VectorCopy( endVelocity, pm->ps->velocity );
}
// don't change velocity if in a timer (FIXME: is this correct?)
if ( pm->ps->pm_time ) {
VectorCopy( primal_velocity, pm->ps->velocity );
}
return ( bumpcount != 0 );
}
/*
==================
PM_StepSlideMove
==================
*/
void PM_StepSlideMove( qboolean gravity ) {
vec3_t start_o, start_v;
// vec3_t down_o, down_v;
trace_t trace;
// float down_dist, up_dist;
// vec3_t delta, delta2;
vec3_t up, down;
VectorCopy( pm->ps->origin, start_o );
VectorCopy( pm->ps->velocity, start_v );
if ( PM_SlideMove( gravity ) == 0 ) {
return; // we got exactly where we wanted to go first try
}
VectorCopy( start_o, down );
down[2] -= STEPSIZE;
pm->trace( &trace, start_o, pm->mins, pm->maxs, down, pm->ps->clientNum, pm->tracemask );
VectorSet( up, 0, 0, 1 );
// never step up when you still have up velocity
if ( pm->ps->velocity[2] > 0 && ( trace.fraction == 1.0 ||
DotProduct( trace.plane.normal, up ) < 0.7 ) ) {
return;
}
// VectorCopy( pm->ps->origin, down_o );
// VectorCopy( pm->ps->velocity, down_v );
VectorCopy( start_o, up );
up[2] += STEPSIZE;
// test the player position if they were a stepheight higher
pm->trace( &trace, up, pm->mins, pm->maxs, up, pm->ps->clientNum, pm->tracemask );
if ( trace.allsolid ) {
if ( pm->debugLevel ) {
Com_Printf( "%i:bend can't step\n", c_pmove );
}
return; // can't step up
}
// try slidemove from this position
VectorCopy( up, pm->ps->origin );
VectorCopy( start_v, pm->ps->velocity );
PM_SlideMove( gravity );
// push down the final amount
VectorCopy( pm->ps->origin, down );
down[2] -= STEPSIZE;
pm->trace( &trace, pm->ps->origin, pm->mins, pm->maxs, down, pm->ps->clientNum, pm->tracemask );
if ( !trace.allsolid ) {
VectorCopy( trace.endpos, pm->ps->origin );
}
if ( trace.fraction < 1.0 ) {
PM_ClipVelocity( pm->ps->velocity, trace.plane.normal, pm->ps->velocity, OVERCLIP );
}
#if 0
// if the down trace can trace back to the original position directly, don't step
pm->trace( &trace, pm->ps->origin, pm->mins, pm->maxs, start_o, pm->ps->clientNum, pm->tracemask );
if ( trace.fraction == 1.0 ) {
// use the original move
VectorCopy( down_o, pm->ps->origin );
VectorCopy( down_v, pm->ps->velocity );
if ( pm->debugLevel ) {
Com_Printf( "%i:bend\n", c_pmove );
}
} else
#endif
{
// use the step move
float delta;
delta = pm->ps->origin[2] - start_o[2];
if ( delta > 2 ) {
if ( delta < 7 ) {
PM_AddEvent( EV_STEP_4 );
} else if ( delta < 11 ) {
PM_AddEvent( EV_STEP_8 );
} else if ( delta < 15 ) {
PM_AddEvent( EV_STEP_12 );
} else {
PM_AddEvent( EV_STEP_16 );
}
}
if ( pm->debugLevel ) {
Com_Printf( "%i:stepped\n", c_pmove );
}
}
}
| 412 | 0.665526 | 1 | 0.665526 | game-dev | MEDIA | 0.870115 | game-dev | 0.871766 | 1 | 0.871766 |
dengzibiao/moba | 2,136 | Assets/Script/UI_LG/UIFieldMap_Enter.cs | using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;
public class UIFieldMap_Enter : GUIBase
{
public static UIFieldMap_Enter instance;
public GUISingleButton enterBtn;
public GUISingleButton cancelBtn;
private UILabel lable;
public UIFieldMap_Enter()
{
instance = this;
}
public override UIPanleID GetUIKey()
{
return UIPanleID.none;
}
protected override void Init()
{
enterBtn.onClick = OnEnterClick;
cancelBtn.onClick = OnCancelClick;
}
//private void OnRefreshClick()
//{
// if (UIMoney.instance.jewelCount > refreshPrice)
// {
// ClientSendDataMgr.GetSingle().GetCShopSend().RefreshGoodsList(playerData.GetInstance().selfData.playerId, playerData.GetInstance().selfData.level, _index, count);
// }
//}
private void OnEnterClick()
{
this.gameObject.SetActive(false);
Singleton<SceneManage>.Instance.Current = EnumSceneID.LGhuangyuan;
//UI_Loading.LoadScene("LGhuangyuan", 3);
GameLibrary.LastScene = SceneManager.GetActiveScene().name;//记录前一个场景名
StartLandingShuJu.GetInstance().GetLoadingData("LGhuangyuan", 3);
SceneManager.LoadScene("Loding");
}
public void OpenWin()
{
Init();
this.gameObject.SetActive(true);
}
public void OnCancelClick()
{
this.gameObject.SetActive(false);
}
//protected override void ShowHandler()
//{
// count = 0;
// print(_index);
// print(VOManager.Instance().GetCSV<ShopCSV>("Shop").GetVO(_index).id);
// //for (int i = 1; i < VOManager.Instance().GetCSV<ShopCSV>("Shop").GetVoList() .Length ; i++)
// //{
// // print(VOManager.Instance().GetCSV<ShopCSV>("Shop").GetVoList()[i]);
// //}
// // vo = VOManager.Instance().GetCSV<ShopCSV>("Shop").GetVO(_index);
// // refreshPrice = vo.refresh_cost[count];
//}
//public static int count;
//private int refreshPrice;
//private int _index;
//private ShopVO vo;
}
| 412 | 0.731603 | 1 | 0.731603 | game-dev | MEDIA | 0.897557 | game-dev | 0.900246 | 1 | 0.900246 |
tanishqmanuja/valorant-rank-yoinker-js | 3,248 | src/table/plugins/player-skins.plugin.ts | import chalk from "chalk";
import { z } from "zod";
import { ValorantApi } from "~/api";
import { GAMESTATES, Weapon } from "~/api/types";
import { SkinsEntity } from "~/entities/definitions/skins.entity";
import { inject } from "~/shared/dependencies";
import { ensureArray } from "~/utils/array";
import type { RGBTuple } from "~/utils/colors/types";
import { tryCatch } from "~/utils/promise";
import { definePlugin } from "../types/plugin.interface";
const PLUGIN_ID = "player-skins";
export const PlayerSkinsPlugin = definePlugin({
id: PLUGIN_ID,
hooks: {
onState: async ({ data, table, config }) => {
if (data._state === GAMESTATES.MENUS) {
return;
}
const api = inject(ValorantApi);
const selectedWeapons = parseWeapons(
api,
ensureArray(config.weapons),
).filter(Boolean) as Weapon[];
const replacements = tryCatch(
() =>
z
.record(z.string(), z.string())
.default({})
.parse(config.replacements),
() => ({}),
);
const entities = await table.entityManager.getEntitiesForPlayers(data, [
SkinsEntity,
]);
selectedWeapons.forEach((weapon, index) => {
const colId = `${PLUGIN_ID}@${index}`;
for (const puuid in entities) {
const { skins } = entities[puuid]!;
if (!skins) {
continue;
}
table.grid.setCell({
rowId: puuid,
colId,
value: formatSkin({
skins,
selected: weapon.displayName,
replacements,
}),
});
}
table.headers.set(colId, weapon.displayName);
});
},
},
});
/* Parser */
function parseWeapons(api: ValorantApi, names: string[]) {
return names.map(name =>
api.content.weapons.find(
w => w.displayName.toLowerCase() === name?.toLowerCase(),
),
);
}
/* Formatter */
function formatSkin(opts: {
skins: Record<string, Weapon["skins"][number]>;
selected: string;
replacements: Record<string, string>;
}) {
const skin = opts.skins[opts.selected.toLowerCase()]!;
const regex = new RegExp(opts.selected, "ig");
const name = skin.displayName.replace(regex, "").trim();
const colorRGB = getSkinColorFromTier(skin.contentTierUuid!);
if (name === "Random Favorite Skin") {
return chalk.rgb(...colorRGB)("Randomized");
}
if (name.toLowerCase() === "standard") {
return chalk.gray(name);
}
const replacement = Object.entries(opts.replacements).find(
([k]) => k.toLowerCase() === name.toLowerCase(),
);
if (replacement) {
return chalk.rgb(...colorRGB)(replacement[1]);
}
return chalk.rgb(...colorRGB)(name);
}
const contentTierColorLUT: Record<string, RGBTuple> = {
"0cebb8be-46d7-c12a-d306-e9907bfc5a25": [0, 149, 135],
"e046854e-406c-37f4-6607-19a9ba8426fc": [241, 184, 45],
"60bca009-4182-7998-dee7-b8a2558dc369": [209, 84, 141],
"12683d76-48d7-84a3-4e09-6985794f0445": [90, 159, 226],
"411e4a55-4e59-7757-41f0-86a53f101bb5": [239, 235, 101],
};
export const getSkinColorFromTier = (tierUUID: string) => {
const color = contentTierColorLUT[tierUUID];
return color ?? [180, 180, 180];
};
| 412 | 0.910713 | 1 | 0.910713 | game-dev | MEDIA | 0.590211 | game-dev | 0.972848 | 1 | 0.972848 |
followingthefasciaplane/source-engine-diff-check | 35,755 | misc/engine/cvar.cpp | //===== Copyright 1996-2005, Valve Corporation, All rights reserved. ======//
//
// Purpose:
//
// $NoKeywords: $
//
//===========================================================================//
#include "cvar.h"
#include "gl_cvars.h"
#include "tier1/convar.h"
#include "filesystem.h"
#include "filesystem_engine.h"
#include "client.h"
#include "server.h"
#include "GameEventManager.h"
#include "netmessages.h"
#include "sv_main.h"
#include "demo.h"
#include <ctype.h>
#include "vstdlib/vstrtools.h"
#ifdef POSIX
#include <wctype.h>
#endif
#ifdef _PS3
#include <ps3/ps3_console.h>
#endif
#ifndef DEDICATED
#include <vgui_controls/Controls.h>
#include <vgui/ILocalize.h>
#endif
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
//-----------------------------------------------------------------------------
// Singleton CCvarUtilities
//-----------------------------------------------------------------------------
static CCvarUtilities g_CvarUtilities;
CCvarUtilities *ConVarUtilities = &g_CvarUtilities;
//-----------------------------------------------------------------------------
// Purpose: Update clients/server when FCVAR_REPLICATED etc vars change
//-----------------------------------------------------------------------------
static void ConVarNetworkChangeCallback( IConVar *pConVar, const char *pOldValue, float flOldValue )
{
ConVarRef var( pConVar );
if ( !pOldValue )
{
if ( var.GetFloat() == flOldValue )
return;
}
else
{
if ( !Q_strcmp( var.GetString(), pOldValue ) )
return;
}
if ( var.IsFlagSet( FCVAR_USERINFO ) )
{
#ifndef DEDICATED
ACTIVE_SPLITSCREEN_PLAYER_GUARD( var.GetSplitScreenPlayerSlot() );
// Are we not a server, but a client and have a change?
if ( GetLocalClient().IsConnected() )
{
// send changed cvar to server
CNETMsg_SetConVar_t convar( var.GetBaseName(), var.GetString() );
GetLocalClient().m_NetChannel->SendNetMsg( convar );
}
#endif
}
// Log changes to server variables
// Print to clients
if ( var.IsFlagSet( FCVAR_NOTIFY ) )
{
IGameEvent *event = g_GameEventManager.CreateEvent( "server_cvar" );
if ( event )
{
event->SetString( "cvarname", var.GetName() );
if ( var.IsFlagSet( FCVAR_PROTECTED ) )
{
event->SetString("cvarvalue", "***PROTECTED***" );
}
else
{
event->SetString("cvarvalue", var.GetString() );
}
g_GameEventManager.FireEvent( event );
}
}
// Force changes down to clients (if running server)
if ( var.IsFlagSet( FCVAR_REPLICATED ) && sv.IsActive() )
{
SV_ReplicateConVarChange( static_cast< ConVar* >( pConVar ), var.GetString() );
}
}
//-----------------------------------------------------------------------------
// Implementation of the ICvarQuery interface
//-----------------------------------------------------------------------------
class CCvarQuery : public CBaseAppSystem< ICvarQuery >
{
public:
bool m_bCallbackInstalled;
CCvarQuery( void )
{
m_bCallbackInstalled = false;
}
virtual bool Connect( CreateInterfaceFn factory )
{
ICvar *pCVar = (ICvar*)factory( CVAR_INTERFACE_VERSION, 0 );
if ( !pCVar )
return false;
pCVar->InstallCVarQuery( this );
return true;
}
virtual InitReturnVal_t Init()
{
// If the value has changed, notify clients/server based on ConVar flags.
// NOTE: this will only happen for non-FCVAR_NEVER_AS_STRING vars.
// Also, this happened in SetDirect for older clients that don't have the
// callback interface.
if (! m_bCallbackInstalled )
{
m_bCallbackInstalled = true;
g_pCVar->InstallGlobalChangeCallback( ConVarNetworkChangeCallback );
}
return INIT_OK;
}
virtual void Shutdown()
{
g_pCVar->RemoveGlobalChangeCallback( ConVarNetworkChangeCallback );
m_bCallbackInstalled = false;
}
virtual void *QueryInterface( const char *pInterfaceName )
{
if ( !Q_stricmp( pInterfaceName, CVAR_QUERY_INTERFACE_VERSION ) )
return (ICvarQuery*)this;
return NULL;
}
// Purpose: Returns true if the commands can be aliased to one another
// Either game/client .dll shared with engine,
// or game and client dll shared and marked FCVAR_REPLICATED
virtual bool AreConVarsLinkable( const ConVar *child, const ConVar *parent )
{
// Both parent and child must be marked replicated for this to work
bool repchild = child->IsFlagSet( FCVAR_REPLICATED );
bool repparent = parent->IsFlagSet( FCVAR_REPLICATED );
if ( repchild && repparent )
{
// Never on protected vars
if ( child->IsFlagSet( FCVAR_PROTECTED ) || parent->IsFlagSet( FCVAR_PROTECTED ) )
{
ConMsg( "FCVAR_REPLICATED can't also be FCVAR_PROTECTED (%s)\n", child->GetName() );
return false;
}
// Only on ConVars
if ( child->IsCommand() || parent->IsCommand() )
{
ConMsg( "FCVAR_REPLICATED not valid on ConCommands (%s)\n", child->GetName() );
return false;
}
// One must be in client .dll and the other in the game .dll, or both in the engine
if ( child->IsFlagSet( FCVAR_GAMEDLL ) && !parent->IsFlagSet( FCVAR_CLIENTDLL ) )
{
ConMsg( "For FCVAR_REPLICATED, ConVar must be defined in client and game .dlls (%s)\n", child->GetName() );
return false;
}
if ( child->IsFlagSet( FCVAR_CLIENTDLL ) && !parent->IsFlagSet( FCVAR_GAMEDLL ) )
{
ConMsg( "For FCVAR_REPLICATED, ConVar must be defined in client and game .dlls (%s)\n", child->GetName() );
return false;
}
// Allowable
return true;
}
// Otherwise need both to allow linkage
if ( repchild || repparent )
{
ConMsg( "Both ConVars must be marked FCVAR_REPLICATED for linkage to work (%s)\n", child->GetName() );
return false;
}
if ( parent->IsFlagSet( FCVAR_CLIENTDLL ) )
{
ConMsg( "Parent cvar in client.dll not allowed (%s)\n", child->GetName() );
return false;
}
if ( parent->IsFlagSet( FCVAR_GAMEDLL ) )
{
ConMsg( "Parent cvar in server.dll not allowed (%s)\n", child->GetName() );
return false;
}
return true;
}
};
//-----------------------------------------------------------------------------
// Singleton
//-----------------------------------------------------------------------------
static CCvarQuery s_CvarQuery;
EXPOSE_SINGLE_INTERFACE_GLOBALVAR( CCvarQuery, ICvarQuery, CVAR_QUERY_INTERFACE_VERSION, s_CvarQuery );
void InstallConVarHook( void )
{
s_CvarQuery.Init();
}
//-----------------------------------------------------------------------------
//
// CVar utilities begins here
//
//-----------------------------------------------------------------------------
static bool IsAllSpaces( const wchar_t *str )
{
const wchar_t *p = str;
while ( p && *p )
{
if ( !iswspace( *p ) )
return false;
++p;
}
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *var -
// *value -
//-----------------------------------------------------------------------------
void CCvarUtilities::SetDirect( ConVar *var, const char *value )
{
const char *pszValue;
char szNew[ 1024 ];
// Bail early if we're trying to set a FCVAR_USERINFO cvar on a dedicated server
if ( var->IsFlagSet( FCVAR_USERINFO ) )
{
if ( sv.IsDedicated() )
{
return;
}
}
pszValue = value;
// This cvar's string must only contain printable characters.
// Strip out any other crap.
// We'll fill in "empty" if nothing is left
if ( var->IsFlagSet( FCVAR_PRINTABLEONLY ) )
{
wchar_t unicode[ 512 ];
#ifndef DEDICATED
if ( sv.IsDedicated() )
{
// Dedicated servers don't have g_pVGuiLocalize, so fall back
V_UTF8ToUnicode( pszValue, unicode, sizeof( unicode ) );
}
else
{
g_pVGuiLocalize->ConvertANSIToUnicode( pszValue, unicode, sizeof( unicode ) );
}
#else
V_UTF8ToUnicode( pszValue, unicode, sizeof( unicode ) );
#endif
wchar_t newUnicode[ 512 ];
const wchar_t *pS;
wchar_t *pD;
// Clear out new string
newUnicode[0] = L'\0';
pS = unicode;
pD = newUnicode;
// Step through the string, only copying back in characters that are printable
while ( *pS )
{
if ( iswcntrl( *pS ) || *pS == '~' )
{
pS++;
continue;
}
*pD++ = *pS++;
}
// Terminate the new string
*pD = L'\0';
// If it's empty or all spaces, then insert a marker string
if ( !wcslen( newUnicode ) || IsAllSpaces( newUnicode ) )
{
wcsncpy( newUnicode, L"#empty", ( sizeof( newUnicode ) / sizeof( wchar_t ) ) - 1 );
newUnicode[ ( sizeof( newUnicode ) / sizeof( wchar_t ) ) - 1 ] = L'\0';
}
#ifndef DEDICATED
if ( sv.IsDedicated() )
{
V_UnicodeToUTF8( newUnicode, szNew, sizeof( szNew ) );
}
else
{
g_pVGuiLocalize->ConvertUnicodeToANSI( newUnicode, szNew, sizeof( szNew ) );
}
#else
V_UnicodeToUTF8( newUnicode, szNew, sizeof( szNew ) );
#endif
// Point the value here.
pszValue = szNew;
}
if ( var->IsFlagSet( FCVAR_NEVER_AS_STRING ) )
{
var->SetValue( (float)atof( pszValue ) );
}
else
{
var->SetValue( pszValue );
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
// If you are changing this, please take a look at IsValidToggleCommand()
bool CCvarUtilities::IsCommand( const CCommand &args, const int iSplitscreenSlot /*= -1*/ )
{
int c = args.ArgC();
if ( c == 0 )
return false;
ConVar *v;
// check variables
v = g_pCVar->FindVar( args[0] );
if ( !v )
return false;
// adjust for split screen convars for slots 2, 3, 4
if ( iSplitscreenSlot > 0 && v->IsFlagSet( FCVAR_SS ) )
{
char buf[512];
Q_snprintf( buf, sizeof(buf), "%s%d", args[0], iSplitscreenSlot+1 );
v = g_pCVar->FindVar( buf );
}
if ( !v )
return false;
// NOTE: Not checking for 'HIDDEN' here so we can actually set hidden convars
if ( v->IsFlagSet(FCVAR_DEVELOPMENTONLY) )
return false;
// perform a variable print or set
if ( c == 1 )
{
ConVar_PrintDescription( v );
return true;
}
if ( v->IsFlagSet( FCVAR_SPONLY ) )
{
#ifndef DEDICATED
// Connected to server?
if ( GetBaseLocalClient().IsConnected() )
{
// Is it not a single player game?
if ( GetBaseLocalClient().m_nMaxClients > 1 )
{
ConMsg( "Can't set %s in multiplayer\n", v->GetName() );
return true;
}
}
#endif
}
if ( v->IsFlagSet( FCVAR_NOT_CONNECTED ) )
{
#ifndef DEDICATED
// Connected to server?
if ( GetBaseLocalClient().IsConnected() )
{
extern IBaseClientDLL *g_ClientDLL;
if ( v->IsFlagSet( FCVAR_USERINFO ) && g_ClientDLL && g_ClientDLL->IsConnectedUserInfoChangeAllowed( v ) )
{
// Client.dll is allowing the convar change
}
else
{
ConMsg( "Can't change %s when playing, disconnect from the server or switch team to spectators\n", v->GetName() );
return true;
}
}
#endif
}
// Allow cheat commands in singleplayer, debug, or multiplayer with sv_cheats on
if ( v->IsFlagSet( FCVAR_CHEAT ) )
{
if ( !Host_IsSinglePlayerGame() && !CanCheat()
#if !defined(DEDICATED)
&& !GetBaseLocalClient().ishltv
#if defined( REPLAY_ENABLED )
&& !GetBaseLocalClient().isreplay
#endif
&& !demoplayer->IsPlayingBack()
#endif
)
{
ConMsg( "Can't use cheat cvar %s in multiplayer, unless the server has sv_cheats set to 1.\n", v->GetName() );
return true;
}
}
// Text invoking the command was typed into the console, decide what to do with it
// if this is a replicated ConVar, except don't worry about restrictions if playing a .dem file
if ( v->IsFlagSet( FCVAR_REPLICATED )
#if !defined(DEDICATED)
&& !demoplayer->IsPlayingBack()
#endif
)
{
#ifndef DEDICATED
// If not running a server but possibly connected as a client, then
// if the message came from console, don't process the command
if ( !sv.IsActive()
&& !sv.IsLoading()
&& GetBaseLocalClient().IsConnected()
)
{
ConMsg( "Can't change replicated ConVar %s from console of client, only server operator can change its value\n", v->GetName() );
return true;
}
#endif
}
// Note that we don't want the tokenized list, send down the entire string
// except for surrounding quotes
char remaining[1024];
const char *pArgS = args.ArgS();
int nLen = Q_strlen( pArgS );
bool bIsQuoted = pArgS[0] == '\"';
if ( !bIsQuoted )
{
Q_strncpy( remaining, args.ArgS(), sizeof(remaining) );
}
else
{
--nLen;
Q_strncpy( remaining, &pArgS[1], sizeof(remaining) );
}
// Now strip off any trailing spaces
char *p = remaining + nLen - 1;
while ( p >= remaining )
{
if ( *p > ' ' )
break;
*p-- = 0;
}
// Strip off ending quote
if ( bIsQuoted && p >= remaining )
{
if ( *p == '\"' )
{
*p = 0;
}
}
SetDirect( v, remaining );
return true;
}
// This is a band-aid copied directly from IsCommand().
bool CCvarUtilities::IsValidToggleCommand( const char *cmd )
{
ConVar *v;
// check variables
v = g_pCVar->FindVar ( cmd );
if (!v)
{
ConMsg( "%s is not a valid cvar\n", cmd );
return false;
}
if ( v->IsFlagSet(FCVAR_DEVELOPMENTONLY) || v->IsFlagSet(FCVAR_HIDDEN) )
return false;
if ( v->IsFlagSet( FCVAR_SPONLY ) )
{
#ifndef DEDICATED
// Connected to server?
if ( GetBaseLocalClient().IsConnected() )
{
// Is it not a single player game?
if ( GetBaseLocalClient().m_nMaxClients > 1 )
{
ConMsg( "Can't set %s in multiplayer\n", v->GetName() );
return false;
}
}
#endif
}
if ( v->IsFlagSet( FCVAR_NOT_CONNECTED ) )
{
#ifndef DEDICATED
// Connected to server?
if ( GetBaseLocalClient().IsConnected() )
{
extern IBaseClientDLL *g_ClientDLL;
if ( v->IsFlagSet( FCVAR_USERINFO ) && g_ClientDLL && g_ClientDLL->IsConnectedUserInfoChangeAllowed( v ) )
{
// Client.dll is allowing the convar change
}
else
{
ConMsg( "Can't change %s when playing, disconnect from the server or switch team to spectators\n", v->GetName() );
return false;
}
}
#endif
}
// Allow cheat commands in singleplayer, debug, or multiplayer with sv_cheats on
if ( v->IsFlagSet( FCVAR_CHEAT ) )
{
if ( !Host_IsSinglePlayerGame() && !CanCheat()
#if !defined(DEDICATED)
&& !demoplayer->IsPlayingBack()
#endif
)
{
ConMsg( "Can't use cheat cvar %s in multiplayer, unless the server has sv_cheats set to 1.\n", v->GetName() );
return false;
}
}
// Text invoking the command was typed into the console, decide what to do with it
// if this is a replicated ConVar, except don't worry about restrictions if playing a .dem file
if ( v->IsFlagSet( FCVAR_REPLICATED )
#if !defined(DEDICATED)
&& !demoplayer->IsPlayingBack()
#endif
)
{
#ifndef DEDICATED
// If not running a server but possibly connected as a client, then
// if the message came from console, don't process the command
if ( !sv.IsActive()
&& !sv.IsLoading()
&& GetBaseLocalClient().IsConnected()
)
{
ConMsg( "Can't change replicated ConVar %s from console of client, only server operator can change its value\n", v->GetName() );
return false;
}
#endif
}
return true;
}
void CCvarUtilities::ResetConVarsToDefaultValues( const char *pMatchStr )
{
ICvar::Iterator iter( g_pCVar );
for ( iter.SetFirst() ; iter.IsValid() ; iter.Next() )
{
ConCommandBase *var = iter.Get();
if ( var->IsCommand() )
continue;
ConVar *cv = (ConVar *)var;
if ( ( ! pMatchStr ) || // null pattern match?
( memcmp( pMatchStr, cv->GetName(), strlen( pMatchStr ) ) == 0 ) // first chars match
)
{
cv->Revert();
}
}
}
static bool CVarSortFunc( ConVar * const &lhs, ConVar * const &rhs )
{
return ( CaselessStringLessThan( lhs->GetName(), rhs->GetName() ) );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *f -
//-----------------------------------------------------------------------------
void CCvarUtilities::WriteVariables( CUtlBuffer *buff, const int iSplitscreenSlot /*= -1*/, bool bSlotRequired /* = false */, void *pConvarsListVoid /*= NULL*/ )
{
CUtlRBTree< ConVar *, int > sorted( 0, 0, CVarSortFunc );
CUtlVector< ConVar * > *pConvarsList = (CUtlVector< ConVar * > *)pConvarsListVoid;
ICvar::Iterator iter( g_pCVar );
for ( iter.SetFirst() ; iter.IsValid() ; iter.Next() )
{
ConCommandBase *var = iter.Get();
if ( var->IsCommand() )
continue;
ConVar *cv = (ConVar *)var;
bool archive = cv->IsFlagSet( IsGameConsole() ? FCVAR_ARCHIVE_GAMECONSOLE : FCVAR_ARCHIVE );
if ( archive )
{
if ( iSplitscreenSlot >= 0 )
{
bool bSlotSpecificConvar = false;
if ( cv->IsFlagSet( FCVAR_SS ) )
{
// only valid for the 0'th player
if ( iSplitscreenSlot != 0 )
{
continue;
}
bSlotSpecificConvar = true;
}
if ( cv->IsFlagSet( FCVAR_SS_ADDED ) )
{
// which added player is this relevant to
CSplitScreenAddedConVar *pCheck = dynamic_cast< CSplitScreenAddedConVar * >( cv );
if ( pCheck && pCheck->GetSplitScreenPlayerSlot() != iSplitscreenSlot )
{
continue;
}
bSlotSpecificConvar = true;
}
if ( bSlotRequired != bSlotSpecificConvar )
{
continue;
}
}
sorted.Insert( cv );
}
}
for ( int i = sorted.FirstInorder(); i != sorted.InvalidIndex(); i = sorted.NextInorder( i ) )
{
ConVar *var = sorted[ i ];
// If we are saving per-controller, we always want to write the base name ( joy_inverty as opposed to joy_inverty2 )
const char *name = ( iSplitscreenSlot >= 0 ) ? var->GetBaseName() : var->GetName();
DevMsg( 2, "%s \"%s\"\n", name, var->GetString() );
if ( buff )
buff->Printf( "%s \"%s\"\n", name, var->GetString() );
if ( pConvarsList )
pConvarsList->AddToTail( var );
}
}
static void Cmd_SetPlayer( int slot, const CCommand &args )
{
if ( slot >= host_state.max_splitscreen_players )
{
DevMsg( 1, "ignore: %d '%s'\n", slot, args.ArgS() );
return;
}
// Strip the cmdN and pass the rest of the command to the appropriate slot
Cbuf_AddText( (ECommandTarget_t)slot, args.ArgS() );
}
CON_COMMAND( cmd1, "sets userinfo string for split screen player in slot 1" )
{
Cmd_SetPlayer( 0, args );
}
CON_COMMAND( cmd2, "sets userinfo string for split screen player in slot 2" )
{
Cmd_SetPlayer( 1, args );
}
CON_COMMAND( cmd3, "sets userinfo string for split screen player in slot 3" )
{
Cmd_SetPlayer( 2, args );
}
CON_COMMAND( cmd4, "sets userinfo string for split screen player in slot 4" )
{
Cmd_SetPlayer( 3, args );
}
static char *StripTabsAndReturns( const char *inbuffer, char *outbuffer, int outbufferSize )
{
char *out = outbuffer;
const char *i = inbuffer;
char *o = out;
out[ 0 ] = 0;
while ( *i && o - out < outbufferSize - 1 )
{
if ( *i == '\n' ||
*i == '\r' ||
*i == '\t' )
{
*o++ = ' ';
i++;
continue;
}
if ( *i == '\"' )
{
*o++ = '\'';
i++;
continue;
}
*o++ = *i++;
}
*o = '\0';
return out;
}
static char *StripQuotes( const char *inbuffer, char *outbuffer, int outbufferSize )
{
char *out = outbuffer;
const char *i = inbuffer;
char *o = out;
out[ 0 ] = 0;
while ( *i && o - out < outbufferSize - 1 )
{
if ( *i == '\"' )
{
*o++ = '\'';
i++;
continue;
}
*o++ = *i++;
}
*o = '\0';
return out;
}
struct ConVarFlags_t
{
int bit;
const char *desc;
const char *shortdesc;
};
#define CONVARFLAG( x, y ) { FCVAR_##x, #x, #y }
static ConVarFlags_t g_ConVarFlags[]=
{
// CONVARFLAG( UNREGISTERED, "u" ),
CONVARFLAG( ARCHIVE, "a" ),
CONVARFLAG( SPONLY, "sp" ),
CONVARFLAG( GAMEDLL, "sv" ),
CONVARFLAG( CHEAT, "cheat" ),
CONVARFLAG( USERINFO, "user" ),
CONVARFLAG( NOTIFY, "nf" ),
CONVARFLAG( PROTECTED, "prot" ),
CONVARFLAG( PRINTABLEONLY, "print" ),
CONVARFLAG( UNLOGGED, "log" ),
CONVARFLAG( NEVER_AS_STRING, "numeric" ),
CONVARFLAG( REPLICATED, "rep" ),
CONVARFLAG( DEMO, "demo" ),
CONVARFLAG( DONTRECORD, "norecord" ),
CONVARFLAG( SERVER_CAN_EXECUTE, "server_can_execute" ),
CONVARFLAG( CLIENTCMD_CAN_EXECUTE, "clientcmd_can_execute" ),
CONVARFLAG( CLIENTDLL, "cl" ),
CONVARFLAG( SS, "ss" ),
CONVARFLAG( SS_ADDED, "ss_added" ),
CONVARFLAG( DEVELOPMENTONLY, "dev_only" ),
};
static void PrintListHeader( FileHandle_t& f )
{
char csvflagstr[ 1024 ];
csvflagstr[ 0 ] = 0;
int c = ARRAYSIZE( g_ConVarFlags );
for ( int i = 0 ; i < c; ++i )
{
char csvf[ 64 ];
ConVarFlags_t & entry = g_ConVarFlags[ i ];
Q_snprintf( csvf, sizeof( csvf ), "\"%s\",", entry.desc );
Q_strncat( csvflagstr, csvf, sizeof( csvflagstr ), COPY_ALL_CHARACTERS );
}
g_pFileSystem->FPrintf( f,"\"%s\",\"%s\",%s,\"%s\"\n", "Name", "Value", csvflagstr, "Help Text" );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *var -
// *f -
//-----------------------------------------------------------------------------
static void PrintCvar( const ConVar *var, bool logging, FileHandle_t& f )
{
char flagstr[ 128 ];
char csvflagstr[ 1024 ];
flagstr[ 0 ] = 0;
csvflagstr[ 0 ] = 0;
int c = ARRAYSIZE( g_ConVarFlags );
for ( int i = 0 ; i < c; ++i )
{
char f[ 32 ];
char csvf[ 64 ];
ConVarFlags_t & entry = g_ConVarFlags[ i ];
if ( var->IsFlagSet( entry.bit ) )
{
Q_snprintf( f, sizeof( f ), ", %s", entry.shortdesc );
Q_strncat( flagstr, f, sizeof( flagstr ), COPY_ALL_CHARACTERS );
Q_snprintf( csvf, sizeof( csvf ), "\"%s\",", entry.desc );
}
else
{
Q_snprintf( csvf, sizeof( csvf ), "," );
}
Q_strncat( csvflagstr, csvf, sizeof( csvflagstr ), COPY_ALL_CHARACTERS );
}
char valstr[ 32 ];
char tempbuff[128];
// Clean up integers
if ( var->GetInt() == (int)var->GetFloat() )
{
Q_snprintf(valstr, sizeof( valstr ), "%-8i", var->GetInt() );
}
else
{
Q_snprintf(valstr, sizeof( valstr ), "%-8.3f", var->GetFloat() );
}
// Print to console
ConMsg( "%-40s : %-8s : %-16s : %s\n", var->GetName(), valstr, flagstr, StripTabsAndReturns( var->GetHelpText(), tempbuff, sizeof(tempbuff) ) );
if ( logging )
{
g_pFileSystem->FPrintf( f,"\"%s\",\"%s\",%s,\"%s\"\n", var->GetName(), valstr, csvflagstr, StripQuotes( var->GetHelpText(), tempbuff, sizeof(tempbuff) ) );
}
}
static void PrintCommand( const ConCommand *cmd, bool logging, FileHandle_t& f )
{
// Print to console
char tempbuff[128];
ConMsg ("%-40s : %-8s : %-16s : %s\n",cmd->GetName(), "cmd", "", StripTabsAndReturns( cmd->GetHelpText(), tempbuff, sizeof(tempbuff) ) );
if ( logging )
{
char emptyflags[ 256 ];
emptyflags[ 0 ] = 0;
int c = ARRAYSIZE( g_ConVarFlags );
for ( int i = 0; i < c; ++i )
{
char csvf[ 64 ];
Q_snprintf( csvf, sizeof( csvf ), "," );
Q_strncat( emptyflags, csvf, sizeof( emptyflags ), COPY_ALL_CHARACTERS );
}
// Names staring with +/- need to be wrapped in single quotes
char name[ 256 ];
Q_snprintf( name, sizeof( name ), "%s", cmd->GetName() );
if ( name[ 0 ] == '+' || name[ 0 ] == '-' )
{
Q_snprintf( name, sizeof( name ), "'%s'", cmd->GetName() );
}
char tempbuff[128];
g_pFileSystem->FPrintf( f, "\"%s\",\"%s\",%s,\"%s\"\n", name, "cmd", emptyflags, StripQuotes( cmd->GetHelpText(), tempbuff, sizeof(tempbuff) ) );
}
}
static bool ConCommandBaseLessFunc( const ConCommandBase * const &lhs, const ConCommandBase * const &rhs )
{
const char *left = lhs->GetName();
const char *right = rhs->GetName();
if ( *left == '-' || *left == '+' )
left++;
if ( *right == '-' || *right == '+' )
right++;
return ( Q_stricmp( left, right ) < 0 );
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : void CCvar::CvarList_f
//-----------------------------------------------------------------------------
void CCvarUtilities::CvarList( const CCommand &args )
{
const ConCommandBase *var; // Temporary Pointer to cvars
int iArgs; // Argument count
const char *partial = NULL; // Partial cvar to search for...
// E.eg
int ipLen = 0; // Length of the partial cvar
FileHandle_t f = FILESYSTEM_INVALID_HANDLE; // FilePointer for logging
bool bLogging = false;
// Are we logging?
iArgs = args.ArgC(); // Get count
// Print usage?
if ( iArgs == 2 && !Q_strcasecmp( args[1],"?" ) )
{
ConMsg( "cvarlist: [log logfile] [ partial ]\n" );
return;
}
if ( !Q_strcasecmp( args[1],"log" ) && iArgs >= 3 )
{
char fn[256];
Q_snprintf( fn, sizeof( fn ), "%s", args[2] );
f = g_pFileSystem->Open( fn,"wb" );
if ( f )
{
bLogging = true;
}
else
{
ConMsg( "Couldn't open '%s' for writing!\n", fn );
return;
}
if ( iArgs == 4 )
{
partial = args[ 3 ];
ipLen = Q_strlen( partial );
}
}
else
{
partial = args[ 1 ];
ipLen = Q_strlen( partial );
}
// Banner
ConMsg( "cvar list\n--------------\n" );
CUtlRBTree< const ConCommandBase * > sorted( 0, 0, ConCommandBaseLessFunc );
// Loop through cvars...
ICvar::Iterator iter( g_pCVar );
for ( iter.SetFirst() ; iter.IsValid() ; iter.Next() )
{
ConCommandBase *var = iter.Get();
bool print = false;
if ( var->IsFlagSet(FCVAR_DEVELOPMENTONLY) || var->IsFlagSet(FCVAR_HIDDEN) )
continue;
if (partial) // Partial string searching?
{
if ( !Q_strncasecmp( var->GetName(), partial, ipLen ) )
{
print = true;
}
}
else
{
print = true;
}
if ( !print )
continue;
sorted.Insert( var );
}
if ( bLogging )
{
PrintListHeader( f );
}
for ( int i = sorted.FirstInorder(); i != sorted.InvalidIndex(); i = sorted.NextInorder( i ) )
{
var = sorted[ i ];
if ( var->IsCommand() )
{
PrintCommand( (ConCommand *)var, bLogging, f );
}
else
{
PrintCvar( (ConVar *)var, bLogging, f );
}
}
// Show total and syntax help...
if ( partial && partial[0] )
{
ConMsg("--------------\n%3i convars/concommands for [%s]\n", sorted.Count(), partial );
}
else
{
ConMsg("--------------\n%3i total convars/concommands\n", sorted.Count() );
}
if ( bLogging )
{
g_pFileSystem->Close( f );
}
}
//-----------------------------------------------------------------------------
// Purpose: Removes the FCVAR_DEVELOPMENTONLY flag from all cvars, making them accessible
//-----------------------------------------------------------------------------
void CCvarUtilities::EnableDevCvars()
{
// Loop through cvars...
ICvar::Iterator iter( g_pCVar );
for ( iter.SetFirst() ; iter.IsValid() ; iter.Next() )
{
ConCommandBase *var = iter.Get();
// remove flag from all cvars
var->RemoveFlags( FCVAR_DEVELOPMENTONLY );
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input :
// Output : int
//-----------------------------------------------------------------------------
int CCvarUtilities::CountVariablesWithFlags( int flags )
{
int c = 0;
ICvar::Iterator iter( g_pCVar );
for ( iter.SetFirst() ; iter.IsValid() ; iter.Next() )
{
ConCommandBase *var = iter.Get();
if ( var->IsCommand() )
continue;
if ( var->IsFlagSet( flags ) )
{
++c;
}
}
return c;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CCvarUtilities::CvarHelp( const CCommand &args )
{
const char *search;
const ConCommandBase *var;
if ( args.ArgC() != 2 )
{
ConMsg( "Usage: help <cvarname>\n" );
return;
}
// Get name of var to find
search = args[1];
// Search for it
var = g_pCVar->FindCommandBase( search );
if ( !var )
{
ConMsg( "help: no cvar or command named %s\n", search );
return;
}
// Show info
ConVar_PrintDescription( var );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CCvarUtilities::CvarDifferences( const CCommand &args )
{
ICvar::Iterator iter( g_pCVar );
for ( iter.SetFirst() ; iter.IsValid() ; iter.Next() )
{
ConCommandBase *var = iter.Get();
if ( var->IsCommand( ) )
continue;
if ( var->IsFlagSet(FCVAR_DEVELOPMENTONLY) || var->IsFlagSet(FCVAR_HIDDEN) )
continue;
if ( !Q_stricmp( ((ConVar *)var)->GetDefault(), ((ConVar *)var)->GetString() ) )
continue;
ConVar_PrintDescription( (ConVar *)var );
}
}
//-----------------------------------------------------------------------------
// Purpose: Toggles a cvar on/off, or cycles through a set of values
//-----------------------------------------------------------------------------
void CCvarUtilities::CvarToggle( const CCommand &args )
{
int i;
int c = args.ArgC();
if ( c < 2 )
{
ConMsg( "Usage: toggle <cvarname> [value1] [value2] [value3]...\n" );
return;
}
ConVar *var = g_pCVar->FindVar( args[1] );
if ( !IsValidToggleCommand( args[1] ) )
{
return;
}
if ( c == 2 )
{
// just toggle it on and off
var->SetValue( !var->GetBool() );
ConVar_PrintDescription( var );
}
else
{
// look for the current value in the command arguments
for( i = 2; i < c; i++ )
{
if ( !Q_strcmp( var->GetString(), args[ i ] ) )
break;
}
// choose the next one
i++;
// if we didn't find it, or were at the last value in the command arguments, use the 1st argument
if ( i >= c )
{
i = 2;
}
var->SetValue( args[ i ] );
ConVar_PrintDescription( var );
}
}
int CCvarUtilities::CvarFindFlagsCompletionCallback( const char *partial, char commands[ COMMAND_COMPLETION_MAXITEMS ][ COMMAND_COMPLETION_ITEM_LENGTH ] )
{
int flagC = ARRAYSIZE( g_ConVarFlags );
char const *pcmd = "findflags ";
int len = Q_strlen( partial );
if ( len < Q_strlen( pcmd ) )
{
int i = 0;
for ( ; i < MIN( flagC, COMMAND_COMPLETION_MAXITEMS ); i++ )
{
Q_snprintf( commands[ i ], sizeof( commands[ i ] ), "%s %s", pcmd, g_ConVarFlags[i].desc );
Q_strlower( commands[ i ] );
}
return i;
}
char const *pSub = partial + Q_strlen( pcmd );
int nSubLen = Q_strlen( pSub );
int values = 0;
for ( int i=0; i < flagC; ++i )
{
if ( Q_strnicmp( g_ConVarFlags[i].desc, pSub, nSubLen ) )
continue;
Q_snprintf( commands[ values ], sizeof( commands[ values ] ), "%s %s", pcmd, g_ConVarFlags[i].desc );
Q_strlower( commands[ values ] );
++values;
if ( values >= COMMAND_COMPLETION_MAXITEMS )
break;
}
return values;
}
void CCvarUtilities::CvarFindFlags_f( const CCommand &args )
{
if ( args.ArgC() < 2 )
{
ConMsg( "Usage: findflags <string>\n" );
ConMsg( "Available flags to search for: \n" );
for ( int i=0; i < ARRAYSIZE( g_ConVarFlags ); i++ )
{
ConMsg( " - %s\n", g_ConVarFlags[i].desc );
}
return;
}
// Get substring to find
const char *search = args[1];
// Loop through vars and print out findings
ICvar::Iterator iter( g_pCVar );
for ( iter.SetFirst() ; iter.IsValid() ; iter.Next() )
{
ConCommandBase *var = iter.Get();
if ( var->IsFlagSet(FCVAR_DEVELOPMENTONLY) || var->IsFlagSet(FCVAR_HIDDEN) )
continue;
for ( int j=0; j < ARRAYSIZE( g_ConVarFlags ); ++j )
{
if ( !var->IsFlagSet( g_ConVarFlags[j].bit ) )
continue;
if ( Q_stricmp( g_ConVarFlags[j].desc, search ) )
continue;
ConVar_PrintDescription( var );
}
}
}
int FindFlagsCompletionCallback( const char *partial, char commands[ COMMAND_COMPLETION_MAXITEMS ][ COMMAND_COMPLETION_ITEM_LENGTH ] )
{
return ConVarUtilities->CvarFindFlagsCompletionCallback( partial, commands );
}
//-----------------------------------------------------------------------------
// Purpose: Hook to command
//-----------------------------------------------------------------------------
CON_COMMAND_F_COMPLETION( findflags, "Find concommands by flags.", 0, FindFlagsCompletionCallback )
{
ConVarUtilities->CvarFindFlags_f( args );
}
//-----------------------------------------------------------------------------
// Purpose: Hook to command
//-----------------------------------------------------------------------------
CON_COMMAND( cvarlist, "Show the list of convars/concommands." )
{
ConVarUtilities->CvarList( args );
}
//-----------------------------------------------------------------------------
// Purpose: Print help text for cvar
//-----------------------------------------------------------------------------
CON_COMMAND( help, "Find help about a convar/concommand." )
{
ConVarUtilities->CvarHelp( args );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CON_COMMAND( differences, "Show all convars which are not at their default values." )
{
ConVarUtilities->CvarDifferences( args );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CON_COMMAND( toggle, "Toggles a convar on or off, or cycles through a set of values." )
{
ConVarUtilities->CvarToggle( args );
}
void ResetGameConVarsToDefaults( void )
{
#if defined( LEFT4DEAD )
ConVarRef testprocess( "test_progression_loop" );
ConVarUtilities->ResetConVarsToDefaultValues( "z_" );
if ( ! testprocess.GetInt() )
{
ConVarUtilities->ResetConVarsToDefaultValues( "sb_" );
}
ConVarUtilities->ResetConVarsToDefaultValues( "survivor_" );
ConVarUtilities->ResetConVarsToDefaultValues( "director_" );
ConVarUtilities->ResetConVarsToDefaultValues( "intensity_" );
ConVarUtilities->ResetConVarsToDefaultValues( "rescue_" );
ConVarUtilities->ResetConVarsToDefaultValues( "tongue_" );
ConVarUtilities->ResetConVarsToDefaultValues( "inferno_" );
ConVarUtilities->ResetConVarsToDefaultValues( "boomer_" );
ConVarUtilities->ResetConVarsToDefaultValues( "hunter_" );
ConVarUtilities->ResetConVarsToDefaultValues( "smoker_" );
ConVarUtilities->ResetConVarsToDefaultValues( "tank_" );
ConVarUtilities->ResetConVarsToDefaultValues( "nav_" );
#endif
}
CON_COMMAND_F( reset_gameconvars, "Reset a bunch of game convars to default values", FCVAR_CHEAT )
{
ResetGameConVarsToDefaults();
}
//-----------------------------------------------------------------------------
// Purpose: Send the cvars to VXConsole
//-----------------------------------------------------------------------------
#if defined( USE_VXCONSOLE )
CON_COMMAND( getcvars, "" )
{
{
// avoid noisy requests
// outer logic to prevent multiple requests more complicated than doing just this
#if defined( _X360 )
bool bConnected = XBX_IsConsoleConnected();
if ( !bConnected )
{
return;
}
#endif
static float s_flLastPublishTime = 0;
if ( s_flLastPublishTime && Plat_FloatTime() < s_flLastPublishTime + 2.0f )
{
return;
}
s_flLastPublishTime = Plat_FloatTime();
}
#if defined( _X360 )
// get the version from the image
// regardles of where the image came from (DVD, HDD) this cracks the embedded version info
int nVersion = 0;
if ( !IsCert() )
{
HANDLE hFile = CreateFile( "d:\\version.xtx", GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
if ( hFile != INVALID_HANDLE_VALUE )
{
DWORD nFileSize = GetFileSize( hFile, NULL );
if ( nFileSize != (DWORD)-1 && nFileSize > 0 )
{
char versionData[1024];
DWORD nBufferSize = MIN( nFileSize, sizeof( versionData ) - 1 );
DWORD nBytesRead = 0;
BOOL bResult = ReadFile( hFile, versionData, nBufferSize, &nBytesRead, NULL );
if ( bResult )
{
versionData[nBytesRead] = '\0';
nVersion = atoi( versionData );
}
}
CloseHandle( hFile );
}
}
XBX_rVersion( nVersion );
#endif
// Host_Init() will be calling us again, so defer this expensive operation until then
if ( host_initialized )
{
#ifdef _PS3
if ( g_pValvePS3Console )
{
g_pCVar->PublishToVXConsole();
}
#else
g_pCVar->PublishToVXConsole();
#endif
}
}
#endif
| 412 | 0.960416 | 1 | 0.960416 | game-dev | MEDIA | 0.774934 | game-dev | 0.947212 | 1 | 0.947212 |
Xeno69/Domination | 1,387 | co30_Domination.Altis/client/fn_camouflage.sqf | // by Xeno
#include "..\x_setup.sqf"
private _oldstance = stance player;
sleep 10;
while {true} do {
if (d_player_canu) then {
if (stance player isNotEqualTo _oldstance) then {
_oldstance = stance player;
call {
if (_oldstance isEqualTo "STAND") exitWith {
if (player getUnitTrait "camouflageCoef" != 1) then {
player setUnitTrait ["camouflageCoef", 1];
};
if (player getUnitTrait "audibleCoef" != 1) then {
player setUnitTrait ["audibleCoef ", 1];
};
};
if (_oldstance isEqualTo "CROUCH") exitWith {
if (player getUnitTrait "camouflageCoef" != 0.8) then {
player setUnitTrait ["camouflageCoef", 0.8];
};
if (player getUnitTrait "audibleCoef" != 0.8) then {
player setUnitTrait ["audibleCoef ", 0.8];
};
};
if (_oldstance isEqualTo "PRONE") exitWith {
if (player getUnitTrait "camouflageCoef" != 0.5) then {
player setUnitTrait ["camouflageCoef", 0.5];
};
if (player getUnitTrait "audibleCoef" != 0.5) then {
player setUnitTrait ["audibleCoef ", 0.5];
};
};
if (player getUnitTrait "camouflageCoef" != 1) then {
player setUnitTrait ["camouflageCoef", 1];
};
if (player getUnitTrait "audibleCoef" != 1) then {
player setUnitTrait ["audibleCoef ", 1];
};
};
};
} else {
waitUntil {sleep 1; d_player_canu};
};
sleep 2;
};
| 412 | 0.707743 | 1 | 0.707743 | game-dev | MEDIA | 0.681737 | game-dev | 0.868056 | 1 | 0.868056 |
stubma/WiEngine | 6,320 | src/com/wiyun/engine/nodes/MenuItemAtlasLabel.java | /*
* Copyright (c) 2010 WiYun Inc.
* Author: luma(stubma@gmail.com)
*
* For all entities this program is free software; you can redistribute
* it and/or modify it under the terms of the 'WiEngine' license with
* the additional provision that 'WiEngine' must be credited in a manner
* that can be be observed by end users, for example, in the credits or during
* start up. (please find WiEngine logo in sdk's logo folder)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.wiyun.engine.nodes;
import com.wiyun.engine.opengl.Texture2D;
import com.wiyun.engine.types.WYColor3B;
import com.wiyun.engine.utils.TargetSelector;
/**
* 图片集文字菜单。这种菜单显示文字内容,但是文字的样式是来自某图片集,因此可以用这种菜单
* 实现各种字体的样式。 从文字到图片的映射是通过<code>startCharMap</code>指定的,比如
* 菜单文字内容是"again", <code>startCharMap</code>是'a', 图片集横向和纵向都包含3个图
* 片, 那么字符g和a的差是6,字符g将会映射到第三行第一列的图片。因为 6 / 3 = 2, 6 % 3 = 0。
*/
public class MenuItemAtlasLabel extends MenuItem {
/**
* 创建图片集文字菜单
*
* @param value 文字内容
* @param texture {@link Texture2D}
* @param map {@link CharMap}
* @return 菜单项实例
*/
public static MenuItemAtlasLabel make(String value, Texture2D texture, CharMap map) {
AtlasLabel label = (AtlasLabel)AtlasLabel.make(value, texture, map).autoRelease();
return new MenuItemAtlasLabel(label, null, null);
}
/**
* 创建图片集文字菜单
*
* @param value 文字内容
* @param texture {@link Texture2D}
* @param map {@link CharMap}
* @param target 回调函数所属对象
* @param selector 回调函数名称,必须是public,且无参数
* @return 菜单项实例
*/
public static MenuItemAtlasLabel make(String value, Texture2D texture, CharMap map, Node target, String selector) {
return make(value, texture, map, new TargetSelector(target, selector, null));
}
/**
* 创建图片集文字菜单
*
* @param value 文字内容
* @param texture {@link Texture2D}
* @param map {@link CharMap}
* @param selector {@link TargetSelector},将在ACTION_UP发生时被调用。回调方法必须是public方法,参数不限。
* @return 菜单项实例
*/
public static MenuItemAtlasLabel make(String value, Texture2D texture, CharMap map, TargetSelector selector) {
AtlasLabel label = (AtlasLabel)AtlasLabel.make(value, texture, map).autoRelease();
return new MenuItemAtlasLabel(label, null, selector);
}
/**
* 创建图片集文字菜单
*
* @param value 文字内容
* @param texture {@link Texture2D}
* @param map {@link CharMap}
* @param downSelector {@link TargetSelector}对象,将在ACTION_DOWN发生时被调用。回调方法必须是public方法,参数不限。
* @param upSelector {@link TargetSelector}对象,将在ACTION_UP发生时被调用。回调方法必须是public方法,参数不限。
* @return 菜单项实例
*/
public static MenuItemAtlasLabel make(String value, Texture2D texture, CharMap map, TargetSelector downSelector, TargetSelector upSelector) {
AtlasLabel label = (AtlasLabel)AtlasLabel.make(value, texture, map).autoRelease();
return new MenuItemAtlasLabel(label, downSelector, upSelector);
}
/**
* 创建图片集文字菜单
*
* @param label {@link AtlasLabel}
* @param downSelector {@link TargetSelector}对象,将在ACTION_DOWN发生时被调用。回调方法必须是public方法,参数不限。
* @param upSelector {@link TargetSelector}对象,将在ACTION_UP发生时被调用。回调方法必须是public方法,参数不限。
* @return 菜单项实例
*/
public static MenuItemAtlasLabel make(AtlasLabel label, TargetSelector downSelector, TargetSelector upSelector) {
return new MenuItemAtlasLabel(label, downSelector, upSelector);
}
/**
* 构造函数
*
* @param label {@link AtlasLabel}
* @param downSelector {@link TargetSelector}对象,将在ACTION_DOWN发生时被调用。回调方法必须是public方法,参数不限。
* @param upSelector {@link TargetSelector}对象,将在ACTION_UP发生时被调用。回调方法必须是public方法,参数不限。
*/
protected MenuItemAtlasLabel(AtlasLabel label, TargetSelector downSelector, TargetSelector upSelector) {
nativeInit(downSelector, upSelector, label);
}
/**
* 从底层指针获得一个MenuItemAtlasLabel的Java对象
*
* @param pointer 底层指针
* @return {@link MenuItemAtlasLabel}
*/
public static MenuItemAtlasLabel from(int pointer) {
return pointer == 0 ? null : new MenuItemAtlasLabel(pointer);
}
protected MenuItemAtlasLabel(int pointer) {
super(pointer);
}
private native void nativeInit(TargetSelector downSelector, TargetSelector upSelector, AtlasLabel label);
public native int getAlpha();
public native void setAlpha(int alpha);
public WYColor3B getColor() {
WYColor3B color = new WYColor3B();
nativeGetColor(color);
return color;
}
private native void nativeGetColor(WYColor3B color);
public void setColor(WYColor3B color) {
nativeSetColor(color.r, color.g, color.b);
}
private native void nativeSetColor(int r, int g, int b);
/**
* 获得禁止状态时的文字颜色
*
* @return {@link WYColor3B}
*/
public WYColor3B getDisabledColor() {
WYColor3B color = new WYColor3B();
nativeGetDisabledColor(color);
return color;
}
private native void nativeGetDisabledColor(WYColor3B color);
private native void nativeSetDisabledColor(int r, int g, int b);
/**
* 设置禁止状态时的文字颜色
*
* @param color {@link WYColor3B}
*/
public void setDisabledColor(WYColor3B color) {
nativeSetDisabledColor(color.r, color.g, color.b);
}
}
| 412 | 0.876962 | 1 | 0.876962 | game-dev | MEDIA | 0.577906 | game-dev | 0.554859 | 1 | 0.554859 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.