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
AntoBrandi/Self-Driving-and-ROS-2-Learn-by-Doing-Plan-Navigation
5,818
Section6_Obstacle_Avoidance/bumperbot_ws/src/bumperbot_planning/src/dijkstra_planner.cpp
#include <queue> #include <vector> #include "bumperbot_planning/dijkstra_planner.hpp" #include "rmw/qos_profiles.h" namespace bumperbot_planning { DijkstraPlanner::DijkstraPlanner() : Node("dijkstra_node") { tf_buffer_ = std::make_unique<tf2_ros::Buffer>(get_clock()); tf_listener_ = std::make_shared<tf2_ros::TransformListener>(*tf_buffer_); rclcpp::QoS map_qos(10); map_qos.durability(RMW_QOS_POLICY_DURABILITY_TRANSIENT_LOCAL); map_sub_ = create_subscription<nav_msgs::msg::OccupancyGrid>( "/costmap", map_qos, std::bind(&DijkstraPlanner::mapCallback, this, std::placeholders::_1)); pose_sub_ = create_subscription<geometry_msgs::msg::PoseStamped>( "/goal_pose", 10, std::bind(&DijkstraPlanner::goalCallback, this, std::placeholders::_1)); path_pub_ = create_publisher<nav_msgs::msg::Path>( "/dijkstra/path", 10 ); map_pub_ = create_publisher<nav_msgs::msg::OccupancyGrid>( "/dijkstra/visited_map", 10 ); } void DijkstraPlanner::mapCallback(const nav_msgs::msg::OccupancyGrid::SharedPtr map) { map_ = map; visited_map_.header.frame_id = map->header.frame_id; visited_map_.info = map->info; visited_map_.data = std::vector<int8_t>(visited_map_.info.height * visited_map_.info.width, -1); } void DijkstraPlanner::goalCallback(const geometry_msgs::msg::PoseStamped::SharedPtr pose) { if(!map_){ RCLCPP_ERROR(get_logger(), "No map received!"); return; } visited_map_.data = std::vector<int8_t>(visited_map_.info.height * visited_map_.info.width, -1); geometry_msgs::msg::TransformStamped map_to_base_tf; try { map_to_base_tf = tf_buffer_->lookupTransform( map_->header.frame_id, "base_footprint", tf2::TimePointZero); } catch (const tf2::TransformException & ex) { RCLCPP_ERROR(get_logger(), "Could not transform from map to base_footprint"); return; } geometry_msgs::msg::Pose map_to_base_pose; map_to_base_pose.position.x = map_to_base_tf.transform.translation.x; map_to_base_pose.position.y = map_to_base_tf.transform.translation.y; map_to_base_pose.orientation = map_to_base_tf.transform.rotation; auto path = plan(map_to_base_pose, pose->pose); if (!path.poses.empty()) { RCLCPP_INFO(this->get_logger(), "Shortest path found!"); path_pub_->publish(path); } else { RCLCPP_WARN(this->get_logger(), "No path found to the goal."); } } nav_msgs::msg::Path DijkstraPlanner::plan(const geometry_msgs::msg::Pose & start, const geometry_msgs::msg::Pose & goal) { std::vector<std::pair<int, int>> explore_directions = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} }; std::priority_queue<GraphNode, std::vector<GraphNode>, std::greater<GraphNode>> pending_nodes; std::vector<GraphNode> visited_nodes; pending_nodes.push(worldToGrid(start)); GraphNode active_node; while (!pending_nodes.empty() && rclcpp::ok()) { active_node = pending_nodes.top(); pending_nodes.pop(); // Goal found! if(worldToGrid(goal) == active_node){ break; } // Explore neighbors for (const auto & dir : explore_directions) { GraphNode new_node = active_node + dir; // Check if the new position is within bounds and not an obstacle if (std::find(visited_nodes.begin(), visited_nodes.end(), new_node) == visited_nodes.end() && poseOnMap(new_node) && map_->data.at(poseToCell(new_node)) < 99 && map_->data.at(poseToCell(new_node)) >= 0) { // If the node is not visited, add it to the queue new_node.cost = active_node.cost + 1 + map_->data.at(poseToCell(new_node)); new_node.prev = std::make_shared<GraphNode>(active_node); pending_nodes.push(new_node); visited_nodes.push_back(new_node); } } visited_map_.data.at(poseToCell(active_node)) = 10; // Blue map_pub_->publish(visited_map_); } nav_msgs::msg::Path path; path.header.frame_id = map_->header.frame_id; while(active_node.prev && rclcpp::ok()) { geometry_msgs::msg::Pose last_pose = gridToWorld(active_node); geometry_msgs::msg::PoseStamped last_pose_stamped; last_pose_stamped.header.frame_id = map_->header.frame_id; last_pose_stamped.pose = last_pose; path.poses.push_back(last_pose_stamped); active_node = *active_node.prev; } std::reverse(path.poses.begin(), path.poses.end()); return path; } bool DijkstraPlanner::poseOnMap(const GraphNode & node) { return node.x < static_cast<int>(map_->info.width) && node.x >= 0 && node.y < static_cast<int>(map_->info.height) && node.y >= 0; } GraphNode DijkstraPlanner::worldToGrid(const geometry_msgs::msg::Pose & pose) { int grid_x = static_cast<int>((pose.position.x - map_->info.origin.position.x) / map_->info.resolution); int grid_y = static_cast<int>((pose.position.y - map_->info.origin.position.y) / map_->info.resolution); return GraphNode(grid_x, grid_y); } geometry_msgs::msg::Pose DijkstraPlanner::gridToWorld(const GraphNode & node) { geometry_msgs::msg::Pose pose; pose.position.x = node.x * map_->info.resolution + map_->info.origin.position.x; pose.position.y = node.y * map_->info.resolution + map_->info.origin.position.y; return pose; } unsigned int DijkstraPlanner::poseToCell(const GraphNode & node) { return map_->info.width * node.y + node.x; } } // namespace bumperbot_planning int main(int argc, char **argv) { rclcpp::init(argc, argv); auto node = std::make_shared<bumperbot_planning::DijkstraPlanner>(); rclcpp::spin(node); rclcpp::shutdown(); return 0; }
1
0.956602
1
0.956602
game-dev
MEDIA
0.2071
game-dev
0.919079
1
0.919079
RagingBigFemaleBird/sgs
1,365
Source/Expansions/Basic/Cards/WuZhongShengYou.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using Sanguosha.Core.UI; using Sanguosha.Core.Skills; using Sanguosha.Core.Players; using Sanguosha.Core.Games; using Sanguosha.Core.Triggers; using Sanguosha.Core.Exceptions; using Sanguosha.Core.Cards; namespace Sanguosha.Expansions.Basic.Cards { public class WuZhongShengYou : CardHandler { protected override void Process(Player source, Player dest, ICard card, ReadOnlyCard readonlyCard, GameEventArgs inResponseTo) { Game.CurrentGame.DrawCards(dest, 2); } public override VerifierResult Verify(Player source, ICard card, List<Player> targets, bool isLooseVerify) { if (!isLooseVerify && targets != null && targets.Count >= 1) { return VerifierResult.Fail; } return VerifierResult.Success; } public override List<Player> ActualTargets(Player source, List<Player> targets, ICard card) { if (targets.Count > 0) { return new List<Player>(targets); } return new List<Player>() { source }; } public override CardCategory Category { get { return CardCategory.ImmediateTool; } } } }
1
0.881864
1
0.881864
game-dev
MEDIA
0.963934
game-dev
0.881792
1
0.881792
EVECompanion/EVECompanion
5,079
EVECompanionKit/Models/ECKMarketOrder.swift
// // ECKMarketOrder.swift // EVECompanionKit // // Created by Jonas Schlabertz on 08.06.24. // import Foundation public final class ECKMarketOrder: Decodable, Identifiable { enum CodingKeys: String, CodingKey { case duration case escrow case isBuyOrder = "is_buy_order" case isCorporation = "is_corporation" case issued case station = "location_id" case minVolume = "min_volume" case orderId = "order_id" case price case region = "region_id" case item = "type_id" case volumeRemain = "volume_remain" case volumeTotal = "volume_total" } public static let dummy1: ECKMarketOrder = .init(duration: 30, escrow: nil, isBuyOrder: false, isCorporation: false, issued: Date() - .fromHours(hours: 5), station: .init(stationId: 60003760, token: .dummy), minVolume: nil, orderId: 0, price: 150_000_000, region: .init(regionId: 10000002), item: .init(typeId: 12729), volumeRemain: 3, volumeTotal: 5) public static let dummy2: ECKMarketOrder = .init(duration: 30, escrow: nil, isBuyOrder: true, isCorporation: false, issued: Date() - .fromHours(hours: 23), station: .init(stationId: 60003760, token: .dummy), minVolume: nil, orderId: 0, price: 260_000_000, region: .init(regionId: 10000002), item: .init(typeId: 22436), volumeRemain: 3, volumeTotal: 5) public let duration: Int public let escrow: Double? public let isBuyOrder: Bool public let isCorporation: Bool public let issued: Date public let station: ECKStation public let minVolume: Int? public let orderId: Int public let price: Double public let region: ECKRegion public let item: ECKItem public let volumeRemain: Int public let volumeTotal: Int public var id: Int { return orderId } init(duration: Int, escrow: Double?, isBuyOrder: Bool, isCorporation: Bool, issued: Date, station: ECKStation, minVolume: Int?, orderId: Int, price: Double, region: ECKRegion, item: ECKItem, volumeRemain: Int, volumeTotal: Int) { self.duration = duration self.escrow = escrow self.isBuyOrder = isBuyOrder self.isCorporation = isCorporation self.issued = issued self.station = station self.minVolume = minVolume self.orderId = orderId self.price = price self.region = region self.item = item self.volumeRemain = volumeRemain self.volumeTotal = volumeTotal } public required init(from decoder: any Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.duration = try container.decode(Int.self, forKey: .duration) self.escrow = try container.decodeIfPresent(Double.self, forKey: .escrow) self.isBuyOrder = try container.decodeIfPresent(Bool.self, forKey: .isBuyOrder) ?? false self.isCorporation = try container.decode(Bool.self, forKey: .isCorporation) self.issued = try container.decode(Date.self, forKey: .issued) self.station = try container.decode(ECKStation.self, forKey: .station) self.minVolume = try container.decodeIfPresent(Int.self, forKey: .minVolume) self.orderId = try container.decode(Int.self, forKey: .orderId) self.price = try container.decode(Double.self, forKey: .price) self.region = try container.decode(ECKRegion.self, forKey: .region) self.item = try container.decode(ECKItem.self, forKey: .item) self.volumeRemain = try container.decode(Int.self, forKey: .volumeRemain) self.volumeTotal = try container.decode(Int.self, forKey: .volumeTotal) } }
1
0.954429
1
0.954429
game-dev
MEDIA
0.307357
game-dev
0.932258
1
0.932258
kiocode/xenon-cheats
6,588
example-oac-internal/OACDump/SDK/ControlSettings_parameters.hpp
#pragma once /* * SDK generated by Dumper-7 * * https://github.com/Encryqed/Dumper-7 */ // Package: ControlSettings #include "Basic.hpp" namespace SDK::Params { // Function ControlSettings.ControlSettings_C.ExecuteUbergraph_ControlSettings // 0x0010 (0x0010 - 0x0000) struct ControlSettings_C_ExecuteUbergraph_ControlSettings final { public: int32 EntryPoint; // 0x0000(0x0004)(BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) uint8 Pad_4[0x4]; // 0x0004(0x0004)(Fixing Size After Last Property [ Dumper-7 ]) class USettingsUI_C* CallFunc_Create_ReturnValue; // 0x0008(0x0008)(ZeroConstructor, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash) }; static_assert(alignof(ControlSettings_C_ExecuteUbergraph_ControlSettings) == 0x000008, "Wrong alignment on ControlSettings_C_ExecuteUbergraph_ControlSettings"); static_assert(sizeof(ControlSettings_C_ExecuteUbergraph_ControlSettings) == 0x000010, "Wrong size on ControlSettings_C_ExecuteUbergraph_ControlSettings"); static_assert(offsetof(ControlSettings_C_ExecuteUbergraph_ControlSettings, EntryPoint) == 0x000000, "Member 'ControlSettings_C_ExecuteUbergraph_ControlSettings::EntryPoint' has a wrong offset!"); static_assert(offsetof(ControlSettings_C_ExecuteUbergraph_ControlSettings, CallFunc_Create_ReturnValue) == 0x000008, "Member 'ControlSettings_C_ExecuteUbergraph_ControlSettings::CallFunc_Create_ReturnValue' has a wrong offset!"); // Function ControlSettings.ControlSettings_C.Set scrollbox visible // 0x0050 (0x0050 - 0x0000) struct ControlSettings_C_Set_scrollbox_visible final { public: class UScrollBox* ScrollBox; // 0x0000(0x0008)(BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash) int32 Temp_int_Array_Index_Variable; // 0x0008(0x0004)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) int32 Temp_int_Loop_Counter_Variable; // 0x000C(0x0004)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) int32 CallFunc_Add_IntInt_ReturnValue; // 0x0010(0x0004)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) uint8 Pad_14[0x4]; // 0x0014(0x0004)(Fixing Size After Last Property [ Dumper-7 ]) TArray<class UWidget*> CallFunc_GetAllChildren_ReturnValue; // 0x0018(0x0010)(ReferenceParm, ContainsInstancedReference) int32 CallFunc_Array_Length_ReturnValue; // 0x0028(0x0004)(ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) uint8 Pad_2C[0x4]; // 0x002C(0x0004)(Fixing Size After Last Property [ Dumper-7 ]) class UWidget* CallFunc_Array_Get_Item; // 0x0030(0x0008)(ZeroConstructor, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash) bool CallFunc_Less_IntInt_ReturnValue; // 0x0038(0x0001)(ZeroConstructor, IsPlainOldData, NoDestructor) uint8 Pad_39[0x7]; // 0x0039(0x0007)(Fixing Size After Last Property [ Dumper-7 ]) class UScrollBox* K2Node_DynamicCast_AsScroll_Box; // 0x0040(0x0008)(ZeroConstructor, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash) bool K2Node_DynamicCast_bSuccess; // 0x0048(0x0001)(ZeroConstructor, IsPlainOldData, NoDestructor) }; static_assert(alignof(ControlSettings_C_Set_scrollbox_visible) == 0x000008, "Wrong alignment on ControlSettings_C_Set_scrollbox_visible"); static_assert(sizeof(ControlSettings_C_Set_scrollbox_visible) == 0x000050, "Wrong size on ControlSettings_C_Set_scrollbox_visible"); static_assert(offsetof(ControlSettings_C_Set_scrollbox_visible, ScrollBox) == 0x000000, "Member 'ControlSettings_C_Set_scrollbox_visible::ScrollBox' has a wrong offset!"); static_assert(offsetof(ControlSettings_C_Set_scrollbox_visible, Temp_int_Array_Index_Variable) == 0x000008, "Member 'ControlSettings_C_Set_scrollbox_visible::Temp_int_Array_Index_Variable' has a wrong offset!"); static_assert(offsetof(ControlSettings_C_Set_scrollbox_visible, Temp_int_Loop_Counter_Variable) == 0x00000C, "Member 'ControlSettings_C_Set_scrollbox_visible::Temp_int_Loop_Counter_Variable' has a wrong offset!"); static_assert(offsetof(ControlSettings_C_Set_scrollbox_visible, CallFunc_Add_IntInt_ReturnValue) == 0x000010, "Member 'ControlSettings_C_Set_scrollbox_visible::CallFunc_Add_IntInt_ReturnValue' has a wrong offset!"); static_assert(offsetof(ControlSettings_C_Set_scrollbox_visible, CallFunc_GetAllChildren_ReturnValue) == 0x000018, "Member 'ControlSettings_C_Set_scrollbox_visible::CallFunc_GetAllChildren_ReturnValue' has a wrong offset!"); static_assert(offsetof(ControlSettings_C_Set_scrollbox_visible, CallFunc_Array_Length_ReturnValue) == 0x000028, "Member 'ControlSettings_C_Set_scrollbox_visible::CallFunc_Array_Length_ReturnValue' has a wrong offset!"); static_assert(offsetof(ControlSettings_C_Set_scrollbox_visible, CallFunc_Array_Get_Item) == 0x000030, "Member 'ControlSettings_C_Set_scrollbox_visible::CallFunc_Array_Get_Item' has a wrong offset!"); static_assert(offsetof(ControlSettings_C_Set_scrollbox_visible, CallFunc_Less_IntInt_ReturnValue) == 0x000038, "Member 'ControlSettings_C_Set_scrollbox_visible::CallFunc_Less_IntInt_ReturnValue' has a wrong offset!"); static_assert(offsetof(ControlSettings_C_Set_scrollbox_visible, K2Node_DynamicCast_AsScroll_Box) == 0x000040, "Member 'ControlSettings_C_Set_scrollbox_visible::K2Node_DynamicCast_AsScroll_Box' has a wrong offset!"); static_assert(offsetof(ControlSettings_C_Set_scrollbox_visible, K2Node_DynamicCast_bSuccess) == 0x000048, "Member 'ControlSettings_C_Set_scrollbox_visible::K2Node_DynamicCast_bSuccess' has a wrong offset!"); }
1
0.781299
1
0.781299
game-dev
MEDIA
0.708675
game-dev
0.545979
1
0.545979
DeltaV-Station/Delta-v
3,492
Content.Server/Wagging/WaggingSystem.cs
using Content.Server.Actions; using Content.Server.Humanoid; using Content.Shared.Humanoid; using Content.Shared.Humanoid.Markings; using Content.Shared.Mobs; using Content.Shared.Toggleable; using Content.Shared.Wagging; using Robust.Shared.Prototypes; namespace Content.Server.Wagging; /// <summary> /// Adds an action to toggle wagging animation for tails markings that supporting this /// </summary> public sealed class WaggingSystem : EntitySystem { [Dependency] private readonly ActionsSystem _actions = default!; [Dependency] private readonly HumanoidAppearanceSystem _humanoidAppearance = default!; [Dependency] private readonly IPrototypeManager _prototype = default!; public override void Initialize() { base.Initialize(); SubscribeLocalEvent<WaggingComponent, MapInitEvent>(OnWaggingMapInit); SubscribeLocalEvent<WaggingComponent, ComponentShutdown>(OnWaggingShutdown); SubscribeLocalEvent<WaggingComponent, ToggleActionEvent>(OnWaggingToggle); SubscribeLocalEvent<WaggingComponent, MobStateChangedEvent>(OnMobStateChanged); } private void OnWaggingMapInit(EntityUid uid, WaggingComponent component, MapInitEvent args) { _actions.AddAction(uid, ref component.ActionEntity, component.Action, uid); } private void OnWaggingShutdown(EntityUid uid, WaggingComponent component, ComponentShutdown args) { _actions.RemoveAction(uid, component.ActionEntity); } private void OnWaggingToggle(EntityUid uid, WaggingComponent component, ref ToggleActionEvent args) { if (args.Handled) return; TryToggleWagging(uid, wagging: component); } private void OnMobStateChanged(EntityUid uid, WaggingComponent component, MobStateChangedEvent args) { if (component.Wagging) TryToggleWagging(uid, wagging: component); } public bool TryToggleWagging(EntityUid uid, WaggingComponent? wagging = null, HumanoidAppearanceComponent? humanoid = null) { if (!Resolve(uid, ref wagging, ref humanoid)) return false; if (!humanoid.MarkingSet.Markings.TryGetValue(MarkingCategories.Tail, out var markings)) return false; if (markings.Count == 0) return false; wagging.Wagging = !wagging.Wagging; for (var idx = 0; idx < markings.Count; idx++) // Animate all possible tails { var currentMarkingId = markings[idx].MarkingId; string newMarkingId; if (wagging.Wagging) { newMarkingId = $"{currentMarkingId}{wagging.Suffix}"; } else { if (currentMarkingId.EndsWith(wagging.Suffix)) { newMarkingId = currentMarkingId[..^wagging.Suffix.Length]; } else { newMarkingId = currentMarkingId; Log.Warning($"Unable to revert wagging for {currentMarkingId}"); } } if (!_prototype.HasIndex<MarkingPrototype>(newMarkingId)) { Log.Warning($"{ToPrettyString(uid)} tried toggling wagging but {newMarkingId} marking doesn't exist"); continue; } _humanoidAppearance.SetMarkingId(uid, MarkingCategories.Tail, idx, newMarkingId, humanoid: humanoid); } return true; } }
1
0.914989
1
0.914989
game-dev
MEDIA
0.90046
game-dev
0.858678
1
0.858678
Field-Robotics-Japan/OpenConstructionSimulator
2,455
Assets/OcsTerrain/Scripts/Excavation/Sand/SpawnSand.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; public class SpawnSand : MonoBehaviour { public int _id; public float _radius; public bool _onTerrain; public SandManager _sandManager; private MeshCollider _mc; private Rigidbody _rb; private void Awake() { _mc = GetComponent<MeshCollider>(); _rb = GetComponent<Rigidbody>(); _rb.maxDepenetrationVelocity = float.MaxValue; gameObject.SetActive(false); } // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } private void OnDisable() { _mc.enabled = false; } private void OnEnable() { this.transform.localScale = new Vector3(2 * _radius * 100, 2 * _radius * 100, 2 * _radius * 100); _onTerrain = false; if(giveMassToNearObj(_radius + _sandManager._maxSandRadius)) { //_sandManager.Dispose(_id); _mc.enabled = true; } else { _mc.enabled = true; } } private bool giveMassToNearObj(float threshold) { var targets = GameObject.FindGameObjectsWithTag(this.gameObject.tag); if (targets.Length == 1) return false; foreach (var target in targets) { if (target == this.gameObject) continue; var targetDistance = Vector3.Distance(transform.position, target.transform.position); if (targetDistance < threshold) { target.SendMessage("ReceiveMass", _rb.mass*0.5f); return true; } } return false; } private void OnCollisionEnter(Collision collision) { if (collision.gameObject.tag == "Terrain") _onTerrain = true; } private void OnCollisionExit(Collision collision) { if (collision.gameObject.tag == "Terrain") _onTerrain = false; } public void ReceiveMass(float mass) { float scale = Mathf.Pow((_rb.mass+mass) / _sandManager._sandDensity, 0.33f); if (scale > _sandManager._maxSandRadius * 2) scale = _sandManager._maxSandRadius*2; _rb.mass = scale * scale * scale * _sandManager._sandDensity; scale *= 100.0f; this.transform.localScale = new Vector3(scale, scale, scale); } }
1
0.902401
1
0.902401
game-dev
MEDIA
0.989278
game-dev
0.992052
1
0.992052
github/codeql-coding-standards
1,750
cpp/common/src/codingstandards/cpp/dominance/BehavioralSet.qll
import cpp import semmle.code.cpp.controlflow.ControlFlowGraph signature class TargetNode extends ControlFlowNode; signature module DominatingSetConfigSig<TargetNode Target> { predicate isTargetBehavior(ControlFlowNode behavior, Target target); default predicate isBlockingBehavior(ControlFlowNode behavior, Target target) { none() } } /** * A module to find whether there exists a dominator set for a node which performs a relevant * behavior. * * For instance, we may wish to see that all paths leading to an `abort()` statement include a * logging call. In this case, the `abort()` statement is the `Target` node, and the config module * predicate `isTargetBehavior` logging statements. * * Additionally, the config may specify `isBlockingBehavior` to prevent searching too far for the * relevant behavior. For instance, if analyzing that all paths to an `fflush()` call are preceded * by a write, we should ignore paths from write operations that have already been flushed through * an intermediary `fflush()` call. */ module DominatingBehavioralSet<TargetNode Target, DominatingSetConfigSig<Target> Config> { /** * Holds if this search step can reach the entry or a blocking node, without passing through a * target behavior, indicating that the target is has no relevant dominator set. */ private predicate searchStep(ControlFlowNode node, Target target) { Config::isBlockingBehavior(node, target) or not Config::isTargetBehavior(node, target) and exists(ControlFlowNode prev | prev = node.getAPredecessor() | searchStep(prev, target)) } predicate isDominatedByBehavior(Target target) { forex(ControlFlowNode prev | prev = target.getAPredecessor() | not searchStep(prev, target)) } }
1
0.917295
1
0.917295
game-dev
MEDIA
0.289736
game-dev
0.899272
1
0.899272
Elfansoer/dota-2-lua-abilities
2,232
scripts/vscripts/lua_abilities/snapfire_scatterblast_lua/modifier_snapfire_scatterblast_lua.lua
-- Created by Elfansoer --[[ Ability checklist (erase if done/checked): - Scepter Upgrade - Break behavior - Linken/Reflect behavior - Spell Immune/Invulnerable/Invisible behavior - Illusion behavior - Stolen behavior ]] -------------------------------------------------------------------------------- modifier_snapfire_scatterblast_lua = class({}) -------------------------------------------------------------------------------- -- Classifications function modifier_snapfire_scatterblast_lua:IsHidden() return false end function modifier_snapfire_scatterblast_lua:IsDebuff() return true end function modifier_snapfire_scatterblast_lua:IsStunDebuff() return false end function modifier_snapfire_scatterblast_lua:IsPurgable() return true end -------------------------------------------------------------------------------- -- Initializations function modifier_snapfire_scatterblast_lua:OnCreated( kv ) -- references self.slow = -self:GetAbility():GetSpecialValueFor( "movement_slow_pct" ) end function modifier_snapfire_scatterblast_lua:OnRefresh( kv ) -- references self.slow = -self:GetAbility():GetSpecialValueFor( "movement_slow_pct" ) end function modifier_snapfire_scatterblast_lua:OnRemoved() end function modifier_snapfire_scatterblast_lua:OnDestroy() end -------------------------------------------------------------------------------- -- Modifier Effects function modifier_snapfire_scatterblast_lua:DeclareFunctions() local funcs = { MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE, } return funcs end function modifier_snapfire_scatterblast_lua:GetModifierMoveSpeedBonus_Percentage() return self.slow end -------------------------------------------------------------------------------- -- Graphics & Animations function modifier_snapfire_scatterblast_lua:GetEffectName() return "particles/units/heroes/hero_snapfire/hero_snapfire_shotgun_debuff.vpcf" end function modifier_snapfire_scatterblast_lua:GetEffectAttachType() return PATTACH_ABSORIGIN_FOLLOW end function modifier_snapfire_scatterblast_lua:GetStatusEffectName() return "particles/status_fx/status_effect_snapfire_slow.vpcf" end function modifier_snapfire_scatterblast_lua:StatusEffectPriority() return MODIFIER_PRIORITY_NORMAL end
1
0.938781
1
0.938781
game-dev
MEDIA
0.744127
game-dev
0.980623
1
0.980623
codemerx/JustDecompileEngine
7,724
src/Mono.Cecil.Shared/Mono.Cecil/GenericParameter.cs
// // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2015 Jb Evain // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System; using Mono.Collections.Generic; using Mono.Cecil.Metadata; namespace Mono.Cecil { public sealed class GenericParameter : TypeReference, ICustomAttributeProvider { internal int position; internal GenericParameterType type; internal IGenericParameterProvider owner; ushort attributes; Collection<TypeReference> constraints; Collection<CustomAttribute> custom_attributes; public GenericParameterAttributes Attributes { get { return (GenericParameterAttributes) attributes; } set { attributes = (ushort) value; } } public int Position { get { return position; } } public GenericParameterType Type { get { return type; } } public IGenericParameterProvider Owner { get { return owner; } } public bool HasConstraints { get { if (constraints != null) return constraints.Count > 0; return HasImage && Module.Read (this, (generic_parameter, reader) => reader.HasGenericConstraints (generic_parameter)); } } public Collection<TypeReference> Constraints { get { if (constraints != null) return constraints; if (HasImage) return Module.Read (ref constraints, this, (generic_parameter, reader) => reader.ReadGenericConstraints (generic_parameter)); return constraints = new Collection<TypeReference> (); } } /*Telerik Authorship*/ private bool? hasCustomAttributes; public bool HasCustomAttributes { get { if (custom_attributes != null) return custom_attributes.Count > 0; /*Telerik Authorship*/ if (hasCustomAttributes != null) return hasCustomAttributes == true; /*Telerik Authorship*/ return this.GetHasCustomAttributes(ref hasCustomAttributes, Module); } } public Collection<CustomAttribute> CustomAttributes { get { return custom_attributes ?? (this.GetCustomAttributes (ref custom_attributes, Module)); } } public override IMetadataScope Scope { get { if (owner == null) return null; return owner.GenericParameterType == GenericParameterType.Method ? ((MethodReference) owner).DeclaringType.Scope : ((TypeReference) owner).Scope; } set { throw new InvalidOperationException (); } } public override TypeReference DeclaringType { get { return owner as TypeReference; } set { throw new InvalidOperationException (); } } public MethodReference DeclaringMethod { get { return owner as MethodReference; } } public override ModuleDefinition Module { get { return module ?? owner.Module; } } public override string Name { get { if (!string.IsNullOrEmpty (base.Name)) return base.Name; return base.Name = (type == GenericParameterType.Method ? "!!" : "!") + position; } } public override string Namespace { get { return string.Empty; } set { throw new InvalidOperationException (); } } public override string FullName { get { return Name; } } public override bool IsGenericParameter { get { return true; } } public override bool ContainsGenericParameter { get { return true; } } public override MetadataType MetadataType { get { return (MetadataType) etype; } } #region GenericParameterAttributes public bool IsNonVariant { get { return attributes.GetMaskedAttributes ((ushort) GenericParameterAttributes.VarianceMask, (ushort) GenericParameterAttributes.NonVariant); } set { attributes = attributes.SetMaskedAttributes ((ushort) GenericParameterAttributes.VarianceMask, (ushort) GenericParameterAttributes.NonVariant, value); } } public bool IsCovariant { get { return attributes.GetMaskedAttributes ((ushort) GenericParameterAttributes.VarianceMask, (ushort) GenericParameterAttributes.Covariant); } set { attributes = attributes.SetMaskedAttributes ((ushort) GenericParameterAttributes.VarianceMask, (ushort) GenericParameterAttributes.Covariant, value); } } public bool IsContravariant { get { return attributes.GetMaskedAttributes ((ushort) GenericParameterAttributes.VarianceMask, (ushort) GenericParameterAttributes.Contravariant); } set { attributes = attributes.SetMaskedAttributes ((ushort) GenericParameterAttributes.VarianceMask, (ushort) GenericParameterAttributes.Contravariant, value); } } public bool HasReferenceTypeConstraint { get { return attributes.GetAttributes ((ushort) GenericParameterAttributes.ReferenceTypeConstraint); } set { attributes = attributes.SetAttributes ((ushort) GenericParameterAttributes.ReferenceTypeConstraint, value); } } public bool HasNotNullableValueTypeConstraint { get { return attributes.GetAttributes ((ushort) GenericParameterAttributes.NotNullableValueTypeConstraint); } set { attributes = attributes.SetAttributes ((ushort) GenericParameterAttributes.NotNullableValueTypeConstraint, value); } } public bool HasDefaultConstructorConstraint { get { return attributes.GetAttributes ((ushort) GenericParameterAttributes.DefaultConstructorConstraint); } set { attributes = attributes.SetAttributes ((ushort) GenericParameterAttributes.DefaultConstructorConstraint, value); } } #endregion public GenericParameter (IGenericParameterProvider owner) : this (string.Empty, owner) { } public GenericParameter (string name, IGenericParameterProvider owner) : base (string.Empty, name) { if (owner == null) throw new ArgumentNullException (); this.position = -1; this.owner = owner; this.type = owner.GenericParameterType; this.etype = ConvertGenericParameterType (this.type); this.token = new MetadataToken (TokenType.GenericParam); } internal GenericParameter (int position, GenericParameterType type, ModuleDefinition module) : base (string.Empty, string.Empty) { if (module == null) throw new ArgumentNullException (); this.position = position; this.type = type; this.etype = ConvertGenericParameterType (type); this.module = module; this.token = new MetadataToken (TokenType.GenericParam); } static ElementType ConvertGenericParameterType (GenericParameterType type) { switch (type) { case GenericParameterType.Type: return ElementType.Var; case GenericParameterType.Method: return ElementType.MVar; } throw new ArgumentOutOfRangeException (); } public override TypeDefinition Resolve () { return null; } } sealed class GenericParameterCollection : Collection<GenericParameter> { readonly IGenericParameterProvider owner; internal GenericParameterCollection (IGenericParameterProvider owner) { this.owner = owner; } internal GenericParameterCollection (IGenericParameterProvider owner, int capacity) : base (capacity) { this.owner = owner; } protected override void OnAdd (GenericParameter item, int index) { UpdateGenericParameter (item, index); } protected override void OnInsert (GenericParameter item, int index) { UpdateGenericParameter (item, index); for (int i = index; i < size; i++) items[i].position = i + 1; } protected override void OnSet (GenericParameter item, int index) { UpdateGenericParameter (item, index); } void UpdateGenericParameter (GenericParameter item, int index) { item.owner = owner; item.position = index; item.type = owner.GenericParameterType; } protected override void OnRemove (GenericParameter item, int index) { item.owner = null; item.position = -1; item.type = GenericParameterType.Type; for (int i = index + 1; i < size; i++) items[i].position = i - 1; } } }
1
0.898684
1
0.898684
game-dev
MEDIA
0.482353
game-dev
0.971181
1
0.971181
ProjectIgnis/CardScripts
2,016
unofficial/c511001090.lua
--Pendulum Statue White Butterfly local s,id=GetID() function s.initial_effect(c) --pendulum summon Pendulum.AddProcedure(c) --gain atk local e2=Effect.CreateEffect(c) e2:SetCategory(CATEGORY_ATKCHANGE) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_PZONE) e2:SetCountLimit(1) e2:SetTarget(s.target) e2:SetOperation(s.activate) c:RegisterEffect(e2) --tohand local e3=Effect.CreateEffect(c) e3:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH) e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e3:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY) e3:SetCode(EVENT_SPSUMMON_SUCCESS) e3:SetCondition(s.thcon) e3:SetTarget(s.thtg) e3:SetOperation(s.thop) c:RegisterEffect(e3) end s.listed_series={0x1550} function s.filter(c) return c:IsFaceup() and c:IsRace(RACE_INSECT) end function s.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(s.filter,tp,LOCATION_MZONE,0,1,nil) end end function s.activate(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetMatchingGroup(s.filter,tp,LOCATION_MZONE,0,nil) local tc=g:GetFirst() while tc do local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetReset(RESET_EVENT+RESETS_STANDARD) e1:SetValue(200) tc:RegisterEffect(e1) tc=g:GetNext() end end function s.thcon(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() return c:GetSummonType()==SUMMON_TYPE_PENDULUM and c:IsPreviousLocation(LOCATION_EXTRA) end function s.afilter(c) return c:IsSetCard(0x1550) and c:IsMonster() and c:IsAbleToHand() end function s.thtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(s.afilter,tp,LOCATION_DECK,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK) end function s.thop(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectMatchingCard(tp,s.afilter,tp,LOCATION_DECK,0,1,1,nil) if #g>0 then Duel.SendtoHand(g,nil,REASON_EFFECT) Duel.ConfirmCards(1-tp,g) end end
1
0.950226
1
0.950226
game-dev
MEDIA
0.988461
game-dev
0.978813
1
0.978813
karmab/kcli
13,628
kvirt/web/static/js/spice/utils.js
"use strict"; /* Copyright (C) 2012 by Jeremy P. White <jwhite@codeweavers.com> This file is part of spice-html5. spice-html5 is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. spice-html5 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with spice-html5. If not, see <http://www.gnu.org/licenses/>. */ import { KeyNames } from './atKeynames.js'; /*---------------------------------------------------------------------------- ** Utility settings and functions for Spice **--------------------------------------------------------------------------*/ var DEBUG = 0; var PLAYBACK_DEBUG = 0; var STREAM_DEBUG = 0; var DUMP_DRAWS = false; var DUMP_CANVASES = false; /*---------------------------------------------------------------------------- ** We use an Image temporarily, and the image/src does not get garbage ** collected as quickly as we might like. This blank image helps with that. **--------------------------------------------------------------------------*/ var EMPTY_GIF_IMAGE = "data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs="; /*---------------------------------------------------------------------------- ** combine_array_buffers ** Combine two array buffers. ** FIXME - this can't be optimal. See wire.js about eliminating the need. **--------------------------------------------------------------------------*/ function combine_array_buffers(a1, a2) { var in1 = new Uint8Array(a1); var in2 = new Uint8Array(a2); var ret = new ArrayBuffer(a1.byteLength + a2.byteLength); var out = new Uint8Array(ret); var o = 0; var i; for (i = 0; i < in1.length; i++) out[o++] = in1[i]; for (i = 0; i < in2.length; i++) out[o++] = in2[i]; return ret; } /*---------------------------------------------------------------------------- ** hexdump_buffer **--------------------------------------------------------------------------*/ function hexdump_buffer(a) { var mg = new Uint8Array(a); var hex = ""; var str = ""; var last_zeros = 0; for (var i = 0; i < mg.length; i++) { var h = Number(mg[i]).toString(16); if (h.length == 1) hex += "0"; hex += h + " "; if (mg[i] == 10 || mg[i] == 13 || mg[i] == 8) str += "."; else str += String.fromCharCode(mg[i]); if ((i % 16 == 15) || (i == (mg.length - 1))) { while (i % 16 != 15) { hex += " "; i++; } if (last_zeros == 0) console.log(hex + " | " + str); if (hex == "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ") { if (last_zeros == 1) { console.log("."); last_zeros++; } else if (last_zeros == 0) last_zeros++; } else last_zeros = 0; hex = str = ""; } } } /*---------------------------------------------------------------------------- ** Convert arraybuffer to string **--------------------------------------------------------------------------*/ function arraybuffer_to_str(buf) { return String.fromCharCode.apply(null, new Uint16Array(buf)); } /*---------------------------------------------------------------------------- ** Converting browser keycodes to AT scancodes is very hard. ** Spice transmits keys using the original AT scan codes, often ** described as 'Scan Code Set 1'. ** There is a confusion of other scan codes; Xorg synthesizes it's ** own in the same atKeynames.c file that has the XT codes. ** Scan code set 2 and 3 are more common, and use different values. ** Further, there is no formal specification for keycodes ** returned by browsers, so we have done our mapping largely with ** empirical testing. ** There has been little rigorous testing with International keyboards, ** and this would be an easy area for non English speakers to contribute. **--------------------------------------------------------------------------*/ var common_scanmap = []; /* The following appear to be keycodes that work in most browsers */ common_scanmap['1'.charCodeAt(0)] = KeyNames.KEY_1; common_scanmap['2'.charCodeAt(0)] = KeyNames.KEY_2; common_scanmap['3'.charCodeAt(0)] = KeyNames.KEY_3; common_scanmap['4'.charCodeAt(0)] = KeyNames.KEY_4; common_scanmap['5'.charCodeAt(0)] = KeyNames.KEY_5; common_scanmap['6'.charCodeAt(0)] = KeyNames.KEY_6; common_scanmap['7'.charCodeAt(0)] = KeyNames.KEY_7; common_scanmap['8'.charCodeAt(0)] = KeyNames.KEY_8; common_scanmap['9'.charCodeAt(0)] = KeyNames.KEY_9; common_scanmap['0'.charCodeAt(0)] = KeyNames.KEY_0; common_scanmap[145] = KeyNames.KEY_ScrollLock; common_scanmap[103] = KeyNames.KEY_KP_7; common_scanmap[104] = KeyNames.KEY_KP_8; common_scanmap[105] = KeyNames.KEY_KP_9; common_scanmap[100] = KeyNames.KEY_KP_4; common_scanmap[101] = KeyNames.KEY_KP_5; common_scanmap[102] = KeyNames.KEY_KP_6; common_scanmap[107] = KeyNames.KEY_KP_Plus; common_scanmap[97] = KeyNames.KEY_KP_1; common_scanmap[98] = KeyNames.KEY_KP_2; common_scanmap[99] = KeyNames.KEY_KP_3; common_scanmap[96] = KeyNames.KEY_KP_0; common_scanmap[109] = KeyNames.KEY_Minus; common_scanmap[110] = KeyNames.KEY_KP_Decimal; common_scanmap[191] = KeyNames.KEY_Slash; common_scanmap[190] = KeyNames.KEY_Period; common_scanmap[188] = KeyNames.KEY_Comma; common_scanmap[220] = KeyNames.KEY_BSlash; common_scanmap[192] = KeyNames.KEY_Tilde; common_scanmap[222] = KeyNames.KEY_Quote; common_scanmap[219] = KeyNames.KEY_LBrace; common_scanmap[221] = KeyNames.KEY_RBrace; common_scanmap['Q'.charCodeAt(0)] = KeyNames.KEY_Q; common_scanmap['W'.charCodeAt(0)] = KeyNames.KEY_W; common_scanmap['E'.charCodeAt(0)] = KeyNames.KEY_E; common_scanmap['R'.charCodeAt(0)] = KeyNames.KEY_R; common_scanmap['T'.charCodeAt(0)] = KeyNames.KEY_T; common_scanmap['Y'.charCodeAt(0)] = KeyNames.KEY_Y; common_scanmap['U'.charCodeAt(0)] = KeyNames.KEY_U; common_scanmap['I'.charCodeAt(0)] = KeyNames.KEY_I; common_scanmap['O'.charCodeAt(0)] = KeyNames.KEY_O; common_scanmap['P'.charCodeAt(0)] = KeyNames.KEY_P; common_scanmap['A'.charCodeAt(0)] = KeyNames.KEY_A; common_scanmap['S'.charCodeAt(0)] = KeyNames.KEY_S; common_scanmap['D'.charCodeAt(0)] = KeyNames.KEY_D; common_scanmap['F'.charCodeAt(0)] = KeyNames.KEY_F; common_scanmap['G'.charCodeAt(0)] = KeyNames.KEY_G; common_scanmap['H'.charCodeAt(0)] = KeyNames.KEY_H; common_scanmap['J'.charCodeAt(0)] = KeyNames.KEY_J; common_scanmap['K'.charCodeAt(0)] = KeyNames.KEY_K; common_scanmap['L'.charCodeAt(0)] = KeyNames.KEY_L; common_scanmap['Z'.charCodeAt(0)] = KeyNames.KEY_Z; common_scanmap['X'.charCodeAt(0)] = KeyNames.KEY_X; common_scanmap['C'.charCodeAt(0)] = KeyNames.KEY_C; common_scanmap['V'.charCodeAt(0)] = KeyNames.KEY_V; common_scanmap['B'.charCodeAt(0)] = KeyNames.KEY_B; common_scanmap['N'.charCodeAt(0)] = KeyNames.KEY_N; common_scanmap['M'.charCodeAt(0)] = KeyNames.KEY_M; common_scanmap[' '.charCodeAt(0)] = KeyNames.KEY_Space; common_scanmap[13] = KeyNames.KEY_Enter; common_scanmap[27] = KeyNames.KEY_Escape; common_scanmap[8] = KeyNames.KEY_BackSpace; common_scanmap[9] = KeyNames.KEY_Tab; common_scanmap[16] = KeyNames.KEY_ShiftL; common_scanmap[17] = KeyNames.KEY_LCtrl; common_scanmap[18] = KeyNames.KEY_Alt; common_scanmap[20] = KeyNames.KEY_CapsLock; common_scanmap[44] = KeyNames.KEY_SysReqest; common_scanmap[144] = KeyNames.KEY_NumLock; common_scanmap[112] = KeyNames.KEY_F1; common_scanmap[113] = KeyNames.KEY_F2; common_scanmap[114] = KeyNames.KEY_F3; common_scanmap[115] = KeyNames.KEY_F4; common_scanmap[116] = KeyNames.KEY_F5; common_scanmap[117] = KeyNames.KEY_F6; common_scanmap[118] = KeyNames.KEY_F7; common_scanmap[119] = KeyNames.KEY_F8; common_scanmap[120] = KeyNames.KEY_F9; common_scanmap[121] = KeyNames.KEY_F10; common_scanmap[122] = KeyNames.KEY_F11; common_scanmap[123] = KeyNames.KEY_F12; /* TODO: Break and Print are complex scan codes. XSpice cheats and uses Xorg synthesized codes to simplify them. Fixing this will require XSpice to handle the scan codes correctly, and then fix spice-html5 to send the complex scan codes. */ common_scanmap[42] = 99; // Print, XSpice only common_scanmap[19] = 101;// Break, XSpice only /* Handle the so called 'GREY' keys, for the extended keys that were grey on the original AT keyboard. These are prefixed, as they were on the PS/2 controller, with an 0xE0 byte to indicate that they are extended */ common_scanmap[111] = 0xE0 | (KeyNames.KEY_Slash << 8);// KP_Divide common_scanmap[106] = 0xE0 | (KeyNames.KEY_KP_Multiply << 8); // KP_Multiply common_scanmap[36] = 0xE0 | (KeyNames.KEY_KP_7 << 8); // Home common_scanmap[38] = 0xE0 | (KeyNames.KEY_KP_8 << 8); // Up common_scanmap[33] = 0xE0 | (KeyNames.KEY_KP_9 << 8); // PgUp common_scanmap[37] = 0xE0 | (KeyNames.KEY_KP_4 << 8); // Left common_scanmap[39] = 0xE0 | (KeyNames.KEY_KP_6 << 8); // Right common_scanmap[35] = 0xE0 | (KeyNames.KEY_KP_1 << 8); // End common_scanmap[40] = 0xE0 | (KeyNames.KEY_KP_2 << 8); // Down common_scanmap[34] = 0xE0 | (KeyNames.KEY_KP_3 << 8); // PgDown common_scanmap[45] = 0xE0 | (KeyNames.KEY_KP_0 << 8); // Insert common_scanmap[46] = 0xE0 | (KeyNames.KEY_KP_Decimal << 8); // Delete common_scanmap[91] = 0xE0 | (0x5B << 8); //KeyNames.KEY_LMeta common_scanmap[92] = 0xE0 | (0x5C << 8); //KeyNames.KEY_RMeta common_scanmap[93] = 0xE0 | (0x5D << 8); //KeyNames.KEY_Menu /* Firefox/Mozilla codes */ var firefox_scanmap = []; firefox_scanmap[173] = KeyNames.KEY_Minus; firefox_scanmap[61] = KeyNames.KEY_Equal; firefox_scanmap[59] = KeyNames.KEY_SemiColon; /* DOM3 codes */ var DOM_scanmap = []; DOM_scanmap[189] = KeyNames.KEY_Minus; DOM_scanmap[187] = KeyNames.KEY_Equal; DOM_scanmap[186] = KeyNames.KEY_SemiColon; function get_scancode(code) { if (common_scanmap[code] === undefined) { if (navigator.userAgent.indexOf("Firefox") != -1) return firefox_scanmap[code]; else return DOM_scanmap[code]; } else return common_scanmap[code]; } function keycode_to_start_scan(code) { var scancode = get_scancode(code); if (scancode === undefined) { alert('no map for ' + code); return 0; } return scancode; } function keycode_to_end_scan(code) { var scancode = get_scancode(code); if (scancode === undefined) return 0; if (scancode < 0x100) { return scancode | 0x80; } else { return scancode | 0x8000; } } function dump_media_element(m) { var ret = "[networkState " + m.networkState + "|readyState " + m.readyState + "|error " + m.error + "|seeking " + m.seeking + "|duration " + m.duration + "|paused " + m.paused + "|ended " + m.error + "|buffered " + dump_timerange(m.buffered) + "]"; return ret; } function dump_media_source(ms) { var ret = "[duration " + ms.duration + "|readyState " + ms.readyState + "]"; return ret; } function dump_source_buffer(sb) { var ret = "[appendWindowStart " + sb.appendWindowStart + "|appendWindowEnd " + sb.appendWindowEnd + "|buffered " + dump_timerange(sb.buffered) + "|timeStampOffset " + sb.timeStampOffset + "|updating " + sb.updating + "]"; return ret; } function dump_timerange(tr) { var ret; if (tr) { var i = tr.length; ret = "{len " + i; if (i > 0) ret += "; start " + tr.start(0) + "; end " + tr.end(i - 1); ret += "}"; } else ret = "N/A"; return ret; } export { DEBUG, PLAYBACK_DEBUG, STREAM_DEBUG, DUMP_DRAWS, DUMP_CANVASES, EMPTY_GIF_IMAGE, combine_array_buffers, hexdump_buffer, arraybuffer_to_str, keycode_to_start_scan, keycode_to_end_scan, dump_media_element, dump_media_source, dump_source_buffer, };
1
0.71177
1
0.71177
game-dev
MEDIA
0.483745
game-dev
0.712574
1
0.712574
Soar-Client/SoarClient
1,751
src/main/java/com/soarclient/management/mod/impl/hud/JumpResetIndicatorMod.java
package com.soarclient.management.mod.impl.hud; import com.soarclient.event.EventBus; import com.soarclient.event.client.RenderSkiaEvent; import com.soarclient.management.mod.api.hud.SimpleHUDMod; import com.soarclient.management.mod.settings.impl.NumberSetting; import com.soarclient.skia.font.Icon; public class JumpResetIndicatorMod extends SimpleHUDMod { private static JumpResetIndicatorMod instance; private NumberSetting tickSetting = new NumberSetting("setting.maxtick", "setting.maxtick.description", Icon.SCHEDULE, this, 10, 1, 100, 1); private int hurtAge, jumpAge; private long lastTime; public JumpResetIndicatorMod() { super("mod.jumpresetindicator.name", "mod.jumpresetindicator.description", Icon.SPORTS_KABADDI); instance = this; } public EventBus.EventListener<RenderSkiaEvent> onRenderSkia = event -> { this.draw(); }; @Override public String getText() { String diff = "No Jump"; if (lastTime + 2500 <= System.currentTimeMillis() || Math.abs(jumpAge - hurtAge) >= tickSetting.getValue()) { diff = "No Jump"; } else if (jumpAge == hurtAge + 1) { diff = "Perfect!"; } else if (hurtAge + 1 < jumpAge) { diff = "Late: ".concat(String.valueOf(jumpAge - hurtAge + 1)).concat(" Tick"); } else if (hurtAge + 1 > jumpAge) { diff = "Early: ".concat(String.valueOf(hurtAge + 1 - jumpAge)).concat(" Tick"); } return diff; } @Override public String getIcon() { return Icon.SPORTS_KABADDI; } public static JumpResetIndicatorMod getInstance() { return instance; } public void setHurtAge(int hurtAge) { this.hurtAge = hurtAge; } public void setJumpAge(int jumpAge) { this.jumpAge = jumpAge; } public void setLastTime(long lastTime) { this.lastTime = lastTime; } }
1
0.921956
1
0.921956
game-dev
MEDIA
0.94708
game-dev
0.955868
1
0.955868
finkkk/SteamP2PGame
6,704
Assets/Mirror/Examples/Room/Scripts/PlayerController.cs
using UnityEngine; namespace Mirror.Examples.NetworkRoom { [AddComponentMenu("")] [RequireComponent(typeof(CapsuleCollider))] [RequireComponent(typeof(CharacterController))] [RequireComponent(typeof(NetworkTransformReliable))] [RequireComponent(typeof(Rigidbody))] public class PlayerController : NetworkBehaviour { public enum GroundState : byte { Jumping, Falling, Grounded } [Header("Avatar Components")] public CharacterController characterController; [Header("Movement")] [Range(1, 20)] public float moveSpeedMultiplier = 8f; [Header("Turning")] [Range(1f, 200f)] public float maxTurnSpeed = 100f; [Range(.5f, 5f)] public float turnDelta = 3f; [Header("Jumping")] [Range(0.1f, 1f)] public float initialJumpSpeed = 0.2f; [Range(1f, 10f)] public float maxJumpSpeed = 5f; [Range(0.1f, 1f)] public float jumpDelta = 0.2f; [Header("Diagnostics")] [ReadOnly, SerializeField] GroundState groundState = GroundState.Grounded; [ReadOnly, SerializeField, Range(-1f, 1f)] float horizontal; [ReadOnly, SerializeField, Range(-1f, 1f)] float vertical; [ReadOnly, SerializeField, Range(-200f, 200f)] float turnSpeed; [ReadOnly, SerializeField, Range(-10f, 10f)] float jumpSpeed; [ReadOnly, SerializeField, Range(-1.5f, 1.5f)] float animVelocity; [ReadOnly, SerializeField, Range(-1.5f, 1.5f)] float animRotation; [ReadOnly, SerializeField] Vector3Int velocity; [ReadOnly, SerializeField] Vector3 direction; protected override void OnValidate() { base.OnValidate(); if (characterController == null) characterController = GetComponent<CharacterController>(); // Override CharacterController default values characterController.enabled = false; characterController.skinWidth = 0.02f; characterController.minMoveDistance = 0f; GetComponent<Rigidbody>().isKinematic = true; this.enabled = false; } public override void OnStartAuthority() { characterController.enabled = true; this.enabled = true; } public override void OnStopAuthority() { this.enabled = false; characterController.enabled = false; } void Update() { if (!characterController.enabled) return; HandleTurning(); HandleJumping(); HandleMove(); // Reset ground state if (characterController.isGrounded) groundState = GroundState.Grounded; else if (groundState != GroundState.Jumping) groundState = GroundState.Falling; // Diagnostic velocity...FloorToInt for display purposes velocity = Vector3Int.FloorToInt(characterController.velocity); } // TODO: Turning works while airborne...feature? void HandleTurning() { // Q and E cancel each other out, reducing the turn to zero. if (Input.GetKey(KeyCode.Q)) turnSpeed = Mathf.MoveTowards(turnSpeed, -maxTurnSpeed, turnDelta); if (Input.GetKey(KeyCode.E)) turnSpeed = Mathf.MoveTowards(turnSpeed, maxTurnSpeed, turnDelta); // If both pressed, reduce turning speed toward zero. if (Input.GetKey(KeyCode.Q) && Input.GetKey(KeyCode.E)) turnSpeed = Mathf.MoveTowards(turnSpeed, 0, turnDelta); // If neither pressed, reduce turning speed toward zero. if (!Input.GetKey(KeyCode.Q) && !Input.GetKey(KeyCode.E)) turnSpeed = Mathf.MoveTowards(turnSpeed, 0, turnDelta); transform.Rotate(0f, turnSpeed * Time.deltaTime, 0f); } void HandleJumping() { // Handle variable force jumping. // Jump starts with initial power on takeoff, and jumps higher / longer // as player holds spacebar. Jump power is increased by a diminishing amout // every frame until it reaches maxJumpSpeed, or player releases the spacebar, // and then changes to the falling state until it gets grounded. if (groundState != GroundState.Falling && Input.GetKey(KeyCode.Space)) { if (groundState != GroundState.Jumping) { // Start jump at initial power. groundState = GroundState.Jumping; jumpSpeed = initialJumpSpeed; } else // Jumping has already started...increase power toward maxJumpSpeed over time. jumpSpeed = Mathf.MoveTowards(jumpSpeed, maxJumpSpeed, jumpDelta); // If power has reached maxJumpSpeed, change to falling until grounded. // This prevents over-applying jump power while already in the air. if (jumpSpeed == maxJumpSpeed) groundState = GroundState.Falling; } else if (groundState != GroundState.Grounded) { // handles running off a cliff and/or player released Spacebar. groundState = GroundState.Falling; jumpSpeed = Mathf.Min(jumpSpeed, maxJumpSpeed); jumpSpeed += Physics.gravity.y * Time.deltaTime; } else jumpSpeed = Physics.gravity.y * Time.deltaTime; } // TODO: Directional input works while airborne...feature? void HandleMove() { // Capture inputs horizontal = Input.GetAxis("Horizontal"); vertical = Input.GetAxis("Vertical"); // Create initial direction vector without jumpSpeed (y-axis). direction = new Vector3(horizontal, 0f, vertical); // Clamp so diagonal strafing isn't a speed advantage. direction = Vector3.ClampMagnitude(direction, 1f); // Transforms direction from local space to world space. direction = transform.TransformDirection(direction); // Multiply for desired ground speed. direction *= moveSpeedMultiplier; // Add jumpSpeed to direction as last step. direction.y = jumpSpeed; // Finally move the character. characterController.Move(direction * Time.deltaTime); } } }
1
0.808108
1
0.808108
game-dev
MEDIA
0.996801
game-dev
0.967338
1
0.967338
jswigart/omni-bot
72,475
GameInterfaces/D3/src/game/Misc.cpp
// Copyright (C) 2004 Id Software, Inc. // /* Various utility objects and functions. */ #include "../idlib/precompiled.h" #pragma hdrstop #include "Game_local.h" /* =============================================================================== idSpawnableEntity A simple, spawnable entity with a model and no functionable ability of it's own. For example, it can be used as a placeholder during development, for marking locations on maps for script, or for simple placed models without any behavior that can be bound to other entities. Should not be subclassed. =============================================================================== */ CLASS_DECLARATION( idEntity, idSpawnableEntity ) END_CLASS /* ====================== idSpawnableEntity::Spawn ====================== */ void idSpawnableEntity::Spawn() { // this just holds dict information } /* =============================================================================== idPlayerStart =============================================================================== */ const idEventDef EV_TeleportStage( "<TeleportStage>", "e" ); CLASS_DECLARATION( idEntity, idPlayerStart ) EVENT( EV_Activate, idPlayerStart::Event_TeleportPlayer ) EVENT( EV_TeleportStage, idPlayerStart::Event_TeleportStage ) END_CLASS /* =============== idPlayerStart::idPlayerStart ================ */ idPlayerStart::idPlayerStart( void ) { teleportStage = 0; } /* =============== idPlayerStart::Spawn ================ */ void idPlayerStart::Spawn( void ) { teleportStage = 0; } /* ================ idPlayerStart::Save ================ */ void idPlayerStart::Save( idSaveGame *savefile ) const { savefile->WriteInt( teleportStage ); } /* ================ idPlayerStart::Restore ================ */ void idPlayerStart::Restore( idRestoreGame *savefile ) { savefile->ReadInt( teleportStage ); } /* ================ idPlayerStart::ClientReceiveEvent ================ */ bool idPlayerStart::ClientReceiveEvent( int event, int time, const idBitMsg &msg ) { int entityNumber; switch( event ) { case EVENT_TELEPORTPLAYER: { entityNumber = msg.ReadBits( GENTITYNUM_BITS ); idPlayer *player = static_cast<idPlayer *>( gameLocal.entities[entityNumber] ); if ( player != NULL && player->IsType( idPlayer::Type ) ) { Event_TeleportPlayer( player ); } return true; } default: { return idEntity::ClientReceiveEvent( event, time, msg ); } } return false; } /* =============== idPlayerStart::Event_TeleportStage FIXME: add functionality to fx system ( could be done with player scripting too ) ================ */ void idPlayerStart::Event_TeleportStage( idEntity *_player ) { idPlayer *player; if ( !_player->IsType( idPlayer::Type ) ) { common->Warning( "idPlayerStart::Event_TeleportStage: entity is not an idPlayer\n" ); return; } player = static_cast<idPlayer*>(_player); float teleportDelay = spawnArgs.GetFloat( "teleportDelay" ); switch ( teleportStage ) { case 0: player->playerView.Flash( colorWhite, 125 ); player->SetInfluenceLevel( INFLUENCE_LEVEL3 ); player->SetInfluenceView( spawnArgs.GetString( "mtr_teleportFx" ), NULL, 0.0f, NULL ); gameSoundWorld->FadeSoundClasses( 0, -20.0f, teleportDelay ); player->StartSound( "snd_teleport_start", SND_CHANNEL_BODY2, 0, false, NULL ); teleportStage++; PostEventSec( &EV_TeleportStage, teleportDelay, player ); break; case 1: gameSoundWorld->FadeSoundClasses( 0, 0.0f, 0.25f ); teleportStage++; PostEventSec( &EV_TeleportStage, 0.25f, player ); break; case 2: player->SetInfluenceView( NULL, NULL, 0.0f, NULL ); TeleportPlayer( player ); player->StopSound( SND_CHANNEL_BODY2, false ); player->SetInfluenceLevel( INFLUENCE_NONE ); teleportStage = 0; break; default: break; } } /* =============== idPlayerStart::TeleportPlayer ================ */ void idPlayerStart::TeleportPlayer( idPlayer *player ) { float pushVel = spawnArgs.GetFloat( "push", "300" ); float f = spawnArgs.GetFloat( "visualEffect", "0" ); const char *viewName = spawnArgs.GetString( "visualView", "" ); idEntity *ent = viewName ? gameLocal.FindEntity( viewName ) : NULL; if ( f && ent ) { // place in private camera view for some time // the entity needs to teleport to where the camera view is to have the PVS right player->Teleport( ent->GetPhysics()->GetOrigin(), ang_zero, this ); player->StartSound( "snd_teleport_enter", SND_CHANNEL_ANY, 0, false, NULL ); player->SetPrivateCameraView( static_cast<idCamera*>(ent) ); // the player entity knows where to spawn from the previous Teleport call if ( !gameLocal.isClient ) { player->PostEventSec( &EV_Player_ExitTeleporter, f ); } } else { // direct to exit, Teleport will take care of the killbox player->Teleport( GetPhysics()->GetOrigin(), GetPhysics()->GetAxis().ToAngles(), NULL ); // multiplayer hijacked this entity, so only push the player in multiplayer if ( gameLocal.isMultiplayer ) { player->GetPhysics()->SetLinearVelocity( GetPhysics()->GetAxis()[0] * pushVel ); } } } /* =============== idPlayerStart::Event_TeleportPlayer ================ */ void idPlayerStart::Event_TeleportPlayer( idEntity *activator ) { idPlayer *player; if ( activator->IsType( idPlayer::Type ) ) { player = static_cast<idPlayer*>( activator ); } else { player = gameLocal.GetLocalPlayer(); } if ( player ) { if ( spawnArgs.GetBool( "visualFx" ) ) { teleportStage = 0; Event_TeleportStage( player ); } else { if ( gameLocal.isServer ) { idBitMsg msg; byte msgBuf[MAX_EVENT_PARAM_SIZE]; msg.Init( msgBuf, sizeof( msgBuf ) ); msg.BeginWriting(); msg.WriteBits( player->entityNumber, GENTITYNUM_BITS ); ServerSendEvent( EVENT_TELEPORTPLAYER, &msg, false, -1 ); } TeleportPlayer( player ); } } } /* =============================================================================== idActivator =============================================================================== */ CLASS_DECLARATION( idEntity, idActivator ) EVENT( EV_Activate, idActivator::Event_Activate ) END_CLASS /* =============== idActivator::Save ================ */ void idActivator::Save( idSaveGame *savefile ) const { savefile->WriteBool( stay_on ); } /* =============== idActivator::Restore ================ */ void idActivator::Restore( idRestoreGame *savefile ) { savefile->ReadBool( stay_on ); if ( stay_on ) { BecomeActive( TH_THINK ); } } /* =============== idActivator::Spawn ================ */ void idActivator::Spawn( void ) { bool start_off; spawnArgs.GetBool( "stay_on", "0", stay_on ); spawnArgs.GetBool( "start_off", "0", start_off ); GetPhysics()->SetClipBox( idBounds( vec3_origin ).Expand( 4 ), 1.0f ); GetPhysics()->SetContents( 0 ); if ( !start_off ) { BecomeActive( TH_THINK ); } } /* =============== idActivator::Think ================ */ void idActivator::Think( void ) { RunPhysics(); if ( thinkFlags & TH_THINK ) { if ( TouchTriggers() ) { if ( !stay_on ) { BecomeInactive( TH_THINK ); } } } Present(); } /* =============== idActivator::Activate ================ */ void idActivator::Event_Activate( idEntity *activator ) { if ( thinkFlags & TH_THINK ) { BecomeInactive( TH_THINK ); } else { BecomeActive( TH_THINK ); } } /* =============================================================================== idPathCorner =============================================================================== */ CLASS_DECLARATION( idEntity, idPathCorner ) EVENT( AI_RandomPath, idPathCorner::Event_RandomPath ) END_CLASS /* ===================== idPathCorner::Spawn ===================== */ void idPathCorner::Spawn( void ) { } /* ===================== idPathCorner::DrawDebugInfo ===================== */ void idPathCorner::DrawDebugInfo( void ) { idEntity *ent; idBounds bnds( idVec3( -4.0, -4.0f, -8.0f ), idVec3( 4.0, 4.0f, 64.0f ) ); for( ent = gameLocal.spawnedEntities.Next(); ent != NULL; ent = ent->spawnNode.Next() ) { if ( !ent->IsType( idPathCorner::Type ) ) { continue; } idVec3 org = ent->GetPhysics()->GetOrigin(); gameRenderWorld->DebugBounds( colorRed, bnds, org, 0 ); } } /* ============ idPathCorner::RandomPath ============ */ idPathCorner *idPathCorner::RandomPath( const idEntity *source, const idEntity *ignore ) { int i; int num; int which; idEntity *ent; idPathCorner *path[ MAX_GENTITIES ]; num = 0; for( i = 0; i < source->targets.Num(); i++ ) { ent = source->targets[ i ].GetEntity(); if ( ent && ( ent != ignore ) && ent->IsType( idPathCorner::Type ) ) { path[ num++ ] = static_cast<idPathCorner *>( ent ); if ( num >= MAX_GENTITIES ) { break; } } } if ( !num ) { return NULL; } which = gameLocal.random.RandomInt( num ); return path[ which ]; } /* ===================== idPathCorner::Event_RandomPath ===================== */ void idPathCorner::Event_RandomPath( void ) { idPathCorner *path; path = RandomPath( this, NULL ); idThread::ReturnEntity( path ); } /* =============================================================================== idDamagable =============================================================================== */ const idEventDef EV_RestoreDamagable( "<RestoreDamagable>" ); CLASS_DECLARATION( idEntity, idDamagable ) EVENT( EV_Activate, idDamagable::Event_BecomeBroken ) EVENT( EV_RestoreDamagable, idDamagable::Event_RestoreDamagable ) END_CLASS /* ================ idDamagable::idDamagable ================ */ idDamagable::idDamagable( void ) { count = 0; nextTriggerTime = 0; } /* ================ idDamagable::Save ================ */ void idDamagable::Save( idSaveGame *savefile ) const { savefile->WriteInt( count ); savefile->WriteInt( nextTriggerTime ); } /* ================ idDamagable::Restore ================ */ void idDamagable::Restore( idRestoreGame *savefile ) { savefile->ReadInt( count ); savefile->ReadInt( nextTriggerTime ); } /* ================ idDamagable::Spawn ================ */ void idDamagable::Spawn( void ) { idStr broken; health = spawnArgs.GetInt( "health", "5" ); spawnArgs.GetInt( "count", "1", count ); nextTriggerTime = 0; // make sure the model gets cached spawnArgs.GetString( "broken", "", broken ); if ( broken.Length() && !renderModelManager->CheckModel( broken ) ) { gameLocal.Error( "idDamagable '%s' at (%s): cannot load broken model '%s'", name.c_str(), GetPhysics()->GetOrigin().ToString(0), broken.c_str() ); } fl.takedamage = true; GetPhysics()->SetContents( CONTENTS_SOLID ); } /* ================ idDamagable::BecomeBroken ================ */ void idDamagable::BecomeBroken( idEntity *activator ) { float forceState; int numStates; int cycle; float wait; if ( gameLocal.time < nextTriggerTime ) { return; } spawnArgs.GetFloat( "wait", "0.1", wait ); nextTriggerTime = gameLocal.time + SEC2MS( wait ); if ( count > 0 ) { count--; if ( !count ) { fl.takedamage = false; } else { health = spawnArgs.GetInt( "health", "5" ); } } idStr broken; spawnArgs.GetString( "broken", "", broken ); if ( broken.Length() ) { SetModel( broken ); } // offset the start time of the shader to sync it to the gameLocal time renderEntity.shaderParms[ SHADERPARM_TIMEOFFSET ] = -MS2SEC( gameLocal.time ); spawnArgs.GetInt( "numstates", "1", numStates ); spawnArgs.GetInt( "cycle", "0", cycle ); spawnArgs.GetFloat( "forcestate", "0", forceState ); // set the state parm if ( cycle ) { renderEntity.shaderParms[ SHADERPARM_MODE ]++; if ( renderEntity.shaderParms[ SHADERPARM_MODE ] > numStates ) { renderEntity.shaderParms[ SHADERPARM_MODE ] = 0; } } else if ( forceState ) { renderEntity.shaderParms[ SHADERPARM_MODE ] = forceState; } else { renderEntity.shaderParms[ SHADERPARM_MODE ] = gameLocal.random.RandomInt( numStates ) + 1; } renderEntity.shaderParms[ SHADERPARM_TIMEOFFSET ] = -MS2SEC( gameLocal.time ); ActivateTargets( activator ); if ( spawnArgs.GetBool( "hideWhenBroken" ) ) { Hide(); PostEventMS( &EV_RestoreDamagable, nextTriggerTime - gameLocal.time ); BecomeActive( TH_THINK ); } } /* ================ idDamagable::Killed ================ */ void idDamagable::Killed( idEntity *inflictor, idEntity *attacker, int damage, const idVec3 &dir, int location ) { if ( gameLocal.time < nextTriggerTime ) { health += damage; return; } BecomeBroken( attacker ); } /* ================ idDamagable::Event_BecomeBroken ================ */ void idDamagable::Event_BecomeBroken( idEntity *activator ) { BecomeBroken( activator ); } /* ================ idDamagable::Event_RestoreDamagable ================ */ void idDamagable::Event_RestoreDamagable( void ) { health = spawnArgs.GetInt( "health", "5" ); Show(); } /* =============================================================================== idExplodable =============================================================================== */ CLASS_DECLARATION( idEntity, idExplodable ) EVENT( EV_Activate, idExplodable::Event_Explode ) END_CLASS /* ================ idExplodable::Spawn ================ */ void idExplodable::Spawn( void ) { Hide(); } /* ================ idExplodable::Event_Explode ================ */ void idExplodable::Event_Explode( idEntity *activator ) { const char *temp; if ( spawnArgs.GetString( "def_damage", "damage_explosion", &temp ) ) { gameLocal.RadiusDamage( GetPhysics()->GetOrigin(), activator, activator, this, this, temp ); } StartSound( "snd_explode", SND_CHANNEL_ANY, 0, false, NULL ); // Show() calls UpdateVisuals, so we don't need to call it ourselves after setting the shaderParms renderEntity.shaderParms[SHADERPARM_RED] = 1.0f; renderEntity.shaderParms[SHADERPARM_GREEN] = 1.0f; renderEntity.shaderParms[SHADERPARM_BLUE] = 1.0f; renderEntity.shaderParms[SHADERPARM_ALPHA] = 1.0f; renderEntity.shaderParms[SHADERPARM_TIMEOFFSET] = -MS2SEC( gameLocal.time ); renderEntity.shaderParms[SHADERPARM_DIVERSITY] = 0.0f; Show(); PostEventMS( &EV_Remove, 2000 ); ActivateTargets( activator ); } /* =============================================================================== idSpring =============================================================================== */ CLASS_DECLARATION( idEntity, idSpring ) EVENT( EV_PostSpawn, idSpring::Event_LinkSpring ) END_CLASS /* ================ idSpring::Think ================ */ void idSpring::Think( void ) { idVec3 start, end, origin; idMat3 axis; // run physics RunPhysics(); if ( thinkFlags & TH_THINK ) { // evaluate force spring.Evaluate( gameLocal.time ); start = p1; if ( ent1->GetPhysics() ) { axis = ent1->GetPhysics()->GetAxis(); origin = ent1->GetPhysics()->GetOrigin(); start = origin + start * axis; } end = p2; if ( ent2->GetPhysics() ) { axis = ent2->GetPhysics()->GetAxis(); origin = ent2->GetPhysics()->GetOrigin(); end = origin + p2 * axis; } gameRenderWorld->DebugLine( idVec4(1, 1, 0, 1), start, end, 0, true ); } Present(); } /* ================ idSpring::Event_LinkSpring ================ */ void idSpring::Event_LinkSpring( void ) { idStr name1, name2; spawnArgs.GetString( "ent1", "", name1 ); spawnArgs.GetString( "ent2", "", name2 ); if ( name1.Length() ) { ent1 = gameLocal.FindEntity( name1 ); if ( !ent1 ) { gameLocal.Error( "idSpring '%s' at (%s): cannot find first entity '%s'", name.c_str(), GetPhysics()->GetOrigin().ToString(0), name1.c_str() ); } } else { ent1 = gameLocal.entities[ENTITYNUM_WORLD]; } if ( name2.Length() ) { ent2 = gameLocal.FindEntity( name2 ); if ( !ent2 ) { gameLocal.Error( "idSpring '%s' at (%s): cannot find second entity '%s'", name.c_str(), GetPhysics()->GetOrigin().ToString(0), name2.c_str() ); } } else { ent2 = gameLocal.entities[ENTITYNUM_WORLD]; } spring.SetPosition( ent1->GetPhysics(), id1, p1, ent2->GetPhysics(), id2, p2 ); BecomeActive( TH_THINK ); } /* ================ idSpring::Spawn ================ */ void idSpring::Spawn( void ) { float Kstretch, damping, restLength; spawnArgs.GetInt( "id1", "0", id1 ); spawnArgs.GetInt( "id2", "0", id2 ); spawnArgs.GetVector( "point1", "0 0 0", p1 ); spawnArgs.GetVector( "point2", "0 0 0", p2 ); spawnArgs.GetFloat( "constant", "100.0f", Kstretch ); spawnArgs.GetFloat( "damping", "10.0f", damping ); spawnArgs.GetFloat( "restlength", "0.0f", restLength ); spring.InitSpring( Kstretch, 0.0f, damping, restLength ); ent1 = ent2 = NULL; PostEventMS( &EV_PostSpawn, 0 ); } /* =============================================================================== idForceField =============================================================================== */ const idEventDef EV_Toggle( "Toggle", NULL ); CLASS_DECLARATION( idEntity, idForceField ) EVENT( EV_Activate, idForceField::Event_Activate ) EVENT( EV_Toggle, idForceField::Event_Toggle ) EVENT( EV_FindTargets, idForceField::Event_FindTargets ) END_CLASS /* =============== idForceField::Toggle ================ */ void idForceField::Toggle( void ) { if ( thinkFlags & TH_THINK ) { BecomeInactive( TH_THINK ); } else { BecomeActive( TH_THINK ); } } /* ================ idForceField::Think ================ */ void idForceField::Think( void ) { if ( thinkFlags & TH_THINK ) { // evaluate force forceField.Evaluate( gameLocal.time ); } Present(); } /* ================ idForceField::Save ================ */ void idForceField::Save( idSaveGame *savefile ) const { savefile->WriteStaticObject( forceField ); } /* ================ idForceField::Restore ================ */ void idForceField::Restore( idRestoreGame *savefile ) { savefile->ReadStaticObject( forceField ); } /* ================ idForceField::Spawn ================ */ void idForceField::Spawn( void ) { idVec3 uniform; float explosion, implosion, randomTorque; if ( spawnArgs.GetVector( "uniform", "0 0 0", uniform ) ) { forceField.Uniform( uniform ); } else if ( spawnArgs.GetFloat( "explosion", "0", explosion ) ) { forceField.Explosion( explosion ); } else if ( spawnArgs.GetFloat( "implosion", "0", implosion ) ) { forceField.Implosion( implosion ); } if ( spawnArgs.GetFloat( "randomTorque", "0", randomTorque ) ) { forceField.RandomTorque( randomTorque ); } if ( spawnArgs.GetBool( "applyForce", "0" ) ) { forceField.SetApplyType( FORCEFIELD_APPLY_FORCE ); } else if ( spawnArgs.GetBool( "applyImpulse", "0" ) ) { forceField.SetApplyType( FORCEFIELD_APPLY_IMPULSE ); } else { forceField.SetApplyType( FORCEFIELD_APPLY_VELOCITY ); } forceField.SetPlayerOnly( spawnArgs.GetBool( "playerOnly", "0" ) ); forceField.SetMonsterOnly( spawnArgs.GetBool( "monsterOnly", "0" ) ); // set the collision model on the force field forceField.SetClipModel( new idClipModel( GetPhysics()->GetClipModel() ) ); // remove the collision model from the physics object GetPhysics()->SetClipModel( NULL, 1.0f ); if ( spawnArgs.GetBool( "start_on" ) ) { BecomeActive( TH_THINK ); } } /* =============== idForceField::Event_Toggle ================ */ void idForceField::Event_Toggle( void ) { Toggle(); } /* ================ idForceField::Event_Activate ================ */ void idForceField::Event_Activate( idEntity *activator ) { float wait; Toggle(); if ( spawnArgs.GetFloat( "wait", "0.01", wait ) ) { PostEventSec( &EV_Toggle, wait ); } } /* ================ idForceField::Event_FindTargets ================ */ void idForceField::Event_FindTargets( void ) { FindTargets(); RemoveNullTargets(); if ( targets.Num() ) { forceField.Uniform( targets[0].GetEntity()->GetPhysics()->GetOrigin() - GetPhysics()->GetOrigin() ); } } /* =============================================================================== idAnimated =============================================================================== */ const idEventDef EV_Animated_Start( "<start>" ); const idEventDef EV_LaunchMissiles( "launchMissiles", "ssssdf" ); const idEventDef EV_LaunchMissilesUpdate( "<launchMissiles>", "dddd" ); const idEventDef EV_AnimDone( "<AnimDone>", "d" ); const idEventDef EV_StartRagdoll( "startRagdoll" ); CLASS_DECLARATION( idAFEntity_Gibbable, idAnimated ) EVENT( EV_Activate, idAnimated::Event_Activate ) EVENT( EV_Animated_Start, idAnimated::Event_Start ) EVENT( EV_StartRagdoll, idAnimated::Event_StartRagdoll ) EVENT( EV_AnimDone, idAnimated::Event_AnimDone ) EVENT( EV_Footstep, idAnimated::Event_Footstep ) EVENT( EV_FootstepLeft, idAnimated::Event_Footstep ) EVENT( EV_FootstepRight, idAnimated::Event_Footstep ) EVENT( EV_LaunchMissiles, idAnimated::Event_LaunchMissiles ) EVENT( EV_LaunchMissilesUpdate, idAnimated::Event_LaunchMissilesUpdate ) END_CLASS /* =============== idAnimated::idAnimated ================ */ idAnimated::idAnimated() { anim = 0; blendFrames = 0; soundJoint = INVALID_JOINT; activated = false; combatModel = NULL; activator = NULL; current_anim_index = 0; num_anims = 0; } /* =============== idAnimated::idAnimated ================ */ idAnimated::~idAnimated() { delete combatModel; combatModel = NULL; } /* =============== idAnimated::Save ================ */ void idAnimated::Save( idSaveGame *savefile ) const { savefile->WriteInt( current_anim_index ); savefile->WriteInt( num_anims ); savefile->WriteInt( anim ); savefile->WriteInt( blendFrames ); savefile->WriteJoint( soundJoint ); activator.Save( savefile ); savefile->WriteBool( activated ); } /* =============== idAnimated::Restore ================ */ void idAnimated::Restore( idRestoreGame *savefile ) { savefile->ReadInt( current_anim_index ); savefile->ReadInt( num_anims ); savefile->ReadInt( anim ); savefile->ReadInt( blendFrames ); savefile->ReadJoint( soundJoint ); activator.Restore( savefile ); savefile->ReadBool( activated ); } /* =============== idAnimated::Spawn ================ */ void idAnimated::Spawn( void ) { idStr animname; int anim2; float wait; const char *joint; joint = spawnArgs.GetString( "sound_bone", "origin" ); soundJoint = animator.GetJointHandle( joint ); if ( soundJoint == INVALID_JOINT ) { gameLocal.Warning( "idAnimated '%s' at (%s): cannot find joint '%s' for sound playback", name.c_str(), GetPhysics()->GetOrigin().ToString(0), joint ); } LoadAF(); // allow bullets to collide with a combat model if ( spawnArgs.GetBool( "combatModel", "0" ) ) { combatModel = new idClipModel( modelDefHandle ); } // allow the entity to take damage if ( spawnArgs.GetBool( "takeDamage", "0" ) ) { fl.takedamage = true; } blendFrames = 0; current_anim_index = 0; spawnArgs.GetInt( "num_anims", "0", num_anims ); blendFrames = spawnArgs.GetInt( "blend_in" ); animname = spawnArgs.GetString( num_anims ? "anim1" : "anim" ); if ( !animname.Length() ) { anim = 0; } else { anim = animator.GetAnim( animname ); if ( !anim ) { gameLocal.Error( "idAnimated '%s' at (%s): cannot find anim '%s'", name.c_str(), GetPhysics()->GetOrigin().ToString(0), animname.c_str() ); } } if ( spawnArgs.GetBool( "hide" ) ) { Hide(); if ( !num_anims ) { blendFrames = 0; } } else if ( spawnArgs.GetString( "start_anim", "", animname ) ) { anim2 = animator.GetAnim( animname ); if ( !anim2 ) { gameLocal.Error( "idAnimated '%s' at (%s): cannot find anim '%s'", name.c_str(), GetPhysics()->GetOrigin().ToString(0), animname.c_str() ); } animator.CycleAnim( ANIMCHANNEL_ALL, anim2, gameLocal.time, 0 ); } else if ( anim ) { // init joints to the first frame of the animation animator.SetFrame( ANIMCHANNEL_ALL, anim, 1, gameLocal.time, 0 ); if ( !num_anims ) { blendFrames = 0; } } spawnArgs.GetFloat( "wait", "-1", wait ); if ( wait >= 0 ) { PostEventSec( &EV_Activate, wait, this ); } } /* =============== idAnimated::LoadAF =============== */ bool idAnimated::LoadAF( void ) { idStr fileName; if ( !spawnArgs.GetString( "ragdoll", "*unknown*", fileName ) ) { return false; } af.SetAnimator( GetAnimator() ); return af.Load( this, fileName ); } /* =============== idAnimated::GetPhysicsToSoundTransform =============== */ bool idAnimated::GetPhysicsToSoundTransform( idVec3 &origin, idMat3 &axis ) { animator.GetJointTransform( soundJoint, gameLocal.time, origin, axis ); axis = renderEntity.axis; return true; } /* ================ idAnimated::StartRagdoll ================ */ bool idAnimated::StartRagdoll( void ) { // if no AF loaded if ( !af.IsLoaded() ) { return false; } // if the AF is already active if ( af.IsActive() ) { return true; } // disable any collision model used GetPhysics()->DisableClip(); // start using the AF af.StartFromCurrentPose( spawnArgs.GetInt( "velocityTime", "0" ) ); return true; } /* ===================== idAnimated::PlayNextAnim ===================== */ void idAnimated::PlayNextAnim( void ) { const char *animname; int len; int cycle; if ( current_anim_index >= num_anims ) { Hide(); if ( spawnArgs.GetBool( "remove" ) ) { PostEventMS( &EV_Remove, 0 ); } else { current_anim_index = 0; } return; } Show(); current_anim_index++; spawnArgs.GetString( va( "anim%d", current_anim_index ), NULL, &animname ); if ( !animname ) { anim = 0; animator.Clear( ANIMCHANNEL_ALL, gameLocal.time, FRAME2MS( blendFrames ) ); return; } anim = animator.GetAnim( animname ); if ( !anim ) { gameLocal.Warning( "missing anim '%s' on %s", animname, name.c_str() ); return; } if ( g_debugCinematic.GetBool() ) { gameLocal.Printf( "%d: '%s' start anim '%s'\n", gameLocal.framenum, GetName(), animname ); } spawnArgs.GetInt( "cycle", "1", cycle ); if ( ( current_anim_index == num_anims ) && spawnArgs.GetBool( "loop_last_anim" ) ) { cycle = -1; } animator.CycleAnim( ANIMCHANNEL_ALL, anim, gameLocal.time, FRAME2MS( blendFrames ) ); animator.CurrentAnim( ANIMCHANNEL_ALL )->SetCycleCount( cycle ); len = animator.CurrentAnim( ANIMCHANNEL_ALL )->PlayLength(); if ( len >= 0 ) { PostEventMS( &EV_AnimDone, len, current_anim_index ); } // offset the start time of the shader to sync it to the game time renderEntity.shaderParms[ SHADERPARM_TIMEOFFSET ] = -MS2SEC( gameLocal.time ); animator.ForceUpdate(); UpdateAnimation(); UpdateVisuals(); Present(); } /* =============== idAnimated::Event_StartRagdoll ================ */ void idAnimated::Event_StartRagdoll( void ) { StartRagdoll(); } /* =============== idAnimated::Event_AnimDone ================ */ void idAnimated::Event_AnimDone( int animindex ) { if ( g_debugCinematic.GetBool() ) { const idAnim *animPtr = animator.GetAnim( anim ); gameLocal.Printf( "%d: '%s' end anim '%s'\n", gameLocal.framenum, GetName(), animPtr ? animPtr->Name() : "" ); } if ( ( animindex >= num_anims ) && spawnArgs.GetBool( "remove" ) ) { Hide(); PostEventMS( &EV_Remove, 0 ); } else if ( spawnArgs.GetBool( "auto_advance" ) ) { PlayNextAnim(); } else { activated = false; } ActivateTargets( activator.GetEntity() ); } /* =============== idAnimated::Event_Activate ================ */ void idAnimated::Event_Activate( idEntity *_activator ) { if ( num_anims ) { PlayNextAnim(); activator = _activator; return; } if ( activated ) { // already activated return; } activated = true; activator = _activator; ProcessEvent( &EV_Animated_Start ); } /* =============== idAnimated::Event_Start ================ */ void idAnimated::Event_Start( void ) { int cycle; int len; Show(); if ( num_anims ) { PlayNextAnim(); return; } if ( anim ) { if ( g_debugCinematic.GetBool() ) { const idAnim *animPtr = animator.GetAnim( anim ); gameLocal.Printf( "%d: '%s' start anim '%s'\n", gameLocal.framenum, GetName(), animPtr ? animPtr->Name() : "" ); } spawnArgs.GetInt( "cycle", "1", cycle ); animator.CycleAnim( ANIMCHANNEL_ALL, anim, gameLocal.time, FRAME2MS( blendFrames ) ); animator.CurrentAnim( ANIMCHANNEL_ALL )->SetCycleCount( cycle ); len = animator.CurrentAnim( ANIMCHANNEL_ALL )->PlayLength(); if ( len >= 0 ) { PostEventMS( &EV_AnimDone, len, 1 ); } } // offset the start time of the shader to sync it to the game time renderEntity.shaderParms[ SHADERPARM_TIMEOFFSET ] = -MS2SEC( gameLocal.time ); animator.ForceUpdate(); UpdateAnimation(); UpdateVisuals(); Present(); } /* =============== idAnimated::Event_Footstep =============== */ void idAnimated::Event_Footstep( void ) { StartSound( "snd_footstep", SND_CHANNEL_BODY, 0, false, NULL ); } /* ===================== idAnimated::Event_LaunchMissilesUpdate ===================== */ void idAnimated::Event_LaunchMissilesUpdate( int launchjoint, int targetjoint, int numshots, int framedelay ) { idVec3 launchPos; idVec3 targetPos; idMat3 axis; idVec3 dir; idEntity * ent; idProjectile * projectile; const idDict * projectileDef; const char * projectilename; projectilename = spawnArgs.GetString( "projectilename" ); projectileDef = gameLocal.FindEntityDefDict( projectilename, false ); if ( !projectileDef ) { gameLocal.Warning( "idAnimated '%s' at (%s): 'launchMissiles' called with unknown projectile '%s'", name.c_str(), GetPhysics()->GetOrigin().ToString(0), projectilename ); return; } StartSound( "snd_missile", SND_CHANNEL_WEAPON, 0, false, NULL ); animator.GetJointTransform( ( jointHandle_t )launchjoint, gameLocal.time, launchPos, axis ); launchPos = renderEntity.origin + launchPos * renderEntity.axis; animator.GetJointTransform( ( jointHandle_t )targetjoint, gameLocal.time, targetPos, axis ); targetPos = renderEntity.origin + targetPos * renderEntity.axis; dir = targetPos - launchPos; dir.Normalize(); gameLocal.SpawnEntityDef( *projectileDef, &ent, false ); if ( !ent || !ent->IsType( idProjectile::Type ) ) { gameLocal.Error( "idAnimated '%s' at (%s): in 'launchMissiles' call '%s' is not an idProjectile", name.c_str(), GetPhysics()->GetOrigin().ToString(0), projectilename ); } projectile = ( idProjectile * )ent; projectile->Create( this, launchPos, dir ); projectile->Launch( launchPos, dir, vec3_origin ); if ( numshots > 0 ) { PostEventMS( &EV_LaunchMissilesUpdate, FRAME2MS( framedelay ), launchjoint, targetjoint, numshots - 1, framedelay ); } } /* ===================== idAnimated::Event_LaunchMissiles ===================== */ void idAnimated::Event_LaunchMissiles( const char *projectilename, const char *sound, const char *launchjoint, const char *targetjoint, int numshots, int framedelay ) { const idDict * projectileDef; jointHandle_t launch; jointHandle_t target; projectileDef = gameLocal.FindEntityDefDict( projectilename, false ); if ( !projectileDef ) { gameLocal.Warning( "idAnimated '%s' at (%s): unknown projectile '%s'", name.c_str(), GetPhysics()->GetOrigin().ToString(0), projectilename ); return; } launch = animator.GetJointHandle( launchjoint ); if ( launch == INVALID_JOINT ) { gameLocal.Warning( "idAnimated '%s' at (%s): unknown launch joint '%s'", name.c_str(), GetPhysics()->GetOrigin().ToString(0), launchjoint ); gameLocal.Error( "Unknown joint '%s'", launchjoint ); } target = animator.GetJointHandle( targetjoint ); if ( target == INVALID_JOINT ) { gameLocal.Warning( "idAnimated '%s' at (%s): unknown target joint '%s'", name.c_str(), GetPhysics()->GetOrigin().ToString(0), targetjoint ); } spawnArgs.Set( "projectilename", projectilename ); spawnArgs.Set( "missilesound", sound ); CancelEvents( &EV_LaunchMissilesUpdate ); ProcessEvent( &EV_LaunchMissilesUpdate, launch, target, numshots - 1, framedelay ); } /* =============================================================================== idStaticEntity Some static entities may be optimized into inline geometry by dmap =============================================================================== */ CLASS_DECLARATION( idEntity, idStaticEntity ) EVENT( EV_Activate, idStaticEntity::Event_Activate ) END_CLASS /* =============== idStaticEntity::idStaticEntity =============== */ idStaticEntity::idStaticEntity( void ) { spawnTime = 0; active = false; fadeFrom.Set( 1, 1, 1, 1 ); fadeTo.Set( 1, 1, 1, 1 ); fadeStart = 0; fadeEnd = 0; runGui = false; } /* =============== idStaticEntity::Save =============== */ void idStaticEntity::Save( idSaveGame *savefile ) const { savefile->WriteInt( spawnTime ); savefile->WriteBool( active ); savefile->WriteVec4( fadeFrom ); savefile->WriteVec4( fadeTo ); savefile->WriteInt( fadeStart ); savefile->WriteInt( fadeEnd ); savefile->WriteBool( runGui ); } /* =============== idStaticEntity::Restore =============== */ void idStaticEntity::Restore( idRestoreGame *savefile ) { savefile->ReadInt( spawnTime ); savefile->ReadBool( active ); savefile->ReadVec4( fadeFrom ); savefile->ReadVec4( fadeTo ); savefile->ReadInt( fadeStart ); savefile->ReadInt( fadeEnd ); savefile->ReadBool( runGui ); } /* =============== idStaticEntity::Spawn =============== */ void idStaticEntity::Spawn( void ) { bool solid; bool hidden; // an inline static model will not do anything at all if ( spawnArgs.GetBool( "inline" ) || gameLocal.world->spawnArgs.GetBool( "inlineAllStatics" ) ) { Hide(); return; } solid = spawnArgs.GetBool( "solid" ); hidden = spawnArgs.GetBool( "hide" ); if ( solid && !hidden ) { GetPhysics()->SetContents( CONTENTS_SOLID ); } else { GetPhysics()->SetContents( 0 ); } spawnTime = gameLocal.time; active = false; idStr model = spawnArgs.GetString( "model" ); if ( model.Find( ".prt" ) >= 0 ) { // we want the parametric particles out of sync with each other renderEntity.shaderParms[ SHADERPARM_TIMEOFFSET ] = gameLocal.random.RandomInt( 32767 ); } fadeFrom.Set( 1, 1, 1, 1 ); fadeTo.Set( 1, 1, 1, 1 ); fadeStart = 0; fadeEnd = 0; // NOTE: this should be used very rarely because it is expensive runGui = spawnArgs.GetBool( "runGui" ); if ( runGui ) { BecomeActive( TH_THINK ); } } /* ================ idStaticEntity::ShowEditingDialog ================ */ void idStaticEntity::ShowEditingDialog( void ) { common->InitTool( EDITOR_PARTICLE, &spawnArgs ); } /* ================ idStaticEntity::Think ================ */ void idStaticEntity::Think( void ) { idEntity::Think(); if ( thinkFlags & TH_THINK ) { if ( runGui && renderEntity.gui[0] ) { idPlayer *player = gameLocal.GetLocalPlayer(); if ( player ) { if ( !player->objectiveSystemOpen ) { renderEntity.gui[0]->StateChanged( gameLocal.time, true ); if ( renderEntity.gui[1] ) { renderEntity.gui[1]->StateChanged( gameLocal.time, true ); } if ( renderEntity.gui[2] ) { renderEntity.gui[2]->StateChanged( gameLocal.time, true ); } } } } if ( fadeEnd > 0 ) { idVec4 color; if ( gameLocal.time < fadeEnd ) { color.Lerp( fadeFrom, fadeTo, ( float )( gameLocal.time - fadeStart ) / ( float )( fadeEnd - fadeStart ) ); } else { color = fadeTo; fadeEnd = 0; BecomeInactive( TH_THINK ); } SetColor( color ); } } } /* ================ idStaticEntity::Fade ================ */ void idStaticEntity::Fade( const idVec4 &to, float fadeTime ) { GetColor( fadeFrom ); fadeTo = to; fadeStart = gameLocal.time; fadeEnd = gameLocal.time + SEC2MS( fadeTime ); BecomeActive( TH_THINK ); } /* ================ idStaticEntity::Hide ================ */ void idStaticEntity::Hide( void ) { idEntity::Hide(); GetPhysics()->SetContents( 0 ); } /* ================ idStaticEntity::Show ================ */ void idStaticEntity::Show( void ) { idEntity::Show(); if ( spawnArgs.GetBool( "solid" ) ) { GetPhysics()->SetContents( CONTENTS_SOLID ); } } /* ================ idStaticEntity::Event_Activate ================ */ void idStaticEntity::Event_Activate( idEntity *activator ) { idStr activateGui; spawnTime = gameLocal.time; active = !active; const idKeyValue *kv = spawnArgs.FindKey( "hide" ); if ( kv ) { if ( IsHidden() ) { Show(); } else { Hide(); } } renderEntity.shaderParms[ SHADERPARM_TIMEOFFSET ] = -MS2SEC( spawnTime ); renderEntity.shaderParms[5] = active; // this change should be a good thing, it will automatically turn on // lights etc.. when triggered so that does not have to be specifically done // with trigger parms.. it MIGHT break things so need to keep an eye on it renderEntity.shaderParms[ SHADERPARM_MODE ] = ( renderEntity.shaderParms[ SHADERPARM_MODE ] ) ? 0.0f : 1.0f; BecomeActive( TH_UPDATEVISUALS ); } /* ================ idStaticEntity::WriteToSnapshot ================ */ void idStaticEntity::WriteToSnapshot( idBitMsgDelta &msg ) const { GetPhysics()->WriteToSnapshot( msg ); WriteBindToSnapshot( msg ); WriteColorToSnapshot( msg ); WriteGUIToSnapshot( msg ); msg.WriteBits( IsHidden()?1:0, 1 ); } /* ================ idStaticEntity::ReadFromSnapshot ================ */ void idStaticEntity::ReadFromSnapshot( const idBitMsgDelta &msg ) { bool hidden; GetPhysics()->ReadFromSnapshot( msg ); ReadBindFromSnapshot( msg ); ReadColorFromSnapshot( msg ); ReadGUIFromSnapshot( msg ); hidden = msg.ReadBits( 1 ) == 1; if ( hidden != IsHidden() ) { if ( hidden ) { Hide(); } else { Show(); } } if ( msg.HasChanged() ) { UpdateVisuals(); } } /* =============================================================================== idFuncEmitter =============================================================================== */ CLASS_DECLARATION( idStaticEntity, idFuncEmitter ) EVENT( EV_Activate, idFuncEmitter::Event_Activate ) END_CLASS /* =============== idFuncEmitter::idFuncEmitter =============== */ idFuncEmitter::idFuncEmitter( void ) { hidden = false; } /* =============== idFuncEmitter::Spawn =============== */ void idFuncEmitter::Spawn( void ) { if ( spawnArgs.GetBool( "start_off" ) ) { hidden = true; renderEntity.shaderParms[SHADERPARM_PARTICLE_STOPTIME] = MS2SEC( 1 ); UpdateVisuals(); } else { hidden = false; } } /* =============== idFuncEmitter::Save =============== */ void idFuncEmitter::Save( idSaveGame *savefile ) const { savefile->WriteBool( hidden ); } /* =============== idFuncEmitter::Restore =============== */ void idFuncEmitter::Restore( idRestoreGame *savefile ) { savefile->ReadBool( hidden ); } /* ================ idFuncEmitter::Event_Activate ================ */ void idFuncEmitter::Event_Activate( idEntity *activator ) { if ( hidden || spawnArgs.GetBool( "cycleTrigger" ) ) { renderEntity.shaderParms[SHADERPARM_PARTICLE_STOPTIME] = 0; renderEntity.shaderParms[SHADERPARM_TIMEOFFSET] = -MS2SEC( gameLocal.time ); hidden = false; } else { renderEntity.shaderParms[SHADERPARM_PARTICLE_STOPTIME] = MS2SEC( gameLocal.time ); hidden = true; } UpdateVisuals(); } /* ================ idFuncEmitter::WriteToSnapshot ================ */ void idFuncEmitter::WriteToSnapshot( idBitMsgDelta &msg ) const { msg.WriteBits( hidden ? 1 : 0, 1 ); msg.WriteFloat( renderEntity.shaderParms[ SHADERPARM_PARTICLE_STOPTIME ] ); msg.WriteFloat( renderEntity.shaderParms[ SHADERPARM_TIMEOFFSET ] ); } /* ================ idFuncEmitter::ReadFromSnapshot ================ */ void idFuncEmitter::ReadFromSnapshot( const idBitMsgDelta &msg ) { hidden = msg.ReadBits( 1 ) != 0; renderEntity.shaderParms[ SHADERPARM_PARTICLE_STOPTIME ] = msg.ReadFloat(); renderEntity.shaderParms[ SHADERPARM_TIMEOFFSET ] = msg.ReadFloat(); if ( msg.HasChanged() ) { UpdateVisuals(); } } /* =============================================================================== idFuncSplat =============================================================================== */ const idEventDef EV_Splat( "<Splat>" ); CLASS_DECLARATION( idFuncEmitter, idFuncSplat ) EVENT( EV_Activate, idFuncSplat::Event_Activate ) EVENT( EV_Splat, idFuncSplat::Event_Splat ) END_CLASS /* =============== idFuncSplat::idFuncSplat =============== */ idFuncSplat::idFuncSplat( void ) { } /* =============== idFuncSplat::Spawn =============== */ void idFuncSplat::Spawn( void ) { } /* ================ idFuncSplat::Event_Splat ================ */ void idFuncSplat::Event_Splat( void ) { const char *splat = NULL; int count = spawnArgs.GetInt( "splatCount", "1" ); for ( int i = 0; i < count; i++ ) { splat = spawnArgs.RandomPrefix( "mtr_splat", gameLocal.random ); if ( splat && *splat ) { float size = spawnArgs.GetFloat( "splatSize", "128" ); float dist = spawnArgs.GetFloat( "splatDistance", "128" ); float angle = spawnArgs.GetFloat( "splatAngle", "0" ); gameLocal.ProjectDecal( GetPhysics()->GetOrigin(), GetPhysics()->GetAxis()[2], dist, true, size, splat, angle ); } } StartSound( "snd_splat", SND_CHANNEL_ANY, 0, false, NULL ); } /* ================ idFuncSplat::Event_Activate ================ */ void idFuncSplat::Event_Activate( idEntity *activator ) { idFuncEmitter::Event_Activate( activator ); PostEventSec( &EV_Splat, spawnArgs.GetFloat( "splatDelay", "0.25" ) ); StartSound( "snd_spurt", SND_CHANNEL_ANY, 0, false, NULL ); } /* =============================================================================== idFuncSmoke =============================================================================== */ CLASS_DECLARATION( idEntity, idFuncSmoke ) EVENT( EV_Activate, idFuncSmoke::Event_Activate ) END_CLASS /* =============== idFuncSmoke::idFuncSmoke =============== */ idFuncSmoke::idFuncSmoke() { smokeTime = 0; smoke = NULL; restart = false; } /* =============== idFuncSmoke::Save =============== */ void idFuncSmoke::Save( idSaveGame *savefile ) const { savefile->WriteInt( smokeTime ); savefile->WriteParticle( smoke ); savefile->WriteBool( restart ); } /* =============== idFuncSmoke::Restore =============== */ void idFuncSmoke::Restore( idRestoreGame *savefile ) { savefile->ReadInt( smokeTime ); savefile->ReadParticle( smoke ); savefile->ReadBool( restart ); } /* =============== idFuncSmoke::Spawn =============== */ void idFuncSmoke::Spawn( void ) { const char *smokeName = spawnArgs.GetString( "smoke" ); if ( *smokeName != '\0' ) { smoke = static_cast<const idDeclParticle *>( declManager->FindType( DECL_PARTICLE, smokeName ) ); } else { smoke = NULL; } if ( spawnArgs.GetBool( "start_off" ) ) { smokeTime = 0; restart = false; } else if ( smoke ) { smokeTime = gameLocal.time; BecomeActive( TH_UPDATEPARTICLES ); restart = true; } GetPhysics()->SetContents( 0 ); } /* ================ idFuncSmoke::Event_Activate ================ */ void idFuncSmoke::Event_Activate( idEntity *activator ) { if ( thinkFlags & TH_UPDATEPARTICLES ) { restart = false; return; } else { BecomeActive( TH_UPDATEPARTICLES ); restart = true; smokeTime = gameLocal.time; } } /* =============== idFuncSmoke::Think ================ */ void idFuncSmoke::Think( void ) { // if we are completely closed off from the player, don't do anything at all if ( CheckDormant() || smoke == NULL || smokeTime == -1 ) { return; } if ( ( thinkFlags & TH_UPDATEPARTICLES) && !IsHidden() ) { if ( !gameLocal.smokeParticles->EmitSmoke( smoke, smokeTime, gameLocal.random.CRandomFloat(), GetPhysics()->GetOrigin(), GetPhysics()->GetAxis() ) ) { if ( restart ) { smokeTime = gameLocal.time; } else { smokeTime = 0; BecomeInactive( TH_UPDATEPARTICLES ); } } } } /* =============================================================================== idTextEntity =============================================================================== */ CLASS_DECLARATION( idEntity, idTextEntity ) END_CLASS /* ================ idTextEntity::Spawn ================ */ void idTextEntity::Spawn( void ) { // these are cached as the are used each frame text = spawnArgs.GetString( "text" ); playerOriented = spawnArgs.GetBool( "playerOriented" ); bool force = spawnArgs.GetBool( "force" ); if ( developer.GetBool() || force ) { BecomeActive(TH_THINK); } } /* ================ idTextEntity::Save ================ */ void idTextEntity::Save( idSaveGame *savefile ) const { savefile->WriteString( text ); savefile->WriteBool( playerOriented ); } /* ================ idTextEntity::Restore ================ */ void idTextEntity::Restore( idRestoreGame *savefile ) { savefile->ReadString( text ); savefile->ReadBool( playerOriented ); } /* ================ idTextEntity::Think ================ */ void idTextEntity::Think( void ) { if ( thinkFlags & TH_THINK ) { gameRenderWorld->DrawText( text, GetPhysics()->GetOrigin(), 0.25, colorWhite, playerOriented ? gameLocal.GetLocalPlayer()->viewAngles.ToMat3() : GetPhysics()->GetAxis().Transpose(), 1 ); for ( int i = 0; i < targets.Num(); i++ ) { if ( targets[i].GetEntity() ) { gameRenderWorld->DebugArrow( colorBlue, GetPhysics()->GetOrigin(), targets[i].GetEntity()->GetPhysics()->GetOrigin(), 1 ); } } } else { BecomeInactive( TH_ALL ); } } /* =============================================================================== idVacuumSeperatorEntity Can be triggered to let vacuum through a portal (blown out window) =============================================================================== */ CLASS_DECLARATION( idEntity, idVacuumSeparatorEntity ) EVENT( EV_Activate, idVacuumSeparatorEntity::Event_Activate ) END_CLASS /* ================ idVacuumSeparatorEntity::idVacuumSeparatorEntity ================ */ idVacuumSeparatorEntity::idVacuumSeparatorEntity( void ) { portal = 0; } /* ================ idVacuumSeparatorEntity::Save ================ */ void idVacuumSeparatorEntity::Save( idSaveGame *savefile ) const { savefile->WriteInt( (int)portal ); savefile->WriteInt( gameRenderWorld->GetPortalState( portal ) ); } /* ================ idVacuumSeparatorEntity::Restore ================ */ void idVacuumSeparatorEntity::Restore( idRestoreGame *savefile ) { int state; savefile->ReadInt( (int &)portal ); savefile->ReadInt( state ); gameLocal.SetPortalState( portal, state ); } /* ================ idVacuumSeparatorEntity::Spawn ================ */ void idVacuumSeparatorEntity::Spawn() { idBounds b; b = idBounds( spawnArgs.GetVector( "origin" ) ).Expand( 16 ); portal = gameRenderWorld->FindPortal( b ); if ( !portal ) { gameLocal.Warning( "VacuumSeparator '%s' didn't contact a portal", spawnArgs.GetString( "name" ) ); return; } gameLocal.SetPortalState( portal, PS_BLOCK_AIR | PS_BLOCK_LOCATION ); } /* ================ idVacuumSeparatorEntity::Event_Activate ================ */ void idVacuumSeparatorEntity::Event_Activate( idEntity *activator ) { if ( !portal ) { return; } gameLocal.SetPortalState( portal, PS_BLOCK_NONE ); } /* =============================================================================== idLocationSeparatorEntity =============================================================================== */ CLASS_DECLARATION( idEntity, idLocationSeparatorEntity ) END_CLASS /* ================ idLocationSeparatorEntity::Spawn ================ */ void idLocationSeparatorEntity::Spawn() { idBounds b; b = idBounds( spawnArgs.GetVector( "origin" ) ).Expand( 16 ); qhandle_t portal = gameRenderWorld->FindPortal( b ); if ( !portal ) { gameLocal.Warning( "LocationSeparator '%s' didn't contact a portal", spawnArgs.GetString( "name" ) ); } gameLocal.SetPortalState( portal, PS_BLOCK_LOCATION ); } /* =============================================================================== idVacuumEntity Levels should only have a single vacuum entity. =============================================================================== */ CLASS_DECLARATION( idEntity, idVacuumEntity ) END_CLASS /* ================ idVacuumEntity::Spawn ================ */ void idVacuumEntity::Spawn() { if ( gameLocal.vacuumAreaNum != -1 ) { gameLocal.Warning( "idVacuumEntity::Spawn: multiple idVacuumEntity in level" ); return; } idVec3 org = spawnArgs.GetVector( "origin" ); gameLocal.vacuumAreaNum = gameRenderWorld->PointInArea( org ); } /* =============================================================================== idLocationEntity =============================================================================== */ CLASS_DECLARATION( idEntity, idLocationEntity ) END_CLASS /* ====================== idLocationEntity::Spawn ====================== */ void idLocationEntity::Spawn() { idStr realName; // this just holds dict information // if "location" not already set, use the entity name. if ( !spawnArgs.GetString( "location", "", realName ) ) { spawnArgs.Set( "location", name ); } } /* ====================== idLocationEntity::GetLocation ====================== */ const char *idLocationEntity::GetLocation( void ) const { return spawnArgs.GetString( "location" ); } /* =============================================================================== idBeam =============================================================================== */ CLASS_DECLARATION( idEntity, idBeam ) EVENT( EV_PostSpawn, idBeam::Event_MatchTarget ) EVENT( EV_Activate, idBeam::Event_Activate ) END_CLASS /* =============== idBeam::idBeam =============== */ idBeam::idBeam() { target = NULL; master = NULL; } /* =============== idBeam::Save =============== */ void idBeam::Save( idSaveGame *savefile ) const { target.Save( savefile ); master.Save( savefile ); } /* =============== idBeam::Restore =============== */ void idBeam::Restore( idRestoreGame *savefile ) { target.Restore( savefile ); master.Restore( savefile ); } /* =============== idBeam::Spawn =============== */ void idBeam::Spawn( void ) { float width; if ( spawnArgs.GetFloat( "width", "0", width ) ) { renderEntity.shaderParms[ SHADERPARM_BEAM_WIDTH ] = width; } SetModel( "_BEAM" ); Hide(); PostEventMS( &EV_PostSpawn, 0 ); } /* ================ idBeam::Think ================ */ void idBeam::Think( void ) { idBeam *masterEnt; if ( !IsHidden() && !target.GetEntity() ) { // hide if our target is removed Hide(); } RunPhysics(); masterEnt = master.GetEntity(); if ( masterEnt ) { const idVec3 &origin = GetPhysics()->GetOrigin(); masterEnt->SetBeamTarget( origin ); } Present(); } /* ================ idBeam::SetMaster ================ */ void idBeam::SetMaster( idBeam *masterbeam ) { master = masterbeam; } /* ================ idBeam::SetBeamTarget ================ */ void idBeam::SetBeamTarget( const idVec3 &origin ) { if ( ( renderEntity.shaderParms[ SHADERPARM_BEAM_END_X ] != origin.x ) || ( renderEntity.shaderParms[ SHADERPARM_BEAM_END_Y ] != origin.y ) || ( renderEntity.shaderParms[ SHADERPARM_BEAM_END_Z ] != origin.z ) ) { renderEntity.shaderParms[ SHADERPARM_BEAM_END_X ] = origin.x; renderEntity.shaderParms[ SHADERPARM_BEAM_END_Y ] = origin.y; renderEntity.shaderParms[ SHADERPARM_BEAM_END_Z ] = origin.z; UpdateVisuals(); } } /* ================ idBeam::Show ================ */ void idBeam::Show( void ) { idBeam *targetEnt; idEntity::Show(); targetEnt = target.GetEntity(); if ( targetEnt ) { const idVec3 &origin = targetEnt->GetPhysics()->GetOrigin(); SetBeamTarget( origin ); } } /* ================ idBeam::Event_MatchTarget ================ */ void idBeam::Event_MatchTarget( void ) { int i; idEntity *targetEnt; idBeam *targetBeam; if ( !targets.Num() ) { return; } targetBeam = NULL; for( i = 0; i < targets.Num(); i++ ) { targetEnt = targets[ i ].GetEntity(); if ( targetEnt && targetEnt->IsType( idBeam::Type ) ) { targetBeam = static_cast<idBeam *>( targetEnt ); break; } } if ( !targetBeam ) { gameLocal.Error( "Could not find valid beam target for '%s'", name.c_str() ); } target = targetBeam; targetBeam->SetMaster( this ); if ( !spawnArgs.GetBool( "start_off" ) ) { Show(); } } /* ================ idBeam::Event_Activate ================ */ void idBeam::Event_Activate( idEntity *activator ) { if ( IsHidden() ) { Show(); } else { Hide(); } } /* ================ idBeam::WriteToSnapshot ================ */ void idBeam::WriteToSnapshot( idBitMsgDelta &msg ) const { GetPhysics()->WriteToSnapshot( msg ); WriteBindToSnapshot( msg ); WriteColorToSnapshot( msg ); msg.WriteFloat( renderEntity.shaderParms[SHADERPARM_BEAM_END_X] ); msg.WriteFloat( renderEntity.shaderParms[SHADERPARM_BEAM_END_Y] ); msg.WriteFloat( renderEntity.shaderParms[SHADERPARM_BEAM_END_Z] ); } /* ================ idBeam::ReadFromSnapshot ================ */ void idBeam::ReadFromSnapshot( const idBitMsgDelta &msg ) { GetPhysics()->ReadFromSnapshot( msg ); ReadBindFromSnapshot( msg ); ReadColorFromSnapshot( msg ); renderEntity.shaderParms[SHADERPARM_BEAM_END_X] = msg.ReadFloat(); renderEntity.shaderParms[SHADERPARM_BEAM_END_Y] = msg.ReadFloat(); renderEntity.shaderParms[SHADERPARM_BEAM_END_Z] = msg.ReadFloat(); if ( msg.HasChanged() ) { UpdateVisuals(); } } /* =============================================================================== idLiquid =============================================================================== */ CLASS_DECLARATION( idEntity, idLiquid ) EVENT( EV_Touch, idLiquid::Event_Touch ) END_CLASS /* ================ idLiquid::Save ================ */ void idLiquid::Save( idSaveGame *savefile ) const { // Nothing to save } /* ================ idLiquid::Restore ================ */ void idLiquid::Restore( idRestoreGame *savefile ) { //FIXME: NO! Spawn(); } /* ================ idLiquid::Spawn ================ */ void idLiquid::Spawn() { /* model = dynamic_cast<idRenderModelLiquid *>( renderEntity.hModel ); if ( !model ) { gameLocal.Error( "Entity '%s' must have liquid model", name.c_str() ); } model->Reset(); GetPhysics()->SetContents( CONTENTS_TRIGGER ); */ } /* ================ idLiquid::Event_Touch ================ */ void idLiquid::Event_Touch( idEntity *other, trace_t *trace ) { // FIXME: for QuakeCon /* idVec3 pos; pos = other->GetPhysics()->GetOrigin() - GetPhysics()->GetOrigin(); model->IntersectBounds( other->GetPhysics()->GetBounds().Translate( pos ), -10.0f ); */ } /* =============================================================================== idShaking =============================================================================== */ CLASS_DECLARATION( idEntity, idShaking ) EVENT( EV_Activate, idShaking::Event_Activate ) END_CLASS /* =============== idShaking::idShaking =============== */ idShaking::idShaking() { active = false; } /* =============== idShaking::Save =============== */ void idShaking::Save( idSaveGame *savefile ) const { savefile->WriteBool( active ); savefile->WriteStaticObject( physicsObj ); } /* =============== idShaking::Restore =============== */ void idShaking::Restore( idRestoreGame *savefile ) { savefile->ReadBool( active ); savefile->ReadStaticObject( physicsObj ); RestorePhysics( &physicsObj ); } /* =============== idShaking::Spawn =============== */ void idShaking::Spawn( void ) { physicsObj.SetSelf( this ); physicsObj.SetClipModel( new idClipModel( GetPhysics()->GetClipModel() ), 1.0f ); physicsObj.SetOrigin( GetPhysics()->GetOrigin() ); physicsObj.SetAxis( GetPhysics()->GetAxis() ); physicsObj.SetClipMask( MASK_SOLID ); SetPhysics( &physicsObj ); active = false; if ( !spawnArgs.GetBool( "start_off" ) ) { BeginShaking(); } } /* ================ idShaking::BeginShaking ================ */ void idShaking::BeginShaking( void ) { int phase; idAngles shake; int period; active = true; phase = gameLocal.random.RandomInt( 1000 ); shake = spawnArgs.GetAngles( "shake", "0.5 0.5 0.5" ); period = spawnArgs.GetFloat( "period", "0.05" ) * 1000; physicsObj.SetAngularExtrapolation( extrapolation_t(EXTRAPOLATION_DECELSINE|EXTRAPOLATION_NOSTOP), phase, period * 0.25f, GetPhysics()->GetAxis().ToAngles(), shake, ang_zero ); } /* ================ idShaking::Event_Activate ================ */ void idShaking::Event_Activate( idEntity *activator ) { if ( !active ) { BeginShaking(); } else { active = false; physicsObj.SetAngularExtrapolation( EXTRAPOLATION_NONE, 0, 0, physicsObj.GetAxis().ToAngles(), ang_zero, ang_zero ); } } /* =============================================================================== idEarthQuake =============================================================================== */ CLASS_DECLARATION( idEntity, idEarthQuake ) EVENT( EV_Activate, idEarthQuake::Event_Activate ) END_CLASS /* =============== idEarthQuake::idEarthQuake =============== */ idEarthQuake::idEarthQuake() { wait = 0.0f; random = 0.0f; nextTriggerTime = 0; shakeStopTime = 0; triggered = false; playerOriented = false; disabled = false; shakeTime = 0.0f; } /* =============== idEarthQuake::Save =============== */ void idEarthQuake::Save( idSaveGame *savefile ) const { savefile->WriteInt( nextTriggerTime ); savefile->WriteInt( shakeStopTime ); savefile->WriteFloat( wait ); savefile->WriteFloat( random ); savefile->WriteBool( triggered ); savefile->WriteBool( playerOriented ); savefile->WriteBool( disabled ); savefile->WriteFloat( shakeTime ); } /* =============== idEarthQuake::Restore =============== */ void idEarthQuake::Restore( idRestoreGame *savefile ) { savefile->ReadInt( nextTriggerTime ); savefile->ReadInt( shakeStopTime ); savefile->ReadFloat( wait ); savefile->ReadFloat( random ); savefile->ReadBool( triggered ); savefile->ReadBool( playerOriented ); savefile->ReadBool( disabled ); savefile->ReadFloat( shakeTime ); if ( shakeStopTime > gameLocal.time ) { BecomeActive( TH_THINK ); } } /* =============== idEarthQuake::Spawn =============== */ void idEarthQuake::Spawn( void ) { nextTriggerTime = 0; shakeStopTime = 0; wait = spawnArgs.GetFloat( "wait", "15" ); random = spawnArgs.GetFloat( "random", "5" ); triggered = spawnArgs.GetBool( "triggered" ); playerOriented = spawnArgs.GetBool( "playerOriented" ); disabled = false; shakeTime = spawnArgs.GetFloat( "shakeTime", "0" ); if ( !triggered ){ PostEventSec( &EV_Activate, spawnArgs.GetFloat( "wait" ), this ); } BecomeInactive( TH_THINK ); } /* ================ idEarthQuake::Event_Activate ================ */ void idEarthQuake::Event_Activate( idEntity *activator ) { if ( nextTriggerTime > gameLocal.time ) { return; } if ( disabled && activator == this ) { return; } idPlayer *player = gameLocal.GetLocalPlayer(); if ( player == NULL ) { return; } nextTriggerTime = 0; if ( !triggered && activator != this ){ // if we are not triggered ( i.e. random ), disable or enable disabled ^= 1; if (disabled) { return; } else { PostEventSec( &EV_Activate, wait + random * gameLocal.random.CRandomFloat(), this ); } } ActivateTargets( activator ); const idSoundShader *shader = declManager->FindSound( spawnArgs.GetString( "snd_quake" ) ); if ( playerOriented ) { player->StartSoundShader( shader, SND_CHANNEL_ANY, SSF_GLOBAL, false, NULL ); } else { StartSoundShader( shader, SND_CHANNEL_ANY, SSF_GLOBAL, false, NULL ); } if ( shakeTime > 0.0f ) { shakeStopTime = gameLocal.time + SEC2MS( shakeTime ); BecomeActive( TH_THINK ); } if ( wait > 0.0f ) { if ( !triggered ) { PostEventSec( &EV_Activate, wait + random * gameLocal.random.CRandomFloat(), this ); } else { nextTriggerTime = gameLocal.time + SEC2MS( wait + random * gameLocal.random.CRandomFloat() ); } } else if ( shakeTime == 0.0f ) { PostEventMS( &EV_Remove, 0 ); } } /* =============== idEarthQuake::Think ================ */ void idEarthQuake::Think( void ) { if ( thinkFlags & TH_THINK ) { if ( gameLocal.time > shakeStopTime ) { BecomeInactive( TH_THINK ); if ( wait <= 0.0f ) { PostEventMS( &EV_Remove, 0 ); } return; } float shakeVolume = gameSoundWorld->CurrentShakeAmplitudeForPosition( gameLocal.time, gameLocal.GetLocalPlayer()->firstPersonViewOrigin ); gameLocal.RadiusPush( GetPhysics()->GetOrigin(), 256, 1500 * shakeVolume, this, this, 1.0f, true ); } BecomeInactive( TH_UPDATEVISUALS ); } /* =============================================================================== idFuncPortal =============================================================================== */ CLASS_DECLARATION( idEntity, idFuncPortal ) EVENT( EV_Activate, idFuncPortal::Event_Activate ) END_CLASS /* =============== idFuncPortal::idFuncPortal =============== */ idFuncPortal::idFuncPortal() { portal = 0; state = false; } /* =============== idFuncPortal::Save =============== */ void idFuncPortal::Save( idSaveGame *savefile ) const { savefile->WriteInt( (int)portal ); savefile->WriteBool( state ); } /* =============== idFuncPortal::Restore =============== */ void idFuncPortal::Restore( idRestoreGame *savefile ) { savefile->ReadInt( (int &)portal ); savefile->ReadBool( state ); gameLocal.SetPortalState( portal, state ? PS_BLOCK_ALL : PS_BLOCK_NONE ); } /* =============== idFuncPortal::Spawn =============== */ void idFuncPortal::Spawn( void ) { portal = gameRenderWorld->FindPortal( GetPhysics()->GetAbsBounds().Expand( 32.0f ) ); if ( portal > 0 ) { state = spawnArgs.GetBool( "start_on" ); gameLocal.SetPortalState( portal, state ? PS_BLOCK_ALL : PS_BLOCK_NONE ); } } /* ================ idFuncPortal::Event_Activate ================ */ void idFuncPortal::Event_Activate( idEntity *activator ) { if ( portal > 0 ) { state = !state; gameLocal.SetPortalState( portal, state ? PS_BLOCK_ALL : PS_BLOCK_NONE ); } } /* =============================================================================== idFuncAASPortal =============================================================================== */ CLASS_DECLARATION( idEntity, idFuncAASPortal ) EVENT( EV_Activate, idFuncAASPortal::Event_Activate ) END_CLASS /* =============== idFuncAASPortal::idFuncAASPortal =============== */ idFuncAASPortal::idFuncAASPortal() { state = false; } /* =============== idFuncAASPortal::Save =============== */ void idFuncAASPortal::Save( idSaveGame *savefile ) const { savefile->WriteBool( state ); } /* =============== idFuncAASPortal::Restore =============== */ void idFuncAASPortal::Restore( idRestoreGame *savefile ) { savefile->ReadBool( state ); gameLocal.SetAASAreaState( GetPhysics()->GetAbsBounds(), AREACONTENTS_CLUSTERPORTAL, state ); } /* =============== idFuncAASPortal::Spawn =============== */ void idFuncAASPortal::Spawn( void ) { state = spawnArgs.GetBool( "start_on" ); gameLocal.SetAASAreaState( GetPhysics()->GetAbsBounds(), AREACONTENTS_CLUSTERPORTAL, state ); } /* ================ idFuncAASPortal::Event_Activate ================ */ void idFuncAASPortal::Event_Activate( idEntity *activator ) { state ^= 1; gameLocal.SetAASAreaState( GetPhysics()->GetAbsBounds(), AREACONTENTS_CLUSTERPORTAL, state ); } /* =============================================================================== idFuncAASObstacle =============================================================================== */ CLASS_DECLARATION( idEntity, idFuncAASObstacle ) EVENT( EV_Activate, idFuncAASObstacle::Event_Activate ) END_CLASS /* =============== idFuncAASObstacle::idFuncAASObstacle =============== */ idFuncAASObstacle::idFuncAASObstacle() { state = false; } /* =============== idFuncAASObstacle::Save =============== */ void idFuncAASObstacle::Save( idSaveGame *savefile ) const { savefile->WriteBool( state ); } /* =============== idFuncAASObstacle::Restore =============== */ void idFuncAASObstacle::Restore( idRestoreGame *savefile ) { savefile->ReadBool( state ); gameLocal.SetAASAreaState( GetPhysics()->GetAbsBounds(), AREACONTENTS_OBSTACLE, state ); } /* =============== idFuncAASObstacle::Spawn =============== */ void idFuncAASObstacle::Spawn( void ) { state = spawnArgs.GetBool( "start_on" ); gameLocal.SetAASAreaState( GetPhysics()->GetAbsBounds(), AREACONTENTS_OBSTACLE, state ); } /* ================ idFuncAASObstacle::Event_Activate ================ */ void idFuncAASObstacle::Event_Activate( idEntity *activator ) { state ^= 1; gameLocal.SetAASAreaState( GetPhysics()->GetAbsBounds(), AREACONTENTS_OBSTACLE, state ); } /* =============================================================================== idFuncRadioChatter =============================================================================== */ const idEventDef EV_ResetRadioHud( "<resetradiohud>", "e" ); CLASS_DECLARATION( idEntity, idFuncRadioChatter ) EVENT( EV_Activate, idFuncRadioChatter::Event_Activate ) EVENT( EV_ResetRadioHud, idFuncRadioChatter::Event_ResetRadioHud ) END_CLASS /* =============== idFuncRadioChatter::idFuncRadioChatter =============== */ idFuncRadioChatter::idFuncRadioChatter() { time = 0.0; } /* =============== idFuncRadioChatter::Save =============== */ void idFuncRadioChatter::Save( idSaveGame *savefile ) const { savefile->WriteFloat( time ); } /* =============== idFuncRadioChatter::Restore =============== */ void idFuncRadioChatter::Restore( idRestoreGame *savefile ) { savefile->ReadFloat( time ); } /* =============== idFuncRadioChatter::Spawn =============== */ void idFuncRadioChatter::Spawn( void ) { time = spawnArgs.GetFloat( "time", "5.0" ); } /* ================ idFuncRadioChatter::Event_Activate ================ */ void idFuncRadioChatter::Event_Activate( idEntity *activator ) { idPlayer *player; const char *sound; const idSoundShader *shader; int length; if ( activator->IsType( idPlayer::Type ) ) { player = static_cast<idPlayer *>( activator ); } else { player = gameLocal.GetLocalPlayer(); } player->hud->HandleNamedEvent( "radioChatterUp" ); sound = spawnArgs.GetString( "snd_radiochatter", "" ); if ( sound && *sound ) { shader = declManager->FindSound( sound ); player->StartSoundShader( shader, SND_CHANNEL_RADIO, SSF_GLOBAL, false, &length ); time = MS2SEC( length + 150 ); } // we still put the hud up because this is used with no sound on // certain frame commands when the chatter is triggered PostEventSec( &EV_ResetRadioHud, time, player ); } /* ================ idFuncRadioChatter::Event_ResetRadioHud ================ */ void idFuncRadioChatter::Event_ResetRadioHud( idEntity *activator ) { idPlayer *player = ( activator->IsType( idPlayer::Type ) ) ? static_cast<idPlayer *>( activator ) : gameLocal.GetLocalPlayer(); player->hud->HandleNamedEvent( "radioChatterDown" ); ActivateTargets( activator ); } /* =============================================================================== idPhantomObjects =============================================================================== */ CLASS_DECLARATION( idEntity, idPhantomObjects ) EVENT( EV_Activate, idPhantomObjects::Event_Activate ) END_CLASS /* =============== idPhantomObjects::idPhantomObjects =============== */ idPhantomObjects::idPhantomObjects() { target = NULL; end_time = 0; throw_time = 0.0f; shake_time = 0.0f; shake_ang.Zero(); speed = 0.0f; min_wait = 0; max_wait = 0; fl.neverDormant = false; } /* =============== idPhantomObjects::Save =============== */ void idPhantomObjects::Save( idSaveGame *savefile ) const { int i; savefile->WriteInt( end_time ); savefile->WriteFloat( throw_time ); savefile->WriteFloat( shake_time ); savefile->WriteVec3( shake_ang ); savefile->WriteFloat( speed ); savefile->WriteInt( min_wait ); savefile->WriteInt( max_wait ); target.Save( savefile ); savefile->WriteInt( targetTime.Num() ); for( i = 0; i < targetTime.Num(); i++ ) { savefile->WriteInt( targetTime[ i ] ); } for( i = 0; i < lastTargetPos.Num(); i++ ) { savefile->WriteVec3( lastTargetPos[ i ] ); } } /* =============== idPhantomObjects::Restore =============== */ void idPhantomObjects::Restore( idRestoreGame *savefile ) { int num; int i; savefile->ReadInt( end_time ); savefile->ReadFloat( throw_time ); savefile->ReadFloat( shake_time ); savefile->ReadVec3( shake_ang ); savefile->ReadFloat( speed ); savefile->ReadInt( min_wait ); savefile->ReadInt( max_wait ); target.Restore( savefile ); savefile->ReadInt( num ); targetTime.SetGranularity( 1 ); targetTime.SetNum( num ); lastTargetPos.SetGranularity( 1 ); lastTargetPos.SetNum( num ); for( i = 0; i < num; i++ ) { savefile->ReadInt( targetTime[ i ] ); } if ( savefile->GetBuildNumber() == INITIAL_RELEASE_BUILD_NUMBER ) { // these weren't saved out in the first release for( i = 0; i < num; i++ ) { lastTargetPos[ i ].Zero(); } } else { for( i = 0; i < num; i++ ) { savefile->ReadVec3( lastTargetPos[ i ] ); } } } /* =============== idPhantomObjects::Spawn =============== */ void idPhantomObjects::Spawn( void ) { throw_time = spawnArgs.GetFloat( "time", "5" ); speed = spawnArgs.GetFloat( "speed", "1200" ); shake_time = spawnArgs.GetFloat( "shake_time", "1" ); throw_time -= shake_time; if ( throw_time < 0.0f ) { throw_time = 0.0f; } min_wait = SEC2MS( spawnArgs.GetFloat( "min_wait", "1" ) ); max_wait = SEC2MS( spawnArgs.GetFloat( "max_wait", "3" ) ); shake_ang = spawnArgs.GetVector( "shake_ang", "65 65 65" ); Hide(); GetPhysics()->SetContents( 0 ); } /* ================ idPhantomObjects::Event_Activate ================ */ void idPhantomObjects::Event_Activate( idEntity *activator ) { int i; float time; float frac; float scale; if ( thinkFlags & TH_THINK ) { BecomeInactive( TH_THINK ); return; } RemoveNullTargets(); if ( !targets.Num() ) { return; } if ( !activator || !activator->IsType( idActor::Type ) ) { target = gameLocal.GetLocalPlayer(); } else { target = static_cast<idActor *>( activator ); } end_time = gameLocal.time + SEC2MS( spawnArgs.GetFloat( "end_time", "0" ) ); targetTime.SetNum( targets.Num() ); lastTargetPos.SetNum( targets.Num() ); const idVec3 &toPos = target.GetEntity()->GetEyePosition(); // calculate the relative times of all the objects time = 0.0f; for( i = 0; i < targetTime.Num(); i++ ) { targetTime[ i ] = SEC2MS( time ); lastTargetPos[ i ] = toPos; frac = 1.0f - ( float )i / ( float )targetTime.Num(); time += ( gameLocal.random.RandomFloat() + 1.0f ) * 0.5f * frac + 0.1f; } // scale up the times to fit within throw_time scale = throw_time / time; for( i = 0; i < targetTime.Num(); i++ ) { targetTime[ i ] = gameLocal.time + SEC2MS( shake_time )+ targetTime[ i ] * scale; } BecomeActive( TH_THINK ); } /* =============== idPhantomObjects::Think ================ */ void idPhantomObjects::Think( void ) { int i; int num; float time; idVec3 vel; idVec3 ang; idEntity *ent; idActor *targetEnt; idPhysics *entPhys; trace_t tr; // if we are completely closed off from the player, don't do anything at all if ( CheckDormant() ) { return; } if ( !( thinkFlags & TH_THINK ) ) { BecomeInactive( thinkFlags & ~TH_THINK ); return; } targetEnt = target.GetEntity(); if ( !targetEnt || ( targetEnt->health <= 0 ) || ( end_time && ( gameLocal.time > end_time ) ) || gameLocal.inCinematic ) { BecomeInactive( TH_THINK ); } const idVec3 &toPos = targetEnt->GetEyePosition(); num = 0; for ( i = 0; i < targets.Num(); i++ ) { ent = targets[ i ].GetEntity(); if ( !ent ) { continue; } if ( ent->fl.hidden ) { // don't throw hidden objects continue; } if ( !targetTime[ i ] ) { // already threw this object continue; } num++; time = MS2SEC( targetTime[ i ] - gameLocal.time ); if ( time > shake_time ) { continue; } entPhys = ent->GetPhysics(); const idVec3 &entOrg = entPhys->GetOrigin(); gameLocal.clip.TracePoint( tr, entOrg, toPos, MASK_OPAQUE, ent ); if ( tr.fraction >= 1.0f || ( gameLocal.GetTraceEntity( tr ) == targetEnt ) ) { lastTargetPos[ i ] = toPos; } if ( time < 0.0f ) { idAI::PredictTrajectory( entPhys->GetOrigin(), lastTargetPos[ i ], speed, entPhys->GetGravity(), entPhys->GetClipModel(), entPhys->GetClipMask(), 256.0f, ent, targetEnt, ai_debugTrajectory.GetBool() ? 1 : 0, vel ); vel *= speed; entPhys->SetLinearVelocity( vel ); if ( !end_time ) { targetTime[ i ] = 0; } else { targetTime[ i ] = gameLocal.time + gameLocal.random.RandomInt( max_wait - min_wait ) + min_wait; } if ( ent->IsType( idMoveable::Type ) ) { idMoveable *ment = static_cast<idMoveable*>( ent ); ment->EnableDamage( true, 2.5f ); } } else { // this is not the right way to set the angular velocity, but the effect is nice, so I'm keeping it. :) ang.Set( gameLocal.random.CRandomFloat() * shake_ang.x, gameLocal.random.CRandomFloat() * shake_ang.y, gameLocal.random.CRandomFloat() * shake_ang.z ); ang *= ( 1.0f - time / shake_time ); entPhys->SetAngularVelocity( ang ); } } if ( !num ) { BecomeInactive( TH_THINK ); } }
1
0.926724
1
0.926724
game-dev
MEDIA
0.902166
game-dev
0.995148
1
0.995148
Dawn-of-Light/DOLSharp
7,708
GameServer/quests/QuestsMgr/Utility/QuestSearchArea.cs
/* * DAWN OF LIGHT - The first free open source DAoC server emulator * * 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. * */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Reflection; using System.Text; using DOL.Database; using DOL.Events; using DOL.GS.PacketHandler; using DOL.Language; using log4net; namespace DOL.GS.Quests { public class QuestSearchArea : Area.Circle { private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public const int DEFAULT_SEARCH_SECONDS = 5; public const int DEFAULT_SEARCH_RADIUS = 150; ushort m_regionId = 0; Type m_questType; DataQuest m_dataQuest = null; int m_validStep; int m_searchSeconds; string m_popupText = ""; /// <summary> /// Create an area used for /search. Area will only be active when player is doing associated quest /// and is on the correct step. /// </summary> /// <param name="questType">The quest associated with this area.</param> /// <param name="validStep">The quest step that uses this area.</param> /// <param name="text">Popup text to show when player enters area. Leave blank to suppress popup.</param> /// <param name="regionId">The region this ares is in.</param> /// <param name="x"></param> /// <param name="y"></param> /// <param name="z"></param> public QuestSearchArea(Type questType, int validStep, string text, ushort regionId, int x, int y, int z) : base(text, x, y, z, DEFAULT_SEARCH_RADIUS) { CreateArea(questType, validStep, DEFAULT_SEARCH_SECONDS, text, regionId); } /// <summary> /// Create an area used for /search. Area will only be active when player is doing associated quest /// and is on the correct step. /// </summary> /// <param name="questType">The quest associated with this area.</param> /// <param name="validStep">The quest step that uses this area.</param> /// <param name="searchSeconds">How long the search progress takes till completion.</param> /// <param name="text">Popup text to show when player enters area. Leave blank to suppress popup.</param> /// <param name="regionId">The region this ares is in.</param> /// <param name="x"></param> /// <param name="y"></param> /// <param name="z"></param> /// <param name="radius">The size of the search area.</param> public QuestSearchArea(Type questType, int validStep, int searchSeconds, string text, ushort regionId, int x, int y, int z, int radius) : base(text, x, y, z, radius) { CreateArea(questType, validStep, searchSeconds, text, regionId); } /// <summary> /// Search area for data quests. Z is not checked, user must specify radius and time in data quest /// </summary> /// <param name="dataQuest"></param> /// <param name="validStep"></param> /// <param name="text"></param> /// <param name="regionId"></param> /// <param name="x"></param> /// <param name="y"></param> /// <param name="radius"></param> /// <param name="searchSeconds"></param> public QuestSearchArea(DataQuest dataQuest, int validStep, string text, ushort regionId, int x, int y, int radius = DEFAULT_SEARCH_RADIUS, int searchSeconds = DEFAULT_SEARCH_SECONDS) : base(text, x, y, 0, radius) { CreateArea(dataQuest, validStep, searchSeconds, text, regionId); } protected void CreateArea(Type questType, int validStep, int searchSeconds, string text, ushort regionId) { m_regionId = regionId; m_questType = questType; m_validStep = validStep; m_searchSeconds = searchSeconds; m_popupText = text; DisplayMessage = false; if (WorldMgr.GetRegion(regionId) != null) { WorldMgr.GetRegion(regionId).AddArea(this); } else { log.Error("Could not find region " + regionId + " when trying to create QuestSearchArea for quest " + m_questType); } } protected void CreateArea(DataQuest dataQuest, int validStep, int searchSeconds, string text, ushort regionId) { m_regionId = regionId; m_questType = typeof(DataQuest); m_dataQuest = dataQuest; m_validStep = validStep; m_searchSeconds = searchSeconds; m_popupText = text; DisplayMessage = false; if (WorldMgr.GetRegion(regionId) != null) { WorldMgr.GetRegion(regionId).AddArea(this); } else { string errorText = "Could not find region " + regionId + " when trying to create QuestSearchArea! "; dataQuest.LastErrorText += errorText; log.Error(errorText); } } public virtual void RemoveArea() { if (WorldMgr.GetRegion(m_regionId) != null) { WorldMgr.GetRegion(m_regionId).RemoveArea(this); } } public override void OnPlayerEnter(GamePlayer player) { bool showText = false; if (m_dataQuest != null) { ChatUtil.SendDebugMessage(player, "Entered QuestSearchArea for DataQuest ID:" + m_dataQuest.ID + ", Step " + Step); // first check active data quests foreach (AbstractQuest quest in player.QuestList) { if (quest is DataQuest) { if ((quest as DataQuest).ID == m_dataQuest.ID && quest.Step == Step && m_popupText != string.Empty) { showText = true; } } } // next check for searches that start a dataquest if (Step == 0 && DataQuest.CheckQuestQualification(player)) { showText = true; } } else { ChatUtil.SendDebugMessage(player, "Entered QuestSearchArea for " + m_questType.Name + ", Step " + Step); // popup a dialog telling the player they should search here if (player.IsDoingQuest(m_questType) != null && player.IsDoingQuest(m_questType).Step == m_validStep && PopupText != string.Empty) { showText = true; } } if (showText) { player.Out.SendDialogBox(eDialogCode.SimpleWarning, 0, 0, 0, 0, eDialogType.Ok, true, m_popupText); } } public Type QuestType { get { return m_questType; } } public DataQuest DataQuest { get { return m_dataQuest; } } public int Step { get { return m_validStep; } } public int SearchSeconds { get { return m_searchSeconds; } } public string PopupText { get { return m_popupText; } } } }
1
0.865497
1
0.865497
game-dev
MEDIA
0.636956
game-dev
0.669126
1
0.669126
magefree/mage
3,868
Mage.Sets/src/mage/cards/e/EmrakulThePromisedEnd.java
package mage.cards.e; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.dynamicvalue.common.CardTypesInGraveyardCount; import mage.abilities.effects.OneShotEffect; import mage.abilities.effects.common.CastSourceTriggeredAbility; import mage.abilities.effects.common.cost.SpellCostReductionForEachSourceEffect; import mage.abilities.keyword.FlyingAbility; import mage.abilities.keyword.ProtectionAbility; import mage.abilities.keyword.TrampleAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.*; import mage.filter.FilterCard; import mage.game.Game; import mage.game.turn.TurnMod; import mage.players.Player; import mage.target.common.TargetOpponent; import java.util.UUID; /** * @author emerald000 */ public final class EmrakulThePromisedEnd extends CardImpl { private static final FilterCard filter = new FilterCard("instants"); static { filter.add(CardType.INSTANT.getPredicate()); } public EmrakulThePromisedEnd(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{13}"); this.supertype.add(SuperType.LEGENDARY); this.subtype.add(SubType.ELDRAZI); this.power = new MageInt(13); this.toughness = new MageInt(13); // Emrakul, the Promised End costs {1} less to cast for each card type among cards in your graveyard. this.addAbility(new SimpleStaticAbility( Zone.ALL, new SpellCostReductionForEachSourceEffect( 1, CardTypesInGraveyardCount.YOU ).setText("this spell costs {1} less to cast for each card type among cards in your graveyard") ).setRuleAtTheTop(true).addHint(CardTypesInGraveyardCount.YOU.getHint())); // When you cast Emrakul, you gain control of target opponent during that player's next turn. After that turn, that player takes an extra turn. Ability ability = new CastSourceTriggeredAbility(new EmrakulThePromisedEndGainControlEffect()); ability.addTarget(new TargetOpponent()); this.addAbility(ability); // Flying this.addAbility(FlyingAbility.getInstance()); // Trample this.addAbility(TrampleAbility.getInstance()); // Protection from instants this.addAbility(new ProtectionAbility(filter)); } private EmrakulThePromisedEnd(final EmrakulThePromisedEnd card) { super(card); } @Override public EmrakulThePromisedEnd copy() { return new EmrakulThePromisedEnd(this); } } class EmrakulThePromisedEndGainControlEffect extends OneShotEffect { EmrakulThePromisedEndGainControlEffect() { super(Outcome.GainControl); this.staticText = "you gain control of target opponent during that player's next turn. After that turn, that player takes an extra turn"; } private EmrakulThePromisedEndGainControlEffect(final EmrakulThePromisedEndGainControlEffect effect) { super(effect); } @Override public EmrakulThePromisedEndGainControlEffect copy() { return new EmrakulThePromisedEndGainControlEffect(this); } @Override public boolean apply(Game game, Ability source) { Player controller = game.getPlayer(source.getControllerId()); Player targetPlayer = game.getPlayer(this.getTargetPointer().getFirst(game, source)); if (controller != null && targetPlayer != null) { TurnMod extraTurnMod = new TurnMod(targetPlayer.getId()).withExtraTurn(); TurnMod newControllerTurnMod = new TurnMod(targetPlayer.getId()).withNewController(controller.getId(), extraTurnMod); game.getState().getTurnMods().add(newControllerTurnMod); return true; } return false; } }
1
0.989511
1
0.989511
game-dev
MEDIA
0.985771
game-dev
0.998373
1
0.998373
alibaba-edu/Driver-Security-Analyzer
15,927
arm64/Arm64TypeAnalyzer.py
# Copyright (C) 2020 Alibaba Group Holding Limited import idaapi idaapi.require("Arm64Utils") from Arm64Utils import * idaapi.require("AnalysisUtils") def checkIfAllGotFuncIsInStubs(): allGOTSegs = getAllSegsOfGOT() allStubsSegs = getAllSegsOfSTUBS() if len(allGOTSegs) == 0 and len(allStubsSegs) == 0: return for gotSeg in allGOTSegs: gotSegStartEA = gotSeg.startEA gotSegEndEA = gotSeg.endEA currentEA = gotSegStartEA while currentEA < gotSegEndEA: realItemEA = Qword(currentEA) if is_func(GetFlags(realItemEA)): xref = get_first_dref_to(currentEA) while xref != None and xref != BADADDR: xrefSegName = get_segm_name(xref) if not xrefSegName.endswith(":__stubs"): print "[!] GOT func item @{:016X} refer @{:016X} is not in stubs".format(currentEA, xref) xref = get_next_dref_to(currentEA, xref) currentEA += 8 def getConstructorsInKextTEXT(kextPrefix): CTextEA2InfoMap = {} textSegStartEA, textSegEndEA = getTextAreaForKEXT(kextPrefix) for funcEA in Functions(textSegStartEA, textSegEndEA): funcName = getName(funcEA) if not None is funcName and isMangledFuncNameConstructor(funcName): realFuncDeName = getDeFuncNameOfName(funcName) className = realFuncDeName[:len(realFuncDeName)/2-1] ClassInstFuncInfo_C = ClassInstFuncInfo(funcName, className, IndicatorKind.INDNAME, [0], False) CTextEA2InfoMap[funcEA] = ClassInstFuncInfo_C return CTextEA2InfoMap def getConstructorsInKextSTUBS(kextPrefix): stubsSegName = kextPrefix + ":__stubs" CStubEA2InfoMap = {} stubsSeg = get_segm_by_name(stubsSegName) if None is stubsSeg: return CStubEA2InfoMap stubsSegStartEA = stubsSeg.startEA stubsSegEndEA = stubsSeg.endEA currentEA = stubsSegStartEA while currentEA < stubsSegEndEA: stubFuncName = getName(currentEA) gotItemName = GetOpnd(currentEA, 1)[1:-5] realFuncName = gotItemName[:gotItemName.rfind("_ptr_")] if isMangledFuncNameConstructor(realFuncName): realFuncDeName = getDeFuncNameOfName(realFuncName) className = realFuncDeName[:len(realFuncDeName)/2-1] ClassInstFuncInfo_C = ClassInstFuncInfo(realFuncName, className, IndicatorKind.INDNAME, [0], False) CStubEA2InfoMap[currentEA] = ClassInstFuncInfo_C currentEA += 12 return CStubEA2InfoMap def isMangledFuncNameConstructor(mangledFuncName): if mangledFuncName.startswith("__ZN11OSMetaClassC2EPKcPKS_j"): return False deFuncName = getDeFuncNameOfName(mangledFuncName) return not None is deFuncName and deFuncName[:len(deFuncName)/2-1] == deFuncName[len(deFuncName)/2+1:] def findUsageOfFuncEAs(usageSegName, funcEAs): usageOfSpecialFuncs = {} for funcEA in funcEAs: usageOfSpecialFuncs[funcEA] = set() xrefs = getXRefsTo(funcEA) for xref in xrefs: xrefSegName = get_segm_name(xref) if xrefSegName == usageSegName: usageOfSpecialFuncs[funcEA].add(xref) elif xrefSegName.endswith(":__text"): print "[!] Stub In %s: %s refed in %s"%(kextPrefix, funcEA, xrefSegName) return usageOfSpecialFuncs def findUsageOfStubFuncNames(stubsSegName, usageSegName, searchFuncNames): stubsSeg = get_segm_by_name(stubsSegName) if None is stubsSeg: return {} stubsSegStartEA = stubsSeg.startEA stubsSegEndEA = stubsSeg.endEA usageOfSpecialFuncs = {} for specialFuncName in searchFuncNames: usageOfSpecialFuncs[specialFuncName] = set() for funcEA in range(stubsSegStartEA, stubsSegEndEA, 12): funcName = getName(funcEA) for specialFuncName in searchFuncNames: if funcName.startswith(specialFuncName): #print "[+] Found ", funcName, specialFuncName xrefs = getXRefsTo(funcEA) for xref in xrefs: xrefSegName = get_segm_name(xref) if xrefSegName == usageSegName: usageOfSpecialFuncs[specialFuncName].add(xref) elif xrefSegName.endswith(":__text"): print "[!] Stub In %s: %s refed in %s"%(kextPrefix, specialFuncName, xrefSegName) return usageOfSpecialFuncs def shouldByPassSolveTypes(funcEA): funcName = getName(funcEA) if "_InitFunc_" in funcName: return True elif GetMnem(funcEA) == "B": return True return False def solveVarTypesByPropInTextSeg(textSegStartEA, textSegEndEA, crossKEXT=False): for funcStartEA in Functions(textSegStartEA, textSegEndEA): if isFuncContainObjArg(funcStartEA): if not shouldByPassSolveTypes(funcStartEA): AnalysisUtils.forward_analysis_in_func(funcStartEA, crossKEXT=crossKEXT) else: #print "[#] func at {:016X} does not have obj arg".format(funcStartEA) pass def solveVarTypesByPropInAll(): print "[+] solveVarTypesByPropInAll" for textSeg in getAllSegsOfText(): solveVarTypesByPropInTextSeg(textSeg.startEA, textSeg.endEA) def solveVarTypesByPropInKEXT(kextPrefix): startea, endea = getTextAreaForKEXT(kextPrefix) if startea == BADADDR: return solveVarTypesByPropInTextSeg(startea, endea, False) def processVFuncArgsForClass(className): vtableStartEA, vtableEndEA = getVTableAddrOfClass(className) currentEA = vtableStartEA vtableStructId = getVTableStructIdOfClass(className) parentClassName, parentVTableStartEA, parentVTableEndEA = findNearestAncestorHaveVT(className) if parentVTableStartEA == BADADDR: print "[!] {}'s parent {}'s vtable is not found! Abort typing".format(className, parentClassName) return while currentEA != vtableEndEA: funcEA = Qword(currentEA) offset = currentEA-vtableStartEA shouldProcess = True if not None is parentClassName and parentVTableStartEA != BADADDR and parentVTableStartEA + offset < parentVTableEndEA: parentFuncEA = Qword(parentVTableStartEA + offset) if funcEA != parentFuncEA: funcName = getName(funcEA) if None is funcName: currentEA += 8 continue if funcName.startswith("__"): deFuncName = getDeFuncNameOfName(funcName) if deFuncName: funcClassName = deFuncName[:deFuncName.rfind("::")] if funcClassName != className: shouldProcess = False elif "::" in funcName: funcClassName = funcName[:funcName.rfind("::")] if funcClassName != className: shouldProcess = False elif funcName == "___cxa_pure_virtual": shouldProcess = False if shouldProcess: processFuncArgs(funcEA, True, className, parentFuncEA) else: processFuncArgs(funcEA, True, className, None) keepCon_VFuncAndVTSMember(funcEA, vtableStructId, offset, False, True) currentEA += 8 def processVFuncArgsBFS(className): if not className in kernelClassNameSet: processVFuncArgsForClass(className) if className in classNameToChildClassNameSetMap: childClassNames = classNameToChildClassNameSetMap[className] for childClassName in childClassNames: processVFuncArgsBFS(childClassName) def processVFuncArgsForKext(kextPrefix): #print moduleNameToClassNamesMap if not kextPrefix in moduleNameToClassNamesMap: return classNameSet = moduleNameToClassNamesMap[kextPrefix] for className in classNameSet: processVFuncArgsForClass(className) #if className in classNameToVTableFuncEAListMap: # processVFuncArgsForClass(className) def processNamedFuncArgsForKext(kextPrefix): #kextPrefix += ":__text" #textSeg = get_segm_by_name(kextPrefix) textSegStartEA, textSegEndEA = getTextAreaForKEXT(kextPrefix) processNamedFuncArgsForSeg(textSegStartEA, textSegEndEA) def processNamedFuncArgsForSeg(textSegStartEA, textSegEndEA): for funcEA in Functions(textSegStartEA, textSegEndEA): funcName = getName(funcEA) if funcName.startswith("__"): funcDeName = getDeFuncNameOfName(funcName) if funcDeName and funcName != "___cxa_pure_virtual": if "::" in funcDeName: className = funcDeName[:funcDeName.rfind("::")] # This may incur error since not all functions are non-static processFuncArgs(funcEA, True, className, None) else: processFuncArgs(funcEA, False, None, None) def processNamedFuncArgsForAll(): print "[+] Process All Named Functions' Arguments" for seg in getAllSegsOfText(): processNamedFuncArgsForSeg(seg.startEA, seg.endEA) def processVFuncArgsForAll(): print "[+] Process All Virtual Functions' Arguments" roots = kernelClassNameSet if len(roots) == 0: roots = findRootClasses() for className in roots: processVFuncArgsBFS(className) keepAllCon_VTAndVTS() def setTypeForAllGlobalVars(): for ea,name in Names(): if None is name: continue if name.endswith("10gMetaClassE"): deName = getDeNameOfName(name) metaClassName = deName[:-12] + "::MetaClass" SetType(ea, metaClassName) elif name.endswith("9metaClassE"): deName = getDeNameOfName(name) metaClassName = deName[:-12] + "::MetaClass" SetType(ea, metaClassName + "*") elif name.startswith("__ZTV"): vtableDeName = getDeNameOfName(name) if not None is vtableDeName: className = vtableDeName[12:] wholeVTableStructId = GetStrucIdByName("whole_vtable_" + className) if wholeVTableStructId == BADADDR or GetStrucSize(wholeVTableStructId) != GetStrucSize(getVTableStructIdOfClass(className))+0x10: wholeVTableStructId = createWholeVTableStructForClass(className) if wholeVTableStructId != BADADDR: SetType(ea, "whole_vtable_" + className) ''' SetType(ea, "whole_vtable_" + className) will make the vtable const a chaos''' processAllVTableConst(True) def analyzeTypesForKEXT(kextPrefix): processNamedFuncArgsForKext(kextPrefix) processVFuncArgsForKext(kextPrefix) # I think this one is useless #setTypeForAllGlobalVars() def analyzeTypesForAll(): print "[+] Start Analyzing Types" processNamedFuncArgsForAll() processVFuncArgsForAll() # I think this one is useless #setTypeForAllGlobalVars() # Keep GOT consistency for type-analyzed funcs and vars processAllGOTSegs() def findSMethodArrayForUCClass(ucClassName): vtableStartEA, vtableEndEA = getVTableAddrOfClass(ucClassName) if vtableStartEA != BADADDR: externMethodNamePrefix = "__ZN" + str(len(ucClassName)) + ucClassName + "14externalMethodE" getTargetNamePrefix = "__ZN" + str(len(ucClassName)) + ucClassName + "26getTargetAndMethodForIndexE" for vtEA in range(vtableStartEA, vtableEndEA, 4): funcEA = Qword(vtEA) funcName = getName(funcEA) if funcName.startswith(externMethodNamePrefix): None elif funcName.startswith(getTargetNamePrefix): None def findSMethodArrayForKext(kextPrefix=None): externSMethods = [] targetSMethods = [] targetConstSegName = "__const" targetTextSegName = "__text" if kextPrefix: targetConstSegName = kextPrefix + ":__const" targetTextSegName = kextPrefix + ":__text" for segStartEA in Segments(): seg = getseg(segStartEA) segName = get_segm_name(segStartEA) if segName != targetSegName: continue constSegStartEA = seg.startEA constSegEndEA = seg.endEA currentEA = constSegStartEA isInVT = False while currentEA < constSegEndEA: currentName = getName(currentEA) if currentName.startswith("__ZTV"): currentEA += 0x10 isInVT = True continue if isInVT: if Qword(currentEA) == 0: isInVT = False currentEA += 8 continue xrefs = getXRefsTo(currentEA) if len(xrefs) == 0: currentEA += 8 continue else: for xref in xrefs: xrefSegName = SegName(xref) if xrefSegName == targetTextSegName: xrefFunc = get_func(xref) if not None is xrefFunc: xrefFuncName = getName(xrefFunc.startEA) xrefDeFuncName = getDeFuncNameOfName(xrefFuncName) className = None if not None is xrefDeFuncName: className = xrefDeFuncName[:xrefDeFuncName.rfind("::")] elif "::" in xrefFuncName: className = xrefFuncName[:xrefFuncName.rfind("::")] sMethods_IOExternalMethodDispatch_cnt = 0 guessEA = currentEA while True: guessValue0 = Qword(guessEA) guessValue1 = Qword(guessEA+8) guessValue2 = Qword(guessEA+0x10) guessValue3 = Qword(guessEA+0x18) if isIOExternalMethodDispatchAtEA(guessEA) : guessEA += 0x18 sMethods_IOExternalMethodDispatch_cnt += 1 elif guessValue0 == 0 and guessValue1 == 0 and guessValue2 == 0 and \ isIOExternalMethodDispatchAtEA(guessEA+0x18, True): guessEA += 0x18 sMethods_IOExternalMethodDispatch_cnt += 1 else: break if sMethods_IOExternalMethodDispatch_cnt != 0: externSMethods.append((currentEA, sMethods_IOExternalMethodDispatch_cnt+1, className)) if not None is className: parseSMethodArrayAtAddr(currentEA, sMethods_IOExternalMethodDispatch_cnt+1, className, True) currentEA = guessEA + 0x18 continue currentEA += 8 return externSMethods, targetSMethods def findSMethodArrayForAll(): externSMethods = [] targetSMethods = [] for kextPrefix in getAllKEXTPrefixes(): externSMethodsOfKext, targetSMethodsOfKext = findSMethodArrayForKext(kextPrefix) externSMethods.extend(externSMethodsOfKext) targetSMethods.extend(targetSMethodsOfKext) externSMethodsOfKext, targetSMethodsOfKext = findSMethodArrayForKext() externSMethods.extend(externSMethodsOfKext) targetSMethods.extend(targetSMethodsOfKext) print "[+] Found SMethods: EA, Size, ClassName" for sMethod in externSMethods: print "{:016X}, {}, {}".format(sMethod[0], sMethod[1], sMethod[2]) print "[+] Arm64TypeAnalyzer loaded"
1
0.764774
1
0.764774
game-dev
MEDIA
0.134502
game-dev
0.606
1
0.606
MehVahdJukaar/Supplementaries
14,626
common/src/main/java/net/mehvahdjukaar/supplementaries/common/block/blocks/PedestalBlock.java
package net.mehvahdjukaar.supplementaries.common.block.blocks; import net.mehvahdjukaar.moonlight.api.block.ItemDisplayTile; import net.mehvahdjukaar.moonlight.api.block.WaterBlock; import net.mehvahdjukaar.moonlight.api.misc.ForgeOverride; import net.mehvahdjukaar.supplementaries.common.block.ModBlockProperties; import net.mehvahdjukaar.supplementaries.common.block.ModBlockProperties.DisplayStatus; import net.mehvahdjukaar.supplementaries.common.block.tiles.PedestalBlockTile; import net.mehvahdjukaar.supplementaries.common.items.SackItem; import net.mehvahdjukaar.supplementaries.common.utils.BlockUtil; import net.mehvahdjukaar.supplementaries.configs.CommonConfigs; import net.mehvahdjukaar.supplementaries.reg.ModRegistry; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.world.*; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.EntityBlock; import net.minecraft.world.level.block.Rotation; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.level.block.state.properties.BooleanProperty; import net.minecraft.world.level.block.state.properties.EnumProperty; import net.minecraft.world.level.material.Fluids; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.HitResult; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; import org.jetbrains.annotations.Nullable; public class PedestalBlock extends WaterBlock implements EntityBlock, WorldlyContainerHolder { protected static final VoxelShape SHAPE = Shapes.or(Shapes.box(0.1875D, 0.125D, 0.1875D, 0.815D, 0.885D, 0.815D), Shapes.box(0.0625D, 0.8125D, 0.0625D, 0.9375D, 1D, 0.9375D), Shapes.box(0.0625D, 0D, 0.0625D, 0.9375D, 0.1875D, 0.9375D)); protected static final VoxelShape SHAPE_UP = Shapes.or(Shapes.box(0.1875D, 0.125D, 0.1875D, 0.815D, 1, 0.815D), Shapes.box(0.0625D, 0D, 0.0625D, 0.9375D, 0.1875D, 0.9375D)); protected static final VoxelShape SHAPE_DOWN = Shapes.or(Shapes.box(0.1875D, 0, 0.1875D, 0.815D, 0.885D, 0.815D), Shapes.box(0.0625D, 0.8125D, 0.0625D, 0.9375D, 1D, 0.9375D)); protected static final VoxelShape SHAPE_UP_DOWN = Shapes.box(0.1875D, 0, 0.1875D, 0.815D, 1, 0.815D); public static final BooleanProperty UP = BlockStateProperties.UP; public static final BooleanProperty DOWN = BlockStateProperties.DOWN; public static final EnumProperty<DisplayStatus> ITEM_STATUS = ModBlockProperties.ITEM_STATUS; public static final EnumProperty<Direction.Axis> AXIS = BlockStateProperties.HORIZONTAL_AXIS; public PedestalBlock(Properties properties) { super(properties); this.registerDefaultState(this.stateDefinition.any().setValue(UP, false).setValue(AXIS, Direction.Axis.X) .setValue(DOWN, false).setValue(WATERLOGGED, false).setValue(ITEM_STATUS, DisplayStatus.EMPTY)); } @ForgeOverride public float getEnchantPowerBonus(BlockState state, LevelReader world, BlockPos pos) { double power = CommonConfigs.Building.CRYSTAL_ENCHANTING.get(); if (power != 0 && world.getBlockEntity(pos) instanceof PedestalBlockTile te) { if (te.getDisplayType() == PedestalBlockTile.DisplayType.CRYSTAL) return (float) power; } return 0; } @Override protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) { builder.add(UP, DOWN, WATERLOGGED, ITEM_STATUS, AXIS); } @Override public BlockState getStateForPlacement(BlockPlaceContext context) { Level level = context.getLevel(); BlockPos pos = context.getClickedPos(); boolean flag = level.getFluidState(pos).getType() == Fluids.WATER; return this.defaultBlockState().setValue(WATERLOGGED, flag).setValue(AXIS, context.getHorizontalDirection().getAxis()) .setValue(ITEM_STATUS, getStatus(level, pos, false)) .setValue(UP, canConnectTo(level.getBlockState(pos.above()), pos, level, Direction.UP, false)) .setValue(DOWN, canConnectTo(level.getBlockState(pos.below()), pos, level, Direction.DOWN, false)); } public static boolean canConnectTo(BlockState state, BlockPos pos, LevelAccessor world, Direction dir, boolean hasItem) { if (state.getBlock() instanceof PedestalBlock) { if (dir == Direction.DOWN) { return !state.getValue(ITEM_STATUS).hasTile(); } else if (dir == Direction.UP) { return !hasItem; } } return false; } //called when a neighbor is placed @Override public BlockState updateShape(BlockState stateIn, Direction facing, BlockState facingState, LevelAccessor level, BlockPos currentPos, BlockPos facingPos) { super.updateShape(stateIn, facing, facingState, level, currentPos, facingPos); if (facing == Direction.UP) { boolean hasItem = stateIn.getValue(ITEM_STATUS).hasItem(); return stateIn.setValue(ITEM_STATUS, getStatus(level, currentPos, hasItem)) .setValue(UP, canConnectTo(facingState, currentPos, level, facing, hasItem)); } else if (facing == Direction.DOWN) { return stateIn.setValue(DOWN, canConnectTo(facingState, currentPos, level, facing, stateIn.getValue(ITEM_STATUS).hasItem())); } return stateIn; } @ForgeOverride public ItemStack getCloneItemStack(BlockState state, HitResult target, BlockGetter world, BlockPos pos, Player player) { if (target.getLocation().y() > pos.getY() + 1 - 0.1875) { if (world.getBlockEntity(pos) instanceof ItemDisplayTile tile) { ItemStack i = tile.getDisplayedItem(); if (!i.isEmpty()) return i; } } return super.getCloneItemStack(world, pos, state); } @Override public InteractionResult use(BlockState state, Level level, BlockPos pos, Player player, InteractionHand handIn, BlockHitResult hit) { InteractionResult resultType = InteractionResult.PASS; if (state.getValue(ITEM_STATUS).hasTile() && level.getBlockEntity(pos) instanceof PedestalBlockTile tile && tile.isAccessibleBy(player)) { ItemStack handItem = player.getItemInHand(handIn); //Indiana Jones swap if (handItem.getItem() instanceof SackItem) { ItemStack it = handItem.copy(); it.setCount(1); ItemStack removed = tile.removeItemNoUpdate(0); tile.setDisplayedItem(it); if (!player.isCreative()) { handItem.shrink(1); } if (!level.isClientSide()) { player.setItemInHand(handIn, removed); level.playSound(null, pos, SoundEvents.ITEM_FRAME_ADD_ITEM, SoundSource.BLOCKS, 1.0F, level.random.nextFloat() * 0.10F + 0.95F); tile.setChanged(); } else { //also refreshTextures visuals on client. will get overwritten by packet tho tile.updateClientVisualsOnLoad(); } resultType = InteractionResult.sidedSuccess(level.isClientSide); } else { resultType = tile.interact(player, handIn); } } return resultType; } public static boolean canHaveItemAbove(LevelAccessor level, BlockPos pos) { BlockState above = level.getBlockState(pos.above()); return !above.is(ModRegistry.PEDESTAL.get()) && !above.isRedstoneConductor(level, pos.above()); } public static DisplayStatus getStatus(LevelAccessor level, BlockPos pos, boolean hasItem) { if (hasItem) return DisplayStatus.FULL; return canHaveItemAbove(level, pos) ? DisplayStatus.EMPTY : DisplayStatus.NONE; } @Override public VoxelShape getShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) { boolean up = state.getValue(UP); boolean down = state.getValue(DOWN); if (!up) { if (!down) { return SHAPE; } else { return SHAPE_DOWN; } } else { if (!down) { return SHAPE_UP; } else { return SHAPE_UP_DOWN; } } } @Nullable @Override public BlockEntity newBlockEntity(BlockPos pPos, BlockState pState) { if (pState.getValue(ITEM_STATUS).hasTile()) { return new PedestalBlockTile(pPos, pState); } return null; } @Override public void onRemove(BlockState state, Level world, BlockPos pos, BlockState newState, boolean isMoving) { if (state.getBlock() != newState.getBlock()) { if (world.getBlockEntity(pos) instanceof ItemDisplayTile tile) { Containers.dropContents(world, pos, tile); world.updateNeighbourForOutputSignal(pos, this); } super.onRemove(state, world, pos, newState, isMoving); } } @Override public boolean hasAnalogOutputSignal(BlockState state) { return true; } @Override public int getAnalogOutputSignal(BlockState blockState, Level world, BlockPos pos) { if (world.getBlockEntity(pos) instanceof PedestalBlockTile tile) return tile.isEmpty() ? 0 : 15; else return 0; } @Override public BlockState rotate(BlockState state, Rotation rotation) { if (rotation == Rotation.CLOCKWISE_180) { return state; } else { return switch (state.getValue(AXIS)) { case Z -> state.setValue(AXIS, Direction.Axis.X); case X -> state.setValue(AXIS, Direction.Axis.Z); default -> state; }; } } @Override public void setPlacedBy(Level world, BlockPos pos, BlockState state, @Nullable LivingEntity placer, ItemStack stack) { BlockUtil.addOptionalOwnership(placer, world, pos); } @Override public WorldlyContainer getContainer(BlockState state, LevelAccessor level, BlockPos pos) { if (state.getValue(ITEM_STATUS).hasTile()) { return (PedestalBlockTile) level.getBlockEntity(pos); } return new TileLessContainer(state, level, pos); } @Deprecated(forRemoval = true) static class TileLessContainer extends SimpleContainer implements WorldlyContainer { private final BlockState state; private final LevelAccessor level; private final BlockPos pos; private PedestalBlockTile tileReference = null; public TileLessContainer(BlockState blockState, LevelAccessor levelAccessor, BlockPos blockPos) { super(1); this.state = blockState; this.level = levelAccessor; this.pos = blockPos; } @Override public boolean stillValid(Player player) { return tileReference == null; } @Override public ItemStack getItem(int slot) { if (tileReference != null) return tileReference.getItem(slot); return super.getItem(slot); } @Override public ItemStack removeItem(int slot, int amount) { if (tileReference != null) return tileReference.removeItem(slot, amount); return super.removeItem(slot, amount); } @Override public boolean isEmpty() { if (tileReference != null) return tileReference.isEmpty(); return super.isEmpty(); } @Override public ItemStack removeItemNoUpdate(int slot) { if (tileReference != null) return tileReference.removeItemNoUpdate(slot); return super.removeItemNoUpdate(slot); } @Override public void clearContent() { if (tileReference != null) tileReference.clearContent(); else super.clearContent(); } @Override public boolean canPlaceItem(int index, ItemStack stack) { if (tileReference != null) return tileReference.canPlaceItem(index, stack); return super.canPlaceItem(index, stack); } @Override public int getMaxStackSize() { if (tileReference != null) return tileReference.getMaxStackSize(); return 1; } @Override public int[] getSlotsForFace(Direction side) { if (tileReference != null) return tileReference.getSlotsForFace(side); return new int[]{0}; } @Override public boolean canPlaceItemThroughFace(int index, ItemStack itemStack, @Nullable Direction direction) { if (tileReference != null) return canTakeItemThroughFace(index, itemStack, direction); return true; } @Override public boolean canTakeItemThroughFace(int index, ItemStack stack, Direction direction) { if (tileReference != null) return tileReference.canTakeItemThroughFace(index, stack, direction); return !this.isEmpty(); } @Override public void setChanged() { if (!this.isEmpty()) { var item = this.getItem(0); if (!item.isEmpty()) { level.setBlock(pos, state.setValue(PedestalBlock.ITEM_STATUS, DisplayStatus.EMPTY), 3); } if (level.getBlockEntity(pos) instanceof PedestalBlockTile tile) { this.tileReference = tile; tile.setDisplayedItem(item); } } } } }
1
0.969055
1
0.969055
game-dev
MEDIA
0.998202
game-dev
0.975037
1
0.975037
mcMMO-Dev/mcMMO
4,963
src/main/java/com/gmail/nossr50/commands/skills/AxesCommand.java
package com.gmail.nossr50.commands.skills; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.skills.axes.Axes; import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.random.ProbabilityUtil; import com.gmail.nossr50.util.skills.CombatUtils; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.text.TextComponentFactory; import java.util.ArrayList; import java.util.List; import net.kyori.adventure.text.Component; import org.bukkit.entity.Player; public class AxesCommand extends SkillCommand { private String critChance; private String critChanceLucky; private double axeMasteryDamage; private double impactDamage; private String skullSplitterLength; private String skullSplitterLengthEndurance; private boolean canSkullSplitter; private boolean canCritical; private boolean canAxeMastery; private boolean canImpact; private boolean canGreaterImpact; public AxesCommand() { super(PrimarySkillType.AXES); } @Override protected void dataCalculations(Player player, float skillValue) { // ARMOR IMPACT if (canImpact) { impactDamage = mmoPlayer.getAxesManager().getImpactDurabilityDamage(); } // AXE MASTERY if (canAxeMastery) { axeMasteryDamage = Axes.getAxeMasteryBonusDamage(player); } // CRITICAL HIT if (canCritical) { String[] criticalHitStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.AXES_CRITICAL_STRIKES); critChance = criticalHitStrings[0]; critChanceLucky = criticalHitStrings[1]; } // SKULL SPLITTER if (canSkullSplitter) { String[] skullSplitterStrings = calculateLengthDisplayValues(player, skillValue); skullSplitterLength = skullSplitterStrings[0]; skullSplitterLengthEndurance = skullSplitterStrings[1]; } } @Override protected void permissionsCheck(Player player) { canSkullSplitter = Permissions.skullSplitter(player) && RankUtils.hasUnlockedSubskill(player, SubSkillType.AXES_SKULL_SPLITTER); canCritical = Permissions.canUseSubSkill(player, SubSkillType.AXES_CRITICAL_STRIKES); canAxeMastery = Permissions.canUseSubSkill(player, SubSkillType.AXES_AXE_MASTERY); canImpact = Permissions.canUseSubSkill(player, SubSkillType.AXES_ARMOR_IMPACT); canGreaterImpact = Permissions.canUseSubSkill(player, SubSkillType.AXES_GREATER_IMPACT); } @Override protected List<String> statsDisplay(Player player, float skillValue, boolean hasEndurance, boolean isLucky) { List<String> messages = new ArrayList<>(); if (canImpact) { messages.add(LocaleLoader.getString("Ability.Generic.Template", LocaleLoader.getString("Axes.Ability.Bonus.2"), LocaleLoader.getString("Axes.Ability.Bonus.3", impactDamage))); } if (canAxeMastery) { messages.add(LocaleLoader.getString("Ability.Generic.Template", LocaleLoader.getString("Axes.Ability.Bonus.0"), LocaleLoader.getString("Axes.Ability.Bonus.1", axeMasteryDamage))); } if (canCritical) { messages.add(getStatMessage(SubSkillType.AXES_CRITICAL_STRIKES, critChance) + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", critChanceLucky) : "")); } if (canGreaterImpact) { messages.add(LocaleLoader.getString("Ability.Generic.Template", LocaleLoader.getString("Axes.Ability.Bonus.4"), LocaleLoader.getString("Axes.Ability.Bonus.5", Axes.greaterImpactBonusDamage))); } if (canSkullSplitter) { messages.add(getStatMessage(SubSkillType.AXES_SKULL_SPLITTER, skullSplitterLength) + (hasEndurance ? LocaleLoader.getString("Perks.ActivationTime.Bonus", skullSplitterLengthEndurance) : "")); } if (Permissions.canUseSubSkill(player, SubSkillType.AXES_AXES_LIMIT_BREAK)) { messages.add(getStatMessage(SubSkillType.AXES_AXES_LIMIT_BREAK, String.valueOf(CombatUtils.getLimitBreakDamageAgainstQuality(player, SubSkillType.AXES_AXES_LIMIT_BREAK, 1000)))); } return messages; } @Override protected List<Component> getTextComponents(Player player) { final List<Component> textComponents = new ArrayList<>(); TextComponentFactory.getSubSkillTextComponents(player, textComponents, PrimarySkillType.AXES); return textComponents; } }
1
0.883031
1
0.883031
game-dev
MEDIA
0.712725
game-dev
0.977231
1
0.977231
Fluorohydride/ygopro-scripts
1,426
c29590905.lua
--スーパージュニア対決! function c29590905.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_ATTACK_ANNOUNCE) e1:SetCondition(c29590905.condition) e1:SetTarget(c29590905.target) e1:SetOperation(c29590905.activate) c:RegisterEffect(e1) end function c29590905.condition(e,tp,eg,ep,ev,re,r,rp) return eg:GetFirst():IsControler(1-tp) end function c29590905.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(Card.IsPosition,tp,LOCATION_MZONE,0,1,nil,POS_FACEUP_DEFENSE) end end function c29590905.activate(e,tp,eg,ep,ev,re,r,rp) local g1=Duel.GetMatchingGroup(Card.IsPosition,tp,0,LOCATION_MZONE,nil,POS_FACEUP_ATTACK) local g2=Duel.GetMatchingGroup(Card.IsPosition,tp,LOCATION_MZONE,0,nil,POS_FACEUP_DEFENSE) if g1:GetCount()==0 or g2:GetCount()==0 then return end local ga=g1:GetMinGroup(Card.GetAttack) local gd=g2:GetMinGroup(Card.GetDefense) if ga:GetCount()>1 then Duel.Hint(HINT_SELECTMSG,tp,aux.Stringid(29590905,0)) ga=ga:Select(tp,1,1,nil) end if gd:GetCount()>1 then Duel.Hint(HINT_SELECTMSG,tp,aux.Stringid(29590905,1)) gd=gd:Select(tp,1,1,nil) end Duel.NegateAttack() local a=ga:GetFirst() local d=gd:GetFirst() if a:IsAttackable() and not a:IsImmuneToEffect(e) and not d:IsImmuneToEffect(e) then Duel.CalculateDamage(a,d) Duel.SkipPhase(1-tp,PHASE_BATTLE,RESET_PHASE+PHASE_BATTLE_STEP,1) end end
1
0.890278
1
0.890278
game-dev
MEDIA
0.99523
game-dev
0.953144
1
0.953144
SpongePowered/Mixin
3,786
src/bridge/java/org/spongepowered/asm/bridge/RemapperAdapterFML.java
/* * This file is part of Mixin, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.asm.bridge; import java.lang.reflect.Field; import java.lang.reflect.Method; import org.spongepowered.asm.mixin.extensibility.IRemapper; /** * Remapper adapter which remaps using FML's deobfuscating remapper */ public final class RemapperAdapterFML extends RemapperAdapter { private static final String DEOBFUSCATING_REMAPPER_CLASS = "fml.common.asm.transformers.deobf.FMLDeobfuscatingRemapper"; private static final String DEOBFUSCATING_REMAPPER_CLASS_FORGE = "net.minecraftforge." + RemapperAdapterFML.DEOBFUSCATING_REMAPPER_CLASS; private static final String DEOBFUSCATING_REMAPPER_CLASS_LEGACY = "cpw.mods." + RemapperAdapterFML.DEOBFUSCATING_REMAPPER_CLASS; private static final String INSTANCE_FIELD = "INSTANCE"; private static final String UNMAP_METHOD = "unmap"; private final Method mdUnmap; private RemapperAdapterFML(org.objectweb.asm.commons.Remapper remapper, Method mdUnmap) { super(remapper); this.logger.info("Initialised Mixin FML Remapper Adapter with {}", remapper); this.mdUnmap = mdUnmap; } @Override public String unmap(String typeName) { try { return this.mdUnmap.invoke(this.remapper, typeName).toString(); } catch (Exception ex) { return typeName; } } /** * Factory method */ public static IRemapper create() { try { Class<?> clDeobfRemapper = RemapperAdapterFML.getFMLDeobfuscatingRemapper(); Field singletonField = clDeobfRemapper.getDeclaredField(RemapperAdapterFML.INSTANCE_FIELD); Method mdUnmap = clDeobfRemapper.getDeclaredMethod(RemapperAdapterFML.UNMAP_METHOD, String.class); org.objectweb.asm.commons.Remapper remapper = (org.objectweb.asm.commons.Remapper)singletonField.get(null); return new RemapperAdapterFML(remapper, mdUnmap); } catch (Exception ex) { ex.printStackTrace(); return null; } } /** * Attempt to get the FML Deobfuscating Remapper, tries the post-1.8 * namespace first and falls back to 1.7.10 if class lookup fails */ private static Class<?> getFMLDeobfuscatingRemapper() throws ClassNotFoundException { try { return Class.forName(RemapperAdapterFML.DEOBFUSCATING_REMAPPER_CLASS_FORGE); } catch (ClassNotFoundException ex) { return Class.forName(RemapperAdapterFML.DEOBFUSCATING_REMAPPER_CLASS_LEGACY); } } }
1
0.853947
1
0.853947
game-dev
MEDIA
0.204788
game-dev
0.652762
1
0.652762
superman-t/PlaneGame
19,329
external/android/armeabi-v7a/include/spidermonkey/jswrapper.h
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * vim: set ts=8 sts=4 et sw=4 tw=99: * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef jswrapper_h #define jswrapper_h #include "mozilla/Attributes.h" #include "js/Proxy.h" namespace js { /* * Helper for Wrapper::New default options. * * Callers of Wrapper::New() who wish to specify a prototype for the created * Wrapper, *MUST* construct a WrapperOptions with a JSContext. */ class MOZ_STACK_CLASS WrapperOptions : public ProxyOptions { public: WrapperOptions() : ProxyOptions(false), proto_() {} explicit WrapperOptions(JSContext* cx) : ProxyOptions(false), proto_() { proto_.emplace(cx); } inline JSObject* proto() const; WrapperOptions& setProto(JSObject* protoArg) { MOZ_ASSERT(proto_); *proto_ = protoArg; return *this; } private: mozilla::Maybe<JS::RootedObject> proto_; }; /* * A wrapper is a proxy with a target object to which it generally forwards * operations, but may restrict access to certain operations or augment those * operations in various ways. * * A wrapper can be "unwrapped" in C++, exposing the underlying object. * Callers should be careful to avoid unwrapping security wrappers in the wrong * context. * * Important: If you add a method implementation here, you probably also need * to add an override in CrossCompartmentWrapper. If you don't, you risk * compartment mismatches. See bug 945826 comment 0. */ class JS_FRIEND_API(Wrapper) : public BaseProxyHandler { unsigned mFlags; public: explicit constexpr Wrapper(unsigned aFlags, bool aHasPrototype = false, bool aHasSecurityPolicy = false) : BaseProxyHandler(&family, aHasPrototype, aHasSecurityPolicy), mFlags(aFlags) { } virtual bool finalizeInBackground(const Value& priv) const override; /* Standard internal methods. */ virtual bool getOwnPropertyDescriptor(JSContext* cx, HandleObject proxy, HandleId id, MutableHandle<PropertyDescriptor> desc) const override; virtual bool defineProperty(JSContext* cx, HandleObject proxy, HandleId id, Handle<PropertyDescriptor> desc, ObjectOpResult& result) const override; virtual bool ownPropertyKeys(JSContext* cx, HandleObject proxy, AutoIdVector& props) const override; virtual bool delete_(JSContext* cx, HandleObject proxy, HandleId id, ObjectOpResult& result) const override; virtual bool enumerate(JSContext* cx, HandleObject proxy, MutableHandleObject objp) const override; virtual bool getPrototype(JSContext* cx, HandleObject proxy, MutableHandleObject protop) const override; virtual bool setPrototype(JSContext* cx, HandleObject proxy, HandleObject proto, ObjectOpResult& result) const override; virtual bool getPrototypeIfOrdinary(JSContext* cx, HandleObject proxy, bool* isOrdinary, MutableHandleObject protop) const override; virtual bool setImmutablePrototype(JSContext* cx, HandleObject proxy, bool* succeeded) const override; virtual bool preventExtensions(JSContext* cx, HandleObject proxy, ObjectOpResult& result) const override; virtual bool isExtensible(JSContext* cx, HandleObject proxy, bool* extensible) const override; virtual bool has(JSContext* cx, HandleObject proxy, HandleId id, bool* bp) const override; virtual bool get(JSContext* cx, HandleObject proxy, HandleValue receiver, HandleId id, MutableHandleValue vp) const override; virtual bool set(JSContext* cx, HandleObject proxy, HandleId id, HandleValue v, HandleValue receiver, ObjectOpResult& result) const override; virtual bool call(JSContext* cx, HandleObject proxy, const CallArgs& args) const override; virtual bool construct(JSContext* cx, HandleObject proxy, const CallArgs& args) const override; /* SpiderMonkey extensions. */ virtual bool getPropertyDescriptor(JSContext* cx, HandleObject proxy, HandleId id, MutableHandle<PropertyDescriptor> desc) const override; virtual bool hasOwn(JSContext* cx, HandleObject proxy, HandleId id, bool* bp) const override; virtual bool getOwnEnumerablePropertyKeys(JSContext* cx, HandleObject proxy, AutoIdVector& props) const override; virtual bool nativeCall(JSContext* cx, IsAcceptableThis test, NativeImpl impl, const CallArgs& args) const override; virtual bool hasInstance(JSContext* cx, HandleObject proxy, MutableHandleValue v, bool* bp) const override; virtual bool getBuiltinClass(JSContext* cx, HandleObject proxy, ESClass* cls) const override; virtual bool isArray(JSContext* cx, HandleObject proxy, JS::IsArrayAnswer* answer) const override; virtual const char* className(JSContext* cx, HandleObject proxy) const override; virtual JSString* fun_toString(JSContext* cx, HandleObject proxy, unsigned indent) const override; virtual bool regexp_toShared(JSContext* cx, HandleObject proxy, RegExpGuard* g) const override; virtual bool boxedValue_unbox(JSContext* cx, HandleObject proxy, MutableHandleValue vp) const override; virtual bool isCallable(JSObject* obj) const override; virtual bool isConstructor(JSObject* obj) const override; virtual JSObject* weakmapKeyDelegate(JSObject* proxy) const override; public: using BaseProxyHandler::Action; enum Flags { CROSS_COMPARTMENT = 1 << 0, LAST_USED_FLAG = CROSS_COMPARTMENT }; static JSObject* New(JSContext* cx, JSObject* obj, const Wrapper* handler, const WrapperOptions& options = WrapperOptions()); static JSObject* Renew(JSContext* cx, JSObject* existing, JSObject* obj, const Wrapper* handler); static const Wrapper* wrapperHandler(JSObject* wrapper); static JSObject* wrappedObject(JSObject* wrapper); unsigned flags() const { return mFlags; } static const char family; static const Wrapper singleton; static const Wrapper singletonWithPrototype; static JSObject* defaultProto; }; inline JSObject* WrapperOptions::proto() const { return proto_ ? *proto_ : Wrapper::defaultProto; } /* Base class for all cross compartment wrapper handlers. */ class JS_FRIEND_API(CrossCompartmentWrapper) : public Wrapper { public: explicit constexpr CrossCompartmentWrapper(unsigned aFlags, bool aHasPrototype = false, bool aHasSecurityPolicy = false) : Wrapper(CROSS_COMPARTMENT | aFlags, aHasPrototype, aHasSecurityPolicy) { } /* Standard internal methods. */ virtual bool getOwnPropertyDescriptor(JSContext* cx, HandleObject wrapper, HandleId id, MutableHandle<PropertyDescriptor> desc) const override; virtual bool defineProperty(JSContext* cx, HandleObject wrapper, HandleId id, Handle<PropertyDescriptor> desc, ObjectOpResult& result) const override; virtual bool ownPropertyKeys(JSContext* cx, HandleObject wrapper, AutoIdVector& props) const override; virtual bool delete_(JSContext* cx, HandleObject wrapper, HandleId id, ObjectOpResult& result) const override; virtual bool enumerate(JSContext* cx, HandleObject wrapper, MutableHandleObject objp) const override; virtual bool getPrototype(JSContext* cx, HandleObject proxy, MutableHandleObject protop) const override; virtual bool setPrototype(JSContext* cx, HandleObject proxy, HandleObject proto, ObjectOpResult& result) const override; virtual bool getPrototypeIfOrdinary(JSContext* cx, HandleObject proxy, bool* isOrdinary, MutableHandleObject protop) const override; virtual bool setImmutablePrototype(JSContext* cx, HandleObject proxy, bool* succeeded) const override; virtual bool preventExtensions(JSContext* cx, HandleObject wrapper, ObjectOpResult& result) const override; virtual bool isExtensible(JSContext* cx, HandleObject wrapper, bool* extensible) const override; virtual bool has(JSContext* cx, HandleObject wrapper, HandleId id, bool* bp) const override; virtual bool get(JSContext* cx, HandleObject wrapper, HandleValue receiver, HandleId id, MutableHandleValue vp) const override; virtual bool set(JSContext* cx, HandleObject wrapper, HandleId id, HandleValue v, HandleValue receiver, ObjectOpResult& result) const override; virtual bool call(JSContext* cx, HandleObject wrapper, const CallArgs& args) const override; virtual bool construct(JSContext* cx, HandleObject wrapper, const CallArgs& args) const override; /* SpiderMonkey extensions. */ virtual bool getPropertyDescriptor(JSContext* cx, HandleObject wrapper, HandleId id, MutableHandle<PropertyDescriptor> desc) const override; virtual bool hasOwn(JSContext* cx, HandleObject wrapper, HandleId id, bool* bp) const override; virtual bool getOwnEnumerablePropertyKeys(JSContext* cx, HandleObject wrapper, AutoIdVector& props) const override; virtual bool nativeCall(JSContext* cx, IsAcceptableThis test, NativeImpl impl, const CallArgs& args) const override; virtual bool hasInstance(JSContext* cx, HandleObject wrapper, MutableHandleValue v, bool* bp) const override; virtual const char* className(JSContext* cx, HandleObject proxy) const override; virtual JSString* fun_toString(JSContext* cx, HandleObject wrapper, unsigned indent) const override; virtual bool regexp_toShared(JSContext* cx, HandleObject proxy, RegExpGuard* g) const override; virtual bool boxedValue_unbox(JSContext* cx, HandleObject proxy, MutableHandleValue vp) const override; // Allocate CrossCompartmentWrappers in the nursery. virtual bool canNurseryAllocate() const override { return true; } static const CrossCompartmentWrapper singleton; static const CrossCompartmentWrapper singletonWithPrototype; }; class JS_FRIEND_API(OpaqueCrossCompartmentWrapper) : public CrossCompartmentWrapper { public: explicit constexpr OpaqueCrossCompartmentWrapper() : CrossCompartmentWrapper(0) { } /* Standard internal methods. */ virtual bool getOwnPropertyDescriptor(JSContext* cx, HandleObject wrapper, HandleId id, MutableHandle<PropertyDescriptor> desc) const override; virtual bool defineProperty(JSContext* cx, HandleObject wrapper, HandleId id, Handle<PropertyDescriptor> desc, ObjectOpResult& result) const override; virtual bool ownPropertyKeys(JSContext* cx, HandleObject wrapper, AutoIdVector& props) const override; virtual bool delete_(JSContext* cx, HandleObject wrapper, HandleId id, ObjectOpResult& result) const override; virtual bool enumerate(JSContext* cx, HandleObject wrapper, MutableHandleObject objp) const override; virtual bool getPrototype(JSContext* cx, HandleObject wrapper, MutableHandleObject protop) const override; virtual bool setPrototype(JSContext* cx, HandleObject wrapper, HandleObject proto, ObjectOpResult& result) const override; virtual bool getPrototypeIfOrdinary(JSContext* cx, HandleObject wrapper, bool* isOrdinary, MutableHandleObject protop) const override; virtual bool setImmutablePrototype(JSContext* cx, HandleObject wrapper, bool* succeeded) const override; virtual bool preventExtensions(JSContext* cx, HandleObject wrapper, ObjectOpResult& result) const override; virtual bool isExtensible(JSContext* cx, HandleObject wrapper, bool* extensible) const override; virtual bool has(JSContext* cx, HandleObject wrapper, HandleId id, bool* bp) const override; virtual bool get(JSContext* cx, HandleObject wrapper, HandleValue receiver, HandleId id, MutableHandleValue vp) const override; virtual bool set(JSContext* cx, HandleObject wrapper, HandleId id, HandleValue v, HandleValue receiver, ObjectOpResult& result) const override; virtual bool call(JSContext* cx, HandleObject wrapper, const CallArgs& args) const override; virtual bool construct(JSContext* cx, HandleObject wrapper, const CallArgs& args) const override; /* SpiderMonkey extensions. */ virtual bool getPropertyDescriptor(JSContext* cx, HandleObject wrapper, HandleId id, MutableHandle<PropertyDescriptor> desc) const override; virtual bool hasOwn(JSContext* cx, HandleObject wrapper, HandleId id, bool* bp) const override; virtual bool getOwnEnumerablePropertyKeys(JSContext* cx, HandleObject wrapper, AutoIdVector& props) const override; virtual bool getBuiltinClass(JSContext* cx, HandleObject wrapper, ESClass* cls) const override; virtual bool isArray(JSContext* cx, HandleObject obj, JS::IsArrayAnswer* answer) const override; virtual const char* className(JSContext* cx, HandleObject wrapper) const override; virtual JSString* fun_toString(JSContext* cx, HandleObject proxy, unsigned indent) const override; static const OpaqueCrossCompartmentWrapper singleton; }; /* * Base class for security wrappers. A security wrapper is potentially hiding * all or part of some wrapped object thus SecurityWrapper defaults to denying * access to the wrappee. This is the opposite of Wrapper which tries to be * completely transparent. * * NB: Currently, only a few ProxyHandler operations are overridden to deny * access, relying on derived SecurityWrapper to block access when necessary. */ template <class Base> class JS_FRIEND_API(SecurityWrapper) : public Base { public: explicit constexpr SecurityWrapper(unsigned flags, bool hasPrototype = false) : Base(flags, hasPrototype, /* hasSecurityPolicy = */ true) { } virtual bool enter(JSContext* cx, HandleObject wrapper, HandleId id, Wrapper::Action act, bool* bp) const override; virtual bool defineProperty(JSContext* cx, HandleObject wrapper, HandleId id, Handle<PropertyDescriptor> desc, ObjectOpResult& result) const override; virtual bool isExtensible(JSContext* cx, HandleObject wrapper, bool* extensible) const override; virtual bool preventExtensions(JSContext* cx, HandleObject wrapper, ObjectOpResult& result) const override; virtual bool setPrototype(JSContext* cx, HandleObject proxy, HandleObject proto, ObjectOpResult& result) const override; virtual bool setImmutablePrototype(JSContext* cx, HandleObject proxy, bool* succeeded) const override; virtual bool nativeCall(JSContext* cx, IsAcceptableThis test, NativeImpl impl, const CallArgs& args) const override; virtual bool getBuiltinClass(JSContext* cx, HandleObject wrapper, ESClass* cls) const override; virtual bool isArray(JSContext* cx, HandleObject wrapper, JS::IsArrayAnswer* answer) const override; virtual bool regexp_toShared(JSContext* cx, HandleObject proxy, RegExpGuard* g) const override; virtual bool boxedValue_unbox(JSContext* cx, HandleObject proxy, MutableHandleValue vp) const override; // Allow isCallable and isConstructor. They used to be class-level, and so could not be guarded // against. virtual bool watch(JSContext* cx, JS::HandleObject proxy, JS::HandleId id, JS::HandleObject callable) const override; virtual bool unwatch(JSContext* cx, JS::HandleObject proxy, JS::HandleId id) const override; /* * Allow our subclasses to select the superclass behavior they want without * needing to specify an exact superclass. */ typedef Base Permissive; typedef SecurityWrapper<Base> Restrictive; }; typedef SecurityWrapper<CrossCompartmentWrapper> CrossCompartmentSecurityWrapper; extern JSObject* TransparentObjectWrapper(JSContext* cx, HandleObject existing, HandleObject obj); inline bool IsWrapper(JSObject* obj) { return IsProxy(obj) && GetProxyHandler(obj)->family() == &Wrapper::family; } // Given a JSObject, returns that object stripped of wrappers. If // stopAtWindowProxy is true, then this returns the WindowProxy if it was // previously wrapped. Otherwise, this returns the first object for // which JSObject::isWrapper returns false. JS_FRIEND_API(JSObject*) UncheckedUnwrap(JSObject* obj, bool stopAtWindowProxy = true, unsigned* flagsp = nullptr); // Given a JSObject, returns that object stripped of wrappers. At each stage, // the security wrapper has the opportunity to veto the unwrap. If // stopAtWindowProxy is true, then this returns the WindowProxy if it was // previously wrapped. JS_FRIEND_API(JSObject*) CheckedUnwrap(JSObject* obj, bool stopAtWindowProxy = true); // Unwrap only the outermost security wrapper, with the same semantics as // above. This is the checked version of Wrapper::wrappedObject. JS_FRIEND_API(JSObject*) UnwrapOneChecked(JSObject* obj, bool stopAtWindowProxy = true); JS_FRIEND_API(bool) IsCrossCompartmentWrapper(JSObject* obj); void NukeCrossCompartmentWrapper(JSContext* cx, JSObject* wrapper); void RemapWrapper(JSContext* cx, JSObject* wobj, JSObject* newTarget); JS_FRIEND_API(bool) RemapAllWrappersForObject(JSContext* cx, JSObject* oldTarget, JSObject* newTarget); // API to recompute all cross-compartment wrappers whose source and target // match the given filters. JS_FRIEND_API(bool) RecomputeWrappers(JSContext* cx, const CompartmentFilter& sourceFilter, const CompartmentFilter& targetFilter); } /* namespace js */ #endif /* jswrapper_h */
1
0.890438
1
0.890438
game-dev
MEDIA
0.453127
game-dev
0.648361
1
0.648361
NetHack/NetHack
136,500
src/insight.c
/* NetHack 3.7 insight.c $NHDT-Date: 1737384766 2025/01/20 06:52:46 $ $NHDT-Branch: NetHack-3.7 $:$NHDT-Revision: 1.128 $ */ /* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985. */ /* NetHack may be freely redistributed. See license for details. */ /* * Enlightenment and Conduct+Achievements and Vanquished+Extinct+Geno'd * and stethoscope/probing feedback. * * Most code used to reside in cmd.c, presumably because ^X was originally * a wizard mode command and the majority of those are in that file. * Some came from end.c where it is used during end of game disclosure. * And some came from priest.c that had once been in pline.c. */ #include "hack.h" staticfn void enlght_out(const char *); staticfn void enlght_line(const char *, const char *, const char *, const char *); staticfn char *enlght_combatinc(const char *, int, int, char *); staticfn void enlght_halfdmg(int, int); staticfn boolean walking_on_water(void); staticfn boolean cause_known(int); staticfn char *attrval(int, int, char *); staticfn char *fmt_elapsed_time(char *, int); staticfn void background_enlightenment(int, int); staticfn void basics_enlightenment(int, int); staticfn void characteristics_enlightenment(int, int); staticfn void one_characteristic(int, int, int); staticfn void status_enlightenment(int, int); staticfn void weapon_insight(int); staticfn void attributes_enlightenment(int, int); staticfn void show_achievements(int); staticfn int QSORTCALLBACK vanqsort_cmp(const genericptr, const genericptr); staticfn int num_extinct(void); staticfn int num_gone(int, int *); staticfn char *size_str(int); staticfn void item_resistance_message(int, const char *, int); extern const char *const hu_stat[]; /* hunger status from eat.c */ extern const char *const enc_stat[]; /* encumbrance status from botl.c */ static const char You_[] = "You ", are[] = "are ", were[] = "were ", have[] = "have ", had[] = "had ", can[] = "can ", could[] = "could "; static const char have_been[] = "have been ", have_never[] = "have never ", never[] = "never "; /* for livelogging: */ struct ll_achieve_msg { long llflag; const char *msg; }; /* ordered per 'enum achievements' in you.h */ /* take care to keep them in sync! */ static struct ll_achieve_msg achieve_msg [] = { { 0, "" }, /* actual achievements are numbered from 1 */ { LL_ACHIEVE, "acquired the Bell of Opening" }, { LL_ACHIEVE, "entered Gehennom" }, { LL_ACHIEVE, "acquired the Candelabrum of Invocation" }, { LL_ACHIEVE, "acquired the Book of the Dead" }, { LL_ACHIEVE, "performed the invocation" }, { LL_ACHIEVE, "acquired The Amulet of Yendor" }, { LL_ACHIEVE, "entered the Elemental Planes" }, { LL_ACHIEVE, "entered the Astral Plane" }, { LL_ACHIEVE, "ascended" }, /* if the type of item isn't discovered yet, disclosing the event via #chronicle would be a spoiler (particularly for gray stone); the ID'd name for the type of item will be appended to the next two messages, for display via livelog and/or dumplog */ { LL_ACHIEVE | LL_SPOILER, "acquired the Mines' End" }, /* " luckstone" */ { LL_ACHIEVE | LL_SPOILER, "acquired the Sokoban" }, /* " <item>" */ { LL_ACHIEVE | LL_UMONST, "killed Medusa" }, /* these two are not logged */ { 0, "hero was always blond, no, blind" }, { 0, "hero never wore armor" }, /* */ { LL_MINORAC | LL_DUMP, "entered the Gnomish Mines" }, { LL_ACHIEVE, "reached Mine Town" }, /* probably minor, but dnh logs it */ { LL_MINORAC, "entered a shop" }, { LL_MINORAC, "entered a temple" }, { LL_ACHIEVE, "consulted the Oracle" }, /* minor, but rare enough */ { LL_MINORAC | LL_DUMP, "read a Discworld novel" }, /* even more so */ { LL_ACHIEVE, "entered Sokoban" }, /* keep as major for turn comparison * with completed sokoban */ { LL_ACHIEVE, "entered the Bigroom" }, /* The following 8 are for advancing through the ranks and messages differ by role so are created on the fly; rank 0 (Xp 1 and 2) isn't an achievement */ { LL_MINORAC | LL_DUMP, "" }, /* Xp 3 */ { LL_MINORAC | LL_DUMP, "" }, /* Xp 6 */ { LL_MINORAC | LL_DUMP, "" }, /* Xp 10 */ { LL_ACHIEVE, "" }, /* Xp 14, so able to attempt the quest */ { LL_ACHIEVE, "" }, /* Xp 18 */ { LL_ACHIEVE, "" }, /* Xp 22 */ { LL_ACHIEVE, "" }, /* Xp 26 */ { LL_ACHIEVE, "" }, /* Xp 30 */ { LL_MINORAC, "learned castle drawbridge's tune" }, /* achievement #31 */ { 0, "" } /* keep this one at the end */ }; /* macros to simplify output of enlightenment messages; also used by conduct and achievements */ #define enl_msg(prefix, present, past, suffix, ps) \ enlght_line((prefix), final ? (past) : (present), (suffix), (ps)) #define you_are(attr, ps) enl_msg(You_, are, were, (attr), (ps)) #define you_have(attr, ps) enl_msg(You_, have, had, (attr), (ps)) #define you_can(attr, ps) enl_msg(You_, can, could, (attr), (ps)) #define you_have_been(goodthing) \ enl_msg(You_, have_been, were, (goodthing), "") #define you_have_never(badthing) \ enl_msg(You_, have_never, never, (badthing), "") #define you_have_X(something) \ enl_msg(You_, have, (const char *) "", (something), "") staticfn void enlght_out(const char *buf) { if (ge.en_via_menu) { add_menu_str(ge.en_win, buf); } else putstr(ge.en_win, 0, buf); } staticfn void enlght_line( const char *start, const char *middle, const char *end, const char *ps) { #ifndef NO_ENLGHT_CONTRACTIONS static const struct contrctn { const char *twowords, *contrctn; } contra[] = { { " are not ", " aren't " }, { " were not ", " weren't " }, { " have not ", " haven't " }, { " had not ", " hadn't " }, { " can not ", " can't " }, { " could not ", " couldn't " }, }; int i; #endif char buf[BUFSZ]; Sprintf(buf, " %s%s%s%s.", start, middle, end, ps); #ifndef NO_ENLGHT_CONTRACTIONS if (strstri(buf, " not ")) { /* TODO: switch to libc strstr() */ for (i = 0; i < SIZE(contra); ++i) (void) strsubst(buf, contra[i].twowords, contra[i].contrctn); } #endif enlght_out(buf); } /* format increased chance to hit or damage or defense (Protection) */ staticfn char * enlght_combatinc( const char *inctyp, /* "to hit" or "damage" or "defense" */ int incamt, /* amount of increment (negative if decrement) */ int final, /* ENL_{GAMEINPROGRESS,GAMEOVERALIVE,GAMEOVERDEAD} */ char *outbuf) { const char *modif, *bonus; boolean invrt; int absamt; absamt = abs(incamt); /* Protection amount is typically larger than damage or to-hit; reduce magnitude by a third in order to stretch modifier ranges (small:1..5, moderate:6..10, large:11..19, huge:20+) */ if (!strcmp(inctyp, "defense")) absamt = (absamt * 2) / 3; if (absamt <= 3) modif = "small"; else if (absamt <= 6) modif = "moderate"; else if (absamt <= 12) modif = "large"; else modif = "huge"; modif = !incamt ? "no" : an(modif); /* ("no" case shouldn't happen) */ bonus = (incamt >= 0) ? "bonus" : "penalty"; /* "bonus <foo>" (to hit) vs "<bar> bonus" (damage, defense) */ invrt = strcmp(inctyp, "to hit") ? TRUE : FALSE; Sprintf(outbuf, "%s %s %s", modif, invrt ? inctyp : bonus, invrt ? bonus : inctyp); if (final || wizard) Sprintf(eos(outbuf), " (%s%d)", (incamt > 0) ? "+" : "", incamt); return outbuf; } /* report half physical or half spell damage */ staticfn void enlght_halfdmg(int category, int final) { const char *category_name; char buf[BUFSZ]; switch (category) { case HALF_PHDAM: category_name = "physical"; break; case HALF_SPDAM: category_name = "spell"; break; default: category_name = "unknown"; break; } Sprintf(buf, " %s %s damage", (final || wizard) ? "half" : "reduced", category_name); enl_msg(You_, "take", "took", buf, from_what(category)); } /* is hero actively using water walking capability on water (or lava)? */ staticfn boolean walking_on_water(void) { if (u.uinwater || Levitation || Flying) return FALSE; return (boolean) (Wwalking && is_pool_or_lava(u.ux, u.uy)); } /* describe u.utraptype; used by status_enlightenment() and self_lookat() */ char * trap_predicament(char *outbuf, int final, boolean wizxtra) { struct trap *t; /* caller has verified u.utrap */ *outbuf = '\0'; switch (u.utraptype) { case TT_BURIEDBALL: Strcpy(outbuf, "tethered to something buried"); break; case TT_LAVA: Sprintf(outbuf, "sinking into %s", final ? "lava" : hliquid("lava")); break; case TT_INFLOOR: Sprintf(outbuf, "stuck in %s", the(surface(u.ux, u.uy))); break; default: /* TT_BEARTRAP, TT_PIT, or TT_WEB */ Strcpy(outbuf, "trapped"); if ((t = t_at(u.ux, u.uy)) != 0) /* should never be null */ Sprintf(eos(outbuf), " in %s", an(trapname(t->ttyp, FALSE))); break; } if (wizxtra) { /* give extra information for wizard mode enlightenment */ /* curly braces: u.utrap is an escape attempt counter rather than a turn timer so use different ornamentation than usual parentheses */ Sprintf(eos(outbuf), " {%u}", u.utrap); } return outbuf; } /* check whether hero is wearing something that player definitely knows confers the target property; item must have been seen and its type discovered but it doesn't necessarily have to be fully identified */ staticfn boolean cause_known( int propindx) /* index of a property which can be conveyed by worn item */ { struct obj *o; long mask = W_ARMOR | W_AMUL | W_RING | W_TOOL; /* simpler than from_what()/what_gives(); we don't attempt to handle artifacts and we deliberately ignore wielded items */ for (o = gi.invent; o; o = o->nobj) { if (!(o->owornmask & mask)) continue; if ((int) objects[o->otyp].oc_oprop == propindx && objects[o->otyp].oc_name_known && o->dknown) return TRUE; } return FALSE; } /* format a characteristic value, accommodating Strength's strangeness */ staticfn char * attrval( int attrindx, int attrvalue, char resultbuf[]) /* should be at least [7] to hold "18/100\0" */ { if (attrindx != A_STR || attrvalue <= 18) Sprintf(resultbuf, "%d", attrvalue); else if (attrvalue > STR18(100)) /* 19 to 25 */ Sprintf(resultbuf, "%d", attrvalue - 100); else /* simplify "18/\**" to be "18/100" */ Sprintf(resultbuf, "18/%02d", attrvalue - 18); return resultbuf; } /* format urealtime.realtime as " D days, H hours, M minutes and S seconds" with any fields having a value of 0 omitted: 0-00:00:20 => " 20 seconds" 0-00:15:05 => " 15 minutes and 5 seconds" 0-00:16:00 => " 16 minutes" 0-01:15:10 => " 1 hour, 15 minutes and 10 seconds" 0-02:00:01 => " 2 hours and 1 second" 3-00:25:40 => " 3 days, 25 minutes and 40 seconds" (note: for a list of more than two entries, nethack usually includes the [style-wise] optional comma before "and" but in this instance it does not) */ staticfn char * fmt_elapsed_time(char *outbuf, int final) { int fieldcnt; long edays, ehours, eminutes, eseconds; /* for a game that's over, reallydone() has updated urealtime.realtime to its final value before calling us during end of game disclosure; for a game that's still in progress, it holds the amount of elapsed game time from previous sessions up through most recent save/restore (or up through latest level change when 'checkpoint' is On); '.start_timing' has a non-zero value even if '.realtime' is 0 */ long etim = urealtime.realtime; if (!final) etim += timet_delta(getnow(), urealtime.start_timing); /* we could use localtime() to convert the value into a 'struct tm' to get date and time fields but this is simple and straightforward */ eseconds = etim % 60L, etim /= 60L; eminutes = etim % 60L, etim /= 60L; ehours = etim % 24L; edays = etim / 24L; fieldcnt = !!edays + !!ehours + !!eminutes + !!eseconds; Strcpy(outbuf, fieldcnt ? "" : " none"); /* 'none' should never happen */ if (edays) { Sprintf(eos(outbuf), " %ld day%s", edays, plur(edays)); if (fieldcnt > 1) /* hours and/or minutes and/or seconds to follow */ Strcat(outbuf, (fieldcnt == 2) ? " and" : ","); --fieldcnt; /* edays has been processed */ } if (ehours) { Sprintf(eos(outbuf), " %ld hour%s", ehours, plur(ehours)); if (fieldcnt > 1) /* minutes and/or seconds to follow */ Strcat(outbuf, (fieldcnt == 2) ? " and" : ","); --fieldcnt; /* ehours has been processed */ } if (eminutes) { Sprintf(eos(outbuf), " %ld minute%s", eminutes, plur(eminutes)); if (fieldcnt > 1) /* seconds to follow */ Strcat(outbuf, " and"); /* eminutes has been processed but no need to decrement fieldcnt */ } if (eseconds) Sprintf(eos(outbuf), " %ld second%s", eseconds, plur(eseconds)); return outbuf; } void enlightenment( int mode, /* BASICENLIGHTENMENT | MAGICENLIGHTENMENT (| both) */ int final) /* ENL_GAMEINPROGRESS:0, ENL_GAMEOVERALIVE, ENL_GAMEOVERDEAD */ { char buf[BUFSZ], tmpbuf[BUFSZ]; ge.en_win = create_nhwindow(NHW_MENU); ge.en_via_menu = !final; if (ge.en_via_menu) start_menu(ge.en_win, MENU_BEHAVE_STANDARD); Strcpy(tmpbuf, svp.plname); *tmpbuf = highc(*tmpbuf); /* same adjustment as bottom line */ /* as in background_enlightenment, when poly'd we need to use the saved gender in u.mfemale rather than the current you-as-monster gender */ Snprintf(buf, sizeof(buf), "%s the %s's attributes:", tmpbuf, ((Upolyd ? u.mfemale : flags.female) && gu.urole.name.f) ? gu.urole.name.f : gu.urole.name.m); /* title */ enlght_out(buf); /* "Conan the Archeologist's attributes:" */ /* background and characteristics; ^X or end-of-game disclosure */ if (mode & BASICENLIGHTENMENT) { /* role, race, alignment, deities, dungeon level, time, experience */ background_enlightenment(mode, final); /* hit points, energy points, armor class, gold */ basics_enlightenment(mode, final); /* strength, dexterity, &c */ characteristics_enlightenment(mode, final); } /* expanded status line information, including things which aren't included there due to space considerations; shown for both basic and magic enlightenment */ status_enlightenment(mode, final); /* remaining attributes; shown for potion,&c or wizard mode and explore mode ^X or end of game disclosure */ if (mode & MAGICENLIGHTENMENT) { /* intrinsics and other traditional enlightenment feedback */ attributes_enlightenment(mode, final); } enlght_out(""); /* separator */ enlght_out("Miscellaneous:"); /* reminder to player and/or information for dumplog */ if ((mode & BASICENLIGHTENMENT) != 0 && (wizard || discover || final)) { if (wizard || discover) { Sprintf(buf, "running in %s mode", wizard ? "debug" : "explore"); you_are(buf, ""); } if (!flags.bones) { /* mention not saving bones iff hero just died */ Sprintf(buf, "disabled loading%s of bones levels", (final == ENL_GAMEOVERDEAD) ? " and storing" : ""); you_have_X(buf); } else if (!u.uroleplay.numbones) { enl_msg(You_, "haven't encountered", "didn't encounter", " any bones levels", ""); } else { Sprintf(buf, "encountered %ld bones level%s", u.uroleplay.numbones, plur(u.uroleplay.numbones)); you_have_X(buf); } } (void) fmt_elapsed_time(buf, final); enl_msg("Total elapsed playing time ", "is", "was", buf, ""); if (!ge.en_via_menu) { display_nhwindow(ge.en_win, TRUE); } else { menu_item *selected = 0; end_menu(ge.en_win, (char *) 0); if (select_menu(ge.en_win, PICK_NONE, &selected) > 0) free((genericptr_t) selected); ge.en_via_menu = FALSE; } destroy_nhwindow(ge.en_win); ge.en_win = WIN_ERR; } /*ARGSUSED*/ /* display role, race, alignment and such to en_win */ staticfn void background_enlightenment(int unused_mode UNUSED, int final) { const char *role_titl, *rank_titl; int innategend, difgend, difalgn; char buf[BUFSZ], tmpbuf[BUFSZ]; /* note that if poly'd, we need to use u.mfemale instead of flags.female to access hero's saved gender-as-human/elf/&c rather than current */ innategend = (Upolyd ? u.mfemale : flags.female) ? 1 : 0; role_titl = (innategend && gu.urole.name.f) ? gu.urole.name.f : gu.urole.name.m; rank_titl = rank_of(u.ulevel, Role_switch, innategend); enlght_out(""); /* separator after title */ enlght_out("Background:"); /* if polymorphed, report current shape before underlying role; will be repeated as first status: "you are transformed" and also among various attributes: "you are in beast form" (after being told about lycanthropy) or "you are polymorphed into <a foo>" (with countdown timer appended for wizard mode); we really want the player to know he's not a samurai at the moment... */ if (Upolyd) { char anbuf[20]; /* includes trailing space; [4] suffices */ struct permonst *uasmon = gy.youmonst.data; boolean altphrasing = vampshifted(&gy.youmonst); tmpbuf[0] = '\0'; /* here we always use current gender, not saved role gender */ if (!is_male(uasmon) && !is_female(uasmon) && !is_neuter(uasmon)) Sprintf(tmpbuf, "%s ", genders[flags.female ? 1 : 0].adj); if (altphrasing) Sprintf(eos(tmpbuf), "%s in ", pmname(&mons[gy.youmonst.cham], flags.female ? FEMALE : MALE)); Snprintf(buf, sizeof(buf), "%s%s%s%s form", !final ? "currently " : "", altphrasing ? just_an(anbuf, tmpbuf) : "in ", tmpbuf, pmname(uasmon, flags.female ? FEMALE : MALE)); you_are(buf, ""); } /* report role; omit gender if it's redundant (eg, "female priestess") */ tmpbuf[0] = '\0'; if (!gu.urole.name.f && ((gu.urole.allow & ROLE_GENDMASK) == (ROLE_MALE | ROLE_FEMALE) || innategend != flags.initgend)) Sprintf(tmpbuf, "%s ", genders[innategend].adj); buf[0] = '\0'; if (Upolyd) Strcpy(buf, "actually "); /* "You are actually a ..." */ if (!strcmpi(rank_titl, role_titl)) { /* omit role when rank title matches it */ Sprintf(eos(buf), "%s, level %d %s%s", an(rank_titl), u.ulevel, tmpbuf, gu.urace.noun); } else { Sprintf(eos(buf), "%s, a level %d %s%s %s", an(rank_titl), u.ulevel, tmpbuf, gu.urace.adj, role_titl); } you_are(buf, ""); /* report alignment (bypass you_are() in order to omit ending period); adverb is used to distinguish between temporary change (helm of opp. alignment), permanent change (one-time conversion), and original */ Sprintf(buf, " %s%s%s, %son a mission for %s", You_, !final ? are : were, align_str(u.ualign.type), /* helm of opposite alignment (might hide conversion) */ (u.ualign.type != u.ualignbase[A_CURRENT]) /* what's the past tense of "currently"? if we used "formerly" it would sound like a reference to the original alignment */ ? (!final ? "currently " : "temporarily ") /* permanent conversion */ : (u.ualign.type != u.ualignbase[A_ORIGINAL]) /* and what's the past tense of "now"? certainly not "then" in a context like this...; "belatedly" == weren't that way sooner (in other words, didn't start that way) */ ? (!final ? "now " : "belatedly ") /* atheist (ignored in very early game) */ : (!u.uconduct.gnostic && svm.moves > 1000L) ? "nominally " /* lastly, normal case */ : "", u_gname()); enlght_out(buf); /* show the rest of this game's pantheon (finishes previous sentence) [appending "also Moloch" at the end would allow for straightforward trailing "and" on all three aligned entries but looks too verbose] */ Sprintf(buf, " who %s opposed by", !final ? "is" : "was"); if (u.ualign.type != A_LAWFUL) Sprintf(eos(buf), " %s (%s) and", align_gname(A_LAWFUL), align_str(A_LAWFUL)); if (u.ualign.type != A_NEUTRAL) Sprintf(eos(buf), " %s (%s)%s", align_gname(A_NEUTRAL), align_str(A_NEUTRAL), (u.ualign.type != A_CHAOTIC) ? " and" : ""); if (u.ualign.type != A_CHAOTIC) Sprintf(eos(buf), " %s (%s)", align_gname(A_CHAOTIC), align_str(A_CHAOTIC)); Strcat(buf, "."); /* terminate sentence */ enlght_out(buf); /* show original alignment,gender,race,role if any have been changed; giving separate message for temporary alignment change bypasses need for tricky phrasing otherwise necessitated by possibility of having helm of opposite alignment mask a permanent alignment conversion */ difgend = (innategend != flags.initgend); difalgn = (((u.ualign.type != u.ualignbase[A_CURRENT]) ? 1 : 0) + ((u.ualignbase[A_CURRENT] != u.ualignbase[A_ORIGINAL]) ? 2 : 0)); if (difalgn & 1) { /* have temporary alignment so report permanent one */ Sprintf(buf, "actually %s", align_str(u.ualignbase[A_CURRENT])); you_are(buf, ""); difalgn &= ~1; /* suppress helm from "started out <foo>" message */ } if (difgend || difalgn) { /* sex change or perm align change or both */ Sprintf(buf, " You started out %s%s%s.", difgend ? genders[flags.initgend].adj : "", (difgend && difalgn) ? " and " : "", difalgn ? align_str(u.ualignbase[A_ORIGINAL]) : ""); enlght_out(buf); } /* "You are left-handed." won't work well if polymorphed into something without hands; use "You are normally left-handed." in that situation */ Sprintf(buf, "%s%s-handed", !strcmp(body_part(HANDED), "handed") ? "" : "normally ", URIGHTY ? "right" : "left"); you_are(buf, ""); /* As of 3.6.2: dungeon level, so that ^X really has all status info as claimed by the comment below; this reveals more information than the basic status display, but that's one of the purposes of ^X; similar information is revealed by #overview; the "You died in <location>" given by really_done() is more rudimentary than this */ *buf = *tmpbuf = '\0'; if (In_endgame(&u.uz)) { int egdepth = observable_depth(&u.uz); (void) endgamelevelname(tmpbuf, egdepth); Snprintf(buf, sizeof(buf), "in the endgame, on the %s%s", !strncmp(tmpbuf, "Plane", 5) ? "Elemental " : "", tmpbuf); } else if (Is_knox(&u.uz)) { /* this gives away the fact that the knox branch is only 1 level */ Sprintf(buf, "on the %s level", svd.dungeons[u.uz.dnum].dname); /* TODO? maybe phrase it differently when actually inside the fort, if we're able to determine that (not trivial) */ } else { char dgnbuf[QBUFSZ]; Strcpy(dgnbuf, svd.dungeons[u.uz.dnum].dname); if (!strncmpi(dgnbuf, "The ", 4)) *dgnbuf = lowc(*dgnbuf); Sprintf(tmpbuf, "level %d", In_quest(&u.uz) ? dunlev(&u.uz) : depth(&u.uz)); /* TODO? maybe extend this bit to include various other automatic annotations from the dungeon overview code */ if (Is_rogue_level(&u.uz)) Strcat(tmpbuf, ", a primitive area"); else if (Is_bigroom(&u.uz) && !Blind) Strcat(tmpbuf, ", a very big room"); Snprintf(buf, sizeof(buf), "in %s, on %s", dgnbuf, tmpbuf); } you_are(buf, ""); /* this is shown even if the 'time' option is off */ if (svm.moves == 1L) { you_have("just started your adventure", ""); } else { /* 'turns' grates on the nerves in this context... */ Sprintf(buf, "the dungeon %ld turn%s ago", svm.moves, plur(svm.moves)); /* same phrasing for current and final: "entered" is unconditional */ enlght_line(You_, "entered ", buf, ""); } /* for gameover, these have been obtained in really_done() so that they won't vary if user leaves a disclosure prompt or --More-- unanswered long enough for the dynamic value to change between then and now */ if (final ? iflags.at_midnight : midnight()) { enl_msg("It ", "is ", "was ", "the midnight hour", ""); } else if (final ? iflags.at_night : night()) { enl_msg("It ", "is ", "was ", "nighttime", ""); } /* other environmental factors */ if (flags.moonphase == FULL_MOON || flags.moonphase == NEW_MOON) { /* [This had "tonight" but has been changed to "in effect". There is a similar issue to Friday the 13th--it's the value at the start of the current session but that session might have dragged on for an arbitrary amount of time. We want to report the values that currently affect play--or affected play when game ended--rather than actual outside situation.] */ Sprintf(buf, "a %s moon in effect%s", (flags.moonphase == FULL_MOON) ? "full" : (flags.moonphase == NEW_MOON) ? "new" /* showing these would probably just lead to confusion since they have no effect on game play... */ : (flags.moonphase < FULL_MOON) ? "first quarter" : "last quarter", /* we don't have access to 'how' here--aside from survived vs died--so settle for general platitude */ final ? " when your adventure ended" : ""); enl_msg("There ", "is ", "was ", buf, ""); } if (flags.friday13) { /* let player know that friday13 penalty is/was in effect; we don't say "it is/was Friday the 13th" because that was at the start of the session and it might be past midnight (or days later if the game has been paused without save/restore), so phrase this similar to the start up message */ Sprintf(buf, " Bad things %s on Friday the 13th.", !final ? "can happen" : (final == ENL_GAMEOVERALIVE) ? "could have happened" /* there's no may to tell whether -1 Luck made a difference but hero has died... */ : "happened"); enlght_out(buf); } if (!Upolyd) { int ulvl = (int) u.ulevel; /* [flags.showexp currently does not matter; should it?] */ /* experience level is already shown above */ Sprintf(buf, "%-1ld experience point%s", u.uexp, plur(u.uexp)); /* TODO? * Remove wizard-mode restriction since patient players can * determine the numbers needed without resorting to spoilers * (even before this started being disclosed for 'final'; * just enable 'showexp' and look at normal status lines * after drinking gain level potions or eating wraith corpses * or being level-drained by vampires). */ if (ulvl < 30 && (final || wizard)) { long nxtlvl = newuexp(ulvl), delta = nxtlvl - u.uexp; Sprintf(eos(buf), ", %ld %s%sneeded %s level %d", delta, (u.uexp > 0) ? "more " : "", /* present tense=="needed", past tense=="were needed" */ !final ? "" : (delta == 1L) ? "was " : "were ", /* "for": grammatically iffy but less likely to wrap */ (ulvl < 18) ? "to attain" : "for", (ulvl + 1)); } you_have(buf, ""); } #ifdef SCORE_ON_BOTL if (flags.showscore) { /* describes what's shown on status line, which is an approximation; only show it here if player has the 'showscore' option enabled */ Sprintf(buf, "%ld%s", botl_score(), !final ? "" : " before end-of-game adjustments"); enl_msg("Your score ", "is ", "was ", buf, ""); } #endif } /* hit points, energy points, armor class -- essential information which doesn't fit very well in other categories */ /*ARGSUSED*/ staticfn void basics_enlightenment(int mode UNUSED, int final) { static char Power[] = "energy points (spell power)"; char buf[BUFSZ]; int pw = u.uen, hp = (Upolyd ? u.mh : u.uhp), pwmax = u.uenmax, hpmax = (Upolyd ? u.mhmax : u.uhpmax); enlght_out(""); /* separator after background */ enlght_out("Basics:"); if (hp < 0) hp = 0; /* "1 out of 1" rather than "all" if max is only 1; should never happen */ if (hp == hpmax && hpmax > 1) Sprintf(buf, "all %d hit points", hpmax); else Sprintf(buf, "%d out of %d hit point%s", hp, hpmax, plur(hpmax)); you_have(buf, ""); /* low max energy is feasible, so handle couple of extra special cases */ if (pwmax == 0 || (pw == pwmax && pwmax == 2)) /* both: not "all 2" */ Sprintf(buf, "%s %s", !pwmax ? "no" : "both", Power); else if (pw == pwmax && pwmax > 2) Sprintf(buf, "all %d %s", pwmax, Power); else Sprintf(buf, "%d out of %d %s", pw, pwmax, Power); you_have(buf, ""); if (Upolyd) { switch (mons[u.umonnum].mlevel) { case 0: /* status line currently being explained shows "HD:0" */ Strcpy(buf, "0 hit dice (actually 1/2)"); break; case 1: Strcpy(buf, "1 hit die"); break; default: Sprintf(buf, "%d hit dice", mons[u.umonnum].mlevel); break; } you_have(buf, ""); } find_ac(); /* enforces AC_MAX cap */ Sprintf(buf, "%d", u.uac); if (abs(u.uac) == AC_MAX) Sprintf(eos(buf), ", the %s possible", (u.uac < 0) ? "best" : "worst"); enl_msg("Your armor class ", "is ", "was ", buf, ""); /* gold; similar to doprgold (#showgold) but without shop billing info; includes container contents, unlike status line but like doprgold */ { long umoney = money_cnt(gi.invent), hmoney = hidden_gold(final); if (!umoney) { Sprintf(buf, " Your wallet %s empty", !final ? "is" : "was"); } else { Sprintf(buf, " Your wallet contain%s %ld %s", !final ? "s" : "ed", umoney, currency(umoney)); } /* terminate the wallet line if appropriate, otherwise add an introduction to subsequent continuation; output now either way */ Strcat(buf, !hmoney ? "." : !umoney ? ", but" : ", and"); enlght_out(buf); /* put contained gold on its own line to avoid excessive width; it's phrased as a continuation of the wallet line so not capitalized */ if (hmoney) { Sprintf(buf, "%ld %s stashed away in your pack", hmoney, umoney ? "more" : currency(hmoney)); enl_msg("you ", "have ", "had ", buf, ""); } } if (flags.pickup) { char ocl[MAXOCLASSES + 1]; Strcpy(buf, "on"); if (costly_spot(u.ux, u.uy)) { /* being in a shop inhibits autopickup, even 'pickup_thrown' */ Strcat(buf, ", but temporarily disabled while inside the shop"); } else { oc_to_str(flags.pickup_types, ocl); Sprintf(eos(buf), " for %s%s%s", *ocl ? "'" : "", *ocl ? ocl : "all types", *ocl ? "'" : ""); if (flags.pickup_thrown && *ocl) Strcat(buf, " plus thrown"); /* show when not 'all types' */ if (ga.apelist) Strcat(buf, ", with exceptions"); } } else Strcpy(buf, "off"); enl_msg("Autopickup ", "is ", "was ", buf, ""); } /* characteristics: expanded version of bottom line strength, dexterity, &c */ staticfn void characteristics_enlightenment(int mode, int final) { char buf[BUFSZ]; enlght_out(""); Sprintf(buf, "%sCharacteristics:", !final ? "" : "Final "); enlght_out(buf); /* bottom line order */ one_characteristic(mode, final, A_STR); /* strength */ one_characteristic(mode, final, A_DEX); /* dexterity */ one_characteristic(mode, final, A_CON); /* constitution */ one_characteristic(mode, final, A_INT); /* intelligence */ one_characteristic(mode, final, A_WIS); /* wisdom */ one_characteristic(mode, final, A_CHA); /* charisma */ } /* display one attribute value for characteristics_enlightenment() */ staticfn void one_characteristic(int mode, int final, int attrindx) { extern const char *const attrname[]; /* attrib.c */ boolean hide_innate_value = FALSE, interesting_alimit; int acurrent, abase, apeak, alimit; const char *paren_pfx; char subjbuf[BUFSZ], valubuf[BUFSZ], valstring[32]; /* being polymorphed or wearing certain cursed items prevents hero from reliably tracking changes to characteristics so we don't show base & peak values then; when the items aren't cursed, hero could take them off to check underlying values and we show those in such case so that player doesn't need to actually resort to doing that */ if (Upolyd) { hide_innate_value = TRUE; } else if (Fixed_abil) { if (stuck_ring(uleft, RIN_SUSTAIN_ABILITY) || stuck_ring(uright, RIN_SUSTAIN_ABILITY)) hide_innate_value = TRUE; } switch (attrindx) { case A_STR: if (uarmg && uarmg->otyp == GAUNTLETS_OF_POWER && uarmg->cursed) hide_innate_value = TRUE; break; case A_DEX: break; case A_CON: if (u_wield_art(ART_OGRESMASHER) && uwep->cursed) hide_innate_value = TRUE; break; case A_INT: if (uarmh && uarmh->otyp == DUNCE_CAP && uarmh->cursed) hide_innate_value = TRUE; break; case A_WIS: if (uarmh && uarmh->otyp == DUNCE_CAP && uarmh->cursed) hide_innate_value = TRUE; break; case A_CHA: break; default: return; /* impossible */ }; /* note: final disclosure includes MAGICENLIGHTENTMENT */ if ((mode & MAGICENLIGHTENMENT) && !Upolyd) hide_innate_value = FALSE; acurrent = ACURR(attrindx); (void) attrval(attrindx, acurrent, valubuf); /* Sprintf(valubuf,"%d",) */ Sprintf(subjbuf, "Your %s ", attrname[attrindx]); if (!hide_innate_value) { /* show abase, amax, and/or attrmax if acurr doesn't match abase (a magic bonus or penalty is in effect) or abase doesn't match amax (some points have been lost to poison or exercise abuse and are restorable) or attrmax is different from normal human (while game is in progress; trying to reduce dependency on spoilers to keep track of such stuff) or attrmax was different from abase (at end of game; this attribute wasn't maxed out) */ abase = ABASE(attrindx); apeak = AMAX(attrindx); alimit = ATTRMAX(attrindx); /* criterium for whether the limit is interesting varies */ interesting_alimit = final ? TRUE /* was originally `(abase != alimit)' */ : (alimit != (attrindx != A_STR ? 18 : STR18(100))); paren_pfx = final ? " (" : " (current; "; if (acurrent != abase) { Sprintf(eos(valubuf), "%sbase:%s", paren_pfx, attrval(attrindx, abase, valstring)); paren_pfx = ", "; } if (abase != apeak) { Sprintf(eos(valubuf), "%speak:%s", paren_pfx, attrval(attrindx, apeak, valstring)); paren_pfx = ", "; } if (interesting_alimit) { Sprintf(eos(valubuf), "%s%slimit:%s", paren_pfx, /* more verbose if exceeding 'limit' due to magic bonus */ (acurrent > alimit) ? "innate " : "", attrval(attrindx, alimit, valstring)); /* paren_pfx = ", "; */ } if (acurrent != abase || abase != apeak || interesting_alimit) Strcat(valubuf, ")"); } enl_msg(subjbuf, "is ", "was ", valubuf, ""); } /* status: selected obvious capabilities, assorted troubles */ staticfn void status_enlightenment(int mode, int final) { boolean magic = (mode & MAGICENLIGHTENMENT) ? TRUE : FALSE; int cap; char buf[BUFSZ], youtoo[BUFSZ], heldmon[BUFSZ]; boolean Riding = (u.usteed /* if hero dies while dismounting, u.usteed will still be set; we want to ignore steed in that situation */ && !(final == ENL_GAMEOVERDEAD && !strcmp(svk.killer.name, "riding accident"))); const char *steedname = (!Riding ? (char *) 0 : x_monnam(u.usteed, u.usteed->mtame ? ARTICLE_YOUR : ARTICLE_THE, (char *) 0, (SUPPRESS_SADDLE | SUPPRESS_HALLUCINATION), FALSE)); /*\ * Status (many are abbreviated on bottom line; others are or * should be discernible to the hero hence to the player) \*/ enlght_out(""); /* separator after title or characteristics */ enlght_out(final ? "Final Status:" : "Status:"); Strcpy(youtoo, You_); /* not a traditional status but inherently obvious to player; more detail given below (attributes section) for magic enlightenment */ if (Upolyd) { Strcpy(buf, "transformed"); if (ugenocided()) Sprintf(eos(buf), " and %s %s inside", final ? "felt" : "feel", udeadinside()); you_are(buf, ""); } /* not a trouble, but we want to display riding status before maybe reporting steed as trapped or hero stuck to cursed saddle */ if (Riding) { Sprintf(buf, "riding %s", steedname); you_are(buf, ""); Sprintf(eos(youtoo), "and %s ", steedname); } /* other movement situations that hero should always know */ if (Levitation) { if (Lev_at_will && magic) you_are("levitating, at will", ""); else enl_msg(youtoo, are, were, "levitating", from_what(LEVITATION)); } else if (Flying) { /* can only fly when not levitating */ enl_msg(youtoo, are, were, "flying", from_what(FLYING)); } if (Underwater) { you_are("underwater", ""); } else if (u.uinwater) { you_are(Swimming ? "swimming" : "in water", from_what(SWIMMING)); } else if (walking_on_water()) { /* show active Wwalking here, potential Wwalking elsewhere */ Sprintf(buf, "walking on %s", is_pool(u.ux, u.uy) ? "water" : is_lava(u.ux, u.uy) ? "lava" : surface(u.ux, u.uy)); /* catchall; shouldn't happen */ you_are(buf, from_what(WWALKING)); } if (Upolyd && (u.uundetected || U_AP_TYPE != M_AP_NOTHING)) youhiding(TRUE, final); /* internal troubles, mostly in the order that prayer ranks them */ if (Stoned) { if (final && (Stoned & I_SPECIAL)) enlght_out(" You turned into stone."); else you_are("turning to stone", ""); } if (Slimed) { if (final && (Slimed & I_SPECIAL)) enlght_out(" You turned into slime."); else you_are("turning into slime", ""); } if (Strangled) { if (u.uburied) { you_are("buried", ""); } else { if (final && (Strangled & I_SPECIAL)) { enlght_out(" You died from strangulation."); } else { Strcpy(buf, "being strangled"); if (wizard) Sprintf(eos(buf), " (%ld)", (Strangled & TIMEOUT)); you_are(buf, from_what(STRANGLED)); } } } if (Sick) { /* the two types of sickness are lumped together; hero can be afflicted by both but there is only one timeout; botl status puts TermIll before FoodPois and death due to timeout reports terminal illness if both are in effect, so do the same here */ if (final && (Sick & I_SPECIAL)) { Sprintf(buf, " %sdied from %s.", You_, /* has trailing space */ (u.usick_type & SICK_NONVOMITABLE) ? "terminal illness" : "food poisoning"); enlght_out(buf); } else { /* unlike death due to sickness, report the two cases separately because it is possible to cure one without curing the other */ if (u.usick_type & SICK_NONVOMITABLE) you_are("terminally sick from illness", ""); if (u.usick_type & SICK_VOMITABLE) you_are("terminally sick from food poisoning", ""); } } if (Vomiting) you_are("nauseated", ""); if (Stunned) you_are("stunned", ""); if (Confusion) you_are("confused", ""); if (Hallucination) you_are("hallucinating", ""); if (Blind) { /* check the reasons in same order as from_what() */ Sprintf(buf, "%s blind", (HBlinded & FROMOUTSIDE) != 0L ? "permanently" : (HBlinded & FROMFORM) ? "innately" /* better phrasing desperately wanted... */ : Blindfolded_only ? "deliberately" /* timed, possibly combined with blindfold */ : "temporarily"); if (wizard && (HBlinded == BlindedTimeout && !Blindfolded)) Sprintf(eos(buf), " (%ld)", BlindedTimeout); /* !haseyes: avoid "you are innately blind innately" */ you_are(buf, !haseyes(gy.youmonst.data) ? "" : from_what(BLINDED)); } if (Deaf) you_are("deaf", from_what(DEAF)); /* external troubles, more or less */ if (Punished) { if (uball) { Sprintf(buf, "chained to %s", ansimpleoname(uball)); } else { impossible("Punished without uball?"); Strcpy(buf, "punished"); } you_are(buf, ""); } if (u.utrap) { char predicament[BUFSZ]; boolean anchored = (u.utraptype == TT_BURIEDBALL); (void) trap_predicament(predicament, final, wizard); if (u.usteed) { /* not `Riding' here */ Sprintf(buf, "%s%s ", anchored ? "you and " : "", steedname); *buf = highc(*buf); enl_msg(buf, (anchored ? "are " : "is "), (anchored ? "were " : "was "), predicament, ""); } else you_are(predicament, ""); } /* (u.utrap) */ heldmon[0] = '\0'; /* lint suppression */ if (u.ustuck) { /* includes u.uswallow */ Strcpy(heldmon, a_monnam(u.ustuck)); if (!strcmp(heldmon, "it") && (!has_mgivenname(u.ustuck) || strcmp(MGIVENNAME(u.ustuck), "it") != 0)) Strcpy(heldmon, "an unseen creature"); } if (u.uswallow) { assert(u.ustuck != NULL); /* implied by u.uswallow */ Snprintf(buf, sizeof buf, "%s by %s", digests(u.ustuck->data) ? "swallowed" : "engulfed", heldmon); if (dmgtype(u.ustuck->data, AD_DGST)) { /* if final, death via digestion can be deduced by u.uswallow still being True and u.uswldtim having been decremented to 0 */ if (final && !u.uswldtim) Strcat(buf, " and got totally digested"); else Sprintf(eos(buf), " and %s being digested", final ? "were" : "are"); } if (wizard) Sprintf(eos(buf), " (%u)", u.uswldtim); you_are(buf, ""); } else if (u.ustuck) { boolean ustick = (Upolyd && sticks(gy.youmonst.data)); int dx = u.ustuck->mx - u.ux, dy = u.ustuck->my - u.uy; Snprintf(buf, sizeof buf, "%s %s (%s)", ustick ? "holding" : "held by", heldmon, dxdy_to_dist_descr(dx, dy, TRUE)); you_are(buf, ""); } if (Riding) { struct obj *saddle = which_armor(u.usteed, W_SADDLE); if (saddle && saddle->cursed) { Sprintf(buf, "stuck to %s %s", s_suffix(steedname), simpleonames(saddle)); you_are(buf, ""); } } if (Wounded_legs) { /* EWounded_legs is used to track left/right/both rather than some form of extrinsic impairment; HWounded_legs is used for timeout; both apply to steed instead of hero when mounted */ long whichleg = (EWounded_legs & BOTH_SIDES); const char *bp = u.usteed ? mbodypart(u.usteed, LEG) : body_part(LEG), *article = "a ", /* precedes "wounded", so never "an " */ *leftright = ""; if (whichleg == BOTH_SIDES) bp = makeplural(bp), article = ""; else leftright = (whichleg == LEFT_SIDE) ? "left " : "right "; Sprintf(buf, "%swounded %s%s", article, leftright, bp); /* when mounted, Wounded_legs applies to steed rather than to hero; we only report steed's wounded legs in wizard mode */ if (u.usteed) { /* not `Riding' here */ if (wizard && steedname) { char steednambuf[BUFSZ]; Strcpy(steednambuf, steedname); *steednambuf = highc(*steednambuf); enl_msg(steednambuf, " has ", " had ", buf, ""); } } else { you_have(buf, ""); } } if (Glib) { Sprintf(buf, "slippery %s", fingers_or_gloves(TRUE)); if (wizard) Sprintf(eos(buf), " (%ld)", (Glib & TIMEOUT)); you_have(buf, ""); } if (Fumbling) { if (magic || cause_known(FUMBLING)) enl_msg(You_, "fumble", "fumbled", "", from_what(FUMBLING)); } if (Sleepy) { if (magic || cause_known(SLEEPY)) { Strcpy(buf, from_what(SLEEPY)); if (wizard) Sprintf(eos(buf), " (%ld)", (HSleepy & TIMEOUT)); enl_msg("You ", "fall", "fell", " asleep uncontrollably", buf); } } /* hunger/nutrition */ if (Hunger) { if (magic || cause_known(HUNGER)) enl_msg(You_, "hunger", "hungered", " rapidly", from_what(HUNGER)); } Strcpy(buf, hu_stat[u.uhs]); /* hunger status; omitted if "normal" */ mungspaces(buf); /* strip trailing spaces */ /* status line doesn't show hunger when state is "not hungry", we do; needed for wizard mode's reveal of u.uhunger but add it for everyone */ if (!*buf) Strcpy(buf, "not hungry"); if (*buf) { /* (since "not hungry" was added, this will always be True) */ *buf = lowc(*buf); /* override capitalization */ if (!strcmp(buf, "weak")) Strcat(buf, " from severe hunger"); else if (!strncmp(buf, "faint", 5)) /* fainting, fainted */ Strcat(buf, " due to starvation"); if (wizard) Sprintf(eos(buf), " <%d>", u.uhunger); you_are(buf, ""); } /* encumbrance */ if ((cap = near_capacity()) > UNENCUMBERED) { const char *adj = "?_?"; /* (should always get overridden) */ Strcpy(buf, enc_stat[cap]); *buf = lowc(*buf); switch (cap) { case SLT_ENCUMBER: adj = "slightly"; break; /* burdened */ case MOD_ENCUMBER: adj = "moderately"; break; /* stressed */ case HVY_ENCUMBER: adj = "very"; break; /* strained */ case EXT_ENCUMBER: adj = "extremely"; break; /* overtaxed */ case OVERLOADED: adj = "not possible"; break; } if (wizard) Sprintf(eos(buf), " <%d>", inv_weight()); Sprintf(eos(buf), "; movement %s %s%s", !final ? "is" : "was", adj, (cap < OVERLOADED) ? " slowed" : ""); you_are(buf, ""); } else { /* last resort entry, guarantees Status section is non-empty (no longer needed for that purpose since weapon status added; still useful though) */ Strcpy(buf, "unencumbered"); if (wizard) Sprintf(eos(buf), " <%d>", inv_weight()); you_are(buf, ""); } /* current weapon(s) and corresponding skill level(s) */ weapon_insight(final); /* unlike ring of increase accuracy's effect, the monk's suit penalty is too blatant to be restricted to magical enlightenment */ if (iflags.tux_penalty && !Upolyd) { (void) enlght_combatinc("to hit", -gu.urole.spelarmr, final, buf); /* if from_what() ever gets extended from wizard mode to normal play, it could be adapted to handle this */ Sprintf(eos(buf), " due to your %s", suit_simple_name(uarm)); you_have(buf, ""); } /* report 'nudity' */ if (!uarm && !uarmu && !uarmc && !uarms && !uarmg && !uarmf && !uarmh) { if (u.uroleplay.nudist) enl_msg(You_, "do", "did", " not wear any armor", ""); else you_are("not wearing any armor", ""); } } /* extracted from status_enlightenment() to reduce clutter there */ staticfn void weapon_insight(int final) { char buf[BUFSZ]; int wtype; /* report being weaponless; distinguish whether gloves are worn [perhaps mention silver ring(s) when not wearing gloves?] */ if (!uwep) { you_are(empty_handed(), ""); /* two-weaponing implies hands and a weapon or wep-tool (not other odd stuff) in each hand */ } else if (u.twoweap) { you_are("wielding two weapons at once", ""); /* report most weapons by their skill class (so a katana will be described as a long sword, for instance; mattock, hook, and aklys are exceptions), or wielded non-weapon item by its object class */ } else { const char *what = weapon_descr(uwep); /* [what about other silver items?] */ if (uwep->otyp == SHIELD_OF_REFLECTION) what = shield_simple_name(uwep); /* silver|smooth shield */ else if (is_wet_towel(uwep)) what = /* (uwep->spe < 3) ? "moist towel" : */ "wet towel"; if (!strcmpi(what, "armor") || !strcmpi(what, "food") || !strcmpi(what, "venom")) Sprintf(buf, "wielding some %s", what); else /* [maybe include known blessed?] */ Sprintf(buf, "wielding %s", (uwep->quan == 1L) ? an(what) : makeplural(what)); you_are(buf, ""); } /* * Skill with current weapon. Might help players who've never * noticed #enhance or decided that it was pointless. */ if ((wtype = weapon_type(uwep)) != P_NONE && (!uwep || !is_ammo(uwep))) { char sklvlbuf[20]; int sklvl = P_SKILL(wtype); boolean hav = (sklvl != P_UNSKILLED && sklvl != P_SKILLED); if (sklvl == P_ISRESTRICTED) Strcpy(sklvlbuf, "no"); else (void) lcase(skill_level_name(wtype, sklvlbuf)); /* "you have no/basic/expert/master/grand-master skill with <skill>" or "you are unskilled/skilled in <skill>" */ Sprintf(buf, "%s %s %s", sklvlbuf, hav ? "skill with" : "in", skill_name(wtype)); if (!u.twoweap) { if (can_advance(wtype, FALSE)) Sprintf(eos(buf), " and %s that", !final ? "can enhance" : "could have enhanced"); if (hav) you_have(buf, ""); else you_are(buf, ""); } else { /* two-weapon */ static const char also_[] = "also "; char pfx[QBUFSZ], sfx[QBUFSZ], sknambuf2[20], sklvlbuf2[20], twobuf[20]; const char *also = "", *also2 = "", *also3 = (char *) 0, *verb_present, *verb_past; int wtype2 = weapon_type(uswapwep), sklvl2 = P_SKILL(wtype2), twoskl = P_SKILL(P_TWO_WEAPON_COMBAT); boolean a1, a2, ab, hav2 = (sklvl2 != P_UNSKILLED && sklvl2 != P_SKILLED); /* normally hero must have access to two-weapon skill in order to initiate u.twoweap, but not if polymorphed into a form which has multiple weapon attacks, so we need to avoid getting bitten by unexpected skill value */ if (twoskl == P_ISRESTRICTED) { twoskl = P_UNSKILLED; /* restricted is the same as unskilled as far as bonus or penalty goes, and it isn't ordinarily seen so skill_level_name() returns "Unknown" for it */ Strcpy(twobuf, "restricted"); } else { (void) lcase(skill_level_name(P_TWO_WEAPON_COMBAT, twobuf)); } /* keep buf[] from above in case skill levels match */ pfx[0] = sfx[0] = '\0'; if (twoskl < sklvl) { /* twoskil won't be restricted so sklvl is at least basic */ Sprintf(pfx, "Your skill in %s ", skill_name(wtype)); Sprintf(sfx, " limited by being %s with two weapons", twobuf); also = also_; } else if (twoskl > sklvl) { /* sklvl might be restricted */ Strcpy(pfx, "Your two weapon skill "); Strcpy(sfx, " limited by "); if (sklvl > P_ISRESTRICTED) Sprintf(eos(sfx), "being %s", sklvlbuf); else Sprintf(eos(sfx), "having no skill"); Sprintf(eos(sfx), " with %s", skill_name(wtype)); also2 = also_; } else { Strcat(buf, " and two weapons"); also3 = also_; } if (*pfx) enl_msg(pfx, "is", "was", sfx, ""); else if (hav) you_have(buf, ""); else you_are(buf, ""); /* skip comparison between secondary and two-weapons if it is identical to the comparison between primary and twoweap */ if (wtype2 != wtype) { Strcpy(sknambuf2, skill_name(wtype2)); (void) lcase(skill_level_name(wtype2, sklvlbuf2)); verb_present = "is", verb_past = "was"; pfx[0] = sfx[0] = buf[0] = '\0'; if (twoskl < sklvl2) { /* twoskil is at least unskilled, sklvl2 at least basic */ Sprintf(pfx, "Your skill in %s ", sknambuf2); Sprintf(sfx, " %slimited by being %s with two weapons", also, twobuf); } else if (twoskl > sklvl2) { /* sklvl2 might be restricted */ Strcpy(pfx, "Your two weapon skill "); Sprintf(sfx, " %slimited by ", also2); if (sklvl2 > P_ISRESTRICTED) Sprintf(eos(sfx), "being %s", sklvlbuf2); else Strcat(eos(sfx), "having no skill"); Sprintf(eos(sfx), " with %s", sknambuf2); } else { /* equal; two-weapon is at least unskilled, so sklvl2 is too; "you [also] have basic/expert/master/grand-master skill with <skill>" or "you [also] are unskilled/ skilled in <skill> */ Sprintf(buf, "%s %s %s", sklvlbuf2, hav2 ? "skill with" : "in", sknambuf2); Strcat(buf, " and two weapons"); if (also3) { Strcpy(pfx, "You also "); Snprintf(sfx, sizeof(sfx), " %s", buf), buf[0] = '\0'; verb_present = hav2 ? "have" : "are"; verb_past = hav2 ? "had" : "were"; } } if (*pfx) enl_msg(pfx, verb_present, verb_past, sfx, ""); else if (hav2) you_have(buf, ""); else you_are(buf, ""); } /* wtype2 != wtype */ /* if training and available skill credits already allow #enhance for any of primary, secondary, or two-weapon, tell the player; avoid attempting figure out whether spending skill credits enhancing one might make either or both of the others become ineligible for enhancement */ a1 = can_advance(wtype, FALSE); a2 = (wtype2 != wtype) ? can_advance(wtype2, FALSE) : FALSE; ab = can_advance(P_TWO_WEAPON_COMBAT, FALSE); if (a1 || a2 || ab) { static const char also_wik_[] = " and also with "; /* for just one, the conditionals yield 1) "skill with <that one>"; for more than one: 2) "skills with <primary> and also with <secondary>" or 3) "skills with <primary> and also with two-weapons" or 4) "skills with <secondary> and also with two-weapons" or 5) "skills with <primary>, <secondary>, and two-weapons" (no 'also's or extra 'with's for case 5); when primary and secondary use the same skill, only cases 1 and 3 are possible because 'a2' gets forced to False above */ Sprintf(sfx, " skill%s with %s%s%s%s%s", ((int) a1 + (int) a2 + (int) ab > 1) ? "s" : "", a1 ? skill_name(wtype) : "", ((a1 && a2 && ab) ? ", " : (a1 && (a2 || ab)) ? also_wik_ : ""), a2 ? skill_name(wtype2) : "", ((a1 && a2 && ab) ? ", and " : (a2 && ab) ? also_wik_ : ""), ab ? "two weapons" : ""); enl_msg(You_, "can enhance", "could have enhanced", sfx, ""); } } /* two-weapon */ } /* skill applies */ } staticfn void item_resistance_message( int adtyp, const char *prot_message, int final) { int protection = u_adtyp_resistance_obj(adtyp); if (protection) { boolean somewhat = protection < 99; enl_msg("Your items ", somewhat ? "are somewhat" : "are", somewhat ? "were somewhat" : "were", prot_message, item_what(adtyp)); } } /* attributes: intrinsics and the like, other non-obvious capabilities */ staticfn void attributes_enlightenment( int unused_mode UNUSED, int final) { static NEARDATA const char if_surroundings_permitted[] = " if surroundings permitted"; int ltmp, armpro, warnspecies; char buf[BUFSZ]; /*\ * Attributes \*/ enlght_out(""); enlght_out(final ? "Final Attributes:" : "Attributes:"); if (u.uevent.uhand_of_elbereth) { static const char *const hofe_titles[3] = { "the Hand of Elbereth", "the Envoy of Balance", "the Glory of Arioch" }; you_are(hofe_titles[u.uevent.uhand_of_elbereth - 1], ""); } Sprintf(buf, "%s", piousness(TRUE, "aligned")); if (u.ualign.record >= 0) you_are(buf, ""); else you_have(buf, ""); if (wizard) { Sprintf(buf, " %d", u.ualign.record); enl_msg("Your alignment ", "is", "was", buf, ""); } /*** Resistances to troubles ***/ if (Invulnerable) you_are("invulnerable", from_what(INVULNERABLE)); if (Antimagic) you_are("magic-protected", from_what(ANTIMAGIC)); if (Fire_resistance) you_are("fire resistant", from_what(FIRE_RES)); item_resistance_message(AD_FIRE, " protected from fire", final); if (Cold_resistance) you_are("cold resistant", from_what(COLD_RES)); item_resistance_message(AD_COLD, " protected from cold", final); if (Sleep_resistance) you_are("sleep resistant", from_what(SLEEP_RES)); if (Disint_resistance) you_are("disintegration resistant", from_what(DISINT_RES)); item_resistance_message(AD_DISN, " protected from disintegration", final); if (Shock_resistance) you_are("shock resistant", from_what(SHOCK_RES)); item_resistance_message(AD_ELEC, " protected from electric shocks", final); if (Poison_resistance) you_are("poison resistant", from_what(POISON_RES)); if (Acid_resistance) { Sprintf(buf, "%.20s%.30s", temp_resist(ACID_RES) ? "temporarily " : "", "acid resistant"); you_are(buf, from_what(ACID_RES)); } item_resistance_message(AD_ACID, " protected from acid", final); if (Drain_resistance) you_are("level-drain resistant", from_what(DRAIN_RES)); if (Sick_resistance) you_are("immune to sickness", from_what(SICK_RES)); if (Stone_resistance) { Sprintf(buf, "%.20s%.30s", temp_resist(STONE_RES) ? "temporarily " : "", "petrification resistant"); you_are(buf, from_what(STONE_RES)); } if (Halluc_resistance) enl_msg(You_, "resist", "resisted", " hallucinations", from_what(HALLUC_RES)); if (u.uedibility) you_can("recognize detrimental food", ""); /*** Vision and senses ***/ if ((HBlinded || EBlinded) && BBlinded) /* blind w/ blindness blocked */ you_can("see", from_what(-BLINDED)); /* Eyes of the Overworld */ if (Blnd_resist && !Blind) /* skip if no eyes or blindfolded */ you_are("not subject to light-induced blindness", from_what(BLND_RES)); if (See_invisible) { if (!Blind) enl_msg(You_, "see", "saw", " invisible", from_what(SEE_INVIS)); else if (!PermaBlind) enl_msg(You_, "will see", "would have seen", " invisible when not blind", ""); else enl_msg(You_, "would see", "would have seen", " invisible if not blind", ""); } if (Blind_telepat) you_are("telepathic", from_what(TELEPAT)); if (Warning) you_are("warned", from_what(WARNING)); if (Warn_of_mon && svc.context.warntype.obj) { Sprintf(buf, "aware of the presence of %s", (svc.context.warntype.obj & M2_ORC) ? "orcs" : (svc.context.warntype.obj & M2_ELF) ? "elves" : (svc.context.warntype.obj & M2_DEMON) ? "demons" : something); you_are(buf, from_what(WARN_OF_MON)); } if (Warn_of_mon && svc.context.warntype.polyd) { Sprintf(buf, "aware of the presence of %s", ((svc.context.warntype.polyd & (M2_HUMAN | M2_ELF)) == (M2_HUMAN | M2_ELF)) ? "humans and elves" : (svc.context.warntype.polyd & M2_HUMAN) ? "humans" : (svc.context.warntype.polyd & M2_ELF) ? "elves" : (svc.context.warntype.polyd & M2_ORC) ? "orcs" : (svc.context.warntype.polyd & M2_DEMON) ? "demons" : "certain monsters"); you_are(buf, ""); } warnspecies = svc.context.warntype.speciesidx; if (Warn_of_mon && ismnum(warnspecies)) { Sprintf(buf, "aware of the presence of %s", makeplural(mons[warnspecies].pmnames[NEUTRAL])); you_are(buf, from_what(WARN_OF_MON)); } if (Undead_warning) you_are("warned of undead", from_what(WARN_UNDEAD)); if (Searching) you_have("automatic searching", from_what(SEARCHING)); if (Clairvoyant) { you_are("clairvoyant", from_what(CLAIRVOYANT)); } else if ((HClairvoyant || EClairvoyant) && BClairvoyant) { Strcpy(buf, from_what(-CLAIRVOYANT)); (void) strsubst(buf, " because of ", " if not for "); enl_msg(You_, "could be", "could have been", " clairvoyant", buf); } if (Infravision) you_have("infravision", from_what(INFRAVISION)); if (Detect_monsters) { Strcpy(buf, "sensing the presence of monsters"); if (wizard) { long detectmon_timeout = (HDetect_monsters & TIMEOUT); if (detectmon_timeout) Sprintf(eos(buf), " (%ld)", detectmon_timeout); } you_are(buf, ""); } if (u.umconf) { /* 'u.umconf' is a counter rather than a timeout */ Strcpy(buf, " monsters when hitting them"); if (wizard && !final) { if (u.umconf == 1) Strcat(buf, " (next hit only)"); else /* u.umconf > 1 */ Sprintf(eos(buf), " (next %u hits)", u.umconf); } enl_msg(You_, "will confuse", "would have confused", buf, ""); } /*** Appearance and behavior ***/ if (Adornment) { int adorn = 0; if (uleft && uleft->otyp == RIN_ADORNMENT) adorn += uleft->spe; if (uright && uright->otyp == RIN_ADORNMENT) adorn += uright->spe; /* the sum might be 0 (+0 ring or two which negate each other); that yields "you are charismatic" (which isn't pointless because it potentially impacts seduction attacks) */ Sprintf(buf, "%scharismatic", (adorn > 0) ? "more " : (adorn < 0) ? "less " : ""); you_are(buf, from_what(ADORNED)); } if (Invisible) you_are("invisible", from_what(INVIS)); else if (Invis) you_are("invisible to others", from_what(INVIS)); /* ordinarily "visible" is redundant; this is a special case for the situation when invisibility would be an expected attribute */ else if ((HInvis || EInvis) && BInvis) you_are("visible", from_what(-INVIS)); if (Displaced) you_are("displaced", from_what(DISPLACED)); if (Stealth) { you_are("stealthy", from_what(STEALTH)); } else if (BStealth && (HStealth || EStealth)) { Sprintf(buf, " stealthy%s", (BStealth == FROMOUTSIDE) ? " if not mounted" : ""); enl_msg(You_, "would be", "would have been", buf, ""); } if (Aggravate_monster) enl_msg("You aggravate", "", "d", " monsters", from_what(AGGRAVATE_MONSTER)); if (Conflict) enl_msg("You cause", "", "d", " conflict", from_what(CONFLICT)); /*** Transportation ***/ if (Jumping) you_can("jump", from_what(JUMPING)); if (Teleportation) you_can("teleport", from_what(TELEPORT)); if (Teleport_control) you_have("teleport control", from_what(TELEPORT_CONTROL)); /* actively levitating handled earlier as a status condition */ if (BLevitation) { /* levitation is blocked */ long save_BLev = BLevitation; BLevitation = 0L; if (Levitation) { /* either trapped in the floor or inside solid rock (or both if chained to buried iron ball and have moved one step into solid rock somehow) */ boolean trapped = (save_BLev & I_SPECIAL) != 0L, terrain = (save_BLev & FROMOUTSIDE) != 0L; Sprintf(buf, "%s%s%s", trapped ? " if not trapped" : "", (trapped && terrain) ? " and" : "", terrain ? if_surroundings_permitted : ""); enl_msg(You_, "would levitate", "would have levitated", buf, ""); } BLevitation = save_BLev; } /* actively flying handled earlier as a status condition */ if (BFlying) { /* flight is blocked */ long save_BFly = BFlying; BFlying = 0L; if (Flying) { enl_msg(You_, "would fly", "would have flown", /* wording quibble: for past tense, "hadn't been" would sound better than "weren't" (and "had permitted" better than "permitted"), but "weren't" and "permitted" are adequate so the extra complexity to handle that isn't worth it */ Levitation ? " if you weren't levitating" : (save_BFly == I_SPECIAL) /* this is an oversimplification; being trapped might also be blocking levitation so flight would still be blocked after escaping trap */ ? " if you weren't trapped" : (save_BFly == FROMOUTSIDE) ? if_surroundings_permitted /* two or more of levitation, surroundings, and being trapped in the floor */ : " if circumstances permitted", ""); } BFlying = save_BFly; } /* including this might bring attention to the fact that ceiling clinging has inconsistencies... */ if (is_clinger(gy.youmonst.data)) { boolean has_lid = has_ceiling(&u.uz); if (has_lid && !u.uinwater) { you_can("cling to the ceiling", ""); } else { Sprintf(buf, " to the ceiling if %s%s%s", !has_lid ? "there was one" : "", (!has_lid && u.uinwater) ? " and " : "", u.uinwater ? (Underwater ? "you weren't underwater" : "you weren't in the water") : ""); /* past tense is applicable for death while Unchanging */ enl_msg(You_, "could cling", "could have clung", buf, ""); } } /* actively walking on water handled earlier as a status condition */ if (Wwalking && !walking_on_water()) you_can("walk on water", from_what(WWALKING)); /* actively swimming (in water but not under it) handled earlier */ if (Swimming && (Underwater || !u.uinwater)) you_can("swim", from_what(SWIMMING)); if (Breathless) you_can("survive without air", from_what(MAGICAL_BREATHING)); else if (Amphibious) you_can("breathe water", from_what(MAGICAL_BREATHING)); if (Passes_walls) you_can("walk through walls", from_what(PASSES_WALLS)); /*** Physical attributes ***/ if (Regeneration) enl_msg("You regenerate", "", "d", "", from_what(REGENERATION)); if (Slow_digestion) you_have("slower digestion", from_what(SLOW_DIGESTION)); if (u.uhitinc) { (void) enlght_combatinc("to hit", u.uhitinc, final, buf); if (iflags.tux_penalty && !Upolyd) Sprintf(eos(buf), " %s your suit's penalty", (u.uhitinc < 0) ? "increasing" : (u.uhitinc < 4 * gu.urole.spelarmr / 5) ? "partly offsetting" : (u.uhitinc < gu.urole.spelarmr) ? "nearly offsetting" : "overcoming"); you_have(buf, ""); } if (u.udaminc) you_have(enlght_combatinc("damage", u.udaminc, final, buf), ""); if (u.uspellprot || Protection) { int prot = 0; if (uleft && uleft->otyp == RIN_PROTECTION) prot += uleft->spe; if (uright && uright->otyp == RIN_PROTECTION) prot += uright->spe; if (uamul && uamul->otyp == AMULET_OF_GUARDING) prot += 2; if (HProtection & INTRINSIC) prot += u.ublessed; prot += u.uspellprot; if (prot) you_have(enlght_combatinc("defense", prot, final, buf), ""); } if ((armpro = magic_negation(&gy.youmonst)) > 0) { /* magic cancellation factor, conferred by worn armor */ static const char *const mc_types[] = { "" /*ordinary*/, "warded", "guarded", "protected", }; /* sanity check */ if (armpro >= SIZE(mc_types)) armpro = SIZE(mc_types) - 1; you_are(mc_types[armpro], ""); } if (Half_physical_damage) enlght_halfdmg(HALF_PHDAM, final); if (Half_spell_damage) enlght_halfdmg(HALF_SPDAM, final); if (Half_gas_damage) enl_msg(You_, "take", "took", " reduced poison gas damage", ""); if (spellid(0) > NO_SPELL) { /* skip if no spells are known yet */ /* greatly simplified edition of percent_success(spell.c)--may need to be suppressed if oversimplification leads to player confusion */ char cast_adj[QBUFSZ]; boolean suit = uarm && is_metallic(uarm), robe = uarmc && uarmc->otyp == ROBE; *cast_adj = '\0'; if (suit) /* omit "wearing" to shorten the text */ Sprintf(cast_adj, " impaired by metallic armor%s", robe ? ", mitigated by your robe" : ""); else if (robe) Strcpy(cast_adj, " enhanced by wearing a robe"); if (*cast_adj) enl_msg("Your spell casting ", "is", "was", cast_adj, ""); } /* polymorph and other shape change */ if (Protection_from_shape_changers) you_are("protected from shape changers", from_what(PROT_FROM_SHAPE_CHANGERS)); if (Unchanging) { const char *what = 0; if (!Upolyd) /* Upolyd handled below after current form */ you_can("not change from your current form", from_what(UNCHANGING)); /* blocked shape changes */ if (Polymorph) what = !final ? "polymorph" : "have polymorphed"; else if (ismnum(u.ulycn)) what = !final ? "change shape" : "have changed shape"; if (what) { Sprintf(buf, "would %s periodically", what); /* omit from_what(UNCHANGING); too verbose */ enl_msg(You_, buf, buf, " if not locked into your current form", ""); } } else if (Polymorph) { you_are("polymorphing periodically", from_what(POLYMORPH)); } if (Polymorph_control) you_have("polymorph control", from_what(POLYMORPH_CONTROL)); if (Upolyd && u.umonnum != u.ulycn /* if we've died from turning into slime, we're polymorphed right now but don't want to list it as a temporary attribute [we need a more reliable way to detect this situation] */ && !(final == ENL_GAMEOVERDEAD && u.umonnum == PM_GREEN_SLIME && !Unchanging)) { /* foreign shape (except were-form which is handled below) */ if (!vampshifted(&gy.youmonst)) Sprintf(buf, "polymorphed into %s", an(pmname(gy.youmonst.data, flags.female ? FEMALE : MALE))); else Sprintf(buf, "polymorphed into %s in %s form", an(pmname(&mons[gy.youmonst.cham], flags.female ? FEMALE : MALE)), pmname(gy.youmonst.data, flags.female ? FEMALE : MALE)); if (wizard) Sprintf(eos(buf), " (%d)", u.mtimedone); you_are(buf, ""); } if (lays_eggs(gy.youmonst.data) && flags.female) /* Upolyd */ you_can("lay eggs", ""); if (ismnum(u.ulycn)) { /* "you are a werecreature [in beast form]" */ Strcpy(buf, an(pmname(&mons[u.ulycn], flags.female ? FEMALE : MALE))); if (u.umonnum == u.ulycn) { Strcat(buf, " in beast form"); if (wizard) Sprintf(eos(buf), " (%d)", u.mtimedone); } you_are(buf, ""); } if (Unchanging && Upolyd) /* !Upolyd handled above */ you_can("not change from your current form", from_what(UNCHANGING)); if (Hate_silver) you_are("harmed by silver", ""); /* movement and non-armor-based protection */ if (Fast) you_are(Very_fast ? "very fast" : "fast", from_what(FAST)); if (Reflecting) you_have("reflection", from_what(REFLECTING)); if (Free_action) you_have("free action", from_what(FREE_ACTION)); if (Fixed_abil) you_have("fixed abilities", from_what(FIXED_ABIL)); if (Lifesaved) enl_msg("Your life ", "will be", "would have been", " saved", ""); /*** Miscellany ***/ if (Luck) { ltmp = abs((int) Luck); Sprintf(buf, "%s%slucky", ltmp >= 10 ? "extremely " : ltmp >= 5 ? "very " : "", Luck < 0 ? "un" : ""); if (wizard) Sprintf(eos(buf), " (%d)", Luck); you_are(buf, ""); } else if (wizard) enl_msg("Your luck ", "is", "was", " zero", ""); if (u.moreluck > 0) you_have("extra luck", ""); else if (u.moreluck < 0) you_have("reduced luck", ""); if (carrying(LUCKSTONE) || stone_luck(TRUE)) { ltmp = stone_luck(FALSE); if (ltmp <= 0) enl_msg("Bad luck ", "does", "did", " not time out for you", ""); if (ltmp >= 0) enl_msg("Good luck ", "does", "did", " not time out for you", ""); } if (u.ugangr) { Sprintf(buf, " %sangry with you", u.ugangr > 6 ? "extremely " : u.ugangr > 3 ? "very " : ""); if (wizard) Sprintf(eos(buf), " (%d)", u.ugangr); enl_msg(u_gname(), " is", " was", buf, ""); } else { /* * We need to suppress this when the game is over, because death * can change the value calculated by can_pray(), potentially * resulting in a false claim that you could have prayed safely. */ if (!final) { #if 0 /* "can [not] safely pray" vs "could [not] have safely prayed" */ Sprintf(buf, "%s%ssafely pray%s", can_pray(FALSE) ? "" : "not ", final ? "have " : "", final ? "ed" : ""); #else Sprintf(buf, "%ssafely pray", can_pray(FALSE) ? "" : "not "); #endif if (wizard) Sprintf(eos(buf), " (%d)", u.ublesscnt); you_can(buf, ""); } } #ifdef DEBUG /* named fruit debugging (doesn't really belong here...); to enable, include 'fruit' in DEBUGFILES list (even though it isn't a file...) */ if (wizard && explicitdebug("fruit")) { struct fruit *f; reorder_fruit(TRUE); /* sort by fruit index, from low to high; * this modifies the gf.ffruit chain, so could * possibly mask or even introduce a problem, * but it does useful sanity checking */ for (f = gf.ffruit; f; f = f->nextf) { Sprintf(buf, "Fruit #%d ", f->fid); enl_msg(buf, "is ", "was ", f->fname, ""); } enl_msg("The current fruit ", "is ", "was ", svp.pl_fruit, ""); Sprintf(buf, "%d", flags.made_fruit); enl_msg("The made fruit flag ", "is ", "was ", buf, ""); } #endif /* saving-grace: show during final disclosure, hide during normal play */ if (final || wizard || discover) { static const char *verbchoices[2][2] = { { "might avoid", "have avoided" }, { "could have avoided", "avoided" }, }; /* u.usaving_grace will always be 0 or 1; final is 0 (game in progress), 1 (game over, survived), or 2 (game over, died) */ const char *verb = verbchoices[!!final][u.usaving_grace]; /* 'verb' has already been set for present or past but enl_msg() needs it twice, one for in progress, the other for game over */ enl_msg(You_, verb, verb, " a one-shot death via saving-grace", ""); } { const char *p; buf[0] = '\0'; if (final < 2) { /* still in progress, or quit/escaped/ascended */ p = "survived after being killed "; switch (u.umortality) { case 0: p = !final ? (char *) 0 : "survived"; break; case 1: Strcpy(buf, "once"); break; case 2: Strcpy(buf, "twice"); break; case 3: Strcpy(buf, "thrice"); break; default: Sprintf(buf, "%d times", u.umortality); break; } } else { /* game ended in character's death */ p = "are dead"; switch (u.umortality) { case 0: impossible("dead without dying?"); FALLTHROUGH; /* FALLTHRU */ case 1: break; /* just "are dead" */ default: Sprintf(buf, " (%d%s time!)", u.umortality, ordin(u.umortality)); break; } } if (p) enl_msg(You_, "have been killed ", p, buf, ""); } } /* ^X command */ int doattributes(void) { int mode = BASICENLIGHTENMENT; /* show more--as if final disclosure--for wizard and explore modes */ if (wizard || discover) mode |= MAGICENLIGHTENMENT; enlightenment(mode, ENL_GAMEINPROGRESS); return ECMD_OK; } void youhiding(boolean via_enlghtmt, /* enlightenment line vs topl message */ int msgflag) /* for variant message phrasing */ { char *bp, buf[BUFSZ]; Strcpy(buf, "hiding"); if (U_AP_TYPE != M_AP_NOTHING) { /* mimic; hero is only able to mimic a strange object or gold or hallucinatory alternative to gold, so we skip the details for the hypothetical furniture and monster cases */ bp = eos(strcpy(buf, "mimicking")); if (U_AP_TYPE == M_AP_OBJECT) { Sprintf(bp, " %s", an(simple_typename(gy.youmonst.mappearance))); } else if (U_AP_TYPE == M_AP_FURNITURE) { Strcpy(bp, " something"); } else if (U_AP_TYPE == M_AP_MONSTER) { Strcpy(bp, " someone"); } else { ; /* something unexpected; leave 'buf' as-is */ } } else if (u.uundetected) { bp = eos(buf); /* points past "hiding" */ if (gy.youmonst.data->mlet == S_EEL) { if (is_pool(u.ux, u.uy)) Sprintf(bp, " in the %s", waterbody_name(u.ux, u.uy)); } else if (hides_under(gy.youmonst.data)) { struct obj *o = svl.level.objects[u.ux][u.uy]; if (o) Sprintf(bp, " underneath %s", ansimpleoname(o)); } else if (is_clinger(gy.youmonst.data) || Flying) { /* Flying: 'lurker above' hides on ceiling but doesn't cling */ Sprintf(bp, " on the %s", ceiling(u.ux, u.uy)); } else { /* on floor; is_hider() but otherwise not special: 'trapper' */ if (u.utrap && u.utraptype == TT_PIT) { struct trap *t = t_at(u.ux, u.uy); Sprintf(bp, " in a %spit", (t && t->ttyp == SPIKED_PIT) ? "spiked " : ""); } else Sprintf(bp, " on the %s", surface(u.ux, u.uy)); } } else { ; /* shouldn't happen; will result in generic "you are hiding" */ } if (via_enlghtmt) { int final = msgflag; /* 'final' is used by you_are() macro */ you_are(buf, ""); } else { /* for dohide(), when player uses '#monster' command */ You("are %s %s.", msgflag ? "already" : "now", buf); } } /* #conduct command [KMH]; shares enlightenment's tense handling */ int doconduct(void) { show_conduct(ENL_GAMEINPROGRESS); return ECMD_OK; } /* display conducts; for doconduct(), also disclose() and dump_everything() */ void show_conduct(int final) { char buf[BUFSZ]; int ngenocided; /* Create the conduct window */ ge.en_win = create_nhwindow(NHW_MENU); putstr(ge.en_win, 0, "Voluntary challenges:"); if (u.uroleplay.blind) you_have_been("blind from birth"); if (u.uroleplay.deaf) you_have_been("deaf from birth"); /* note: we don't report "you are without possessions" unless the game started with the pauper option set */ if (u.uroleplay.pauper) enl_msg(You_, gi.invent ? "started" : "are", "started out", " without possessions", ""); /* nudist is far more than a subset of possessionless, and a much more impressive accomplishment, but showing "started out without possessions" before "faithfully nudist" looks more logical */ if (u.uroleplay.nudist) you_have_been("faithfully nudist"); if (!u.uconduct.food) enl_msg(You_, "have gone", "went", " without food", ""); /* but beverages are okay */ else if (!u.uconduct.unvegan) you_have_X("followed a strict vegan diet"); else if (!u.uconduct.unvegetarian) you_have_been("vegetarian"); if (!u.uconduct.gnostic) you_have_been("an atheist"); if (!u.uconduct.weaphit) { you_have_never("hit with a wielded weapon"); } else if (wizard) { Sprintf(buf, "hit with a wielded weapon %ld time%s", u.uconduct.weaphit, plur(u.uconduct.weaphit)); you_have_X(buf); } if (!u.uconduct.killer) you_have_been("a pacifist"); if (!u.uconduct.literate) { you_have_been("illiterate"); } else if (wizard) { Sprintf(buf, "read items or engraved %ld time%s", u.uconduct.literate, plur(u.uconduct.literate)); you_have_X(buf); } if (!u.uconduct.pets) you_have_never("had a pet"); ngenocided = num_genocides(); if (ngenocided == 0) { you_have_never("genocided any monsters"); } else { Sprintf(buf, "genocided %d type%s of monster%s", ngenocided, plur(ngenocided), plur(ngenocided)); you_have_X(buf); } if (!u.uconduct.polypiles) { you_have_never("polymorphed an object"); } else if (wizard) { Sprintf(buf, "polymorphed %ld item%s", u.uconduct.polypiles, plur(u.uconduct.polypiles)); you_have_X(buf); } if (!u.uconduct.polyselfs) { you_have_never("changed form"); } else if (wizard) { Sprintf(buf, "changed form %ld time%s", u.uconduct.polyselfs, plur(u.uconduct.polyselfs)); you_have_X(buf); } if (!u.uconduct.wishes) { you_have_X("used no wishes"); } else { Sprintf(buf, "used %ld wish%s", u.uconduct.wishes, (u.uconduct.wishes > 1L) ? "es" : ""); if (u.uconduct.wisharti) { /* if wisharti == wishes * 1 wish (for an artifact) * 2 wishes (both for artifacts) * N wishes (all for artifacts) * else (N is at least 2 in order to get here; M < N) * N wishes (1 for an artifact) * N wishes (M for artifacts) */ if (u.uconduct.wisharti == u.uconduct.wishes) Sprintf(eos(buf), " (%s", (u.uconduct.wisharti > 2L) ? "all " : (u.uconduct.wisharti == 2L) ? "both " : ""); else Sprintf(eos(buf), " (%ld ", u.uconduct.wisharti); Sprintf(eos(buf), "for %s)", (u.uconduct.wisharti == 1L) ? "an artifact" : "artifacts"); } you_have_X(buf); if (!u.uconduct.wisharti) enl_msg(You_, "have not wished", "did not wish", " for any artifacts", ""); } /* only report Sokoban conduct if the Sokoban branch has been entered */ if (sokoban_in_play()) { const char *presentverb = "have violated", *pastverb = "violated"; Strcpy(buf, " the special Sokoban rules "); switch (u.uconduct.sokocheat) { case 0L: presentverb = "have not violated"; pastverb = "did not violate"; Strcpy(buf, " any of the special Sokoban rules"); break; case 1L: Strcat(buf, "once"); break; case 2L: Strcat(buf, "twice"); break; case 3L: Strcat(buf, "thrice"); break; default: Sprintf(eos(buf), "%ld times", u.uconduct.sokocheat); break; } enl_msg(You_, presentverb, pastverb, buf, ""); } show_achievements(final); /* Pop up the window and wait for a key */ display_nhwindow(ge.en_win, TRUE); destroy_nhwindow(ge.en_win); ge.en_win = WIN_ERR; } /* * Achievements (see 'enum achievements' in you.h). */ staticfn void show_achievements( int final) /* 'final' is used "behind the curtain" by enl_foo() macros */ { int i, achidx, absidx, acnt; char title[QBUFSZ], buf[QBUFSZ]; winid awin = WIN_ERR; /* unfortunately we can't show the achievements (at least not all of them) while the game is in progress because it would give away the ID of luckstone (at Mine's End) and of real Amulet of Yendor */ if (!final && !wizard) return; /* first, figure whether any achievements have been accomplished so that we don't show the header for them if the resulting list below it would be empty */ if ((acnt = count_achievements()) == 0) return; if (ge.en_win != WIN_ERR) { awin = ge.en_win; /* end of game disclosure window */ putstr(awin, 0, ""); } else { awin = create_nhwindow(NHW_MENU); } Sprintf(title, "Achievement%s:", plur(acnt)); putstr(awin, 0, title); /* display achievements in the order in which they were recorded; lone exception is to defer the Amulet if we just ascended; it warrants alternate wording when given away during ascension, but the Amulet achievement is always attained before entering endgame and the alternate wording looks strange if shown before "reached endgame" and "reached Astral" */ if (remove_achievement(ACH_UWIN)) { /* UWIN == Ascended! */ /* for ascension, force it to be last and Amulet next to last by taking them out and then adding them back */ if (remove_achievement(ACH_AMUL)) /* should always be True here */ record_achievement(ACH_AMUL); record_achievement(ACH_UWIN); } for (i = 0; i < acnt; ++i) { achidx = u.uachieved[i]; absidx = abs(achidx); switch (absidx) { case ACH_BLND: enl_msg(You_, "are exploring", "explored", " without being able to see", ""); break; case ACH_NUDE: enl_msg(You_, "have gone", "went", " without any armor", ""); break; case ACH_MINE: you_have_X("entered the Gnomish Mines"); break; case ACH_TOWN: you_have_X("entered Minetown"); break; case ACH_SHOP: you_have_X("entered a shop"); break; case ACH_TMPL: you_have_X("entered a temple"); break; case ACH_ORCL: you_have_X("consulted the Oracle of Delphi"); break; case ACH_NOVL: you_have_X("read from a Discworld novel"); break; case ACH_SOKO: you_have_X("entered Sokoban"); break; case ACH_SOKO_PRIZE: /* hard to reach guaranteed bag or amulet */ you_have_X("completed Sokoban"); break; case ACH_MINE_PRIZE: /* hidden guaranteed luckstone */ you_have_X("completed the Gnomish Mines"); break; case ACH_BGRM: you_have_X("entered the Big Room"); break; case ACH_MEDU: you_have_X("defeated Medusa"); break; case ACH_TUNE: you_have_X( "learned the tune to open and close the Castle's drawbridge"); break; case ACH_BELL: /* alternate phrasing for present vs past and also for possessing the item vs once held it */ enl_msg(You_, u.uhave.bell ? "have" : "have handled", u.uhave.bell ? "had" : "handled", " the Bell of Opening", ""); break; case ACH_HELL: enl_msg(You_, "have ", "", "entered Gehennom", ""); break; case ACH_CNDL: enl_msg(You_, u.uhave.menorah ? "have" : "have handled", u.uhave.menorah ? "had" : "handled", " the Candelabrum of Invocation", ""); break; case ACH_BOOK: enl_msg(You_, u.uhave.book ? "have" : "have handled", u.uhave.book ? "had" : "handled", " the Book of the Dead", ""); break; case ACH_INVK: you_have_X("gained access to Moloch's Sanctum"); break; case ACH_AMUL: /* alternate wording for ascended (always past tense) since hero had it until #offer forced it to be relinquished */ enl_msg(You_, u.uhave.amulet ? "have" : "have obtained", u.uevent.ascended ? "delivered" : u.uhave.amulet ? "had" : "had obtained", " the Amulet of Yendor", ""); break; /* reaching Astral makes feedback about reaching the Planes be redundant and ascending makes both be redundant, but we display all that apply */ case ACH_ENDG: you_have_X("reached the Elemental Planes"); break; case ACH_ASTR: you_have_X("reached the Astral Plane"); break; case ACH_UWIN: /* the ultimate achievement... */ enlght_out(" You ascended!"); break; /* rank 0 is the starting condition, not an achievement; 8 is Xp 30 */ case ACH_RNK1: case ACH_RNK2: case ACH_RNK3: case ACH_RNK4: case ACH_RNK5: case ACH_RNK6: case ACH_RNK7: case ACH_RNK8: Sprintf(buf, "attained the rank of %s", rank_of(rank_to_xlev(absidx - (ACH_RNK1 - 1)), Role_switch, (achidx < 0) ? TRUE : FALSE)); you_have_X(buf); break; default: Sprintf(buf, " [Unexpected achievement #%d.]", achidx); enlght_out(buf); break; } /* switch */ } /* for */ if (awin != ge.en_win) { display_nhwindow(awin, TRUE); destroy_nhwindow(awin); } } /* record an achievement (add at end of list unless already present) */ void record_achievement(schar achidx) { int i, absidx; int repeat_achievement = 0; absidx = abs(achidx); /* valid achievements range from 1 to N_ACH-1; however, ranks can be stored as the complement (ie, negative) to track gender */ if ((achidx < 1 && (absidx < ACH_RNK1 || absidx > ACH_RNK8)) || achidx >= N_ACH) { impossible("Achievement #%d is out of range.", achidx); return; } /* the list has an extra slot so there is always at least one 0 at its end (more than one unless all N_ACH-1 possible achievements have been recorded); find first empty slot or achievement #achidx; an attempt to duplicate an achievement can happen if any of Bell, Candelabrum, Book, or Amulet is dropped then picked up again */ for (i = 0; u.uachieved[i]; ++i) if (abs(u.uachieved[i]) == absidx) { repeat_achievement = 1; break; } /* * We do the sound for an achievement, even if it has already been * achieved before. Some players might have set up level-based * theme music or something. We do let the sound interface know * that it's not the original achievement though. */ SoundAchievement(achidx, 0, repeat_achievement); if (repeat_achievement) return; /* already recorded, don't duplicate it */ u.uachieved[i] = achidx; /* avoid livelog for achievements recorded during final disclosure: nudist and blind-from-birth; also ascension which is suppressed by this gets logged separately in really_done() */ if (program_state.gameover) return; if (absidx >= ACH_RNK1 && absidx <= ACH_RNK8) { livelog_printf(achieve_msg[absidx].llflag, "attained the rank of %s (level %d)", rank_of(rank_to_xlev(absidx - (ACH_RNK1 - 1)), Role_switch, (achidx < 0) ? TRUE : FALSE), u.ulevel); } else if (achidx == ACH_SOKO_PRIZE || achidx == ACH_MINE_PRIZE) { /* need to supply extra information for these two */ short otyp = ((achidx == ACH_SOKO_PRIZE) ? svc.context.achieveo.soko_prize_otyp : svc.context.achieveo.mines_prize_otyp); /* note: OBJ_NAME() works here because both "bag of holding" and "amulet of reflection" are fully named in their objects[] entry but that's not true in the general case */ livelog_printf(achieve_msg[achidx].llflag, "%s %s", achieve_msg[achidx].msg, OBJ_NAME(objects[otyp])); } else { livelog_printf(achieve_msg[absidx].llflag, "%s", achieve_msg[absidx].msg); } } /* discard a recorded achievement; return True if removed, False otherwise */ boolean remove_achievement(schar achidx) { int i; for (i = 0; u.uachieved[i]; ++i) if (abs(u.uachieved[i]) == abs(achidx)) break; /* stop when found */ if (!u.uachieved[i]) /* not found */ return FALSE; /* list is 0 terminated so any beyond the removed one move up a slot */ do { u.uachieved[i] = u.uachieved[i + 1]; } while (u.uachieved[++i]); return TRUE; } /* used to decide whether there are any achievements to display */ int count_achievements(void) { int i, acnt = 0; for (i = 0; u.uachieved[i]; ++i) ++acnt; return acnt; } /* convert a rank index to an achievement number; encode it when female in order to subsequently report gender-specific ranks accurately */ schar achieve_rank(int rank) /* 1..8 */ { schar achidx = (schar) ((rank - 1) + ACH_RNK1); if (flags.female) achidx = -achidx; return achidx; } /* return True if sokoban branch has been entered, False otherwise */ boolean sokoban_in_play(void) { int achidx; /* TODO? move this to dungeon.c and test furthest level reached of the sokoban branch instead of relying on the entered-sokoban achievement */ for (achidx = 0; u.uachieved[achidx]; ++achidx) if (u.uachieved[achidx] == ACH_SOKO) return TRUE; return FALSE; } /* #chronicle command */ int do_gamelog(void) { #ifdef CHRONICLE if (gg.gamelog) { show_gamelog(ENL_GAMEINPROGRESS); } else { pline("No chronicled events."); } #else pline("Chronicle was turned off during compile-time."); #endif /* !CHRONICLE */ return ECMD_OK; } /* 'major' events for dumplog; inclusion or exclusion here may need tuning */ #define LL_majors (0L \ | LL_WISH \ | LL_ACHIEVE \ | LL_UMONST \ | LL_DIVINEGIFT \ | LL_LIFESAVE \ | LL_ARTIFACT \ | LL_GENOCIDE \ | LL_DUMP) /* explicitly for dumplog */ #define majorevent(llmsg) (((llmsg)->flags & LL_majors) != 0) #define spoilerevent(llmsg) (((llmsg)->flags & LL_SPOILER) != 0) /* #chronicle details */ void show_gamelog(int final) { #ifdef CHRONICLE struct gamelog_line *llmsg; winid win; char buf[BUFSZ]; int eventcnt = 0; win = create_nhwindow(NHW_TEXT); Sprintf(buf, "%s events:", final ? "Major" : "Logged"); putstr(win, 0, buf); for (llmsg = gg.gamelog; llmsg; llmsg = llmsg->next) { if (final && !majorevent(llmsg)) continue; if (!final && !wizard && spoilerevent(llmsg)) continue; if (!eventcnt++) putstr(win, 0, " Turn"); Snprintf(buf, sizeof buf, "%5ld: %s", llmsg->turn, llmsg->text); putstr(win, 0, buf); } /* since start of game is logged as a major event, 'eventcnt' should never end up as 0; for 'final', end of game is a major event too */ if (!eventcnt) putstr(win, 0, " none"); display_nhwindow(win, TRUE); destroy_nhwindow(win); #else nhUse(final); #endif /* !CHRONICLE */ return; } /* * Vanquished monsters. */ /* the two uppercase choices are implemented but suppressed from menu. also used in options.c */ const char *const vanqorders[NUM_VANQ_ORDER_MODES][3] = { { "t", "traditional: by monster level", "traditional: by monster level, by internal monster index" }, { "d", "by monster difficulty rating", "by monster difficulty rating, by internal monster index" }, { "a", "alphabetically, unique monsters separate", "alphabetically, first unique monsters, then others" }, { "A", "alphabetically, unique monsters intermixed", "alphabetically, unique monsters and others intermixed" }, { "C", "by monster class, high to low level in class", "by monster class, high to low level within class" }, { "c", "by monster class, low to high level in class", "by monster class, low to high level within class" }, { "n", "by count, high to low", "by count, high to low, by internal index within tied count" }, { "z", "by count, low to high", "by count, low to high, by internal index within tied count" }, }; staticfn int QSORTCALLBACK vanqsort_cmp( const genericptr vptr1, const genericptr vptr2) { int indx1 = *(short *) vptr1, indx2 = *(short *) vptr2, mlev1, mlev2, mstr1, mstr2, uniq1, uniq2, died1, died2, res; const char *name1, *name2, *punct; schar mcls1, mcls2; switch (flags.vanq_sortmode) { default: case VANQ_MLVL_MNDX: /* sort by monster level */ mlev1 = mons[indx1].mlevel; mlev2 = mons[indx2].mlevel; res = mlev2 - mlev1; /* mlevel high to low */ break; case VANQ_MSTR_MNDX: /* sort by monster toughness */ mstr1 = mons[indx1].difficulty; mstr2 = mons[indx2].difficulty; res = mstr2 - mstr1; /* monstr high to low */ break; case VANQ_ALPHA_SEP: uniq1 = ((mons[indx1].geno & G_UNIQ) && indx1 != PM_HIGH_CLERIC); uniq2 = ((mons[indx2].geno & G_UNIQ) && indx2 != PM_HIGH_CLERIC); if (uniq1 ^ uniq2) { /* one or other uniq, but not both */ res = uniq2 - uniq1; break; } /* else both unique or neither unique */ FALLTHROUGH; /*FALLTHRU*/ case VANQ_ALPHA_MIX: name1 = mons[indx1].pmnames[NEUTRAL]; name2 = mons[indx2].pmnames[NEUTRAL]; res = strcmpi(name1, name2); /* caseblind alpha, low to high */ break; case VANQ_MCLS_HTOL: case VANQ_MCLS_LTOH: /* mons[].mlet is a small integer, 1..N, of type plain char; if 'char' happens to be unsigned, (mlet1 - mlet2) would yield an inappropriate result when mlet2 is greater than mlet1, so force our copies (mcls1, mcls2) to be signed */ mcls1 = (schar) mons[indx1].mlet; mcls2 = (schar) mons[indx2].mlet; /* S_ANT through S_ZRUTY correspond to lowercase monster classes, S_ANGEL through S_ZOMBIE correspond to uppercase, and various punctuation characters are used for classes beyond those */ if (mcls1 > S_ZOMBIE && mcls2 > S_ZOMBIE) { /* force a specific order to the punctuation classes that's different from the internal order; internal order is ok if neither or just one is punctuation since letters have lower values so come out before punct */ static const char punctclasses[] = { S_LIZARD, S_EEL, S_GOLEM, S_GHOST, S_DEMON, S_HUMAN, '\0' }; if ((punct = strchr(punctclasses, mcls1)) != 0) mcls1 = (schar) (S_ZOMBIE + 1 + (int) (punct - punctclasses)); if ((punct = strchr(punctclasses, mcls2)) != 0) mcls2 = (schar) (S_ZOMBIE + 1 + (int) (punct - punctclasses)); } res = mcls1 - mcls2; /* class */ if (res == 0) { /* Riders are in the same class as major demons, yielding res==0 above when both mcls1 and mcls2 are either Riders or demons or one of each; force Riders to be sorted before demons */ res = is_rider(&mons[indx2]) - is_rider(&mons[indx1]); /* res -1 => #1 is a Rider, #2 isn't; 0 => both Riders or neither; +1 => #2 is a Rider, #1 isn't */ if (res) break; mlev1 = mons[indx1].mlevel; mlev2 = mons[indx2].mlevel; res = mlev1 - mlev2; /* mlevel low to high */ if (flags.vanq_sortmode == VANQ_MCLS_HTOL) res = -res; /* mlevel high to low */ } break; case VANQ_COUNT_H_L: case VANQ_COUNT_L_H: died1 = svm.mvitals[indx1].died; died2 = svm.mvitals[indx2].died; res = died2 - died1; /* dead count high to low */ if (flags.vanq_sortmode == VANQ_COUNT_L_H) res = -res; /* dead count low to high */ break; } /* tiebreaker: internal mons[] index */ if (res == 0) res = indx1 - indx2; /* mndx low to high */ return res; } /* returns -1 if cancelled via ESC */ int set_vanq_order(boolean for_vanq) { winid tmpwin; menu_item *selected; anything any; char buf[BUFSZ]; const char *desc; int i, n, choice, clr = NO_COLOR; tmpwin = create_nhwindow(NHW_MENU); start_menu(tmpwin, MENU_BEHAVE_STANDARD); any = cg.zeroany; /* zero out all bits */ for (i = 0; i < SIZE(vanqorders); i++) { if (i == VANQ_ALPHA_MIX || i == VANQ_MCLS_HTOL) /* skip these */ continue; /* suppress some orderings if this menu if for 'm #genocided' */ if (!for_vanq && (i == VANQ_COUNT_H_L || i == VANQ_COUNT_L_H)) continue; desc = vanqorders[i][2]; /* unique monsters can't be genocided so "alpha, unique separate" and "alpha, unique intermixed" are confusing descriptions when this menu is for #genocided rather than for #vanquished */ if (!for_vanq && i == VANQ_ALPHA_SEP) desc = "alphabetically"; any.a_int = i + 1; add_menu(tmpwin, &nul_glyphinfo, &any, *vanqorders[i][0], 0, ATR_NONE, clr, desc, (i == flags.vanq_sortmode) ? MENU_ITEMFLAGS_SELECTED : MENU_ITEMFLAGS_NONE); } Sprintf(buf, "Sort order for %s", for_vanq ? "vanquished monster counts (also genocided types)" : "genocided monster types (also vanquished counts)"); end_menu(tmpwin, buf); n = select_menu(tmpwin, PICK_ONE, &selected); destroy_nhwindow(tmpwin); if (n > 0) { choice = selected[0].item.a_int - 1; /* skip preselected entry if we have more than one item chosen */ if (n > 1 && choice == flags.vanq_sortmode) choice = selected[1].item.a_int - 1; free((genericptr_t) selected); flags.vanq_sortmode = choice; } return (n < 0) ? -1 : flags.vanq_sortmode; } /* #vanquished command */ int dovanquished(void) { list_vanquished(iflags.menu_requested ? 'A' : 'y', FALSE); iflags.menu_requested = FALSE; return ECMD_OK; } /* high priests aren't unique but are flagged as such to simplify something */ #define UniqCritterIndx(mndx) \ ((mons[mndx].geno & G_UNIQ) != 0 && mndx != PM_HIGH_CLERIC) #define done_stopprint program_state.stopprint /* used for #vanquished and end of game disclosure and end of game dumplog */ void list_vanquished(char defquery, boolean ask) { int i; int pfx, nkilled; unsigned ntypes, ni; long total_killed = 0L; winid klwin; short mindx[NUMMONS]; char c, buf[BUFSZ], buftoo[BUFSZ]; /* 'A' is only supplied by 'm #vanquished'; 'd' is only supplied by dump_everything() when writing dumplog, so won't happen if built without '#define DUMPLOG' but there's no need for conditionals here */ boolean force_sort = (defquery == 'A'), dumping = (defquery == 'd'); /* normally we don't ask about sort order for the vanquished list unless it contains at least two entries; however, if player has used explicit 'm #vanquished', choose order no matter what it contains so far */ if (force_sort) { /* iflags.menu_requested via dovanquished() */ /* choose value for vanq_sortmode via menu; ESC cancels choosing sort order but continues with vanquishd monsters display */ (void) set_vanq_order(TRUE); } if (dumping || force_sort) { /* switch from 'A' or 'd' to 'y'; 'ask' is already False for the cases that might supply 'A' or 'd' */ defquery = 'y'; ask = FALSE; /* redundant */ } /* get totals first */ ntypes = 0; for (i = LOW_PM; i < NUMMONS; i++) { if ((nkilled = (int) svm.mvitals[i].died) == 0) continue; mindx[ntypes++] = i; total_killed += (long) nkilled; } /* vanquished creatures list; * includes all dead monsters, not just those killed by the player */ if (ntypes != 0) { char mlet, prev_mlet = 0; /* used as small integer, not character */ boolean class_header, uniq_header, Rider, was_uniq = FALSE, special_hdr = FALSE; if (ask) { char allow_yn[10]; if (ntypes > 1) { Strcpy(allow_yn, ynaqchars); } else { Strcpy(allow_yn, ynqchars); /* don't include 'a', but */ Strcat(allow_yn, "\033a"); /* allow user to answer 'a' */ if (defquery == 'a') /* potential default from 'disclose' */ defquery = 'y'; } c = yn_function("Do you want an account of creatures vanquished?", allow_yn, defquery, TRUE); } else { c = defquery; } if (c == 'q') done_stopprint++; if (c == 'y' || c == 'a') { if (c == 'a' && ntypes > 1) { /* ask user to choose sort order */ /* choose value for vanq_sortmode via menu; ESC cancels list of vanquished monsters but does not set 'done_stopprint' */ if (set_vanq_order(TRUE) < 0) return; } uniq_header = (flags.vanq_sortmode == VANQ_ALPHA_SEP); class_header = ((flags.vanq_sortmode == VANQ_MCLS_LTOH || flags.vanq_sortmode == VANQ_MCLS_HTOL) && ntypes > 1); klwin = create_nhwindow(NHW_MENU); putstr(klwin, 0, "Vanquished creatures:"); if (!dumping) putstr(klwin, 0, ""); qsort((genericptr_t) mindx, ntypes, sizeof *mindx, vanqsort_cmp); for (ni = 0; ni < ntypes; ni++) { i = mindx[ni]; nkilled = svm.mvitals[i].died; Rider = is_rider(&mons[i]); mlet = mons[i].mlet; if (class_header && (mlet != prev_mlet || (special_hdr && !Rider))) { if (!Rider) { Strcpy(buf, def_monsyms[(int) mlet].explain); special_hdr = FALSE; } else { Strcpy(buf, "Rider"); special_hdr = TRUE; } /* 'ask' implies final disclosure, where highlighting of various header lines is suppressed */ putstr(klwin, ask ? ATR_NONE : iflags.menu_headings.attr, upstart(buf)); prev_mlet = mlet; } if (UniqCritterIndx(i)) { Sprintf(buf, "%s%s", !type_is_pname(&mons[i]) ? "the " : "", mons[i].pmnames[NEUTRAL]); if (nkilled > 1) { switch (nkilled) { case 2: Sprintf(eos(buf), " (twice)"); break; case 3: Sprintf(eos(buf), " (thrice)"); break; default: Sprintf(eos(buf), " (%d times)", nkilled); break; } } was_uniq = TRUE; } else { if (uniq_header && was_uniq) { putstr(klwin, 0, ""); was_uniq = FALSE; } /* trolls or undead might have come back, but we don't keep track of that */ if (nkilled == 1) Strcpy(buf, an(mons[i].pmnames[NEUTRAL])); else Sprintf(buf, "%3d %s", nkilled, makeplural(mons[i].pmnames[NEUTRAL])); } /* number of leading spaces to match 3 digit prefix */ pfx = !strncmpi(buf, "the ", 4) ? 0 : !strncmpi(buf, "an ", 3) ? 1 : !strncmpi(buf, "a ", 2) ? 2 : !digit(buf[2]) ? 4 : 0; if (class_header) ++pfx; Snprintf(buftoo, sizeof buftoo, "%*s%s", pfx, "", buf); putstr(klwin, 0, buftoo); } /* * if (Hallucination) * putstr(klwin, 0, "and a partridge in a pear tree"); */ if (ntypes > 1) { if (!dumping) putstr(klwin, 0, ""); Sprintf(buf, "%ld creatures vanquished.", total_killed); putstr(klwin, 0, buf); } display_nhwindow(klwin, TRUE); destroy_nhwindow(klwin); } /* * For end-of-game disclosure, we're only called when some monsters * were vanquished and won't reach these 'else-if's. * * If no monsters have been vanquished, we're either called for game * still in progress, so use present tense via pline(), or for dumplog * which needs putstr() and past tense. */ } else if (!program_state.gameover) { /* #vanquished rather than final disclosure, so pline() is ok */ pline("No creatures have been vanquished."); #ifdef DUMPLOG } else if (dumping) { putstr(0, 0, "No creatures were vanquished."); /* not pline() */ #endif } } /* number of monster species which have been genocided */ int num_genocides(void) { int i, n = 0; for (i = LOW_PM; i < NUMMONS; ++i) { if (svm.mvitals[i].mvflags & G_GENOD) { ++n; if (UniqCritterIndx(i)) impossible("unique creature '%d: %s' genocided?", i, mons[i].pmnames[NEUTRAL]); } } return n; } /* return a count of the number of extinct species */ staticfn int num_extinct(void) { int i, n = 0; for (i = LOW_PM; i < NUMMONS; ++i) { if (UniqCritterIndx(i)) continue; if ((svm.mvitals[i].mvflags & G_GONE) == G_EXTINCT) ++n; } return n; } /* collect both genocides and extinctions, skipping uniques */ staticfn int num_gone(int mvflags, int *mindx) { uchar mflg = (uchar) mvflags; int i, n = 0; (void) memset((genericptr_t) mindx, 0, NUMMONS * sizeof *mindx); for (i = LOW_PM; i < NUMMONS; ++i) { /* uniques can't be genocided but can become extinct; however, they're never reported as extinct, so skip them */ if (UniqCritterIndx(i)) continue; if ((svm.mvitals[i].mvflags & mflg) != 0) mindx[n++] = i; } return n; } /* show genocided and extinct monster types for final disclosure/dumplog or for the #genocided command */ void list_genocided(char defquery, boolean ask) { int i, mndx; int ngenocided, nextinct, ngone, mvflags, mindx[NUMMONS]; char c; winid klwin; char buf[BUFSZ]; boolean genoing, /* prompting for genocide or class genocide */ dumping; /* for DUMPLOG; doesn't need to be conditional */ boolean both = (program_state.gameover || wizard || discover); dumping = (defquery == 'd'); genoing = (defquery == 'g'); if (dumping || genoing) defquery = 'y'; if (genoing) both = FALSE; /* genocides only, not extinctions */ /* this goes through the whole monster list up to three times but will happen rarely and is simpler than a more general single pass check; extinctions are only revealed during end of game disclosure or when running in wizard or explore mode */ ngenocided = num_genocides(); nextinct = both ? num_extinct() : 0; mvflags = G_GENOD | (both ? G_EXTINCT : 0); ngone = num_gone(mvflags, mindx); /* genocided or extinct species list */ if (ngone > 0) { Sprintf(buf, "Do you want a list of %sspecies%s%s?", (nextinct && !ngenocided) ? "extinct " : "", (ngenocided) ? " genocided" : "", (nextinct && ngenocided) ? " and extinct" : ""); c = ask ? yn_function(buf, (ngone > 1) ? "ynaq" : "ynq\033a", defquery, TRUE) : defquery; if (c == 'q') done_stopprint++; if (c == 'y' || c == 'a') { int save_sortmode; char mlet, prev_mlet = 0; boolean class_header = FALSE; if (ngone > 1) { if (c == 'a') { /* ask player to choose sort order */ /* #genocided shares #vanquished's sort order */ if (set_vanq_order(FALSE) < 0) return; } /* sort orderings count-high-to-low or count-low-to-high don't make sense for genocides; if the preferred order to set to either of those, use alphabetical instead; note: the tie breaker for by-class is level-high-to-low or level-low-to-high rather than count so is ok as-is */ save_sortmode = flags.vanq_sortmode; if (flags.vanq_sortmode == VANQ_COUNT_H_L || flags.vanq_sortmode == VANQ_COUNT_L_H) flags.vanq_sortmode = VANQ_ALPHA_MIX; qsort((genericptr_t) mindx, ngone, sizeof *mindx, vanqsort_cmp); class_header = (flags.vanq_sortmode == VANQ_MCLS_LTOH || flags.vanq_sortmode == VANQ_MCLS_HTOL); flags.vanq_sortmode = save_sortmode; } klwin = create_nhwindow(NHW_MENU); Sprintf(buf, "%s%s species:", (ngenocided) ? "Genocided" : "Extinct", (nextinct && ngenocided) ? " or extinct" : ""); putstr(klwin, 0, buf); if (!dumping) putstr(klwin, 0, ""); for (i = 0; i < ngone; ++i) { mndx = mindx[i]; mlet = mons[mndx].mlet; if (class_header && mlet != prev_mlet) { Strcpy(buf, def_monsyms[(int) mlet].explain); /* 'ask' implies final disclosure, where highlighting of various header lines is suppressed */ putstr(klwin, ask ? ATR_NONE : iflags.menu_headings.attr, upstart(buf)); prev_mlet = mlet; } Sprintf(buf, " %s", makeplural(mons[mndx].pmnames[NEUTRAL])); /* * "Extinct" is unfortunate terminology. A species * is marked extinct when its birth limit is reached, * but there might be members of the species still * alive, contradicting the meaning of the word. * * We only append "(extinct)" if the G_GENOD bit is * clear. During normal play, 'mndx' won't be in the * collected list unless that bit is set. */ if ((svm.mvitals[mndx].mvflags & G_GONE) == G_EXTINCT) Strcat(buf, " (extinct)"); putstr(klwin, 0, buf); } if (!dumping) putstr(klwin, 0, ""); if (ngenocided > 0) { Sprintf(buf, "%d species genocided.", ngenocided); putstr(klwin, 0, buf); } if (nextinct > 0) { Sprintf(buf, "%d species extinct.", nextinct); putstr(klwin, 0, buf); } display_nhwindow(klwin, TRUE); destroy_nhwindow(klwin); } /* See the comment for similar code near the end of list_vanquished(). */ } else if (!program_state.gameover) { /* #genocided rather than final disclosure, so pline() is ok and extinction has been ignored */ pline("No creatures have been genocided%s.", genoing ? " yet" : ""); #ifdef DUMPLOG } else if (dumping) { /* 'gameover' is True if we make it here */ putstr(0, 0, "No species were genocided or became extinct."); #endif } } /* M-g - #genocided command */ int dogenocided(void) { list_genocided(iflags.menu_requested ? 'a' : 'y', FALSE); return ECMD_OK; } DISABLE_WARNING_FORMAT_NONLITERAL /* #wizborn extended command */ int doborn(void) { static const char fmt[] = "%4i %4i %c %-30s"; int i; winid datawin = create_nhwindow(NHW_TEXT); char buf[BUFSZ]; int nborn = 0, ndied = 0; putstr(datawin, 0, "died born"); for (i = LOW_PM; i < NUMMONS; i++) if (svm.mvitals[i].born || svm.mvitals[i].died || (svm.mvitals[i].mvflags & G_GONE) != 0) { Sprintf(buf, fmt, svm.mvitals[i].died, svm.mvitals[i].born, ((svm.mvitals[i].mvflags & G_GONE) == G_EXTINCT) ? 'E' : ((svm.mvitals[i].mvflags & G_GONE) == G_GENOD) ? 'G' : ((svm.mvitals[i].mvflags & G_GONE) != 0) ? 'X' : ' ', mons[i].pmnames[NEUTRAL]); putstr(datawin, 0, buf); nborn += svm.mvitals[i].born; ndied += svm.mvitals[i].died; } putstr(datawin, 0, ""); Sprintf(buf, fmt, ndied, nborn, ' ', ""); display_nhwindow(datawin, FALSE); destroy_nhwindow(datawin); return ECMD_OK; } RESTORE_WARNING_FORMAT_NONLITERAL /* * align_str(), piousness(), mstatusline() and ustatusline() once resided * in pline.c, then got moved to priest.c just to be out of there. They * fit better here. */ const char * align_str(aligntyp alignment) { switch ((int) alignment) { case A_CHAOTIC: return "chaotic"; case A_NEUTRAL: return "neutral"; case A_LAWFUL: return "lawful"; case A_NONE: return "unaligned"; } return "unknown"; } staticfn char * size_str(int msize) { static char outbuf[40]; switch (msize) { case MZ_TINY: Strcpy(outbuf, "tiny"); break; case MZ_SMALL: Strcpy(outbuf, "small"); break; case MZ_MEDIUM: Strcpy(outbuf, "medium"); break; case MZ_LARGE: Strcpy(outbuf, "large"); break; case MZ_HUGE: Strcpy(outbuf, "huge"); break; case MZ_GIGANTIC: Strcpy(outbuf, "gigantic"); break; default: Sprintf(outbuf, "unknown size (%d)", msize); break; } return outbuf; } /* used for self-probing */ char * piousness(boolean showneg, const char *suffix) { static char buf[32]; /* bigger than "insufficiently neutral" */ const char *pio; /* note: piousness 20 matches MIN_QUEST_ALIGN (quest.h) */ if (u.ualign.record >= 20) pio = "piously"; else if (u.ualign.record > 13) pio = "devoutly"; else if (u.ualign.record > 8) pio = "fervently"; else if (u.ualign.record > 3) pio = "stridently"; else if (u.ualign.record == 3) pio = ""; else if (u.ualign.record > 0) pio = "haltingly"; else if (u.ualign.record == 0) pio = "nominally"; else if (!showneg) pio = "insufficiently"; else if (u.ualign.record >= -3) pio = "strayed"; else if (u.ualign.record >= -8) pio = "sinned"; else pio = "transgressed"; Sprintf(buf, "%s", pio); if (suffix && (!showneg || u.ualign.record >= 0)) { if (u.ualign.record != 3) Strcat(buf, " "); Strcat(buf, suffix); } return buf; } /* stethoscope or probing applied to monster -- one-line feedback */ void mstatusline(struct monst *mtmp) { aligntyp alignment = mon_aligntyp(mtmp); char info[BUFSZ], monnambuf[BUFSZ]; info[0] = 0; if (mtmp->mtame) { Strcat(info, ", tame"); if (wizard) { Sprintf(eos(info), " (%d", mtmp->mtame); if (!mtmp->isminion) Sprintf(eos(info), "; hungry %ld; apport %d", EDOG(mtmp)->hungrytime, EDOG(mtmp)->apport); Strcat(info, ")"); } } else if (mtmp->mpeaceful) Strcat(info, ", peaceful"); if (mtmp->data == &mons[PM_LONG_WORM]) { int segndx, nsegs = count_wsegs(mtmp); /* the worm code internals don't consider the head to be one of the worm's segments, but we count it as such when presenting worm feedback to the player */ if (!nsegs) { Strcat(info, ", single segment"); } else { ++nsegs; /* include head in the segment count */ segndx = wseg_at(mtmp, gb.bhitpos.x, gb.bhitpos.y); Sprintf(eos(info), ", %d%s of %d segments", segndx, ordin(segndx), nsegs); } } if (ismnum(mtmp->cham) && mtmp->data != &mons[mtmp->cham]) /* don't reveal the innate form (chameleon, vampire, &c), just expose the fact that this current form isn't it */ Strcat(info, ", shapechanger"); /* pets eating mimic corpses mimic while eating, so this comes first */ if (mtmp->meating) Strcat(info, ", eating"); /* a stethoscope exposes mimic before getting here so this won't be relevant for it, but wand of probing doesn't */ if (mtmp->mundetected || mtmp->m_ap_type || visible_region_at(gb.bhitpos.x, gb.bhitpos.y)) mhidden_description(mtmp, MHID_PREFIX | MHID_ARTICLE | MHID_ALTMON | MHID_REGION, eos(info)); if (mtmp->mcan) Strcat(info, ", cancelled"); if (mtmp->mconf) Strcat(info, ", confused"); if (mtmp->mblinded || !mtmp->mcansee) Strcat(info, ", blind"); if (mtmp->mstun) Strcat(info, ", stunned"); if (mtmp->msleeping) Strcat(info, ", asleep"); #if 0 /* unfortunately mfrozen covers temporary sleep and being busy * (donning armor, for instance) as well as paralysis */ else if (mtmp->mfrozen) Strcat(info, ", paralyzed"); #else else if (mtmp->mfrozen || !mtmp->mcanmove) Strcat(info, ", can't move"); #endif /* [arbitrary reason why it isn't moving] */ else if ((mtmp->mstrategy & STRAT_WAITMASK) != 0) Strcat(info, ", meditating"); if (mtmp->mflee) Strcat(info, ", scared"); if (mtmp->mtrapped) Strcat(info, ", trapped"); if (mtmp->mspeed) Strcat(info, (mtmp->mspeed == MFAST) ? ", fast" : (mtmp->mspeed == MSLOW) ? ", slow" : ", [? speed]"); if (mtmp->minvis) Strcat(info, ", invisible"); if (mtmp == u.ustuck) { struct permonst *pm = u.ustuck->data; /* being swallowed/engulfed takes priority over sticks(youmonst); this used to have that backwards and checked sticks() first */ Strcat(info, u.uswallow ? (digests(pm) ? ", digesting you" /* note: the "swallowing you" case won't happen because all animal engulfers either digest their victims (purple worm) or enfold them (trappers and lurkers above) */ : (is_animal(pm) && !enfolds(pm)) ? ", swallowing you" : ", engulfing you") /* !u.uswallow; if both youmonst and ustuck are holders, youmonst wins */ : (!sticks(gy.youmonst.data) ? ", holding you" : ", held by you")); } if (mtmp == u.usteed) { Strcat(info, ", carrying you"); if (Wounded_legs) { /* EWounded_legs is used to track left/right/both rather than some form of extrinsic impairment; HWounded_legs is used for timeout; both apply to steed instead of hero when mounted */ long legs = (EWounded_legs & BOTH_SIDES); const char *what = mbodypart(mtmp, LEG); if (legs == BOTH_SIDES) what = makeplural(what); Sprintf(eos(info), ", injured %s", what); } } if (mtmp->mleashed) Strcat(info, ", leashed"); /* avoid "Status of the invisible newt ..., invisible" */ /* and unlike a normal mon_nam, use "saddled" even if it has a name */ Strcpy(monnambuf, x_monnam(mtmp, ARTICLE_YOUR, (char *) 0, (SUPPRESS_IT | SUPPRESS_INVISIBLE), FALSE)); pline("Status of %s (%s, %s): Level %d HP %d(%d) AC %d%s.", monnambuf, align_str(alignment), size_str(mtmp->data->msize), mtmp->m_lev, mtmp->mhp, mtmp->mhpmax, find_mac(mtmp), info); } /* stethoscope or probing applied to hero -- one-line feedback */ void ustatusline(void) { NhRegion *reg; char info[BUFSZ]; size_t ln; info[0] = '\0'; if (Sick) { Strcat(info, ", dying from"); if (u.usick_type & SICK_VOMITABLE) Strcat(info, " food poisoning"); if (u.usick_type & SICK_NONVOMITABLE) { if (u.usick_type & SICK_VOMITABLE) Strcat(info, " and"); Strcat(info, " illness"); } } if (Stoned) Strcat(info, ", solidifying"); if (Slimed) Strcat(info, ", becoming slimy"); if (Strangled) Strcat(info, ", being strangled"); if (Vomiting) Strcat(info, ", nauseated"); /* !"nauseous" */ if (Confusion) Strcat(info, ", confused"); if (Blind) { Strcat(info, ", blind"); if (u.ucreamed) { if ((long) u.ucreamed < BlindedTimeout || Blindfolded || !haseyes(gy.youmonst.data)) Strcat(info, ", cover"); Strcat(info, "ed by sticky goop"); } /* note: "goop" == "glop"; variation is intentional */ } if (Stunned) Strcat(info, ", stunned"); if (Wounded_legs && !u.usteed) { /* EWounded_legs is used to track left/right/both rather than some form of extrinsic impairment; HWounded_legs is used for timeout; both apply to steed instead of hero when mounted */ long legs = (EWounded_legs & BOTH_SIDES); const char *what = body_part(LEG); if (legs == BOTH_SIDES) what = makeplural(what); /* when it's just one leg, ^X reports which, left or right; ustatusline() doesn't, in order to keep the output a bit shorter */ Sprintf(eos(info), ", injured %s", what); } if (Glib) Sprintf(eos(info), ", slippery %s", fingers_or_gloves(TRUE)); if (u.utrap) Strcat(info, ", trapped"); if (Fast) Strcat(info, Very_fast ? ", very fast" : ", fast"); if (u.uundetected) Strcat(info, ", concealed"); else if (U_AP_TYPE != M_AP_NOTHING) Strcat(info, ", disguised"); if (Invis) Strcat(info, ", invisible"); if (u.ustuck) { if (u.uswallow) Strcat(info, digests(u.ustuck->data) ? ", being digested by " : ", engulfed by "); else if (!sticks(gy.youmonst.data)) Strcat(info, ", held by "); else Strcat(info, ", holding "); /* FIXME? a_monnam() uses x_monnam() which has a special case that forces "the" instead of "a" when formatting u.ustuck while hero is swallowed; we don't really want that here but it isn't worth fiddling with just for self-probing while engulfed */ Strcat(info, a_monnam(u.ustuck)); } if (!u.uswallow && (reg = visible_region_at(u.ux, u.uy)) != 0 && (ln = strlen(info)) < sizeof info) Snprintf(eos(info), sizeof info - ln, ", in a cloud of %s", reg_damg(reg) ? "poison gas" : "vapor"); pline("Status of %s (%s): Level %d HP %d(%d) AC %d%s.", svp.plname, piousness(FALSE, align_str(u.ualign.type)), Upolyd ? mons[u.umonnum].mlevel : u.ulevel, Upolyd ? u.mh : u.uhp, Upolyd ? u.mhmax : u.uhpmax, u.uac, info); } /* for 'onefile' processing where end of this file isn't necessarily the end of the source code seen by the compiler */ #undef enl_msg #undef you_are #undef you_have #undef you_can #undef you_have_been #undef you_have_never #undef you_have_X #undef LL_majors #undef majorevent #undef spoilerevent #undef UniqCritterIndx #undef done_stopprint /*insight.c*/
1
0.92286
1
0.92286
game-dev
MEDIA
0.749985
game-dev
0.773681
1
0.773681
11011010/BFA-Frankenstein-Core
3,351
src/server/scripts/EasternKingdoms/TheStockade/boss_lord_overheat.cpp
/* * Copyright (C) 2020 BfaCore * * 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/>. */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "the_stockade.h" enum Spells { SPELL_FIREBALL = 12466, //starts 1-2 secs from pull SPELL_OVERHEAT = 86633, //probably cast every 10 secs, need to confirm. SPELL_RAIN_OF_FIRE = 86636 //probably cast every 10 secs, need to confirm }; enum Events { EVENT_OVERHEAT = 1, EVENT_RAIN_OF_FIRE, EVENT_FIREBALL }; enum Says { SAY_PULL = 0, //Yell: ALL MUST BURN! SAY_DEATH = 1 //Yell: FIRE... EXTINGUISHED! }; class boss_lord_overheat : public CreatureScript { public: boss_lord_overheat() : CreatureScript("boss_lord_overheat") {} struct boss_lord_overheatAI : public BossAI { boss_lord_overheatAI(Creature* creature) : BossAI(creature, DATA_LORD_OVERHEAT) { } void EnterCombat(Unit* /*who*/) override { _EnterCombat(); Talk(SAY_PULL); events.ScheduleEvent(EVENT_FIREBALL, Seconds(2)); events.ScheduleEvent(EVENT_OVERHEAT, Seconds(9), Seconds(11)); events.ScheduleEvent(EVENT_RAIN_OF_FIRE, Seconds(10), Seconds(13)); } void JustDied(Unit* /*killer*/) override { Talk(SAY_DEATH); _JustDied(); } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_FIREBALL: DoCastVictim(SPELL_FIREBALL); events.Repeat(Seconds(2)); break; case EVENT_OVERHEAT: if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100.0f, true)) DoCast(target, SPELL_OVERHEAT); events.Repeat(Seconds(9), Seconds(10)); break; case EVENT_RAIN_OF_FIRE: DoCastAOE(SPELL_RAIN_OF_FIRE); events.Repeat(Seconds(15), Seconds(20)); break; default: break; } if (me->HasUnitState(UNIT_STATE_CASTING)) return; } DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* creature) const override { return GetStormwindStockadeAI<boss_lord_overheatAI>(creature); } }; void AddSC_boss_lord_overheat() { new boss_lord_overheat(); }
1
0.961423
1
0.961423
game-dev
MEDIA
0.9232
game-dev
0.805341
1
0.805341
LtxProgrammer/Changed-Minecraft-Mod
2,548
src/main/java/net/ltxprogrammer/changed/fluid/WolfGas.java
package net.ltxprogrammer.changed.fluid; import net.ltxprogrammer.changed.Changed; import net.ltxprogrammer.changed.init.ChangedBlocks; import net.ltxprogrammer.changed.init.ChangedFluids; import net.ltxprogrammer.changed.init.ChangedTransfurVariants; import net.ltxprogrammer.changed.util.Color3; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.block.LiquidBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.material.Fluid; import net.minecraft.world.level.material.FluidState; import net.minecraftforge.fluids.FluidAttributes; import net.minecraftforge.fluids.ForgeFlowingFluid; public abstract class WolfGas extends TransfurGas { public static final ForgeFlowingFluid.Properties PROPERTIES = new ForgeFlowingFluid.Properties( ChangedFluids.WOLF_GAS, ChangedFluids.WOLF_GAS_FLOWING, FluidAttributes.builder(Changed.modResource("blocks/wolf_gas"), Changed.modResource("blocks/wolf_gas")) .viscosity(200).color(0x7FFFFFFF)) .explosionResistance(100f) .tickRate(4).levelDecreasePerBlock(1) .block(ChangedBlocks.WOLF_GAS); protected WolfGas() { super(PROPERTIES, ChangedTransfurVariants.GAS_WOLF); } @Override public Color3 getColor() { return Color3.fromInt(0x7fbaff); } @Override public BlockState createLegacyBlock(FluidState fluidState) { return ChangedBlocks.WOLF_GAS.get().defaultBlockState().setValue(LiquidBlock.LEVEL, getLegacyLevel(fluidState)); } public static class Flowing extends WolfGas { public Flowing() { registerDefaultState(getStateDefinition().any().setValue(LEVEL, 7)); } protected void createFluidStateDefinition(StateDefinition.Builder<Fluid, FluidState> builder) { super.createFluidStateDefinition(builder); builder.add(LEVEL); } public int getAmount(FluidState state) { return state.getValue(LEVEL); } public boolean isSource(FluidState state) { return false; } } public static class Source extends WolfGas { public Source() {} public int getAmount(FluidState state) { return 8; } public boolean isSource(FluidState state) { return true; } } }
1
0.632055
1
0.632055
game-dev
MEDIA
0.993347
game-dev
0.702477
1
0.702477
q-gears/q-gears
2,556
QGearsMain/src/map/QGearsMapFileManager.cpp
/* ----------------------------------------------------------------------------- Copyright (c) 27.10.2013 Tobias Peters <tobias.peters@kreativeffekt.at> This file is part of Q-Gears Q-Gears 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, version 2.0 (GPLv2) of the License. Q-Gears 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. ----------------------------------------------------------------------------- */ #include "map/QGearsMapFileManager.h" template<> QGears::MapFileManager *Ogre::Singleton<QGears::MapFileManager>::msSingleton = nullptr; namespace QGears { //-------------------------------------------------------------------------- MapFileManager *MapFileManager::getSingletonPtr() { return msSingleton; } //-------------------------------------------------------------------------- MapFileManager &MapFileManager::getSingleton() { assert( msSingleton ); return(*msSingleton ); } //-------------------------------------------------------------------------- MapFileManager::MapFileManager() { mResourceType = MapFile::RESOURCE_TYPE; // low, because it will likely reference other resources mLoadOrder = 30.0f; // this is how we register the ResourceManager with OGRE Ogre::ResourceGroupManager::getSingleton()._registerResourceManager( mResourceType, this ); } //-------------------------------------------------------------------------- MapFileManager::~MapFileManager() { Ogre::ResourceGroupManager::getSingleton()._unregisterResourceManager( mResourceType ); } //-------------------------------------------------------------------------- Ogre::Resource *MapFileManager::createImpl( const Ogre::String &name , Ogre::ResourceHandle handle, const Ogre::String &group, bool isManual , Ogre::ManualResourceLoader *loader , const Ogre::NameValuePairList *createParams ) { return new MapFile( this, name, handle, group, isManual, loader ); } //-------------------------------------------------------------------------- }
1
0.943192
1
0.943192
game-dev
MEDIA
0.567098
game-dev,desktop-app
0.564362
1
0.564362
cms-sw/cmssw
7,054
FWCore/Framework/interface/GetterOfProducts.h
#ifndef FWCore_Framework_GetterOfProducts_h #define FWCore_Framework_GetterOfProducts_h /** \class edm::GetterOfProducts Intended to be used by EDProducers, EDFilters, and EDAnalyzers to get products from the Event, Run, LuminosityBlock or ProcessBlock. In most cases, the preferred method to get products is not to use this class. In most cases the preferred method is to use the function getByToken with a token obtained from a consumes call which was passed a configurable InputTag. But occasionally getByToken will not work because one wants to select the product based on the data that is available and not have to modify the configuration as the data content changes. A real example would be a module that collects HLT trigger information from products written by the many HLT filters. The number and labels of those products vary so much that it would not be reasonable to modify the configuration to get all of them each time a different HLT trigger table was used. This class handles that and similar cases. This method can select by type and branch type. There exists a predicate (in ProcessMatch.h) to also select on process name. It is possible to write other predicates which will select on anything in the ProductDescription. The selection is done during the initialization of the process. During this initialization a list of tokens is filled with all matching products from the ProductRegistry. This list of tokens is accessible to the module. The fillHandles functions will get a handle for each product on the list of tokens that is actually present in the current Event, LuminosityBlock, Run, or ProcessBlock. Internally, this function uses tokens and depends on the same things as getByToken and benefits from performance optimizations of getByToken. Typically one would use this as follows: Add these headers: #include "FWCore/Framework/interface/GetterOfProducts.h" #include "FWCore/Framework/interface/ProcessMatch.h" Add this data member: edm::GetterOfProducts<YourDataType> getterOfProducts_; Add these to the constructor (1st line is usually in the data member initializer list and the 2nd line in the body of the constructor) getterOfProducts_(edm::ProcessMatch(processName_), this) { callWhenNewProductsRegistered(getterOfProducts_); Add this to the method called for each event: std::vector<edm::Handle<YourDataType> > handles; getterOfProducts_.fillHandles(event, handles); And that is all you need in most cases. In the above example, "YourDataType" is the type of the product you want to get. There are some variants for special cases - Use an extra argument to the constructor for products in a Run, LuminosityBlock or ProcessBlock For example: getterOfProducts_ = edm::GetterOfProducts<Thing>(edm::ProcessMatch(processName_), this, edm::InRun); - You can use multiple GetterOfProducts's in the same module. The only tricky part is to use a lambda as follows to register the callbacks: callWhenNewProductsRegistered([this](edm::ProductDescription const& bd) { getterOfProducts1_(bd); getterOfProducts2_(bd); }); - One can use "*" for the processName_ to select from all processes (this will just select based on type). - You can define your own predicate to replace ProcessMatch in the above example and select based on anything in the ProductDescription. See ProcessMatch.h for an example of how to write this predicate. \author W. David Dagenhart, created 6 August, 2012 */ #include "DataFormats/Common/interface/Handle.h" #include "DataFormats/Provenance/interface/ProductDescription.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/EventForOutput.h" #include "FWCore/Framework/interface/LuminosityBlock.h" #include "FWCore/Framework/interface/LuminosityBlockForOutput.h" #include "FWCore/Framework/interface/ProcessBlock.h" #include "FWCore/Framework/interface/ProcessBlockForOutput.h" #include "FWCore/Framework/interface/Run.h" #include "FWCore/Framework/interface/RunForOutput.h" #include "FWCore/Framework/interface/WillGetIfMatch.h" #include "FWCore/Utilities/interface/BranchType.h" #include "FWCore/Utilities/interface/EDGetToken.h" #include "FWCore/Utilities/interface/TypeID.h" #include <functional> #include <memory> #include <string> #include <vector> namespace edm { template <typename U> struct BranchTypeForContainerType { static constexpr BranchType branchType = InEvent; }; template <> struct BranchTypeForContainerType<LuminosityBlock> { static constexpr BranchType branchType = InLumi; }; template <> struct BranchTypeForContainerType<LuminosityBlockForOutput> { static constexpr BranchType branchType = InLumi; }; template <> struct BranchTypeForContainerType<Run> { static constexpr BranchType branchType = InRun; }; template <> struct BranchTypeForContainerType<RunForOutput> { static constexpr BranchType branchType = InRun; }; template <> struct BranchTypeForContainerType<ProcessBlock> { static constexpr BranchType branchType = InProcess; }; template <> struct BranchTypeForContainerType<ProcessBlockForOutput> { static constexpr BranchType branchType = InProcess; }; template <typename T> class GetterOfProducts { public: GetterOfProducts() : branchType_(edm::InEvent) {} template <typename U, typename M> GetterOfProducts(U const& match, M* module, edm::BranchType branchType = edm::InEvent) : matcher_(WillGetIfMatch<T>(match, module)), tokens_(new std::vector<edm::EDGetTokenT<T>>), branchType_(branchType) {} void operator()(edm::ProductDescription const& productDescription) { if (productDescription.dropped()) return; if (productDescription.branchType() == branchType_ && productDescription.unwrappedTypeID() == edm::TypeID(typeid(T))) { auto const& token = matcher_(productDescription); if (not token.isUninitialized()) { tokens_->push_back(token); } } } template <typename ProductContainer> void fillHandles(ProductContainer const& productContainer, std::vector<edm::Handle<T>>& handles) const { handles.clear(); if (branchType_ == BranchTypeForContainerType<ProductContainer>::branchType) { handles.reserve(tokens_->size()); for (auto const& token : *tokens_) { if (auto handle = productContainer.getHandle(token)) { handles.push_back(handle); } } } } std::vector<edm::EDGetTokenT<T>> const& tokens() const { return *tokens_; } edm::BranchType branchType() const { return branchType_; } private: std::function<EDGetTokenT<T>(ProductDescription const&)> matcher_; // A shared pointer is needed because objects of this type get assigned // to std::function's and we want the copies in those to share the same vector. std::shared_ptr<std::vector<edm::EDGetTokenT<T>>> tokens_; edm::BranchType branchType_; }; } // namespace edm #endif
1
0.933255
1
0.933255
game-dev
MEDIA
0.201913
game-dev
0.765713
1
0.765713
FirstPersonKSP/AvionicsSystems
1,957
GameData/MOARdV/MAS_ASET/Push_Button_Modular/MAS_pb_SH02_AG2.cfg
PROP { name = MAS_pb_SH02_AG2 // ASET MPB SH02 style. Action Group toggle. MODEL { model = ASET/ASET_Props/Control/Push_Button_Modular/models/pb_SplitHorizontal_Cap texture = pb_Full_Cap_Black,ASET/ASET_Props/Control/Push_Button_Modular/models/pb_Full_Cap_Black texture = Switch_TUMBLEDiffuse,ASET/ASET_Props/Control/Switch_Tumble/Switch_TUMBLEDiffuse } MODEL { model = ASET/ASET_Props/Control/Push_Button_Modular/models/pb_Collider } MODULE { name = MASComponent COLLIDER_EVENT { collider = pb_Collider sound = ASET/ASET_Props/Sounds/pb_Push02 volume = 1 onClick = fc.ToggleActionGroup(2) } ANIMATION_PLAYER { name = Button press animation animation = pb_PushAnim animationSpeed = 1.0 variable = fc.GetActionGroup(2) } TEXT_LABEL { name = Upper Legend transform = Legend_Upper fontSize = 3.9 lineSpacing = 0.9 font = Liberation Sans style = Bold alignment = Center anchor = MiddleCenter emissive = never passiveColor = COLOR_MOARdV_UnlitBlackText text = AG 2 } TEXT_LABEL { name = Lower Legend transform = Legend_Lower fontSize = 3.9 lineSpacing = 0.9 font = Liberation Sans style = Bold alignment = Center anchor = MiddleCenter emissive = active passiveColor = COLOR_MOARdV_PassiveBacklightText activeColor = COLOR_MOARdV_IndicatorLampAmber text = AG 2 variable = fc.Conditioned(fc.ActionGroupHasActions(2) and not fc.GetActionGroup(2)) } COLOR_SHIFT { name = Upper Panel transform = pb_SH_TopLens_obj passiveColor = 0,0,0,255 activeColor = COLOR_MOARdV_IndicatorPanelGreen variable = fc.Conditioned(fc.ActionGroupHasActions(2) and fc.GetActionGroup(2)) } TEXTURE_SHIFT { name = Upper Panel transform = pb_SH_TopLens_obj startUV = 0, 0 endUV = 0, -0.5 layers = _Emissive variable = fc.Conditioned(fc.ActionGroupHasActions(2) and fc.GetActionGroup(2)) } } }
1
0.935113
1
0.935113
game-dev
MEDIA
0.799269
game-dev
0.698704
1
0.698704
copperdevs/CopperDevs.DearImGui
1,492
src/Core/CopperDevs.DearImGui/Rendering/Renderers/EnumFieldRenderer.cs
namespace CopperDevs.DearImGui.Rendering.Renderers; internal class EnumFieldRenderer : FieldRenderer { public override void ReflectionRenderer(FieldInfo fieldInfo, object component, int id, Action valueChanged = null!) { var enumValue = fieldInfo.GetValue(component)!; RenderEnum(fieldInfo.FieldType, ref enumValue, id, fieldInfo.Name.ToTitleCase(), valueChanged); fieldInfo.SetValue(component, enumValue); } public override void ValueRenderer(ref object value, int id, Action valueChanged = null!) { RenderEnum(value.GetType(), ref value, id, value.GetType().Name.ToTitleCase(), valueChanged); } private static void RenderEnum(Type type, ref object component, int id, string title, Action valueChanged = null!) { var enumValues = Enum.GetValues(type).Cast<object>().ToList(); var currentValue = enumValues[(int)Convert.ChangeType(component, Enum.GetUnderlyingType(type))]!; var tempComponent = component; CopperImGui.HorizontalGroup( () => { CopperImGui.Text(title); }, () => { CopperImGui.Button($"{currentValue}###{title}{id}", () => { var targetIndex = (enumValues.IndexOf(currentValue) + 1) % enumValues.Count; tempComponent = enumValues[targetIndex]; valueChanged?.Invoke(); }); }); component = tempComponent; } }
1
0.931002
1
0.931002
game-dev
MEDIA
0.55896
game-dev
0.97226
1
0.97226
Ghost-chu/QuickShop-Reremake
17,155
src/main/java/org/maxgamer/quickshop/localization/game/game/MojangGameLanguageImpl.java
/* * This file is a part of project QuickShop, the name is MojangGameLanguageImpl.java * Copyright (C) PotatoCraft Studio 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 <http://www.gnu.org/licenses/>. * */ package org.maxgamer.quickshop.localization.game.game; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import lombok.Getter; import lombok.SneakyThrows; import org.apache.commons.codec.digest.DigestUtils; import org.bukkit.Material; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.EntityType; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.Plugin; import org.bukkit.potion.PotionEffectType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.maxgamer.quickshop.QuickShop; import org.maxgamer.quickshop.util.MsgUtil; import org.maxgamer.quickshop.util.ReflectFactory; import org.maxgamer.quickshop.util.Util; import org.maxgamer.quickshop.util.mojangapi.*; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Level; /** * MojangGameLanguageImpl - A simple GameLanguage impl * * @author Ghost_chu and sandtechnology */ public class MojangGameLanguageImpl extends BukkitGameLanguageImpl implements GameLanguage { private final static Lock LOCK = new ReentrantLock(); private static final Condition DOWNLOAD_CONDITION = LOCK.newCondition(); private final QuickShop plugin; @Nullable private final JsonObject lang; private MojangApiMirror mirror; @SneakyThrows public MojangGameLanguageImpl(@NotNull QuickShop plugin, @NotNull String languageCode) { super(plugin); this.plugin = plugin; languageCode = MsgUtil.processGameLanguageCode(languageCode); switch (plugin.getConfiguration().getOrDefault("mojangapi-mirror", 0)) { case 0: mirror = new MojangApiOfficialMirror(); plugin.getLogger().info("Game assets server selected: Mojang API"); break; case 1: mirror = new MojangApiBmclApiMirror(); plugin.getLogger().info("Game assets server selected: BMCLAPI"); plugin.getLogger().info("===Mirror description==="); plugin.getLogger().info("BMCLAPI is a non-profit mirror service made by @bangbang93 to speed up download in China mainland region."); plugin.getLogger().info("Donate BMCLAPI or get details about BMCLAPI, check here: https://bmclapidoc.bangbang93.com"); plugin.getLogger().info("You should only use this mirror if your server in China mainland or have connection trouble with Mojang server, otherwise use Mojang Official server"); plugin.getLogger().warning("You're selected unofficial game assets server, use at your own risk."); break; case 2: mirror = new MojangApiMcbbsApiMirror(); plugin.getLogger().info("Game assets server selected: BMCLAPI"); plugin.getLogger().info("===Mirror description==="); plugin.getLogger().info("MCBBSAPI is a special server of OpenBMCLAPI made by @bangbang93 but managed by MCBBS, same with BMCLAPI, MCBBSAPI is target speed up download in China mainland region."); plugin.getLogger().info("Donate BMCLAPI or get details about BMCLAPI (includes MCBBSAPI), check here: https://bmclapidoc.bangbang93.com"); plugin.getLogger().info("You should only use this mirror if your server in China mainland or have connection trouble with Mojang server, otherwise use Mojang Official server"); plugin.getLogger().warning("You're selected unofficial game assets server, use at your own risk."); break; } LOCK.lock(); try { final GameLanguageLoadThread loadThread = new GameLanguageLoadThread(plugin, languageCode, mirror); loadThread.start(); boolean timeout = !DOWNLOAD_CONDITION.await(20, TimeUnit.SECONDS); if (timeout) { Util.debugLog("No longer waiting file downloading because it now timed out, now downloading in background."); plugin.getLogger().info("No longer waiting file downloading because it now timed out, now downloading in background, please reset itemi18n.yml, potioni18n.yml and enchi18n.yml after download completed."); } this.lang = loadThread.getLang(); // Get the Lang whatever thread running or died. } finally { LOCK.unlock(); } } @Override public @NotNull String getName() { return "Mojang API"; } @Override public @NotNull Plugin getPlugin() { return plugin; } @Override public @NotNull String getItem(@NotNull ItemStack itemStack) { return getItem(itemStack.getType()); } @Override public @NotNull String getItem(@NotNull Material material) { if (lang == null) { return super.getItem(material); } JsonElement element = lang.get("item.minecraft." + material.name().toLowerCase()); if (element == null) { return getBlock(material); } else { return element.getAsString(); } } /** * Get block only translations, if not found, it WON'T call getItem() * * @param material The material * @return The translations for material */ @NotNull public String getBlock(@NotNull Material material) { if (lang == null) { return super.getItem(material); } JsonElement jsonElement = lang.get("block.minecraft." + material.name().toLowerCase()); if (jsonElement == null) { return super.getItem(material); } return jsonElement.getAsString(); } @Override public @NotNull String getPotion(@NotNull PotionEffectType potionEffectType) { if (lang == null) { return super.getPotion(potionEffectType); } JsonElement jsonElement = lang.get("effect.minecraft." + potionEffectType.getName().toLowerCase()); if (jsonElement == null) { return super.getPotion(potionEffectType); } return jsonElement.getAsString(); } @Override public @NotNull String getEnchantment(@NotNull Enchantment enchantment) { if (lang == null) { return super.getEnchantment(enchantment); } JsonElement jsonElement = lang.get("enchantment.minecraft." + enchantment.getKey().getKey().toLowerCase()); if (jsonElement == null) { return super.getEnchantment(enchantment); } return jsonElement.getAsString(); } @Override public @NotNull String getEntity(@NotNull EntityType entityType) { if (lang == null) { return super.getEntity(entityType); } JsonElement jsonElement = lang.get("entity.minecraft." + entityType.name().toLowerCase()); if (jsonElement == null) { return super.getEntity(entityType); } return jsonElement.getAsString(); } @Getter static class GameLanguageLoadThread extends Thread { private final String languageCode; private final QuickShop plugin; private final MojangApiMirror mirror; private JsonObject lang; private boolean isLatest = false; //Does assets is latest? private boolean isUpdated = false; //Did we tried update assets? public GameLanguageLoadThread(@NotNull QuickShop plugin, @NotNull String languageCode, @NotNull MojangApiMirror mirror) { this.plugin = plugin; this.languageCode = languageCode; this.mirror = mirror; } @Override public void run() { LOCK.lock(); try { execute(); DOWNLOAD_CONDITION.signalAll(); } finally { LOCK.unlock(); } } public void execute() { try { File cacheFile = new File(Util.getCacheFolder(), "mojanglang.cache"); // Load cache file if (!cacheFile.exists()) { //noinspection ResultOfMethodCallIgnored cacheFile.createNewFile(); } YamlConfiguration yamlConfiguration = new YamlConfiguration(); yamlConfiguration.load(cacheFile); /* The cache data, if it all matches, we doesn't need connect to internet to download files again. */ String cacheVersion = yamlConfiguration.getString("ver", "ERROR"); String cacheSha1 = yamlConfiguration.getString("sha1", "ERROR"); String cacheCode = yamlConfiguration.getString("lang"); /* If language name is default, use computer language */ if ("en_us".equalsIgnoreCase(languageCode)) { isLatest = true; return; //Ignore english language } File cachedFile = new File(Util.getCacheFolder(), cacheSha1); if (languageCode.equals(cacheCode)) { //Language same if (cachedFile.exists()) { //File exists try (FileInputStream cacheFileInputSteam = new FileInputStream(cachedFile)) { if (DigestUtils.sha1Hex(cacheFileInputSteam).equals(cacheSha1)) { //Check if file broken Util.debugLog("MojangAPI in-game translation digest check passed."); if (cacheVersion.equals(ReflectFactory.getServerVersion())) { isLatest = true; try (FileReader reader = new FileReader(cachedFile)) { lang = new JsonParser().parse(reader).getAsJsonObject(); return; //We doesn't need to update it } catch (Exception e) { //Keep it empty so continue to update files } } } } } } //UPDATE isUpdated = true; plugin.getLogger().info("Loading required files from Mojang API, Please allow up to 20 secs."); //Download new things from Mojang launcher meta site MojangAPI mojangAPI = new MojangAPI(mirror); MojangAPI.AssetsAPI assetsAPI = mojangAPI.getAssetsAPI(ReflectFactory.getServerVersion()); if (!assetsAPI.isAvailable()) { //This version no meta can be found, bug? Util.debugLog("AssetsAPI returns not available, This may caused by Mojang servers down or connection issue."); plugin.getLogger().warning("Failed to update game assets from MojangAPI server, This may caused by Mojang servers down, connection issue or invalid language code."); return; } //Download AssetsIndex Optional<MojangAPI.AssetsFileData> assetsFileData = assetsAPI.getGameAssetsFile(); if (!assetsFileData.isPresent()) { Util.debugLog("AssetsAPI returns nothing about required game asset file, This may caused by Mojang servers down or connection issue."); plugin.getLogger().warning("Failed to update game assets from MojangAPI server, This may caused by Mojang servers down, connection issue or invalid language code."); return; } Util.debugLog(MsgUtil.fillArgs("Assets file loaded! id:[{0}], sha1:[{1}], Content Length:[{2}]", assetsFileData.get().getId(), assetsFileData.get().getSha1(), String.valueOf(assetsFileData.get().getContent().length()))); String indexSha1Hex = DigestUtils.sha1Hex(assetsFileData.get().getContent()); if (!assetsFileData.get().getSha1().equals(indexSha1Hex)) { Util.debugLog(MsgUtil.fillArgs("File hashing equals failed! excepted:[{0}], file:[{1}]", assetsFileData.get().getSha1(), indexSha1Hex)); plugin.getLogger().warning("Failed to update game assets from MojangAPI server because the file seems invalid, please try again later."); return; } try { Files.write(new File(Util.getCacheFolder(), indexSha1Hex).toPath(), assetsFileData.get().getContent().getBytes(StandardCharsets.UTF_8)); } catch (IOException ioException) { plugin.getLogger().log(Level.WARNING, "Failed save file to local drive, game language system caches will stop work, we will try download again in next reboot. skipping...", ioException); } //Download language json JsonElement indexJson = new JsonParser().parse(assetsFileData.get().getContent()); if (!indexJson.isJsonObject()) { plugin.getLogger().warning("Failed to update game assets from MojangAPI server because the json structure seems invalid, please try again later."); return; } if (!indexJson.getAsJsonObject().get("objects").isJsonObject()) { plugin.getLogger().warning("Failed to update game assets from MojangAPI server because the json structure about objects seems invalid, please try again later."); return; } JsonElement langElement = indexJson.getAsJsonObject().get("objects").getAsJsonObject().get("minecraft/lang/" + languageCode + ".json"); if (langElement == null) { plugin.getLogger().warning("Failed to update game assets from MojangAPI server because the language code " + languageCode + " not supported by Minecraft."); return; } String langHash = langElement.getAsJsonObject().get("hash").getAsString(); Optional<String> langContent = mojangAPI.getResourcesAPI().get(langHash); if (!langContent.isPresent()) { plugin.getLogger().warning("Failed to update game assets from MojangAPI server because network connection issue."); return; } try { Files.write(new File(Util.getCacheFolder(), langHash).toPath(), langContent.get().getBytes(StandardCharsets.UTF_8)); } catch (IOException ioException) { plugin.getLogger().log(Level.WARNING, "Failed save file to local drive, game language system caches will stop work, we will try download again in next reboot. skipping...", ioException); } //Save the caches lang = new JsonParser().parse(langContent.get()).getAsJsonObject(); yamlConfiguration.set("ver", ReflectFactory.getServerVersion()); yamlConfiguration.set("sha1", langHash); yamlConfiguration.set("lang", languageCode); yamlConfiguration.save(cacheFile); isLatest = true; Util.debugLog("Successfully update game assets."); plugin.getLogger().info("Success! The game assets now up-to-date :)"); plugin.getLogger().info("Now you can execute [/qs reset lang] command to regenerate files with localized."); } catch (Exception e) { plugin.getSentryErrorReporter().ignoreThrow(); plugin.getLogger().log(Level.WARNING, "Something going wrong when loading game translation assets", e); } } public boolean isLatest() { return isLatest; } } }
1
0.977319
1
0.977319
game-dev
MEDIA
0.922661
game-dev
0.931643
1
0.931643
526077247/ETPro
9,331
Unity/Packages/com.unity.render-pipelines.universal@10.8.1/Editor/2D/ShapeEditor/EditablePath/BezierUtility.cs
using UnityEngine; namespace UnityEditor.Experimental.Rendering.Universal.Path2D { internal static class BezierUtility { static Vector3[] s_TempPoints = new Vector3[3]; public static Vector3 BezierPoint(Vector3 startPosition, Vector3 startTangent, Vector3 endTangent, Vector3 endPosition, float t) { float s = 1.0f - t; return startPosition * s * s * s + startTangent * s * s * t * 3.0f + endTangent * s * t * t * 3.0f + endPosition * t * t * t; } public static Vector3 ClosestPointOnCurve(Vector3 point, Vector3 startPosition, Vector3 endPosition, Vector3 startTangent, Vector3 endTangent, out float t) { Vector3 startToEnd = endPosition - startPosition; Vector3 startToTangent = (startTangent - startPosition); Vector3 endToTangent = (endTangent - endPosition); float sqrError = 0.001f; if (Colinear(startToTangent, startToEnd, sqrError) && Colinear(endToTangent, startToEnd, sqrError)) return ClosestPointToSegment(point, startPosition, endPosition, out t); Vector3 leftStartPosition; Vector3 leftEndPosition; Vector3 leftStartTangent; Vector3 leftEndTangent; Vector3 rightStartPosition; Vector3 rightEndPosition; Vector3 rightStartTangent; Vector3 rightEndTangent; float leftStartT = 0f; float leftEndT = 0.5f; float rightStartT = 0.5f; float rightEndT = 1f; SplitBezier(0.5f, startPosition, endPosition, startTangent, endTangent, out leftStartPosition, out leftEndPosition, out leftStartTangent, out leftEndTangent, out rightStartPosition, out rightEndPosition, out rightStartTangent, out rightEndTangent); Vector3 pointLeft = ClosestPointOnCurveIterative(point, leftStartPosition, leftEndPosition, leftStartTangent, leftEndTangent, sqrError, ref leftStartT, ref leftEndT); Vector3 pointRight = ClosestPointOnCurveIterative(point, rightStartPosition, rightEndPosition, rightStartTangent, rightEndTangent, sqrError, ref rightStartT, ref rightEndT); if ((point - pointLeft).sqrMagnitude < (point - pointRight).sqrMagnitude) { t = leftStartT; return pointLeft; } t = rightStartT; return pointRight; } public static Vector3 ClosestPointOnCurveFast(Vector3 point, Vector3 startPosition, Vector3 endPosition, Vector3 startTangent, Vector3 endTangent, out float t) { float sqrError = 0.001f; float startT = 0f; float endT = 1f; Vector3 closestPoint = ClosestPointOnCurveIterative(point, startPosition, endPosition, startTangent, endTangent, sqrError, ref startT, ref endT); t = startT; return closestPoint; } private static Vector3 ClosestPointOnCurveIterative(Vector3 point, Vector3 startPosition, Vector3 endPosition, Vector3 startTangent, Vector3 endTangent, float sqrError, ref float startT, ref float endT) { while ((startPosition - endPosition).sqrMagnitude > sqrError) { Vector3 startToEnd = endPosition - startPosition; Vector3 startToTangent = (startTangent - startPosition); Vector3 endToTangent = (endTangent - endPosition); if (Colinear(startToTangent, startToEnd, sqrError) && Colinear(endToTangent, startToEnd, sqrError)) { float t; Vector3 closestPoint = ClosestPointToSegment(point, startPosition, endPosition, out t); t *= (endT - startT); startT += t; endT -= t; return closestPoint; } Vector3 leftStartPosition; Vector3 leftEndPosition; Vector3 leftStartTangent; Vector3 leftEndTangent; Vector3 rightStartPosition; Vector3 rightEndPosition; Vector3 rightStartTangent; Vector3 rightEndTangent; SplitBezier(0.5f, startPosition, endPosition, startTangent, endTangent, out leftStartPosition, out leftEndPosition, out leftStartTangent, out leftEndTangent, out rightStartPosition, out rightEndPosition, out rightStartTangent, out rightEndTangent); s_TempPoints[0] = leftStartPosition; s_TempPoints[1] = leftStartTangent; s_TempPoints[2] = leftEndTangent; float sqrDistanceLeft = SqrDistanceToPolyLine(point, s_TempPoints); s_TempPoints[0] = rightEndPosition; s_TempPoints[1] = rightEndTangent; s_TempPoints[2] = rightStartTangent; float sqrDistanceRight = SqrDistanceToPolyLine(point, s_TempPoints); if (sqrDistanceLeft < sqrDistanceRight) { startPosition = leftStartPosition; endPosition = leftEndPosition; startTangent = leftStartTangent; endTangent = leftEndTangent; endT -= (endT - startT) * 0.5f; } else { startPosition = rightStartPosition; endPosition = rightEndPosition; startTangent = rightStartTangent; endTangent = rightEndTangent; startT += (endT - startT) * 0.5f; } } return endPosition; } public static void SplitBezier(float t, Vector3 startPosition, Vector3 endPosition, Vector3 startRightTangent, Vector3 endLeftTangent, out Vector3 leftStartPosition, out Vector3 leftEndPosition, out Vector3 leftStartTangent, out Vector3 leftEndTangent, out Vector3 rightStartPosition, out Vector3 rightEndPosition, out Vector3 rightStartTangent, out Vector3 rightEndTangent) { Vector3 tangent0 = (startRightTangent - startPosition); Vector3 tangent1 = (endLeftTangent - endPosition); Vector3 tangentEdge = (endLeftTangent - startRightTangent); Vector3 tangentPoint0 = startPosition + tangent0 * t; Vector3 tangentPoint1 = endPosition + tangent1 * (1f - t); Vector3 tangentEdgePoint = startRightTangent + tangentEdge * t; Vector3 newTangent0 = tangentPoint0 + (tangentEdgePoint - tangentPoint0) * t; Vector3 newTangent1 = tangentPoint1 + (tangentEdgePoint - tangentPoint1) * (1f - t); Vector3 newTangentEdge = newTangent1 - newTangent0; Vector3 bezierPoint = newTangent0 + newTangentEdge * t; leftStartPosition = startPosition; leftEndPosition = bezierPoint; leftStartTangent = tangentPoint0; leftEndTangent = newTangent0; rightStartPosition = bezierPoint; rightEndPosition = endPosition; rightStartTangent = newTangent1; rightEndTangent = tangentPoint1; } private static Vector3 ClosestPointToSegment(Vector3 point, Vector3 segmentStart, Vector3 segmentEnd, out float t) { Vector3 relativePoint = point - segmentStart; Vector3 segment = (segmentEnd - segmentStart); Vector3 segmentDirection = segment.normalized; float length = segment.magnitude; float dot = Vector3.Dot(relativePoint, segmentDirection); if (dot <= 0f) dot = 0f; else if (dot >= length) dot = length; t = dot / length; return segmentStart + segment * t; } private static float SqrDistanceToPolyLine(Vector3 point, Vector3[] points) { float minDistance = float.MaxValue; for (int i = 0; i < points.Length - 1; ++i) { float distance = SqrDistanceToSegment(point, points[i], points[i + 1]); if (distance < minDistance) minDistance = distance; } return minDistance; } private static float SqrDistanceToSegment(Vector3 point, Vector3 segmentStart, Vector3 segmentEnd) { Vector3 relativePoint = point - segmentStart; Vector3 segment = (segmentEnd - segmentStart); Vector3 segmentDirection = segment.normalized; float length = segment.magnitude; float dot = Vector3.Dot(relativePoint, segmentDirection); if (dot <= 0f) return (point - segmentStart).sqrMagnitude; else if (dot >= length) return (point - segmentEnd).sqrMagnitude; return Vector3.Cross(relativePoint, segmentDirection).sqrMagnitude; } private static bool Colinear(Vector3 v1, Vector3 v2, float error = 0.0001f) { return Mathf.Abs(v1.x * v2.y - v1.y * v2.x + v1.x * v2.z - v1.z * v2.x + v1.y * v2.z - v1.z * v2.y) < error; } } }
1
0.694402
1
0.694402
game-dev
MEDIA
0.675183
game-dev,graphics-rendering
0.925528
1
0.925528
OpenXRay/xray-16
8,197
src/xrGame/ai/monsters/poltergeist/poltergeist.h
#pragma once #include "ai/monsters/basemonster/base_monster.h" #include "ai/monsters/telekinesis.h" #include "ai/monsters/energy_holder.h" class CPhysicsShellHolder; class CStateManagerPoltergeist; class CPoltergeisMovementManager; class CPolterSpecialAbility; class CPolterTele; ////////////////////////////////////////////////////////////////////////// class CPoltergeist : public CBaseMonster, public CTelekinesis, public CEnergyHolder { typedef CBaseMonster inherited; typedef CEnergyHolder Energy; friend class CPoltergeisMovementManager; friend class CPolterTele; float m_height; bool m_disable_hide; SMotionVel invisible_vel; CPolterSpecialAbility* m_flame; CPolterSpecialAbility* m_tele; bool m_actor_ignore; TTime m_last_detection_time; Fvector m_last_actor_pos; char const* m_detection_pp_effector_name; u32 m_detection_pp_type_index; float m_detection_near_range_factor; float m_detection_far_range_factor; float m_detection_far_range; float m_detection_speed_factor; float m_detection_loose_speed; float m_current_detection_level; float m_detection_success_level; float m_detection_max_level; public: bool m_detect_without_sight; public: CPoltergeist(); virtual ~CPoltergeist(); virtual void Load(LPCSTR section); virtual void reload(LPCSTR section); virtual void reinit(); virtual bool net_Spawn(CSE_Abstract* DC); virtual void net_Destroy(); virtual void net_Relcase(IGameObject* O); virtual void UpdateCL(); virtual void shedule_Update(u32 dt); void set_actor_ignore(bool const actor_ignore) { m_actor_ignore = actor_ignore; } bool get_actor_ignore() const { return m_actor_ignore; } virtual void Die(IGameObject* who); virtual CMovementManager* create_movement_manager(); virtual void ForceFinalAnimation(); virtual void on_activate(); virtual void on_deactivate(); virtual void Hit(SHit* pHDS); pcstr get_monster_class_name() override { return "poltergeist"; } bool detected_enemy(); float get_fly_around_distance() const { return m_fly_around_distance; } float get_fly_around_change_direction_time() const { return m_fly_around_change_direction_time; } void renderable_Render(u32 context_id, IRenderable* root) override; IC CPolterSpecialAbility* ability() { return (m_flame ? m_flame : m_tele); } IC bool is_hidden() { return state_invisible; } // Poltergeist ability void PhysicalImpulse(const Fvector& position); void StrangeSounds(const Fvector& position); ref_sound m_strange_sound; // Movement Fvector m_current_position; // Позиция на ноде // Dynamic Height u32 time_height_updated; float target_height; void UpdateHeight(); // Invisibility void EnableHide() { m_disable_hide = false; } void DisableHide() { m_disable_hide = true; } public: virtual bool run_home_point_when_enemy_inaccessible() const { return false; } private: void Hide(); void Show(); float m_height_change_velocity; u32 m_height_change_min_time; u32 m_height_change_max_time; float m_height_min; float m_height_max; float m_fly_around_level; float m_fly_around_distance; float m_fly_around_change_direction_time; float get_current_detection_level() const { return m_current_detection_level; } bool check_work_condition() const; void remove_pp_effector(); void update_detection(); float get_detection_near_range_factor(); float get_detection_far_range_factor(); float get_detection_loose_speed(); float get_detection_far_range(); float get_detection_speed_factor(); float get_detection_success_level(); float get_post_process_factor() const; public: #ifdef DEBUG virtual CBaseMonster::SDebugInfo show_debug_info(); #endif friend class CPolterFlame; private: DECLARE_SCRIPT_REGISTER_FUNCTION(CGameObject); }; ////////////////////////////////////////////////////////////////////////// // Interface ////////////////////////////////////////////////////////////////////////// class CPolterSpecialAbility { CParticlesObject* m_particles_object; CParticlesObject* m_particles_object_electro; LPCSTR m_particles_hidden; LPCSTR m_particles_damage; LPCSTR m_particles_death; LPCSTR m_particles_idle; ref_sound m_sound_base; u32 m_last_hit_frame; protected: CPoltergeist* m_object; public: CPolterSpecialAbility(CPoltergeist* polter); virtual ~CPolterSpecialAbility(); virtual void load(LPCSTR section); virtual void update_schedule(); virtual void update_frame(); virtual void on_hide(); virtual void on_show(); virtual void on_destroy() {} virtual void on_die(); virtual void on_hit(SHit* pHDS); }; ////////////////////////////////////////////////////////////////////////// // Flame ////////////////////////////////////////////////////////////////////////// class CPolterFlame : public CPolterSpecialAbility { typedef CPolterSpecialAbility inherited; ref_sound m_sound; LPCSTR m_particles_prepare; LPCSTR m_particles_fire; LPCSTR m_particles_stop; u32 m_time_fire_delay; u32 m_time_fire_play; float m_length; float m_hit_value; u32 m_hit_delay; u32 m_count; u32 m_delay; // between 2 flames u32 m_time_flame_started; float m_min_flame_dist; float m_max_flame_dist; float m_min_flame_height; float m_max_flame_height; float m_pmt_aura_radius; // Scanner float m_scan_radius; u32 m_scan_delay_min; u32 m_scan_delay_max; SPPInfo m_scan_effector_info; float m_scan_effector_time; float m_scan_effector_time_attack; float m_scan_effector_time_release; ref_sound m_scan_sound; bool m_state_scanning; u32 m_scan_next_time; enum EFlameState { ePrepare, eFire, eStop }; public: struct SFlameElement { const IGameObject* target_object; Fvector position; Fvector target_dir; u32 time_started; ref_sound sound; CParticlesObject* particles_object; EFlameState state; u32 time_last_hit; }; private: using FLAME_ELEMS_VEC = xr_vector<SFlameElement*>; FLAME_ELEMS_VEC m_flames; public: CPolterFlame(CPoltergeist* polter); virtual ~CPolterFlame(); virtual void load(LPCSTR section); virtual void update_schedule(); virtual void on_destroy(); virtual void on_die(); private: void select_state(SFlameElement* elem, EFlameState state); bool get_valid_flame_position(const IGameObject* target_object, Fvector& res_pos); void create_flame(const IGameObject* target_object); }; ////////////////////////////////////////////////////////////////////////// // TELE ////////////////////////////////////////////////////////////////////////// class CPolterTele : public CPolterSpecialAbility { typedef CPolterSpecialAbility inherited; xr_vector<IGameObject*> m_nearest; // external params float m_pmt_radius; float m_pmt_object_min_mass; float m_pmt_object_max_mass; u32 m_pmt_object_count; u32 m_pmt_time_to_hold; u32 m_pmt_time_to_wait; u32 m_pmt_time_to_wait_in_objects; u32 m_pmt_raise_time_to_wait_in_objects; float m_pmt_distance; float m_pmt_object_height; u32 m_pmt_time_object_keep; float m_pmt_raise_speed; float m_pmt_fly_velocity; float m_pmt_object_collision_damage; ref_sound m_sound_tele_hold; ref_sound m_sound_tele_throw; enum ETeleState { eStartRaiseObjects, eRaisingObjects, eFireObjects, eWait } m_state; u32 m_time; u32 m_time_next; public: CPolterTele(CPoltergeist* polter); virtual ~CPolterTele(); virtual void load(LPCSTR section); virtual void update_schedule(); virtual void update_frame(); private: void tele_find_objects(xr_vector<IGameObject*>& objects, const Fvector& pos); bool tele_raise_objects(); void tele_fire_objects(); bool trace_object(IGameObject* obj, const Fvector& target); };
1
0.689384
1
0.689384
game-dev
MEDIA
0.989479
game-dev
0.553483
1
0.553483
LuminolMC/Luminol
12,213
luminol-server/minecraft-patches/features/0025-Gale-Optimize-noise-generation.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: MrHua269 <wangxyper@163.com> Date: Wed, 22 Jan 2025 17:23:16 +0800 Subject: [PATCH] Gale: Optimize noise generation Co-authored by: Martijn Muijsers <martijnmuijsers@live.nl> ishland <ishlandmc@yeah.net> As part of: Gale (https://github.com/GaleMC/Gale/blob/276e903b2688f23b19bdc8d493c0bf87656d2400/patches/server/0106-Optimize-noise-generation.patch) C2ME (https://github.com/RelativityMC/C2ME-fabric) Licensed under: MIT (https://opensource.org/licenses/MIT) diff --git a/net/minecraft/world/level/levelgen/synth/ImprovedNoise.java b/net/minecraft/world/level/levelgen/synth/ImprovedNoise.java index fb11a2eea540d55e50eab59f9857ca5d99f556f8..dcc1a3f8b611c9f103b848db90b077b984b60ada 100644 --- a/net/minecraft/world/level/levelgen/synth/ImprovedNoise.java +++ b/net/minecraft/world/level/levelgen/synth/ImprovedNoise.java @@ -11,6 +11,27 @@ public final class ImprovedNoise { public final double yo; public final double zo; + // Gale start - C2ME - optimize noise generation + private static final double[] FLAT_SIMPLEX_GRAD = new double[]{ + 1, 1, 0, 0, + -1, 1, 0, 0, + 1, -1, 0, 0, + -1, -1, 0, 0, + 1, 0, 1, 0, + -1, 0, 1, 0, + 1, 0, -1, 0, + -1, 0, -1, 0, + 0, 1, 1, 0, + 0, -1, 1, 0, + 0, 1, -1, 0, + 0, -1, -1, 0, + 1, 1, 0, 0, + 0, -1, 1, 0, + -1, 1, 0, 0, + 0, -1, -1, 0, + }; + // Gale end - C2ME - optimize noise generation + public ImprovedNoise(RandomSource random) { this.xo = random.nextDouble() * 256.0; this.yo = random.nextDouble() * 256.0; @@ -38,9 +59,11 @@ public final class ImprovedNoise { double d = x + this.xo; double d1 = y + this.yo; double d2 = z + this.zo; - int floor = Mth.floor(d); - int floor1 = Mth.floor(d1); - int floor2 = Mth.floor(d2); + // Gale start - C2ME - optimize noise generation - optimize: remove frequent type conversions + double floor = Math.floor(d); + double floor1 = Math.floor(d1); + double floor2 = Math.floor(d2); + // Gale end - C2ME - optimize noise generation - optimize: remove frequent type conversions double d3 = d - floor; double d4 = d1 - floor1; double d5 = d2 - floor2; @@ -53,25 +76,27 @@ public final class ImprovedNoise { d6 = d4; } - d7 = Mth.floor(d6 / yScale + 1.0E-7F) * yScale; + d7 = Math.floor(d6 / yScale + 1.0E-7F) * yScale; // Gale - C2ME - optimize noise generation - optimize: remove frequent type conversions } else { d7 = 0.0; } - return this.sampleAndLerp(floor, floor1, floor2, d3, d4 - d7, d5, d4); + return this.sampleAndLerp((int) floor, (int) floor1, (int) floor2, d3, d4 - d7, d5, d4); // Gale - C2ME - optimize noise generation - optimize: remove frequent type conversions } public double noiseWithDerivative(double x, double y, double z, double[] values) { double d = x + this.xo; double d1 = y + this.yo; double d2 = z + this.zo; - int floor = Mth.floor(d); - int floor1 = Mth.floor(d1); - int floor2 = Mth.floor(d2); + // Gale start - C2ME - optimize noise generation - optimize: remove frequent type conversions + double floor = Math.floor(d); + double floor1 = Math.floor(d1); + double floor2 = Math.floor(d2); + // Gale end - C2ME - optimize noise generation - optimize: remove frequent type conversions double d3 = d - floor; double d4 = d1 - floor1; double d5 = d2 - floor2; - return this.sampleWithDerivative(floor, floor1, floor2, d3, d4, d5, values); + return this.sampleWithDerivative((int) floor, (int) floor1, (int) floor2, d3, d4, d5, values); // Gale - C2ME - optimize noise generation - optimize: remove frequent type conversions } private static double gradDot(int gradIndex, double xFactor, double yFactor, double zFactor) { @@ -83,24 +108,69 @@ public final class ImprovedNoise { } private double sampleAndLerp(int gridX, int gridY, int gridZ, double deltaX, double weirdDeltaY, double deltaZ, double deltaY) { - int i = this.p(gridX); - int i1 = this.p(gridX + 1); - int i2 = this.p(i + gridY); - int i3 = this.p(i + gridY + 1); - int i4 = this.p(i1 + gridY); - int i5 = this.p(i1 + gridY + 1); - double d = gradDot(this.p(i2 + gridZ), deltaX, weirdDeltaY, deltaZ); - double d1 = gradDot(this.p(i4 + gridZ), deltaX - 1.0, weirdDeltaY, deltaZ); - double d2 = gradDot(this.p(i3 + gridZ), deltaX, weirdDeltaY - 1.0, deltaZ); - double d3 = gradDot(this.p(i5 + gridZ), deltaX - 1.0, weirdDeltaY - 1.0, deltaZ); - double d4 = gradDot(this.p(i2 + gridZ + 1), deltaX, weirdDeltaY, deltaZ - 1.0); - double d5 = gradDot(this.p(i4 + gridZ + 1), deltaX - 1.0, weirdDeltaY, deltaZ - 1.0); - double d6 = gradDot(this.p(i3 + gridZ + 1), deltaX, weirdDeltaY - 1.0, deltaZ - 1.0); - double d7 = gradDot(this.p(i5 + gridZ + 1), deltaX - 1.0, weirdDeltaY - 1.0, deltaZ - 1.0); - double d8 = Mth.smoothstep(deltaX); - double d9 = Mth.smoothstep(deltaY); - double d10 = Mth.smoothstep(deltaZ); - return Mth.lerp3(d8, d9, d10, d, d1, d2, d3, d4, d5, d6, d7); + // Gale start - C2ME - optimize noise generation - inline math & small optimization: remove frequent type conversions and redundant ops + final int var0 = gridX & 0xFF; + final int var1 = (gridX + 1) & 0xFF; + final int var2 = this.p[var0] & 0xFF; + final int var3 = this.p[var1] & 0xFF; + final int var4 = (var2 + gridY) & 0xFF; + final int var5 = (var3 + gridY) & 0xFF; + final int var6 = (var2 + gridY + 1) & 0xFF; + final int var7 = (var3 + gridY + 1) & 0xFF; + final int var8 = this.p[var4] & 0xFF; + final int var9 = this.p[var5] & 0xFF; + final int var10 = this.p[var6] & 0xFF; + final int var11 = this.p[var7] & 0xFF; + + final int var12 = (var8 + gridZ) & 0xFF; + final int var13 = (var9 + gridZ) & 0xFF; + final int var14 = (var10 + gridZ) & 0xFF; + final int var15 = (var11 + gridZ) & 0xFF; + final int var16 = (var8 + gridZ + 1) & 0xFF; + final int var17 = (var9 + gridZ + 1) & 0xFF; + final int var18 = (var10 + gridZ + 1) & 0xFF; + final int var19 = (var11 + gridZ + 1) & 0xFF; + final int var20 = (this.p[var12] & 15) << 2; + final int var21 = (this.p[var13] & 15) << 2; + final int var22 = (this.p[var14] & 15) << 2; + final int var23 = (this.p[var15] & 15) << 2; + final int var24 = (this.p[var16] & 15) << 2; + final int var25 = (this.p[var17] & 15) << 2; + final int var26 = (this.p[var18] & 15) << 2; + final int var27 = (this.p[var19] & 15) << 2; + final double var60 = deltaX - 1.0; + final double var61 = weirdDeltaY - 1.0; + final double var62 = deltaZ - 1.0; + final double var87 = FLAT_SIMPLEX_GRAD[(var20) | 0] * deltaX + FLAT_SIMPLEX_GRAD[(var20) | 1] * weirdDeltaY + FLAT_SIMPLEX_GRAD[(var20) | 2] * deltaZ; + final double var88 = FLAT_SIMPLEX_GRAD[(var21) | 0] * var60 + FLAT_SIMPLEX_GRAD[(var21) | 1] * weirdDeltaY + FLAT_SIMPLEX_GRAD[(var21) | 2] * deltaZ; + final double var89 = FLAT_SIMPLEX_GRAD[(var22) | 0] * deltaX + FLAT_SIMPLEX_GRAD[(var22) | 1] * var61 + FLAT_SIMPLEX_GRAD[(var22) | 2] * deltaZ; + final double var90 = FLAT_SIMPLEX_GRAD[(var23) | 0] * var60 + FLAT_SIMPLEX_GRAD[(var23) | 1] * var61 + FLAT_SIMPLEX_GRAD[(var23) | 2] * deltaZ; + final double var91 = FLAT_SIMPLEX_GRAD[(var24) | 0] * deltaX + FLAT_SIMPLEX_GRAD[(var24) | 1] * weirdDeltaY + FLAT_SIMPLEX_GRAD[(var24) | 2] * var62; + final double var92 = FLAT_SIMPLEX_GRAD[(var25) | 0] * var60 + FLAT_SIMPLEX_GRAD[(var25) | 1] * weirdDeltaY + FLAT_SIMPLEX_GRAD[(var25) | 2] * var62; + final double var93 = FLAT_SIMPLEX_GRAD[(var26) | 0] * deltaX + FLAT_SIMPLEX_GRAD[(var26) | 1] * var61 + FLAT_SIMPLEX_GRAD[(var26) | 2] * var62; + final double var94 = FLAT_SIMPLEX_GRAD[(var27) | 0] * var60 + FLAT_SIMPLEX_GRAD[(var27) | 1] * var61 + FLAT_SIMPLEX_GRAD[(var27) | 2] * var62; + + final double var95 = deltaX * 6.0 - 15.0; + final double var96 = deltaY * 6.0 - 15.0; + final double var97 = deltaZ * 6.0 - 15.0; + final double var98 = deltaX * var95 + 10.0; + final double var99 = deltaY * var96 + 10.0; + final double var100 = deltaZ * var97 + 10.0; + final double var101 = deltaX * deltaX * deltaX * var98; + final double var102 = deltaY * deltaY * deltaY * var99; + final double var103 = deltaZ * deltaZ * deltaZ * var100; + + final double var113 = var87 + var101 * (var88 - var87); + final double var114 = var93 + var101 * (var94 - var93); + final double var115 = var91 + var101 * (var92 - var91); + final double var116 = var89 + var101 * (var90 - var89); + final double var117 = var114 - var115; + final double var118 = var102 * (var116 - var113); + final double var119 = var102 * var117; + final double var120 = var113 + var118; + final double var121 = var115 + var119; + return var120 + (var103 * (var121 - var120)); + // Gale end - C2ME - optimize noise generation - inline math & small optimization: remove frequent type conversions and redundant ops } private double sampleWithDerivative(int gridX, int gridY, int gridZ, double deltaX, double deltaY, double deltaZ, double[] noiseValues) { diff --git a/net/minecraft/world/level/levelgen/synth/PerlinNoise.java b/net/minecraft/world/level/levelgen/synth/PerlinNoise.java index da3c26fbad32d75d71f7e59c8c3341316a754756..2c28bb2fed04542a2ee126fe0c1c1f0253a3e2eb 100644 --- a/net/minecraft/world/level/levelgen/synth/PerlinNoise.java +++ b/net/minecraft/world/level/levelgen/synth/PerlinNoise.java @@ -26,6 +26,10 @@ public class PerlinNoise { private final double lowestFreqValueFactor; private final double lowestFreqInputFactor; private final double maxValue; + // Gale start - C2ME - optimize noise generation + private final int octaveSamplersCount; + private final double [] amplitudesArray; + // Gale end - C2ME - optimize noise generation @Deprecated public static PerlinNoise createLegacyForBlendedNoise(RandomSource random, IntStream octaves) { @@ -127,6 +131,10 @@ public class PerlinNoise { this.lowestFreqInputFactor = Math.pow(2.0, -i); this.lowestFreqValueFactor = Math.pow(2.0, size - 1) / (Math.pow(2.0, size) - 1.0); this.maxValue = this.edgeValue(2.0); + // Gale start - C2ME - optimize noise generation + this.octaveSamplersCount = this.noiseLevels.length; + this.amplitudesArray = this.amplitudes.toDoubleArray(); + // Gale end - C2ME - optimize noise generation } protected double maxValue() { @@ -138,7 +146,27 @@ public class PerlinNoise { } public double getValue(double x, double y, double z) { - return this.getValue(x, y, z, 0.0, 0.0, false); + // Gale start - C2ME - optimize noise generation - optimize for common cases + double d = 0.0; + double e = this.lowestFreqInputFactor; + double f = this.lowestFreqValueFactor; + + for (int i = 0; i < this.octaveSamplersCount; ++i) { + ImprovedNoise perlinNoiseSampler = this.noiseLevels[i]; + if (perlinNoiseSampler != null) { + @SuppressWarnings("deprecation") + double g = perlinNoiseSampler.noise( + wrap(x * e), wrap(y * e), wrap(z * e), 0.0, 0.0 + ); + d += this.amplitudesArray[i] * g * f; + } + + e *= 2.0; + f /= 2.0; + } + + return d; + // Gale end - C2ME - optimize noise generation - optimize for common cases } @Deprecated
1
0.877506
1
0.877506
game-dev
MEDIA
0.603777
game-dev
0.825479
1
0.825479
jbunke/tdsm
3,806
src/com/jordanbunke/tdsm/menu/pre_export/ColorReplacementButton.java
package com.jordanbunke.tdsm.menu.pre_export; import com.jordanbunke.delta_time.debug.GameDebugger; import com.jordanbunke.delta_time.image.GameImage; import com.jordanbunke.delta_time.io.InputEventLogger; import com.jordanbunke.delta_time.menu.menu_elements.button.MenuButtonStub; import com.jordanbunke.delta_time.utility.math.Bounds2D; import com.jordanbunke.delta_time.utility.math.Coord2D; import com.jordanbunke.tdsm.menu.Button; import com.jordanbunke.tdsm.util.Cursor; import com.jordanbunke.tdsm.util.Tooltip; import java.awt.*; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import static com.jordanbunke.tdsm.util.Graphics.drawColReplButton; import static com.jordanbunke.tdsm.util.Layout.COL_REPL_OFF_DIM; import static com.jordanbunke.tdsm.util.Layout.COL_SEL_BUTTON_DIM; public final class ColorReplacementButton extends MenuButtonStub implements Button { private static final Bounds2D DIMS = new Bounds2D( COL_SEL_BUTTON_DIM + COL_REPL_OFF_DIM, COL_SEL_BUTTON_DIM); private final Color color; private final Function<Color, Color> replaceGetter; private final Supplier<Color> selectGetter; private final Consumer<Color> selector; private Color replacement; private final String tooltip; private GameImage base, highlight, selected; public ColorReplacementButton( final Coord2D position, final Color color, final String tooltip, final Function<Color, Color> replaceGetter, final Supplier<Color> selectGetter, final Consumer<Color> selector ) { super(position, DIMS, Anchor.LEFT_TOP, true); this.color = color; this.tooltip = tooltip; this.replaceGetter = replaceGetter; this.selectGetter = selectGetter; this.selector = selector; replacement = replaceGetter.apply(color); redraw(); } private void redraw() { base = drawColReplButton(color, replacement, Button.sim(false, false)); highlight = drawColReplButton(color, replacement, Button.sim(false, true)); selected = drawColReplButton(color, replacement, Button.sim(true, false)); } @Override public void execute() { selector.accept(isSelected() ? null : color); } @Override public void update(final double deltaTime) { final Color retrieved = replaceGetter.apply(color); // redraw assets if replacement color has changed if ((replacement == null && retrieved != null) || (replacement != null && !replacement.equals(retrieved))) { replacement = retrieved; redraw(); } // check whether selected if (color.equals(selectGetter.get())) select(); else deselect(); } @Override public void render(final GameImage canvas) { draw(getAsset(), canvas); } @Override public void process(final InputEventLogger eventLogger) { super.process(eventLogger); final Coord2D mousePos = eventLogger.getAdjustedMousePosition(); final boolean inBounds = mouseIsWithinBounds(mousePos); setHighlighted(inBounds); if (inBounds) { Tooltip.get().ping(tooltip, mousePos); Cursor.ping(Cursor.POINTER); } } @Override public void debugRender(final GameImage canvas, final GameDebugger debugger) {} @Override public GameImage getBaseAsset() { return base; } @Override public GameImage getHighlightedAsset() { return highlight; } @Override public GameImage getSelectedAsset() { return selected; } }
1
0.910305
1
0.910305
game-dev
MEDIA
0.769487
game-dev,desktop-app
0.965517
1
0.965517
RosaryMala/armok-vision
10,422
Assets/Scripts/CameraScripts/FirstPersonController.cs
using UnityEngine; using UnityEngine.EventSystems; using UnityStandardAssets.CrossPlatformInput; using UnityStandardAssets.Utility; using Random = UnityEngine.Random; #pragma warning disable 0649 //Variable not assigned. namespace UnityStandardAssets.Characters.FirstPerson { [RequireComponent(typeof (CharacterController))] [RequireComponent(typeof (AudioSource))] public class FirstPersonController : MonoBehaviour { [SerializeField] private bool m_IsWalking; [SerializeField] private float m_WalkSpeed; [SerializeField] private float m_RunSpeed; [SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten; [SerializeField] private float m_JumpSpeed; [SerializeField] private float m_StickToGroundForce; [SerializeField] private float m_GravityMultiplier; [SerializeField] private MouseLook m_MouseLook; [SerializeField] private bool m_UseFovKick; [SerializeField] private FOVKick m_FovKick = new FOVKick(); [SerializeField] private bool m_UseHeadBob; [SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob(); [SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob(); [SerializeField] private float m_StepInterval; [SerializeField] private AudioClip[] m_FootstepSounds; // an array of footstep sounds that will be randomly selected from. [SerializeField] private AudioClip m_JumpSound; // the sound played when character leaves the ground. [SerializeField] private AudioClip m_LandSound; // the sound played when character touches back on ground. private Camera m_Camera; private bool m_Jump; private float m_YRotation; private Vector3 m_Input; private Vector3 m_MoveDir = Vector3.zero; private CharacterController m_CharacterController; private CollisionFlags m_CollisionFlags; private bool m_PreviouslyGrounded; private Vector3 m_OriginalCameraPosition; private float m_StepCycle; private float m_NextStep; private bool m_Jumping; private AudioSource m_AudioSource; // Use this for initialization private void OnEnable() { m_CharacterController = GetComponent<CharacterController>(); m_Camera = Camera.main; m_OriginalCameraPosition = m_Camera.transform.localPosition; m_FovKick.Setup(m_Camera); m_HeadBob.Setup(m_Camera, m_StepInterval); m_StepCycle = 0f; m_NextStep = m_StepCycle/2f; m_Jumping = false; m_AudioSource = GetComponent<AudioSource>(); m_MouseLook.Init(transform , m_Camera.transform); } // Update is called once per frame private void Update() { RotateView(); // the jump state needs to read here to make sure it is not missed if (!m_Jump) { m_Jump = CrossPlatformInputManager.GetButtonDown("Jump"); } if (!m_PreviouslyGrounded && m_CharacterController.isGrounded) { StartCoroutine(m_JumpBob.DoBobCycle()); PlayLandingSound(); m_MoveDir.y = 0f; m_Jumping = false; } if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded) { m_MoveDir.y = 0f; } m_PreviouslyGrounded = m_CharacterController.isGrounded; } private void PlayLandingSound() { m_AudioSource.clip = m_LandSound; m_AudioSource.Play(); m_NextStep = m_StepCycle + .5f; } private void FixedUpdate() { if (EventSystem.current.currentSelectedGameObject != null) return; float speed; GetInput(out speed); // always move along the camera forward as it is the direction that it being aimed at Vector3 desiredMove = transform.forward * m_Input.y + transform.right * m_Input.x + transform.up * m_Input.z; //if we're on a ladder, the normal collision stuff doesn't apply. if (MapDataStore.Main.CheckCollision(transform.position) == MapDataStore.CollisionState.Stairs) { m_MoveDir.x = desiredMove.x * speed; m_MoveDir.z = desiredMove.z * speed; m_MoveDir.y = desiredMove.y * speed; } else { // get a normal for the surface that is being touched to move along it RaycastHit hitInfo; Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo, m_CharacterController.height / 2f, Physics.AllLayers, QueryTriggerInteraction.Ignore); desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized; m_MoveDir.x = desiredMove.x * speed; m_MoveDir.z = desiredMove.z * speed; if (m_CharacterController.isGrounded) { m_MoveDir.y = -m_StickToGroundForce; if (m_Jump) { m_MoveDir.y = m_JumpSpeed; PlayJumpSound(); m_Jump = false; m_Jumping = true; } } else { m_MoveDir += Physics.gravity * m_GravityMultiplier * Time.fixedDeltaTime; } } m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime); ProgressStepCycle(speed); UpdateCameraPosition(speed); m_MouseLook.UpdateCursorLock(); } private void PlayJumpSound() { m_AudioSource.clip = m_JumpSound; m_AudioSource.Play(); } private void ProgressStepCycle(float speed) { if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0)) { m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))* Time.fixedDeltaTime; } if (!(m_StepCycle > m_NextStep)) { return; } m_NextStep = m_StepCycle + m_StepInterval; PlayFootStepAudio(); } private void PlayFootStepAudio() { if (!m_CharacterController.isGrounded && MapDataStore.Main.CheckCollision(transform.position) != MapDataStore.CollisionState.Stairs) { return; } // pick & play a random footstep sound from the array, // excluding sound at index 0 int n = Random.Range(1, m_FootstepSounds.Length); m_AudioSource.clip = m_FootstepSounds[n]; m_AudioSource.PlayOneShot(m_AudioSource.clip); // move picked sound to index 0 so it's not picked next time m_FootstepSounds[n] = m_FootstepSounds[0]; m_FootstepSounds[0] = m_AudioSource.clip; } private void UpdateCameraPosition(float speed) { Vector3 newCameraPosition; if (!m_UseHeadBob) { return; } if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded) { m_Camera.transform.localPosition = m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten))); newCameraPosition = m_Camera.transform.localPosition; newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset(); } else { newCameraPosition = m_Camera.transform.localPosition; newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset(); } m_Camera.transform.localPosition = newCameraPosition; } private void GetInput(out float speed) { // Read input float horizontal = CrossPlatformInputManager.GetAxis("Horizontal"); float vertical = CrossPlatformInputManager.GetAxis("Vertical"); float upDown = Input.GetAxis("CamUpDown"); bool waswalking = m_IsWalking; #if !MOBILE_INPUT // On standalone builds, walk/run speed is modified by a key press. // keep track of whether or not the character is walking or running m_IsWalking = !Input.GetKey(KeyCode.LeftShift); #endif // set the desired speed to be walking or running speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed; m_Input = new Vector3(horizontal, vertical, upDown); // normalize input if it exceeds 1 in combined length: if (m_Input.sqrMagnitude > 1) { m_Input.Normalize(); } // handle speed change to give an fov kick // only if the player is going to a run, is running and the fovkick is to be used if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0) { StopAllCoroutines(); StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown()); } } private void RotateView() { m_MouseLook.LookRotation (transform, m_Camera.transform); } private void OnControllerColliderHit(ControllerColliderHit hit) { Rigidbody body = hit.collider.attachedRigidbody; //dont move the rigidbody if the character is on top of it if (m_CollisionFlags == CollisionFlags.Below) { return; } if (body == null || body.isKinematic) { return; } body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse); } } }
1
0.752976
1
0.752976
game-dev
MEDIA
0.987122
game-dev
0.987182
1
0.987182
vagenv/Rade
7,669
Source/RTargetLib/RPlayerTargetMgr.cpp
// Copyright 2015-2023 Vagen Ayrapetyan #include "RPlayerTargetMgr.h" #include "RTargetComponent.h" #include "RWorldTargetMgr.h" #include "RUtilLib/RUtil.h" #include "RUtilLib/RCheck.h" #include "RUtilLib/RLog.h" #include "RUtilLib/RTimer.h" #include "Net/UnrealNetwork.h" //============================================================================= // Core //============================================================================= URPlayerTargetMgr::URPlayerTargetMgr () { PrimaryComponentTick.bCanEverTick = true; // --- Targetable FRichCurve* TargetAngleToLerpPowerData = TargetAngleToLerpPower.GetRichCurve (); TargetAngleToLerpPowerData->AddKey (0, 10); TargetAngleToLerpPowerData->AddKey (1, 9); TargetAngleToLerpPowerData->AddKey (5, 7); TargetAngleToLerpPowerData->AddKey (20, 4); TargetAngleToLerpPowerData->AddKey (40, 5); } // Replication void URPlayerTargetMgr::GetLifetimeReplicatedProps (TArray<FLifetimeProperty> &OutLifetimeProps) const { Super::GetLifetimeReplicatedProps (OutLifetimeProps); } void URPlayerTargetMgr::BeginPlay () { Super::BeginPlay (); FindWorldTargetMgr (); World = URUtil::GetWorld (this); } void URPlayerTargetMgr::EndPlay (const EEndPlayReason::Type EndPlayReason) { SetTargetCheckEnabled (false); Super::EndPlay (EndPlayReason); } //============================================================================= // Init //============================================================================= void URPlayerTargetMgr::FindWorldTargetMgr () { WorldTargetMgr = URWorldTargetMgr::GetInstance (this); if (!WorldTargetMgr.IsValid ()) { FTimerHandle RetryHandle; RTIMER_START (RetryHandle, this, &URPlayerTargetMgr::FindWorldTargetMgr, 1, false); return; } SetTargetCheckEnabled (true); } void URPlayerTargetMgr::SetTargetCheckEnabled (bool Enabled) { if (Enabled) { RTIMER_START (TargetCheckHandle, this, &URPlayerTargetMgr::TargetCheck, 1, true); } else { RTIMER_STOP (TargetCheckHandle, this); } } //============================================================================= // Get functions //============================================================================= bool URPlayerTargetMgr::IsTargeting () const { return (TargetCurrent.IsValid () || !CustomTargetDir.IsNearlyZero ()); } URTargetComponent* URPlayerTargetMgr::GetCurrentTarget () const { return TargetCurrent.IsValid () ? TargetCurrent.Get () : nullptr; } FVector URPlayerTargetMgr::GetTargetDir () const { FVector Result = FVector::Zero (); // --- Focus Target if (TargetCurrent.IsValid ()) { FVector TargetLocation = TargetCurrent->GetComponentLocation (); Result = TargetLocation - GetComponentLocation (); Result.Normalize (); // --- Focus Angle } else if (!CustomTargetDir.IsNearlyZero ()) { Result = CustomTargetDir; } return Result; } FRotator URPlayerTargetMgr::GetControlRotation () { // Current rotation FRotator Result = GetComponentRotation (); FVector CurrentDir = Result.Vector (); FVector TargetDir = GetTargetDir (); // --- Is there a target if (!TargetDir.IsNearlyZero () && World.IsValid () && !World->bIsTearingDown) { // Normalize Direction and add offset; TargetDir.Normalize (); TargetDir += FVector (0, 0, TargetVerticalOffset); // Camera lerp speed float LerpPower = 4; float Angle = URUtil::GetAngle (CurrentDir, TargetDir); // Transform Angle to Lerp power LerpPower = URUtil::GetRuntimeFloatCurveValue (TargetAngleToLerpPower, Angle); // Remove targeting if (!CustomTargetDir.IsNearlyZero () && Angle < TargetStopAngle) CustomTargetDir = FVector::Zero (); // Tick DeltaTime float DeltaTime = World->GetDeltaSeconds (); // Lerp to Target Rotation float LerpValue = FMath::Clamp (DeltaTime * LerpPower, 0, 1); Result = FMath::Lerp (CurrentDir, TargetDir, LerpValue).Rotation (); } return Result; } //============================================================================= // Functions //============================================================================= // Camera input to change target void URPlayerTargetMgr::TargetAdjust (float OffsetX, float OffsetY) { // If there was input stop turning if (!CustomTargetDir.IsNearlyZero ()) CustomTargetDir = FVector::Zero (); if ( TargetCurrent.IsValid () && ( FMath::Abs (OffsetX) > TargetAdjustMinOffset || FMath::Abs (OffsetY) > TargetAdjustMinOffset)) { SearchNewTarget (FVector2D (OffsetX, OffsetY)); } } // Targeting enabled/disabled void URPlayerTargetMgr::TargetToggle () { if (TargetCurrent.IsValid ()) { SetTargetCurrent (nullptr); } else { SearchNewTarget (); // No Target. Focus forward if (!TargetCurrent.IsValid ()) CustomTargetDir = GetOwner ()->GetActorRotation ().Vector (); } } // Check if target is valid void URPlayerTargetMgr::TargetCheck () { if (TargetCurrent.IsValid () && WorldTargetMgr.IsValid ()) { bool RemoveTarget = false; // --- Check distance float Distance = FVector::Dist (GetOwner ()->GetActorLocation (), TargetCurrent->GetComponentLocation ()); if (Distance > WorldTargetMgr->SearchDistanceMax) RemoveTarget = true; // Check if target was disabled if (!TargetCurrent->GetIsTargetable ()) RemoveTarget = true; // Remove if (RemoveTarget) { SetTargetCurrent (nullptr); SearchNewTarget (); } } } // Perform search for new target void URPlayerTargetMgr::SearchNewTarget (FVector2D InputVector) { if (!WorldTargetMgr.IsValid () || !World.IsValid ()) return; // --- Limit the amount of camera adjustments double CurrentTime = World->GetTimeSeconds (); if (CurrentTime < LastTargetSearch + TargetSearchDelay) return; LastTargetSearch = CurrentTime; URTargetComponent* TargetNew = nullptr; if (TargetCurrent.IsValid ()) { // --- Adjust target TargetNew = WorldTargetMgr->Find_Screen (this, InputVector, TArray<AActor*>(), { TargetCurrent.Get () }); } else { // --- Search new target TargetNew = WorldTargetMgr->Find_Target (this, TArray<AActor*>(), TArray<URTargetComponent*>()); } if (IsValid (TargetNew)) SetTargetCurrent (TargetNew); } // Change the current target and notify the old and new target void URPlayerTargetMgr::SetTargetCurrent (URTargetComponent* NewTarget) { // Notify the old target if (TargetCurrent.IsValid ()) { TargetCurrent->SetIsTargeted (false); } // Reset the state TargetCurrent = nullptr; // Set new target and notify it if (IsValid (NewTarget)) { TargetCurrent = NewTarget; TargetCurrent->SetIsTargeted (true); } // Report ReportTargetUpdate (); if (R_IS_NET_CLIENT) SetTargetCurrent_Server (NewTarget); } void URPlayerTargetMgr::SetTargetCurrent_Server_Implementation (URTargetComponent* NewTarget) { TargetCurrent = NewTarget; ReportTargetUpdate (); } void URPlayerTargetMgr::ReportTargetUpdate () const { if (R_IS_VALID_WORLD && OnTargetUpdated.IsBound ()) OnTargetUpdated.Broadcast (); }
1
0.940058
1
0.940058
game-dev
MEDIA
0.932103
game-dev
0.94741
1
0.94741
sharpdx/SharpDX
3,785
Source/SharpDX.Direct2D1/DirectWrite/FontCollectionLoaderShadow.cs
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // 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. using System; using System.Diagnostics; using System.Runtime.InteropServices; namespace SharpDX.DirectWrite { /// <summary> /// Internal FontCollectionLoader Callback /// </summary> internal class FontCollectionLoaderShadow : SharpDX.ComObjectShadow { private static readonly FontCollectionLoaderVtbl Vtbl = new FontCollectionLoaderVtbl(); private Factory _factory; public static IntPtr ToIntPtr(FontCollectionLoader loader) { return ToCallbackPtr<FontCollectionLoader>(loader); } public static void SetFactory(FontCollectionLoader loader, Factory factory) { var shadowPtr = ToIntPtr(loader); var shadow = ToShadow<FontCollectionLoaderShadow>(shadowPtr); shadow._factory = factory; } private class FontCollectionLoaderVtbl : ComObjectVtbl { public FontCollectionLoaderVtbl() : base(1) { AddMethod(new CreateEnumeratorFromKeyDelegate(CreateEnumeratorFromKeyImpl)); } /// <unmanaged>HRESULT IDWriteFontCollectionLoader::CreateEnumeratorFromKey([None] IDWriteFactory* factory,[In, Buffer] const void* collectionKey,[None] int collectionKeySize,[Out] IDWriteFontFileEnumerator** fontFileEnumerator)</unmanaged> [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int CreateEnumeratorFromKeyDelegate(IntPtr thisPtr, IntPtr factory, IntPtr collectionKey, int collectionKeySize, out IntPtr fontFileEnumerator); private static int CreateEnumeratorFromKeyImpl(IntPtr thisPtr, IntPtr factory, IntPtr collectionKey, int collectionKeySize, out IntPtr fontFileEnumerator) { fontFileEnumerator = IntPtr.Zero; try { var shadow = ToShadow<FontCollectionLoaderShadow>(thisPtr); var callback = (FontCollectionLoader)shadow.Callback; Debug.Assert(factory == shadow._factory.NativePointer); var enumerator = callback.CreateEnumeratorFromKey(shadow._factory, new DataPointer(collectionKey, collectionKeySize)); fontFileEnumerator = FontFileEnumeratorShadow.ToIntPtr(enumerator); } catch (Exception exception) { return (int)SharpDX.Result.GetResultFromException(exception); } return Result.Ok.Code; } } protected override CppObjectVtbl GetVtbl { get { return Vtbl; } } } }
1
0.917125
1
0.917125
game-dev
MEDIA
0.225728
game-dev
0.927676
1
0.927676
oot-pc-port/oot-pc-port
1,872
asm/non_matchings/overlays/actors/ovl_En_Heishi4/func_80A56E14.s
glabel func_80A56E14 /* 00D44 80A56E14 24010009 */ addiu $at, $zero, 0x0009 ## $at = 00000009 /* 00D48 80A56E18 AFA40000 */ sw $a0, 0x0000($sp) /* 00D4C 80A56E1C AFA60008 */ sw $a2, 0x0008($sp) /* 00D50 80A56E20 14A10007 */ bne $a1, $at, .L80A56E40 /* 00D54 80A56E24 AFA7000C */ sw $a3, 0x000C($sp) /* 00D58 80A56E28 8FA20014 */ lw $v0, 0x0014($sp) /* 00D5C 80A56E2C 8FA30010 */ lw $v1, 0x0010($sp) /* 00D60 80A56E30 844F0268 */ lh $t7, 0x0268($v0) ## 00000268 /* 00D64 80A56E34 846E0000 */ lh $t6, 0x0000($v1) ## 00000000 /* 00D68 80A56E38 01CFC021 */ addu $t8, $t6, $t7 /* 00D6C 80A56E3C A4780000 */ sh $t8, 0x0000($v1) ## 00000000 .L80A56E40: /* 00D70 80A56E40 24010010 */ addiu $at, $zero, 0x0010 ## $at = 00000010 /* 00D74 80A56E44 8FA20014 */ lw $v0, 0x0014($sp) /* 00D78 80A56E48 14A10009 */ bne $a1, $at, .L80A56E70 /* 00D7C 80A56E4C 8FA30010 */ lw $v1, 0x0010($sp) /* 00D80 80A56E50 84790000 */ lh $t9, 0x0000($v1) ## 00000000 /* 00D84 80A56E54 84480262 */ lh $t0, 0x0262($v0) ## 00000262 /* 00D88 80A56E58 846A0004 */ lh $t2, 0x0004($v1) ## 00000004 /* 00D8C 80A56E5C 03284821 */ addu $t1, $t9, $t0 /* 00D90 80A56E60 A4690000 */ sh $t1, 0x0000($v1) ## 00000000 /* 00D94 80A56E64 844B0264 */ lh $t3, 0x0264($v0) ## 00000264 /* 00D98 80A56E68 014B6021 */ addu $t4, $t2, $t3 /* 00D9C 80A56E6C A46C0004 */ sh $t4, 0x0004($v1) ## 00000004 .L80A56E70: /* 00DA0 80A56E70 03E00008 */ jr $ra /* 00DA4 80A56E74 00001025 */ or $v0, $zero, $zero ## $v0 = 00000000
1
0.626557
1
0.626557
game-dev
MEDIA
0.957608
game-dev
0.536077
1
0.536077
ElunaLuaEngine/ElunaTrinityWotlk
7,519
src/server/scripts/Northrend/Naxxramas/boss_faerlina.cpp
/* * This file is part of the TrinityCore 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 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/>. */ #include "ScriptMgr.h" #include "InstanceScript.h" #include "naxxramas.h" #include "ObjectAccessor.h" #include "Player.h" #include "ScriptedCreature.h" #include "SpellAuras.h" enum Yells { SAY_GREET = 0, SAY_AGGRO = 1, SAY_SLAY = 2, SAY_DEATH = 3, EMOTE_WIDOW_EMBRACE = 4, EMOTE_FRENZY = 5 }; enum Spells { SPELL_POISON_BOLT_VOLLEY = 28796, SPELL_RAIN_OF_FIRE = 28794, SPELL_FRENZY = 28798, SPELL_WIDOWS_EMBRACE = 28732, SPELL_ADD_FIREBALL = 54095 // 25-man: 54096 }; #define SPELL_WIDOWS_EMBRACE_HELPER RAID_MODE<uint32>(28732, 54097) enum Events { EVENT_POISON = 1, EVENT_FIRE = 2, EVENT_FRENZY = 3 }; enum SummonGroups { SUMMON_GROUP_WORSHIPPERS = 1, SUMMON_GROUP_FOLLOWERS = 2 }; enum Misc { DATA_FRENZY_DISPELS = 1 }; struct boss_faerlina : public BossAI { boss_faerlina(Creature* creature) : BossAI(creature, BOSS_FAERLINA), _frenzyDispels(0) { } void SummonAdds() { me->SummonCreatureGroup(SUMMON_GROUP_WORSHIPPERS); if (Is25ManRaid()) me->SummonCreatureGroup(SUMMON_GROUP_FOLLOWERS); } void InitializeAI() override { if (!me->isDead() && instance->GetBossState(BOSS_FAERLINA) != DONE) { Reset(); SummonAdds(); } } void JustReachedHome() override { _JustReachedHome(); SummonAdds(); } void JustEngagedWith(Unit* who) override { BossAI::JustEngagedWith(who); Talk(SAY_AGGRO); summons.DoZoneInCombat(); events.ScheduleEvent(EVENT_POISON, randtime(Seconds(10), Seconds(15))); events.ScheduleEvent(EVENT_FIRE, randtime(Seconds(6), Seconds(18))); events.ScheduleEvent(EVENT_FRENZY, Minutes(1)+randtime(0s, Seconds(20))); } void Reset() override { _Reset(); _frenzyDispels = 0; } void KilledUnit(Unit* victim) override { if (victim->GetTypeId() == TYPEID_PLAYER) Talk(SAY_SLAY); } void JustDied(Unit* /*killer*/) override { _JustDied(); Talk(SAY_DEATH); } void SpellHit(WorldObject* caster, SpellInfo const* spellInfo) override { Unit* unitCaster = caster->ToUnit(); if (!unitCaster) return; if (spellInfo->Id == SPELL_WIDOWS_EMBRACE_HELPER) { ++_frenzyDispels; Talk(EMOTE_WIDOW_EMBRACE, caster); Unit::Kill(me, unitCaster); } } uint32 GetData(uint32 type) const override { if (type == DATA_FRENZY_DISPELS) return _frenzyDispels; return 0; } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_POISON: if (!me->HasAura(SPELL_WIDOWS_EMBRACE_HELPER)) DoCastAOE(SPELL_POISON_BOLT_VOLLEY); events.Repeat(randtime(Seconds(8), Seconds(15))); break; case EVENT_FIRE: if (Unit* target = SelectTarget(SelectTargetMethod::Random, 0)) DoCast(target, SPELL_RAIN_OF_FIRE); events.Repeat(randtime(Seconds(6), Seconds(18))); break; case EVENT_FRENZY: if (Aura* widowsEmbrace = me->GetAura(SPELL_WIDOWS_EMBRACE_HELPER)) events.ScheduleEvent(EVENT_FRENZY, Milliseconds(widowsEmbrace->GetDuration()+1)); else { DoCast(SPELL_FRENZY); Talk(EMOTE_FRENZY); events.Repeat(Minutes(1) + randtime(0s, Seconds(20))); } break; } if (me->HasUnitState(UNIT_STATE_CASTING)) return; } DoMeleeAttackIfReady(); } private: uint32 _frenzyDispels; }; struct npc_faerlina_add : public ScriptedAI { npc_faerlina_add(Creature* creature) : ScriptedAI(creature), _instance(creature->GetInstanceScript()) { } void Reset() override { if (!Is25ManRaid()) { me->ApplySpellImmune(0, IMMUNITY_EFFECT, SPELL_EFFECT_BIND, true); me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_CHARM, true); } } void JustEngagedWith(Unit* /*who*/) override { if (Creature* faerlina = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_FAERLINA))) faerlina->AI()->DoZoneInCombat(); } void JustDied(Unit* /*killer*/) override { if (!Is25ManRaid()) if (Creature* faerlina = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_FAERLINA))) DoCast(faerlina, SPELL_WIDOWS_EMBRACE); } void UpdateAI(uint32 /*diff*/) override { if (!UpdateVictim()) return; if (me->HasUnitState(UNIT_STATE_CASTING)) return; DoCastVictim(SPELL_ADD_FIREBALL); DoMeleeAttackIfReady(); // this will only happen if the fireball cast fails for some reason } private: InstanceScript* const _instance; }; class achievement_momma_said_knock_you_out : public AchievementCriteriaScript { public: achievement_momma_said_knock_you_out() : AchievementCriteriaScript("achievement_momma_said_knock_you_out") { } bool OnCheck(Player* /*source*/, Unit* target) override { return target && !target->GetAI()->GetData(DATA_FRENZY_DISPELS); } }; class at_faerlina_entrance : public OnlyOnceAreaTriggerScript { public: at_faerlina_entrance() : OnlyOnceAreaTriggerScript("at_faerlina_entrance") { } bool TryHandleOnce(Player* player, AreaTriggerEntry const* /*areaTrigger*/) override { InstanceScript* instance = player->GetInstanceScript(); if (!instance || instance->GetBossState(BOSS_FAERLINA) != NOT_STARTED) return true; if (Creature* faerlina = ObjectAccessor::GetCreature(*player, instance->GetGuidData(DATA_FAERLINA))) faerlina->AI()->Talk(SAY_GREET); return true; } }; void AddSC_boss_faerlina() { RegisterNaxxramasCreatureAI(boss_faerlina); RegisterNaxxramasCreatureAI(npc_faerlina_add); new at_faerlina_entrance(); new achievement_momma_said_knock_you_out(); }
1
0.971762
1
0.971762
game-dev
MEDIA
0.968528
game-dev
0.992652
1
0.992652
kripken/ammo.js
4,561
bullet/src/BulletCollision/CollisionShapes/btTriangleShape.h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BT_OBB_TRIANGLE_MINKOWSKI_H #define BT_OBB_TRIANGLE_MINKOWSKI_H #include "btConvexShape.h" #include "btBoxShape.h" ATTRIBUTE_ALIGNED16(class) btTriangleShape : public btPolyhedralConvexShape { public: BT_DECLARE_ALIGNED_ALLOCATOR(); btVector3 m_vertices1[3]; virtual int getNumVertices() const { return 3; } btVector3& getVertexPtr(int index) { return m_vertices1[index]; } const btVector3& getVertexPtr(int index) const { return m_vertices1[index]; } virtual void getVertex(int index,btVector3& vert) const { vert = m_vertices1[index]; } virtual int getNumEdges() const { return 3; } virtual void getEdge(int i,btVector3& pa,btVector3& pb) const { getVertex(i,pa); getVertex((i+1)%3,pb); } virtual void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax)const { // btAssert(0); getAabbSlow(t,aabbMin,aabbMax); } btVector3 localGetSupportingVertexWithoutMargin(const btVector3& dir)const { btVector3 dots = dir.dot3(m_vertices1[0], m_vertices1[1], m_vertices1[2]); return m_vertices1[dots.maxAxis()]; } virtual void batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const { for (int i=0;i<numVectors;i++) { const btVector3& dir = vectors[i]; btVector3 dots = dir.dot3(m_vertices1[0], m_vertices1[1], m_vertices1[2]); supportVerticesOut[i] = m_vertices1[dots.maxAxis()]; } } btTriangleShape() : btPolyhedralConvexShape () { m_shapeType = TRIANGLE_SHAPE_PROXYTYPE; } btTriangleShape(const btVector3& p0,const btVector3& p1,const btVector3& p2) : btPolyhedralConvexShape () { m_shapeType = TRIANGLE_SHAPE_PROXYTYPE; m_vertices1[0] = p0; m_vertices1[1] = p1; m_vertices1[2] = p2; } virtual void getPlane(btVector3& planeNormal,btVector3& planeSupport,int i) const { getPlaneEquation(i,planeNormal,planeSupport); } virtual int getNumPlanes() const { return 1; } void calcNormal(btVector3& normal) const { normal = (m_vertices1[1]-m_vertices1[0]).cross(m_vertices1[2]-m_vertices1[0]); normal.normalize(); } virtual void getPlaneEquation(int i, btVector3& planeNormal,btVector3& planeSupport) const { (void)i; calcNormal(planeNormal); planeSupport = m_vertices1[0]; } virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const { (void)mass; btAssert(0); inertia.setValue(btScalar(0.),btScalar(0.),btScalar(0.)); } virtual bool isInside(const btVector3& pt,btScalar tolerance) const { btVector3 normal; calcNormal(normal); //distance to plane btScalar dist = pt.dot(normal); btScalar planeconst = m_vertices1[0].dot(normal); dist -= planeconst; if (dist >= -tolerance && dist <= tolerance) { //inside check on edge-planes int i; for (i=0;i<3;i++) { btVector3 pa,pb; getEdge(i,pa,pb); btVector3 edge = pb-pa; btVector3 edgeNormal = edge.cross(normal); edgeNormal.normalize(); btScalar dist = pt.dot( edgeNormal); btScalar edgeConst = pa.dot(edgeNormal); dist -= edgeConst; if (dist < -tolerance) return false; } return true; } return false; } //debugging virtual const char* getName()const { return "Triangle"; } virtual int getNumPreferredPenetrationDirections() const { return 2; } virtual void getPreferredPenetrationDirection(int index, btVector3& penetrationVector) const { calcNormal(penetrationVector); if (index) penetrationVector *= btScalar(-1.); } }; #endif //BT_OBB_TRIANGLE_MINKOWSKI_H
1
0.935338
1
0.935338
game-dev
MEDIA
0.982759
game-dev
0.99391
1
0.99391
Rz-C/Mohist
1,893
src/main/java/net/minecraftforge/common/extensions/IForgeRawTagBuilder.java
/* * Copyright (c) Forge Development LLC and contributors * SPDX-License-Identifier: LGPL-2.1-only */ package net.minecraftforge.common.extensions; import com.google.gson.JsonObject; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.TagBuilder; import net.minecraft.tags.TagEntry; public interface IForgeRawTagBuilder { default TagBuilder getRawBuilder() { return (TagBuilder)this; } /** * @deprecated Never used, tags use a Codec now, so remove this later. */ @Deprecated(forRemoval = true, since = "1.20.1") default void serializeTagAdditions(final JsonObject tagJson) {} /** * Adds a tag entry to the remove list. * @param tagEntry The tag entry to add to the remove list * @param source The source of the caller for logging purposes (generally a modid) * @return The builder for chaining purposes */ default TagBuilder remove(final TagEntry tagEntry, final String source) { return this.getRawBuilder().remove(tagEntry); } /** * Adds a single-element entry to the remove list. * @param elementID The ID of the element to add to the remove list * @param source The source of the caller for logging purposes (generally a modid) * @return The builder for chaining purposes */ default TagBuilder removeElement(final ResourceLocation elementID, final String source) { return this.remove(TagEntry.element(elementID), source); } /** * Adds a tag to the remove list. * @param tagID The ID of the tag to add to the remove list * @param source The source of the caller for logging purposes (generally a modid) * @return The builder for chaining purposes */ default TagBuilder removeTag(final ResourceLocation tagID, final String source) { return this.remove(TagEntry.tag(tagID), source); } }
1
0.795837
1
0.795837
game-dev
MEDIA
0.857772
game-dev
0.817208
1
0.817208
RCInet/LastEpoch_Mods
5,453
AssetBundleExport/Library/PackageCache/com.unity.ugui@9496653a3df6/Editor/TMP/PropertyDrawers/TMP_GlyphPropertyDrawer.cs
using UnityEngine; using UnityEngine.TextCore; using UnityEditor; using System.Collections.Generic; namespace TMPro.EditorUtilities { [CustomPropertyDrawer(typeof(Glyph))] public class TMP_GlyphPropertyDrawer : PropertyDrawer { private static readonly GUIContent k_ScaleLabel = new GUIContent("Scale:", "The scale of this glyph."); private static readonly GUIContent k_AtlasIndexLabel = new GUIContent("Atlas Index:", "The index of the atlas texture that contains this glyph."); private static readonly GUIContent k_ClassTypeLabel = new GUIContent("Class Type:", "The class definition type of this glyph."); public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { SerializedProperty prop_GlyphIndex = property.FindPropertyRelative("m_Index"); SerializedProperty prop_GlyphMetrics = property.FindPropertyRelative("m_Metrics"); SerializedProperty prop_GlyphRect = property.FindPropertyRelative("m_GlyphRect"); SerializedProperty prop_Scale = property.FindPropertyRelative("m_Scale"); SerializedProperty prop_AtlasIndex = property.FindPropertyRelative("m_AtlasIndex"); SerializedProperty prop_ClassDefinitionType = property.FindPropertyRelative("m_ClassDefinitionType"); GUIStyle style = new GUIStyle(EditorStyles.label); style.richText = true; Rect rect = new Rect(position.x + 70, position.y, position.width, 49); float labelWidth = GUI.skin.label.CalcSize(new GUIContent("ID: " + prop_GlyphIndex.intValue)).x; EditorGUI.LabelField(new Rect(position.x + (64 - labelWidth) / 2, position.y + 85, 64f, 18f), new GUIContent("ID: <color=#FFFF80>" + prop_GlyphIndex.intValue + "</color>"), style); // We get Rect since a valid position may not be provided by the caller. EditorGUI.PropertyField(new Rect(rect.x, rect.y, position.width, 49), prop_GlyphRect); rect.y += 45; EditorGUI.PropertyField(rect, prop_GlyphMetrics); EditorGUIUtility.labelWidth = 40f; EditorGUI.PropertyField(new Rect(rect.x, rect.y + 65, 75, 18), prop_Scale, k_ScaleLabel); EditorGUIUtility.labelWidth = 70f; EditorGUI.PropertyField(new Rect(rect.x + 85, rect.y + 65, 95, 18), prop_AtlasIndex, k_AtlasIndexLabel); if (prop_ClassDefinitionType != null) { EditorGUIUtility.labelWidth = 70f; float minWidth = Mathf.Max(90, rect.width - 270); EditorGUI.PropertyField(new Rect(rect.x + 190, rect.y + 65, minWidth, 18), prop_ClassDefinitionType, k_ClassTypeLabel); } DrawGlyph(new Rect(position.x, position.y + 2, 64, 80), property); } public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { return 130f; } void DrawGlyph(Rect glyphDrawPosition, SerializedProperty property) { // Get a reference to the serialized object which can either be a TMP_FontAsset or FontAsset. SerializedObject so = property.serializedObject; if (so == null) return; Texture2D atlasTexture; int atlasIndex = property.FindPropertyRelative("m_AtlasIndex").intValue; int padding = so.FindProperty("m_AtlasPadding").intValue; if (TMP_PropertyDrawerUtilities.TryGetAtlasTextureFromSerializedObject(so, atlasIndex, out atlasTexture) == false) return; Material mat; if (TMP_PropertyDrawerUtilities.TryGetMaterial(so, atlasTexture, out mat) == false) return; GlyphRect glyphRect = TMP_PropertyDrawerUtilities.GetGlyphRectFromGlyphSerializedProperty(property); int glyphOriginX = glyphRect.x - padding; int glyphOriginY = glyphRect.y - padding; int glyphWidth = glyphRect.width + padding * 2; int glyphHeight = glyphRect.height + padding * 2; SerializedProperty faceInfoProperty = so.FindProperty("m_FaceInfo"); float ascentLine = faceInfoProperty.FindPropertyRelative("m_AscentLine").floatValue; float descentLine = faceInfoProperty.FindPropertyRelative("m_DescentLine").floatValue; float normalizedHeight = ascentLine - descentLine; float scale = glyphDrawPosition.width / normalizedHeight; // Compute the normalized texture coordinates Rect texCoords = new Rect((float)glyphOriginX / atlasTexture.width, (float)glyphOriginY / atlasTexture.height, (float)glyphWidth / atlasTexture.width, (float)glyphHeight / atlasTexture.height); if (Event.current.type == EventType.Repaint) { glyphDrawPosition.x += (glyphDrawPosition.width - glyphWidth * scale) / 2; glyphDrawPosition.y += (glyphDrawPosition.height - glyphHeight * scale) / 2; glyphDrawPosition.width = glyphWidth * scale; glyphDrawPosition.height = glyphHeight * scale; // Could switch to using the default material of the font asset which would require passing scale to the shader. Graphics.DrawTexture(glyphDrawPosition, atlasTexture, texCoords, 0, 0, 0, 0, new Color(1f, 1f, 1f), mat); } } } }
1
0.830189
1
0.830189
game-dev
MEDIA
0.582064
game-dev,graphics-rendering
0.989221
1
0.989221
tx00100xt/SeriousSamClassic-VK
8,801
SamTSE/Sources/External/SDL2/SDL_joystick.h
/* Simple DirectMedia Layer Copyright (C) 1997-2016 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /** * \file SDL_joystick.h * * Include file for SDL joystick event handling * * The term "device_index" identifies currently plugged in joystick devices between 0 and SDL_NumJoysticks, with the exact joystick * behind a device_index changing as joysticks are plugged and unplugged. * * The term "instance_id" is the current instantiation of a joystick device in the system, if the joystick is removed and then re-inserted * then it will get a new instance_id, instance_id's are monotonically increasing identifiers of a joystick plugged in. * * The term JoystickGUID is a stable 128-bit identifier for a joystick device that does not change over time, it identifies class of * the device (a X360 wired controller for example). This identifier is platform dependent. * * */ #ifndef _SDL_joystick_h #define _SDL_joystick_h #include "SDL_stdinc.h" #include "SDL_error.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /** * \file SDL_joystick.h * * In order to use these functions, SDL_Init() must have been called * with the ::SDL_INIT_JOYSTICK flag. This causes SDL to scan the system * for joysticks, and load appropriate drivers. * * If you would like to receive joystick updates while the application * is in the background, you should set the following hint before calling * SDL_Init(): SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS */ /* The joystick structure used to identify an SDL joystick */ struct _SDL_Joystick; typedef struct _SDL_Joystick SDL_Joystick; /* A structure that encodes the stable unique id for a joystick device */ typedef struct { Uint8 data[16]; } SDL_JoystickGUID; typedef Sint32 SDL_JoystickID; typedef enum { SDL_JOYSTICK_POWER_UNKNOWN = -1, SDL_JOYSTICK_POWER_EMPTY, SDL_JOYSTICK_POWER_LOW, SDL_JOYSTICK_POWER_MEDIUM, SDL_JOYSTICK_POWER_FULL, SDL_JOYSTICK_POWER_WIRED, SDL_JOYSTICK_POWER_MAX } SDL_JoystickPowerLevel; /* Function prototypes */ /** * Count the number of joysticks attached to the system right now */ extern DECLSPEC int SDLCALL SDL_NumJoysticks(void); /** * Get the implementation dependent name of a joystick. * This can be called before any joysticks are opened. * If no name can be found, this function returns NULL. */ extern DECLSPEC const char *SDLCALL SDL_JoystickNameForIndex(int device_index); /** * Open a joystick for use. * The index passed as an argument refers to the N'th joystick on the system. * This index is not the value which will identify this joystick in future * joystick events. The joystick's instance id (::SDL_JoystickID) will be used * there instead. * * \return A joystick identifier, or NULL if an error occurred. */ extern DECLSPEC SDL_Joystick *SDLCALL SDL_JoystickOpen(int device_index); /** * Return the SDL_Joystick associated with an instance id. */ extern DECLSPEC SDL_Joystick *SDLCALL SDL_JoystickFromInstanceID(SDL_JoystickID joyid); /** * Return the name for this currently opened joystick. * If no name can be found, this function returns NULL. */ extern DECLSPEC const char *SDLCALL SDL_JoystickName(SDL_Joystick * joystick); /** * Return the GUID for the joystick at this index */ extern DECLSPEC SDL_JoystickGUID SDLCALL SDL_JoystickGetDeviceGUID(int device_index); /** * Return the GUID for this opened joystick */ extern DECLSPEC SDL_JoystickGUID SDLCALL SDL_JoystickGetGUID(SDL_Joystick * joystick); /** * Return a string representation for this guid. pszGUID must point to at least 33 bytes * (32 for the string plus a NULL terminator). */ extern DECLSPEC void SDLCALL SDL_JoystickGetGUIDString(SDL_JoystickGUID guid, char *pszGUID, int cbGUID); /** * convert a string into a joystick formatted guid */ extern DECLSPEC SDL_JoystickGUID SDLCALL SDL_JoystickGetGUIDFromString(const char *pchGUID); /** * Returns SDL_TRUE if the joystick has been opened and currently connected, or SDL_FALSE if it has not. */ extern DECLSPEC SDL_bool SDLCALL SDL_JoystickGetAttached(SDL_Joystick * joystick); /** * Get the instance ID of an opened joystick or -1 if the joystick is invalid. */ extern DECLSPEC SDL_JoystickID SDLCALL SDL_JoystickInstanceID(SDL_Joystick * joystick); /** * Get the number of general axis controls on a joystick. */ extern DECLSPEC int SDLCALL SDL_JoystickNumAxes(SDL_Joystick * joystick); /** * Get the number of trackballs on a joystick. * * Joystick trackballs have only relative motion events associated * with them and their state cannot be polled. */ extern DECLSPEC int SDLCALL SDL_JoystickNumBalls(SDL_Joystick * joystick); /** * Get the number of POV hats on a joystick. */ extern DECLSPEC int SDLCALL SDL_JoystickNumHats(SDL_Joystick * joystick); /** * Get the number of buttons on a joystick. */ extern DECLSPEC int SDLCALL SDL_JoystickNumButtons(SDL_Joystick * joystick); /** * Update the current state of the open joysticks. * * This is called automatically by the event loop if any joystick * events are enabled. */ extern DECLSPEC void SDLCALL SDL_JoystickUpdate(void); /** * Enable/disable joystick event polling. * * If joystick events are disabled, you must call SDL_JoystickUpdate() * yourself and check the state of the joystick when you want joystick * information. * * The state can be one of ::SDL_QUERY, ::SDL_ENABLE or ::SDL_IGNORE. */ extern DECLSPEC int SDLCALL SDL_JoystickEventState(int state); /** * Get the current state of an axis control on a joystick. * * The state is a value ranging from -32768 to 32767. * * The axis indices start at index 0. */ extern DECLSPEC Sint16 SDLCALL SDL_JoystickGetAxis(SDL_Joystick * joystick, int axis); /** * \name Hat positions */ /* @{ */ #define SDL_HAT_CENTERED 0x00 #define SDL_HAT_UP 0x01 #define SDL_HAT_RIGHT 0x02 #define SDL_HAT_DOWN 0x04 #define SDL_HAT_LEFT 0x08 #define SDL_HAT_RIGHTUP (SDL_HAT_RIGHT|SDL_HAT_UP) #define SDL_HAT_RIGHTDOWN (SDL_HAT_RIGHT|SDL_HAT_DOWN) #define SDL_HAT_LEFTUP (SDL_HAT_LEFT|SDL_HAT_UP) #define SDL_HAT_LEFTDOWN (SDL_HAT_LEFT|SDL_HAT_DOWN) /* @} */ /** * Get the current state of a POV hat on a joystick. * * The hat indices start at index 0. * * \return The return value is one of the following positions: * - ::SDL_HAT_CENTERED * - ::SDL_HAT_UP * - ::SDL_HAT_RIGHT * - ::SDL_HAT_DOWN * - ::SDL_HAT_LEFT * - ::SDL_HAT_RIGHTUP * - ::SDL_HAT_RIGHTDOWN * - ::SDL_HAT_LEFTUP * - ::SDL_HAT_LEFTDOWN */ extern DECLSPEC Uint8 SDLCALL SDL_JoystickGetHat(SDL_Joystick * joystick, int hat); /** * Get the ball axis change since the last poll. * * \return 0, or -1 if you passed it invalid parameters. * * The ball indices start at index 0. */ extern DECLSPEC int SDLCALL SDL_JoystickGetBall(SDL_Joystick * joystick, int ball, int *dx, int *dy); /** * Get the current state of a button on a joystick. * * The button indices start at index 0. */ extern DECLSPEC Uint8 SDLCALL SDL_JoystickGetButton(SDL_Joystick * joystick, int button); /** * Close a joystick previously opened with SDL_JoystickOpen(). */ extern DECLSPEC void SDLCALL SDL_JoystickClose(SDL_Joystick * joystick); /** * Return the battery level of this joystick */ extern DECLSPEC SDL_JoystickPowerLevel SDLCALL SDL_JoystickCurrentPowerLevel(SDL_Joystick * joystick); /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* _SDL_joystick_h */ /* vi: set ts=4 sw=4 expandtab: */
1
0.749134
1
0.749134
game-dev
MEDIA
0.966618
game-dev
0.602946
1
0.602946
ReaTeam/ReaScripts
9,174
Items Editing/js_Render items INTO next take (apply track FX and toggle freeze active take FX).lua
--[[ ReaScript name: js_Render items INTO next take (apply track FX and toggle freeze active take FX).lua Version: 0.92 Author: juliansader Screenshot: https://stash.reaper.fm/32789/REAPER%20-%20Render%20take%20INTO%20next%20take%2C%20set%20FX%20offline.gif Website: https://forum.cockos.com/showthread.php?t=202505 Donation: https://www.paypal.me/juliansader About: # DESCRIPTION This script employs REAPER's multi-take capabilities to achieve multi-step freezing of items, as well as easy editing and re-rendering of frozen items. Each take can represent a step in the editing process, e.g. MIDI (with VSTi's as Take FX) -> audio (with Take Envelopes) -> audio (with stretch markers) -> etc * Edits can be made to first MIDI take, and re-rendered as new audio into the subsequent takes, without losing any of the audio edits in later takes. * Take FX, particularly VSTi samplers that require lots of memory, can be set offline after rendering the MIDI. # DETAILS * The active take is rendered *into* the next take, replacing the next take's source without altering the next take's FX, stretch markers or envelopes. * Before rendering, the active take's offline Take FX are set online; and after rendering, online Take FX are set offline. * In this variant of the script, track FX are applied, and their online/offline/bypass status are not changed. * The script automatically renders to the same source type as the next take: either MIDI, mono audio or multi-channel audio. * If any of the selected items cannot be rendered (for example if the active take is the last take), it will be deselected. ]] --[[ Changelog: * v0.90 (2018-09-14) + Initial beta release. * v0.91 (2018-09-14) + Stretch marker warning message. * v0.92 (2018-09-26) + Apply track FX. ]] reaper.Undo_BeginBlock2(0) reaper.PreventUIRefresh(1) -- -- REAPER's API doesn't have "render" functions, so must use Actions. Different Actions may be used on different items, so -- must store IDs of all selected item, then deselect them all and re-select one-by-one. -- Items that don't have next takes (i.e. render "into" is not applicable, will be deselected after the script). -- Also store IDs of all tracks that contain selected items, so that their FX can be bypassed. local tItems = {} local tTracks = {} for i = 0, reaper.CountSelectedMediaItems(0)-1 do local item = reaper.GetSelectedMediaItem(0, i) local track = reaper.GetMediaItem_Track(item) tItems[item] = true --{active = active, activeNum = activeNum} --tTracks[track] = {track = true} end reaper.SelectAllMediaItems(0, false) -- Toggle bypass of track FX, and remember which were enabled for track, tFX in pairs(tTracks) do for f = 0, reaper.TrackFX_GetCount(track)-1 do if reaper.TrackFX_GetEnabled(track, f) then reaper.TrackFX_SetEnabled(track, f, false) tFX[#tFX+1] = f end end end -- Iterate through all selected items, render into next take for item in pairs(tItems) do local activeTake = reaper.GetActiveTake(item) local activeNum = reaper.GetMediaItemTakeInfo_Value(activeTake, "IP_TAKENUMBER") -- If active take is last take, i.e. no "next" take, skip this item and leave unselected if activeNum >= reaper.CountTakes(item)-1 then tItems[item] = nil else local nextTake = reaper.GetTake(item, 1 + activeNum) -- Next take in sequence local nextSource = reaper.GetMediaItemTake_Source(nextTake) local nextOffset = reaper.GetMediaItemTakeInfo_Value(nextTake, "D_STARTOFFS") -- REAPER offers several "Appply FX to new take" actions. Must find action that will give same source type as next take's local command if reaper.TakeIsMIDI(nextTake) then command = 40436 else local nextChannels = reaper.GetMediaSourceNumChannels(nextSource) if nextChannels == 1 then command = 40361 elseif nextChannels > 1 then command = 41993 end end -- Is it posisble for number of channels to be 0? if not command then tItems[item] = nil else -- The newly rendered take should be last in sequemce, but to make absolutely sure, -- store all original take IDs, so that can be compared after render. local tTakes = {} for t = 0, reaper.CountTakes(item)-1 do tTakes[reaper.GetTake(item, t)] = true end -- Stretch markers prevent changing take offset. So store and temporarily delete. local tStretch = {} local numStretchMarkers = reaper.GetTakeNumStretchMarkers(nextTake) for s = 0, numStretchMarkers-1 do local OK, pos, srcpos = reaper.GetTakeStretchMarker(nextTake, s) if OK then slope = reaper.GetTakeStretchMarkerSlope(nextTake, s) tStretch[#tStretch+1] = {pos = pos, srcpos = srcpos, slope = slope} else stretchError = true end end local numDeleted = reaper.DeleteTakeStretchMarkers(nextTake, 0, numStretchMarkers) if not (numDeleted == numStretchMarkers) then stretchError = true end -- Set all *offline* Take FX of active take online (ignore bypassed FX) for f = 0, reaper.TakeFX_GetCount(activeTake)-1 do if reaper.TakeFX_GetOffline(activeTake, f) then reaper.TakeFX_SetOffline(activeTake, f, false) reaper.TakeFX_SetEnabled(activeTake, f, true) end end -- APPLY COMMAND TO RENDER! reaper.SetMediaItemSelected(item, true) reaper.Main_OnCommandEx(command, 0, 0) -- Item: Apply track/take FX to items -- Set Take FX offline again. (Ignore bypassed FX.) for f = 0, reaper.TakeFX_GetCount(activeTake)-1 do if reaper.TakeFX_GetEnabled(activeTake, f) then reaper.TakeFX_SetOffline(activeTake, f, true) end end -- New take is supposed to be last in sequence, but is this always true? Find new take. local newTake local newNum local newSource for t = 0, reaper.CountTakes(item)-1 do local take = reaper.GetTake(item, t) if not tTakes[take] then newTake = take newNum = t break end end -- Move newTake's source into nextTake. -- NB: Must swap, otherwise REAPER will crash. -- NB: Must perform in this sequence, otherwise nextTake cannot be opened in MIDI editor - don't know why? -- A rendered take has same start position as item, so STARTOFFS must be 0. if newTake then newSource = reaper.GetMediaItemTake_Source(newTake) reaper.SetMediaItemTake_Source(newTake, nextSource) reaper.SetMediaItemTake_Source(nextTake, newSource) reaper.SetMediaItemTakeInfo_Value(nextTake, "D_STARTOFFS", 0) reaper.SetActiveTake(newTake) reaper.Main_OnCommandEx(40129, 0, 0) -- Take: Delete active take from items reaper.SetActiveTake(nextTake) end -- Restore stretch markers -- Since the new source has same start position as the item (offset of 0), -- the first stretch marker (which is not stretched at the left), must have the equal pos and srcpos -- (positions relative to item start and source start). -- Thus all srcpos must be adjusted with (- tStretch[1].srcpos + tStretch[1].pos) for s = 1, #tStretch do local newSourcePos = tStretch[s].srcpos - tStretch[1].srcpos + tStretch[1].pos local index = reaper.SetTakeStretchMarker(nextTake, -1, tStretch[s].pos, newSourcePos) ---nextOffset) if index ~= -1 then reaper.SetTakeStretchMarkerSlope(nextTake, index, tStretch[s].slope) else stretchError = true end end end reaper.SetMediaItemSelected(item, false) end end -- Re-select all items for item in pairs(tItems) do reaper.SetMediaItemSelected(item, true) end -- Toggle bypass of track FX to original state for track, tFX in pairs(tTracks) do for f = 1, #tFX do reaper.TrackFX_SetEnabled(track, tFX[f], true) end end reaper.PreventUIRefresh(-1) reaper.UpdateArrange() if stretchError then reaper.MB("Some stretch markers may have been misplaced or deleted", "WARNING", 0) end reaper.Undo_EndBlock2(0, "Render items into next take", -1)
1
0.976103
1
0.976103
game-dev
MEDIA
0.369338
game-dev
0.991156
1
0.991156
Kaedrin/nwn2cc
1,649
NWN2 WIP/Override/override_latest/Scripts/cmi_s2_neteamworka.NSS
//:://///////////////////////////////////////////// //:: Teamwork (Nightsong Enforcer) //:: cmi_s2_neteamworka //:: Purpose: //:: Created By: Kaedrin (Matt) //:: Created On: November 8, 2007 //::////////////////////////////////////////////// #include "x0_i0_spells" #include "x2_inc_spellhook" #include "cmi_includes" //#include "cmi_ginc_spells" void main() { object oTarget = GetEnteringObject(); object oCaster = GetAreaOfEffectCreator(); if (oTarget != oCaster) { if(spellsIsTarget(oTarget, SPELL_TARGET_ALLALLIES, oCaster) || (oTarget == oCaster)) { if (!GetHasSpellEffect(SPELL_SPELLABILITY_AURA_NE_TEAMWORK, OBJECT_SELF)) { int nClassLevel = GetLevelByClass(CLASS_NIGHTSONG_ENFORCER, oCaster); int nSkillBonus = 2; if (nClassLevel > 6) { nSkillBonus = 4; } effect eSkillBonusListen = EffectSkillIncrease(SKILL_LISTEN,nSkillBonus); effect eSkillBonusHide = EffectSkillIncrease(SKILL_HIDE,nSkillBonus); effect eSkillBonusMoveSilent = EffectSkillIncrease(SKILL_MOVE_SILENTLY,nSkillBonus); effect eSkillBonusSpot = EffectSkillIncrease(SKILL_SPOT,nSkillBonus); effect eLink = EffectLinkEffects(eSkillBonusListen, eSkillBonusHide); eLink = EffectLinkEffects(eLink, eSkillBonusMoveSilent); eLink = EffectLinkEffects(eLink, eSkillBonusSpot); eLink = SupernaturalEffect(eLink); //eLink = SetEffectSpellId (eLink, SPELL_SPELLABILITY_AURA_NE_TEAMWORK); SignalEvent (oTarget, EventSpellCastAt(oCaster, SPELL_SPELLABILITY_AURA_NE_TEAMWORK, FALSE)); ApplyEffectToObject(DURATION_TYPE_PERMANENT, eLink, oTarget); } } } }
1
0.724279
1
0.724279
game-dev
MEDIA
0.976779
game-dev
0.799333
1
0.799333
CLADevs/VanillaX
8,533
src/CLADevs/VanillaX/entities/utils/villager/VillagerProfession.php
<?php namespace CLADevs\VanillaX\entities\utils\villager; use CLADevs\VanillaX\entities\utils\ItemHelper; use CLADevs\VanillaX\entities\utils\villager\professions\NitwitProfession; use CLADevs\VanillaX\utils\Utils; use InvalidArgumentException; use pocketmine\block\Block; use pocketmine\block\BlockLegacyIds; use pocketmine\item\Item; use pocketmine\item\LegacyStringToItemParser; use pocketmine\item\LegacyStringToItemParserException; abstract class VillagerProfession{ const TIER_NOVICE = 0; const TIER_APPRENTICE = 1; const TIER_JOURNEYMAN = 2; const TIER_EXPERT = 3; const TIER_MASTER = 4; const BIOME_PLAINS = 0; const BIOME_DESERT = 1; const BIOME_JUNGLE = 2; const BIOME_SAVANNA = 3; const BIOME_SNOW = 4; const BIOME_SWAMP = 5; const BIOME_TAIGA = 6; const UNEMPLOYED = 0; const FARMER = 1; const FISHERMAN = 2; const SHEPHERD = 3; const FLETCHER = 4; const LIBRARIAN = 5; const CARTOGRAPHER = 6; const CLERIC = 7; const ARMORER = 8; const WEAPON_SMITH = 9; const TOOL_SMITH = 10; const BUTCHER = 11; const LEATHER_WORKER = 12; const MASON = 14; const NITWIT = 15; private int $id; private string $name; private int $block; /** @var string[] */ protected array $data = []; /** @var VillagerProfession[] */ private static array $professions = []; /** @var VillagerOffer[][] */ private array $recipes = []; /** @var VillagerOffer[] */ private array $offers = []; public function __construct(int $id, string $name, int $block = BlockLegacyIds::AIR){ $this->id = $id; $this->name = $name; $this->block = $block; if($this->hasTrades()){ $this->data = json_decode(file_get_contents(Utils::getResourceFile("trades" . DIRECTORY_SEPARATOR . strtolower(str_replace(" ", "_", $name)) . "_trades.json")), true); } } public static function init(): void{ self::$professions = []; $path = "entities" . DIRECTORY_SEPARATOR . "utils" . DIRECTORY_SEPARATOR . "villager" . DIRECTORY_SEPARATOR . "professions"; Utils::callDirectory($path, function (string $namespace): void{ self::registerProfession(new $namespace()); }); } public static function registerProfession(VillagerProfession $profession): void{ self::$professions[$profession->getId()] = $profession; } public static function getProfession(int $id): VillagerProfession{ return self::$professions[$id] ?? new NitwitProfession(); } public function getId(): int{ return $this->id; } public function getName(): string{ return $this->name; } public function getBlock(): int{ return $this->block; } public function hasTrades(): bool{ return true; } public function getProfessionExp(int $tier): int{ return $this->data["tiers"][$tier]["total_exp_required"] ?? 0; } public function getNovice(): array{ return $this->getTrades(self::TIER_NOVICE); } /** * @return VillagerOffer[] */ public function getApprentice(): array{ return $this->getTrades(self::TIER_APPRENTICE); } /** * @return VillagerOffer[] */ public function getJourneyman(): array{ return $this->getTrades(self::TIER_JOURNEYMAN); } /** * @return VillagerOffer[] */ public function getExpert(): array{ return $this->getTrades(self::TIER_EXPERT); } /** * @return VillagerOffer[] */ public function getMaster(): array{ return $this->getTrades(self::TIER_MASTER); } /** * @param int $tier * @return VillagerOffer[] */ private function getTrades(int $tier): array{ $values = []; $data = $this->data["tiers"][$tier]["groups"] ?? []; if(count($data) < 1){ return []; } foreach($data as $i){ $trades = $i["trades"]; if(count($trades) > 1){ $trades = [$trades[array_rand($trades)]]; } foreach($trades as $trade){ $wants = $trade["wants"]; $gives = $trade["gives"]; $traderExp = $trade["trader_exp"]; $rewardExp = $trade["reward_exp"]; $maxUses = $trade["max_uses"]; $priceMultiplierA = 1; $priceMultiplierB = 1; $input = null; $input2 = null; $result = null; foreach($wants as $key => $want){ $item = $want["item"] ?? null; $functions = $give["functions"] ?? []; try{ $choice = $want["choice"] ?? null; if($item === null && $choice === null){ continue; } if(is_array($choice)){ $item = $choice[array_rand($choice)]; $functions = $item["functions"] ?? []; } $item = LegacyStringToItemParser::getInstance()->parse(is_array($item) ? $item["item"] : $item); $item->setCount(is_array($item) ? ($item["quantity"] ?? 1) : ($want["quantity"] ?? 1)); $this->applyFunction($item, $functions); }catch (InvalidArgumentException $e){ continue; } if($key === 0){ $input = $item; $priceMultiplierA = $want["price_multiplier"] ?? 1; }elseif($key === 1){ $input2 = $item; $priceMultiplierB = $want["price_multiplier"] ?? 1; break; } } foreach($gives as $give){ $item = $give["item"] ?? null; $functions = $give["functions"] ?? []; try{ $choice = $give["choice"] ?? null; if($item === null && $choice === null){ continue; } if(is_array($choice)){ $item = $choice[array_rand($choice)]; $functions = $item["functions"] ?? []; } $item = LegacyStringToItemParser::getInstance()->parse(is_array($item) ? $item["item"] : $item); $item->setCount(is_array($item) ? ($item["quantity"] ?? 1) : ($give["quantity"] ?? 1)); $this->applyFunction($item, $functions); }catch (InvalidArgumentException|LegacyStringToItemParserException){ continue; } $result = $item; break; } if($result === null){ continue; } $values[] = new VillagerOffer($input, $input2, $result, $traderExp, $rewardExp, $priceMultiplierA, $priceMultiplierB, $maxUses); } } return $values; } private function applyFunction(Item $item, array $functions): void{ foreach($functions as $function){ $name = $function["function"] ?? null; switch($name){ case "enchant_with_levels": ItemHelper::applyEnchantWithLevel($item, $function["treasure"] ?? false, $function["levels"]["min"], $function["levels"]["max"]); return; case "exploration_map": //TODO return; case "random_aux_value": ItemHelper::applyRandomAuxValue($item, $function["values"]["min"], $function["values"]["max"]); return; case "random_dye": ItemHelper::applyRandomDye($item); return; case "enchant_book_for_trading": //TODO for now using random enchants ItemHelper::applyEnchantRandomly($item, true); return; case "random_block_state": ItemHelper::applyRandomAuxValue($item, 0, 15); return; } } } }
1
0.85326
1
0.85326
game-dev
MEDIA
0.763398
game-dev
0.906377
1
0.906377
Dan6040/SharpDX-Rastertek-Tutorials
26,881
DSharpDXRastertekSeries2/Series2/TutTerr09/Graphics/Models/DTerrain.cs
using DSharpDXRastertek.Series2.TutTerr09.System; using SharpDX; using SharpDX.Direct3D11; using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Runtime.InteropServices; namespace DSharpDXRastertek.Series2.TutTerr09.Graphics.Models { public class DTerrain { // Structs [StructLayout(LayoutKind.Sequential)] public struct DVertexType { public Vector3 position; public Vector2 texture; public Vector3 normal; public Vector3 tangent; public Vector3 binormal; public Vector3 color; } [StructLayout(LayoutKind.Sequential)] public struct DHeightMapType { public float x, y, z; public float tu, tv; public float nx, ny, nz; public float tx, ty, tz; public float bx, by, bz; public float r, g, b; } [StructLayout(LayoutKind.Sequential)] public struct DVectorTypeShareNormal { public float x, y, z; // public float tu, tv; public float nx, ny, nz; public float r, g, b; } [StructLayout(LayoutKind.Sequential)] public struct DVector { public float x, y, z; } [StructLayout(LayoutKind.Sequential)] public struct DColorVertexType { internal Vector3 position; internal Vector4 color; } [StructLayout(LayoutKind.Sequential)] public struct DTempVertex { public float x, y, z; public float tu, tv; public float nx, ny, nz; } // Variables public int m_CellCount; private int m_TerrainWidth, m_TerrainHeight, m_ColourMapWidth, m_ColourMapHeight; private float m_TerrainScale = 12.0f; private string m_TerrainHeightManName, m_ColorMapName; // Properties private int VertexCount { get; set; } public int IndexCount { get; private set; } public DTerrainCell[] TerrainCells { get; set; } public List<DHeightMapType> HeightMap = new List<DHeightMapType>(); public DHeightMapType[] TerrainModel { get; set; } // Constructor public DTerrain() { } // Methods. public bool Initialize(SharpDX.Direct3D11.Device device, string setupFilename) { // Get the terrain filename, dimensions, and so forth from the setup file. if (!LoadSetupFile(setupFilename)) return false; // Initialize the terrain height map with the data from the raw file. if (!LoadRawHeightMap()) return false; // Setup the X and Z coordinates for the height map as well as scale the terrain height by the height scale value. SetTerrainCoordinates(); // Calculate the normals for the terrain data. if (!CalculateNormals()) return false; // Load in the ColorMap for the terrain if (!LoadColorMap()) return false; if (!BuildTerrainModel()) return false; // Calculate the tangent and binormal for the terrain model. CalculateTerrainVectors(); // Create and load the cells with the terrain data. if (!LoadTerrainCells(device)) return false; return true; } private bool LoadTerrainCells(SharpDX.Direct3D11.Device device) { // Set the height and width of each terrain cell to a fixed 33x33 vertex array. int cellHeight = 33; int cellWidth = 33; // Calculate the number of cells needed to store the terrain data. int cellRowCount = (m_TerrainWidth - 1) / (cellWidth - 1); m_CellCount = cellRowCount * cellRowCount; // Create the terrain cell array. TerrainCells = new DTerrainCell[m_CellCount]; // Loop through and initialize all the terrain cells. for (int j = 0; j < cellRowCount; j++) for (int i = 0; i < cellRowCount; i++) { int index = (cellRowCount * j) + i; TerrainCells[index] = new DTerrainCell(); if (!TerrainCells[index].Initialize(device, TerrainModel, i, j, cellHeight, cellWidth, m_TerrainWidth)) return false; } ShutdownHeightMap(); return true; } private bool LoadRawHeightMap() { byte[] bytesData = File.ReadAllBytes(DSystemConfiguration.TextureFilePath + m_TerrainHeightManName); //// Create the structure to hold the height map data. HeightMap = new List<DHeightMapType>(m_TerrainWidth * m_TerrainHeight); ushort tester; int ind = 0, index = 0; // Copy the image data into the height map array. for (int j = 0; j < m_TerrainHeight; j++) { for (int i = 0; i < m_TerrainWidth; i++) { index = (m_TerrainWidth * j) + i; // Store the height at this point in the height map array. tester = BitConverter.ToUInt16(bytesData, ind); HeightMap.Add(new DHeightMapType() { x = i, y = tester, z = j }); ind += 2; } } bytesData = null; return true; } private bool BuildTerrainModel() { try { // Set the number of vertices in the model. VertexCount = (m_TerrainWidth - 1) * (m_TerrainHeight - 1) * 6; // Create the terrain model array. TerrainModel = new DHeightMapType[VertexCount]; // Load the terrain model with the height map terrain data. int index = 0; for (int j = 0; j < (m_TerrainHeight - 1); j++) { for (int i = 0; i < (m_TerrainWidth - 1); i++) { int index1 = (m_TerrainWidth * j) + i; // Bottom left. int index2 = (m_TerrainWidth * j) + (i + 1); // Bottom right. int index3 = (m_TerrainWidth * (j + 1)) + i; // Upper left. int index4 = (m_TerrainWidth * (j + 1)) + (i + 1); // Upper right. // Upper left. TerrainModel[index].x = HeightMap[index3].x; TerrainModel[index].y = HeightMap[index3].y; TerrainModel[index].z = HeightMap[index3].z; TerrainModel[index].nx = HeightMap[index3].nx; TerrainModel[index].ny = HeightMap[index3].ny; TerrainModel[index].nz = HeightMap[index3].nz; TerrainModel[index].tu = 0.0f; TerrainModel[index].tv = 0.0f; TerrainModel[index].r = HeightMap[index3].r; TerrainModel[index].g = HeightMap[index3].g; TerrainModel[index].b = HeightMap[index3].b; index++; // Upper right. TerrainModel[index].x = HeightMap[index4].x; TerrainModel[index].y = HeightMap[index4].y; TerrainModel[index].z = HeightMap[index4].z; TerrainModel[index].nx = HeightMap[index4].nx; TerrainModel[index].ny = HeightMap[index4].ny; TerrainModel[index].nz = HeightMap[index4].nz; TerrainModel[index].tu = 1.0f; TerrainModel[index].tv = 0.0f; TerrainModel[index].r = HeightMap[index4].r; TerrainModel[index].g = HeightMap[index4].g; TerrainModel[index].b = HeightMap[index4].b; index++; // Bottom left. TerrainModel[index].x = HeightMap[index1].x; TerrainModel[index].y = HeightMap[index1].y; TerrainModel[index].z = HeightMap[index1].z; TerrainModel[index].nx = HeightMap[index1].nx; TerrainModel[index].ny = HeightMap[index1].ny; TerrainModel[index].nz = HeightMap[index1].nz; TerrainModel[index].tu = 0.0f; TerrainModel[index].tv = 1.0f; TerrainModel[index].r = HeightMap[index1].r; TerrainModel[index].g = HeightMap[index1].g; TerrainModel[index].b = HeightMap[index1].b; index++; // Bottom left. TerrainModel[index].x = HeightMap[index1].x; TerrainModel[index].y = HeightMap[index1].y; TerrainModel[index].z = HeightMap[index1].z; TerrainModel[index].nx = HeightMap[index1].nx; TerrainModel[index].ny = HeightMap[index1].ny; TerrainModel[index].nz = HeightMap[index1].nz; TerrainModel[index].tu = 0.0f; TerrainModel[index].tv = 1.0f; TerrainModel[index].r = HeightMap[index1].r; TerrainModel[index].g = HeightMap[index1].g; TerrainModel[index].b = HeightMap[index1].b; index++; // Upper right. TerrainModel[index].x = HeightMap[index4].x; TerrainModel[index].y = HeightMap[index4].y; TerrainModel[index].z = HeightMap[index4].z; TerrainModel[index].nx = HeightMap[index4].nx; TerrainModel[index].ny = HeightMap[index4].ny; TerrainModel[index].nz = HeightMap[index4].nz; TerrainModel[index].tu = 1.0f; TerrainModel[index].tv = 0.0f; TerrainModel[index].r = HeightMap[index4].r; TerrainModel[index].g = HeightMap[index4].g; TerrainModel[index].b = HeightMap[index4].b; index++; // Bottom right. TerrainModel[index].x = HeightMap[index2].x; TerrainModel[index].y = HeightMap[index2].y; TerrainModel[index].z = HeightMap[index2].z; TerrainModel[index].nx = HeightMap[index2].nx; TerrainModel[index].ny = HeightMap[index2].ny; TerrainModel[index].nz = HeightMap[index2].nz; TerrainModel[index].tu = 1.0f; TerrainModel[index].tv = 1.0f; TerrainModel[index].r = HeightMap[index2].r; TerrainModel[index].g = HeightMap[index2].g; TerrainModel[index].b = HeightMap[index2].b; index++; } } HeightMap?.Clear(); HeightMap = null; } catch { return false; } return true; } private void CalculateTerrainVectors() { // Calculate the number of vertices in the terrain mesh. VertexCount = (m_TerrainWidth - 1) * (m_TerrainHeight - 1) * 6; // Calculate the number of faces in the terrain model. int faceCount = VertexCount / 3; // Initialize the index to the model data. int index = 0; DTempVertex vertex1, vertex2, vertex3; DVector tangent = new DVector(); DVector binormal = new DVector(); // Go through all the faces and calculate the the tangent, binormal, and normal vectors. for (int i = 0; i < faceCount; i++) { // Get the three vertices for this face from the terrain model. vertex1.x = TerrainModel[index].x; vertex1.y = TerrainModel[index].y; vertex1.z = TerrainModel[index].z; vertex1.tu = TerrainModel[index].tu; vertex1.tv = TerrainModel[index].tv; vertex1.nx = TerrainModel[index].nx; vertex1.ny = TerrainModel[index].ny; vertex1.nz = TerrainModel[index].nz; index++; vertex2.x = TerrainModel[index].x; vertex2.y = TerrainModel[index].y; vertex2.z = TerrainModel[index].z; vertex2.tu = TerrainModel[index].tu; vertex2.tv = TerrainModel[index].tv; vertex2.nx = TerrainModel[index].nx; vertex2.ny = TerrainModel[index].ny; vertex2.nz = TerrainModel[index].nz; index++; vertex3.x = TerrainModel[index].x; vertex3.y = TerrainModel[index].y; vertex3.z = TerrainModel[index].z; vertex3.tu = TerrainModel[index].tu; vertex3.tv = TerrainModel[index].tv; vertex3.nx = TerrainModel[index].nx; vertex3.ny = TerrainModel[index].ny; vertex3.nz = TerrainModel[index].nz; index++; /// MAKE SUEW that the tangent nad Binoemals calculated are being sent into the model after the method below. // Calculate the tangent and binormal of that face. CalculateTangentBinormal(vertex1, vertex2, vertex3, out tangent, out binormal); // Store the tangent and binormal for this face back in the model structure. var temp = TerrainModel[index - 1]; temp.tx = tangent.x; temp.ty = tangent.y; temp.tz = tangent.z; temp.bx = binormal.x; temp.by = binormal.y; temp.bz = binormal.z; TerrainModel[index - 1] = temp; var temp2 = TerrainModel[index - 2]; temp2.tx = tangent.x; temp2.ty = tangent.y; temp2.tz = tangent.z; temp2.bx = binormal.x; temp2.by = binormal.y; temp2.bz = binormal.z; TerrainModel[index - 2] = temp2; var temp3 = TerrainModel[index - 3]; temp3.tx = tangent.x; temp3.ty = tangent.y; temp3.tz = tangent.z; temp3.bx = binormal.x; temp3.by = binormal.y; temp3.bz = binormal.z; TerrainModel[index - 3] = temp3; } } private void CalculateTangentBinormal(DTempVertex vertex1, DTempVertex vertex2, DTempVertex vertex3, out DVector tangent, out DVector binormal) { float[] vector1 = new float[3]; float[] vector2 = new float[3]; float[] tuVector = new float[2]; float[] tvVector = new float[2]; // Calculate the two vectors for this face. vector1[0] = vertex2.x - vertex1.x; vector1[1] = vertex2.y - vertex1.y; vector1[2] = vertex2.z - vertex1.z; vector2[0] = vertex3.x - vertex1.x; vector2[1] = vertex3.y - vertex1.y; vector2[2] = vertex3.z - vertex1.z; // Calculate the tu and tv texture space vectors. tuVector[0] = vertex2.tu - vertex1.tu; tvVector[0] = vertex2.tv - vertex1.tv; tuVector[1] = vertex3.tu - vertex1.tu; tvVector[1] = vertex3.tv - vertex1.tv; // Calculate the denominator of the tangent/binormal equation. float den = 1.0f / (tuVector[0] * tvVector[1] - tuVector[1] * tvVector[0]); // Calculate the cross products and multiply by the coefficient to get the tangent and binormal. tangent.x = (tvVector[1] * vector1[0] - tvVector[0] * vector2[0]) * den; tangent.y = (tvVector[1] * vector1[1] - tvVector[0] * vector2[1]) * den; tangent.z = (tvVector[1] * vector1[2] - tvVector[0] * vector2[2]) * den; binormal.x = (tuVector[0] * vector2[0] - tuVector[1] * vector1[0]) * den; binormal.y = (tuVector[0] * vector2[1] - tuVector[1] * vector1[1]) * den; binormal.z = (tuVector[0] * vector2[2] - tuVector[1] * vector1[2]) * den; // Calculate the length of this normal. float length = (float)Math.Sqrt((tangent.x * tangent.x) + (tangent.y * tangent.y) + (tangent.z * tangent.z)); // Normalize the normal and then store it binormal.x = binormal.x / length; binormal.y = binormal.y / length; binormal.z = binormal.z / length; } private bool LoadColorMap() { Bitmap colourBitMap; try { // Open the color map file in binary. colourBitMap = new Bitmap(DSystemConfiguration.TextureFilePath + m_ColorMapName); } catch { return false; } // This check is optional. // Make sure the color map dimensions are the same as the terrain dimensions for easy 1 to 1 mapping. m_ColourMapWidth = colourBitMap.Width; m_ColourMapHeight = colourBitMap.Height; if ((m_ColourMapWidth != m_TerrainWidth) || (m_ColourMapHeight != m_TerrainHeight)) return false; // Read the image data into the color map portion of the height map structure. int index; for (int j = 0; j < m_ColourMapHeight; j++) for (int i = 0; i < m_ColourMapWidth; i++) { index = (m_ColourMapHeight * j) + i; DHeightMapType tempCopy = HeightMap[index]; tempCopy.r = colourBitMap.GetPixel(i, j).R / 255.0f; // 117.75f; //// 0.678431392 tempCopy.g = colourBitMap.GetPixel(i, j).G / 255.0f; //117.75f; // 0.619607866 tempCopy.b = colourBitMap.GetPixel(i, j).B / 255.0f; // 117.75f; // 0.549019635 HeightMap[index] = tempCopy; } // Release the bitmap image data. colourBitMap?.Dispose(); colourBitMap = null; return true; } private bool CalculateNormals() { // Create a temporary array to hold the un-normalized normal vectors. int index; float length; Vector3 vertex1, vertex2, vertex3, vector1, vector2, sum; DVectorTypeShareNormal[] normals = new DVectorTypeShareNormal[(m_TerrainHeight - 1) * (m_TerrainWidth - 1)]; // Go through all the faces in the mesh and calculate their normals. for (int j = 0; j < (m_TerrainHeight - 1); j++) { for (int i = 0; i < (m_TerrainWidth - 1); i++) { int index1 = (j * m_TerrainHeight) + i; int index2 = (j * m_TerrainHeight) + (i + 1); int index3 = ((j + 1) * m_TerrainHeight) + i; // Get three vertices from the face. vertex1.X = HeightMap[index1].x; vertex1.Y = HeightMap[index1].y; vertex1.Z = HeightMap[index1].z; vertex2.X = HeightMap[index2].x; vertex2.Y = HeightMap[index2].y; vertex2.Z = HeightMap[index2].z; vertex3.X = HeightMap[index3].x; vertex3.Y = HeightMap[index3].y; vertex3.Z = HeightMap[index3].z; // Calculate the two vectors for this face. vector1 = vertex1 - vertex3; vector2 = vertex3 - vertex2; index = (j * (m_TerrainHeight - 1)) + i; // Calculate the cross product of those two vectors to get the un-normalized value for this face normal. Vector3 vecTestCrossProduct = Vector3.Cross(vector1, vector2); normals[index].x = vecTestCrossProduct.X; normals[index].y = vecTestCrossProduct.Y; normals[index].z = vecTestCrossProduct.Z; } } // Now go through all the vertices and take an average of each face normal // that the vertex touches to get the averaged normal for that vertex. for (int j = 0; j < m_TerrainHeight; j++) { for (int i = 0; i < m_TerrainWidth; i++) { // Initialize the sum. sum = Vector3.Zero; // Initialize the count. int count = 9; // Bottom left face. if (((i - 1) >= 0) && ((j - 1) >= 0)) { index = ((j - 1) * (m_TerrainHeight - 1)) + (i - 1); sum[0] += normals[index].x; sum[1] += normals[index].y; sum[2] += normals[index].z; count++; } // Bottom right face. if ((i < (m_TerrainWidth - 1)) && ((j - 1) >= 0)) { index = ((j - 1) * (m_TerrainHeight - 1)) + i; sum[0] += normals[index].x; sum[1] += normals[index].y; sum[2] += normals[index].z; count++; } // Upper left face. if (((i - 1) >= 0) && (j < (m_TerrainHeight - 1))) { index = (j * (m_TerrainHeight - 1)) + (i - 1); sum[0] += normals[index].x; sum[1] += normals[index].y; sum[2] += normals[index].z; count++; } // Upper right face. if ((i < (m_TerrainWidth - 1)) && (j < (m_TerrainHeight - 1))) { index = (j * (m_TerrainHeight - 1)) + i; sum.X += normals[index].x; sum.Y += normals[index].y; sum.Z += normals[index].z; count++; } // Take the average of the faces touching this vertex. sum.X = (sum.X / (float)count); sum.Y = (sum.Y / (float)count); sum.Z = (sum.Z / (float)count); // Calculate the length of this normal. length = (float)Math.Sqrt((sum.X * sum.X) + (sum.Y * sum.Y) + (sum.Z * sum.Z)); // Get an index to the vertex location in the height map array. index = (j * m_TerrainHeight) + i; // Normalize the final shared normal for this vertex and store it in the height map array. DHeightMapType editHeightMap = HeightMap[index]; editHeightMap.nx = (sum.X / length); editHeightMap.ny = (sum.Y / length); editHeightMap.nz = (sum.Z / length); HeightMap[index] = editHeightMap; } } // Release the temporary normals. normals = null; return true; } private bool LoadSetupFile(string setupFilename) { // Open the setup file. If it could not open the file then exit. setupFilename = DSystemConfiguration.DataFilePath + setupFilename; // Get all the lines containing the font data. var setupLines = File.ReadAllLines(setupFilename); // Read in the terrain file name. m_TerrainHeightManName = setupLines[0].Trim("Terrain Filename: ".ToCharArray()); // Read in the terrain height & width. m_TerrainHeight = int.Parse(setupLines[1].Trim("Terrain Height: ".ToCharArray())); m_TerrainWidth = int.Parse(setupLines[2].Trim("Terrain Width: ".ToCharArray())); // Read in the terrain height scaling. m_TerrainScale = float.Parse(setupLines[3].Trim("Terrain Scaling: ".ToCharArray())); // Read in the ColorMap File Name. m_ColorMapName = setupLines[4].TrimStart("Color Map Filename: ".ToCharArray()); setupLines = null; return true; } private void SetTerrainCoordinates() { for (var i = 0; i < HeightMap.Count; i++) { var temp = HeightMap[i]; temp.y /= m_TerrainScale; HeightMap[i] = temp; } } public void ShutDown() { // Release the terrain cells. ShutdownTerrainCells(); // Release the height map. ShutdownHeightMap(); } private void ShutdownHeightMap() { // Release the height map array. TerrainModel = null; } private void ShutdownTerrainCells() { // Release the terrain cell array. for (int i = 0; i < m_CellCount; i++) TerrainCells[i].ShutDown(); TerrainCells = null; } public void RenderCell(DeviceContext deviceContext, int cellID) { TerrainCells[cellID].Render(deviceContext); } public void RenderCellLines(DeviceContext deviceContext, int cellID) { TerrainCells[cellID].RenderLineBuffers(deviceContext); } public int GetCellIndexCount(int childIndex) { return TerrainCells[childIndex].IndexCount; } public int GetCellLinesIndexCount(int childIndex) { return TerrainCells[childIndex].LineIndexCount; } } }
1
0.880808
1
0.880808
game-dev
MEDIA
0.85406
game-dev
0.99301
1
0.99301
ds58/Panilla
1,080
paper-v1_20_6/src/main/java/com/ruinscraft/panilla/paper/v1_20_6/io/PlayerInjector.java
package com.ruinscraft.panilla.paper.v1_20_6.io; import com.ruinscraft.panilla.api.IPanillaPlayer; import com.ruinscraft.panilla.api.io.IPlayerInjector; import de.tr7zw.changeme.nbtapi.NBT; import io.netty.channel.Channel; import io.netty.handler.codec.ByteToMessageDecoder; import net.minecraft.server.level.ServerPlayer; import org.bukkit.craftbukkit.entity.CraftPlayer; public class PlayerInjector implements IPlayerInjector { static { NBT.preloadApi(); } @Override public Channel getPlayerChannel(IPanillaPlayer player) throws IllegalArgumentException { CraftPlayer craftPlayer = (CraftPlayer) player.getHandle(); ServerPlayer entityPlayer = craftPlayer.getHandle(); return entityPlayer.connection.connection.channel; } @Override public int getCompressionLevel() { return 256; } @Override public ByteToMessageDecoder getDecompressor() { return null; } @Override public ByteToMessageDecoder getDecoder() { throw new RuntimeException("Not implemented"); } }
1
0.864326
1
0.864326
game-dev
MEDIA
0.948115
game-dev
0.602694
1
0.602694
PrimeDecomp/prime
3,016
src/MetroidPrime/ScriptObjects/CScriptSpawnPoint.cpp
#include "MetroidPrime/ScriptObjects/CScriptSpawnPoint.hpp" #include "MetroidPrime/CGameArea.hpp" #include "MetroidPrime/CStateManager.hpp" #include "MetroidPrime/CWorld.hpp" #include "MetroidPrime/Player/CPlayer.hpp" CScriptSpawnPoint::CScriptSpawnPoint( TUniqueId uid, const rstl::string& name, const CEntityInfo& info, const CTransform4f& xf, const rstl::reserved_vector< int, int(CPlayerState::kIT_Max) >& itemCounts, const bool defaultSpawn, const bool active, const bool morphed) : CEntity(uid, info, active, name) , x34_xf(xf) , x64_itemCounts(itemCounts) , x10c_24_firstSpawn(defaultSpawn) , x10c_25_morphed(morphed) {} CScriptSpawnPoint::~CScriptSpawnPoint() {} const CTransform4f& CScriptSpawnPoint::GetTransform() const { return x34_xf; } int CScriptSpawnPoint::GetPowerup(const CPlayerState::EItemType& type) const { if (CPlayerState::kIT_Max <= type || type < 0) { return x64_itemCounts.front(); } return x64_itemCounts[type]; } void CScriptSpawnPoint::AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId objId, CStateManager& stateMgr) { CEntity::AcceptScriptMsg(msg, objId, stateMgr); switch (msg) { case kSM_Reset: for (int i = 0; i < CPlayerState::kIT_Max; ++i) { const CPlayerState::EItemType e = CPlayerState::EItemType(i); stateMgr.PlayerState()->SetPowerUp(e, GetPowerup(e)); stateMgr.PlayerState()->SetPickup(e, GetPowerup(e)); } case kSM_SetToZero: if (GetActive()) { CPlayer* player = stateMgr.Player(); TAreaId thisAreaId = GetCurrentAreaId(); TAreaId nextAreaId = stateMgr.GetNextAreaId(); if (thisAreaId != nextAreaId) { bool propagateAgain = false; CGameArea* area = stateMgr.World()->Area(thisAreaId); CGameArea::EOcclusionState occlusionState = area->IsLoaded() ? area->GetOcclusionState() : CGameArea::kOS_Occluded; if (occlusionState == CGameArea::kOS_Occluded) { while (!area->TryTakingOutOfARAM()) { } CWorld::PropogateAreaChain(CGameArea::kOS_Visible, area, stateMgr.World()); propagateAgain = true; } stateMgr.SetCurrentAreaId(thisAreaId); stateMgr.SetActorAreaId(*player, thisAreaId); player->Teleport(x34_xf, stateMgr, true); player->SetSpawnedMorphBallState( x10c_25_morphed ? CPlayer::kMS_Morphed : CPlayer::kMS_Unmorphed, stateMgr); if (propagateAgain) { CWorld::PropogateAreaChain(CGameArea::kOS_Occluded, stateMgr.World()->Area(nextAreaId), stateMgr.World()); } } else { player->Teleport(x34_xf, stateMgr, true); player->SetSpawnedMorphBallState( x10c_25_morphed ? CPlayer::kMS_Morphed : CPlayer::kMS_Unmorphed, stateMgr); } CEntity::SendScriptMsgs(kSS_Zero, stateMgr, kSM_None); } default: break; } } void CScriptSpawnPoint::Accept(IVisitor& visitor) { visitor.Visit(*this); }
1
0.893338
1
0.893338
game-dev
MEDIA
0.969371
game-dev
0.866136
1
0.866136
Swiftshine/key
1,513
src/nw4r/g3d/g3d_scnrfl.h
#ifndef NW4R_G3D_SCNRFL_H #define NW4R_G3D_SCNRFL_H #include "nw4r/types_nw4r.h" #include "g3d_scnleaf.h" #include <RFL/RFL_Model.h> #include <RFL/RFL_MiddleDatabase.h> namespace nw4r { namespace g3d { class ScnRfl : public ScnLeaf { public: struct RflData { bool SetupCharModel(RFLDataSource, u16, RFLMiddleDB *); }; public: static ScnRfl * Construct(MEMAllocator *, u32 *, RFLResolution, u32, u32); ScnRfl(MEMAllocator *, ScnRfl *, RflData *, void *, u32); virtual bool IsDerivedFrom(TypeObj other) const // at 0x8 { return (other == GetTypeObjStatic()); } virtual void G3dProc(u32, u32, void *); // at 0xC virtual ~ScnRfl(); // at 0x10 virtual const TypeObj GetTypeObj() const // at 0x14 { return TypeObj(TYPE_NAME); } virtual const char * GetTypeName() const // at 0x18 { return GetTypeObj().GetTypeName(); } bool GetExpression(RFLExpression *); bool SetExpression(RFLExpression); void SetFogIdx(int); void SetLightSetIdx(int); static const nw4r::g3d::G3dObj::TypeObj GetTypeObjStatic() { return TypeObj(TYPE_NAME); } private: NW4R_G3D_TYPE_OBJ_DECL(ScnRfl); }; } } #endif
1
0.721011
1
0.721011
game-dev
MEDIA
0.45789
game-dev
0.514532
1
0.514532
Critical-Impact/InventoryTools
1,577
InventoryTools/Logic/Filters/VentureTypeFilter.cs
using System.Linq; using AllaganLib.GameSheets.Caches; using AllaganLib.GameSheets.ItemSources; using AllaganLib.GameSheets.Sheets.Rows; using AllaganLib.Shared.Extensions; using CriticalCommonLib.Models; using InventoryTools.Logic.Filters.Abstract; using InventoryTools.Services; using Microsoft.Extensions.Logging; namespace InventoryTools.Logic.Filters; public class VentureTypeFilter : StringFilter { public VentureTypeFilter(ILogger<VentureTypeFilter> logger, ImGuiService imGuiService) : base(logger, imGuiService) { } public override string Key { get; set; } = "VentureTypeFilter"; public override string Name { get; set; } = "Venture Type"; public override string HelpText { get; set; } = "The type of the venture"; public override FilterCategory FilterCategory { get; set; } = FilterCategory.Acquisition; public override bool? FilterItem(FilterConfiguration configuration, InventoryItem item) { return FilterItem(configuration, item.Item); } public override bool? FilterItem(FilterConfiguration configuration, ItemRow item) { var currentValue = CurrentValue(configuration); if (!string.IsNullOrEmpty(currentValue)) { var ventureNames = string.Join(",", item.GetSourcesByCategory<ItemVentureSource>(ItemInfoCategory.AllVentures) .Select(c => c.RetainerTaskRow.FormattedName)); if (!ventureNames.ToLower().PassesFilter(currentValue.ToLower())) { return false; } } return true; } }
1
0.942577
1
0.942577
game-dev
MEDIA
0.399251
game-dev
0.924434
1
0.924434
Autodesk/Aurora
9,477
Libraries/Aurora/Source/Transpiler.cpp
// Copyright 2025 Autodesk, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "pch.h" #include "Transpiler.h" #include <slang.h> #include <slang-com-ptr.h> BEGIN_AURORA // Slang string blob. Simple wrapper around std::string that can be used by Slang compiler. struct StringSlangBlob : public ISlangBlob, ISlangCastable { StringSlangBlob(const string& str) : _str(str) {} virtual ~StringSlangBlob() = default; // Get a pointer to the string. virtual SLANG_NO_THROW void const* SLANG_MCALL getBufferPointer() override { return _str.data(); } // Get the length of the string. virtual SLANG_NO_THROW size_t SLANG_MCALL getBufferSize() override { return _str.length(); } // Default queryInterface implementation for Slang type system. virtual SLANG_NO_THROW SlangResult SLANG_MCALL queryInterface( SlangUUID const& uuid, void** outObject) SLANG_OVERRIDE { *outObject = getInterface(uuid); return *outObject ? SLANG_OK : SLANG_E_NOT_IMPLEMENTED; } // Do not implement ref counting, just return 1. virtual SLANG_NO_THROW uint32_t SLANG_MCALL addRef() SLANG_OVERRIDE { return 1; } virtual SLANG_NO_THROW uint32_t SLANG_MCALL release() SLANG_OVERRIDE { return 1; } // Default castAs implementation for Slang type system. void* castAs(const SlangUUID& guid) override { return getInterface(guid); } // Allow casting as Unknown and Blob, but nothing else. void* getInterface(const SlangUUID& uuid) { if (uuid == ISlangUnknown::getTypeGuid() || uuid == ISlangBlob::getTypeGuid()) { return static_cast<ISlangBlob*>(this); } return nullptr; } // The actual string data. const string& _str; }; // Slang filesystem that reads from a simple lookup table of strings. struct AuroraSlangFileSystem : public ISlangFileSystem { AuroraSlangFileSystem(const std::map<std::string, const std::string&>& fileText) : _fileText(fileText) { } virtual ~AuroraSlangFileSystem() = default; virtual SLANG_NO_THROW SlangResult SLANG_MCALL loadFile( char const* path, ISlangBlob** outBlob) override { // Is if we already have blob for this path, return that. auto iter = _fileBlobs.find(path); if (iter != _fileBlobs.end()) { *outBlob = iter->second.get(); return SLANG_OK; } // Read from the text file map. auto shaderIter = _fileText.find(path); if (shaderIter != _fileText.end()) { // Create a blob from the text file string, add to the blob map, and return it. _fileBlobs[path] = make_unique<StringSlangBlob>(shaderIter->second); *outBlob = _fileBlobs[path].get(); return SLANG_OK; } return SLANG_FAIL; } // Slang type interface not needed, just return null. virtual SLANG_NO_THROW SlangResult SLANG_MCALL queryInterface( SlangUUID const& /* uuid*/, void** /* outObject*/) SLANG_OVERRIDE { return SLANG_E_NOT_IMPLEMENTED; } // Do not implement ref counting, just return 1. virtual SLANG_NO_THROW uint32_t SLANG_MCALL addRef() SLANG_OVERRIDE { return 1; } virtual SLANG_NO_THROW uint32_t SLANG_MCALL release() SLANG_OVERRIDE { return 1; } // Slang type interface not needed, just return null. void* castAs(const SlangUUID&) override { return nullptr; } // Set a string directly as blob in file blobs map. void setSource(const string& name, const string& code) { _fileBlobs[name] = make_unique<StringSlangBlob>(code); } slang::IBlob* getSource(const string& name) { auto iter = _fileBlobs.find(name); return iter != _fileBlobs.end() ? iter->second.get() : nullptr; } // Map of string blobs. map<string, unique_ptr<StringSlangBlob>> _fileBlobs; // Map of file strings. const std::map<std::string, const std::string&>& _fileText; }; Transpiler::Transpiler(const std::map<std::string, const std::string&>& fileText) { _pFileSystem = make_unique<AuroraSlangFileSystem>(fileText); SlangGlobalSessionDesc desc; desc.enableGLSL = true; slang::createGlobalSession(&desc, &_pSession); } Transpiler::~Transpiler() { _pSession->release(); } void Transpiler::setSource(const string& name, const string& code) { _pFileSystem->setSource(name, code); } bool Transpiler::transpileCode(const string& shaderCode, string& codeOut, string& errorOut, Language target, const map<string, string>& preprocessorDefines) { #if defined(__APPLE__) // TODO: We do actually want to be transpiling here eventually return true; #endif // Dummy file name to use as container for shader code. const string codeFileName = "__shaderCode"; // Set the shader code "file". setSource(codeFileName, shaderCode); // Transpile the shader code. bool res = transpile(codeFileName, codeOut, errorOut, target, preprocessorDefines); // Clear the shader source to release memory. setSource(codeFileName, ""); return res; } bool Transpiler::transpile(const string& shaderName, string& codeOut, string& errorOut, Language target, const map<string, string>& preprocessorDefines) { // Clear result. errorOut.clear(); codeOut.clear(); // TODO: Multithreading. using namespace slang; // Create the target description for the session. TargetDesc targetDesc; switch (target) { case Language::HLSL: targetDesc.format = SLANG_HLSL; targetDesc.profile = _pSession->findProfile("lib_6_3"); break; case Language::GLSL: targetDesc.format = SLANG_GLSL; targetDesc.profile = _pSession->findProfile("glsl_460"); break; case Language::Metal: targetDesc.format = SLANG_METAL; targetDesc.profile = _pSession->findProfile("metallib_2_3"); break; default: AU_FAIL("Unsupported target language for transpiler."); return false; } // Use standard line directives (with filename). targetDesc.lineDirectiveMode = SLANG_LINE_DIRECTIVE_MODE_STANDARD; // TODO: The buffer layout might be an issue, need to work out correct flags. // targetDesc.forceGLSLScalarBufferLayout = true; // Create compiler options. std::vector<CompilerOptionEntry> compilerOptions; compilerOptions.push_back( { CompilerOptionName::NoMangle, { CompilerOptionValueKind::Int, 1, 0, nullptr, nullptr } }); compilerOptions.push_back({ CompilerOptionName::GenerateWholeProgram, { CompilerOptionValueKind::Int, 1, 0, nullptr, nullptr } }); targetDesc.compilerOptionEntries = compilerOptions.data(); targetDesc.compilerOptionEntryCount = static_cast<uint32_t>(compilerOptions.size()); // Create the session description. SessionDesc sessionDesc; sessionDesc.targets = &targetDesc; sessionDesc.targetCount = 1; sessionDesc.fileSystem = _pFileSystem.get(); sessionDesc.defaultMatrixLayoutMode = SLANG_MATRIX_LAYOUT_COLUMN_MAJOR; sessionDesc.allowGLSLSyntax = true; // Setup pre-defined macros. std::vector<PreprocessorMacroDesc> preprocessorMacros; for (const auto& [key, value] : preprocessorDefines) { preprocessorMacros.push_back({ key.c_str(), value.c_str() }); } preprocessorMacros.push_back({ "DIRECTX", target == Language::HLSL ? "1" : "0" }); sessionDesc.preprocessorMacros = preprocessorMacros.data(); sessionDesc.preprocessorMacroCount = preprocessorMacros.size(); // Create a session representing a scope for compilation with a consistent set of compiler // options. Slang::ComPtr<ISession> session; _pSession->createSession(sessionDesc, session.writeRef()); // Transpile the file. Slang::ComPtr<IBlob> diagnostics; const string fileName = shaderName + ".slang"; Slang::ComPtr<IModule> sessionModule(session->loadModuleFromSource(shaderName.c_str(), fileName.c_str(), _pFileSystem->getSource(shaderName), diagnostics.writeRef())); if (diagnostics) { errorOut = (const char*)diagnostics->getBufferPointer(); return false; } // Link the module to get a program Slang::ComPtr<IComponentType> linkedProgram; sessionModule->link(linkedProgram.writeRef(), diagnostics.writeRef()); if (diagnostics) { errorOut = (const char*)diagnostics->getBufferPointer(); return false; } // Get blob for result. Slang::ComPtr<ISlangBlob> outBlob; linkedProgram->getTargetCode(0 /* targetIndex */, outBlob.writeRef(), diagnostics.writeRef()); if (diagnostics) { errorOut = (const char*)diagnostics->getBufferPointer(); return false; } codeOut = (const char*)outBlob->getBufferPointer(); return true; } END_AURORA
1
0.82232
1
0.82232
game-dev
MEDIA
0.199509
game-dev
0.723569
1
0.723569
guilhermelhr/unityro
11,020
UnityClient/Assets/UnityRO.io/Loaders/MapLoader.cs
using ROIO.Models.FileTypes; using ROIO.Utils; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace ROIO.Loaders { public class AsyncMapLoader { public struct GameMapData { public string Name; public RSW World; public GND Ground; public GAT Altitude; public RSM[] Models; public RSM.CompiledModel[] CompiledModels; public GND.Mesh CompiledGround; } public async Task<GameMapData> Load(string mapname) { RSW world = await LoadWorld(mapname); GND ground = await LoadGround(mapname); GAT altitude = await LoadAltitude(mapname); GND.Mesh compiledGround = await CompileGroundMesh(ground, world); RSM[] models = LoadModels(world.modelDescriptors); RSM.CompiledModel[] compiledModels = await CompileModels(models); return new GameMapData { Name = mapname, World = world, Ground = ground, Altitude = altitude, Models = models, CompiledModels = compiledModels, CompiledGround = compiledGround }; } private async Task<RSW> LoadWorld(string mapname) { string rswPath = "data/" + GetFilePath(mapname); RSW world = await Task.Run(() => FileManager.Load(rswPath) as RSW); if (world == null) { throw new Exception("Could not load rsw for " + mapname); } return world; } private async Task<GAT> LoadAltitude(string mapname) { string gatPath = "data/" + GetFilePath(WorldLoader.files.gat); GAT altitude = await Task.Run(() => FileManager.Load(gatPath) as GAT); if (altitude == null) { throw new Exception("Could not load gat for " + mapname); } return altitude; } private async Task<GND> LoadGround(string mapname) { string gndPath = "data/" + GetFilePath(WorldLoader.files.gnd); GND ground = await Task.Run(() => FileManager.Load(gndPath) as GND); if (ground == null) { throw new Exception("Could not load gnd for " + mapname); } return ground; } private async Task<GND.Mesh> CompileGroundMesh(GND ground, RSW world) { GND.Mesh compiledGround = await Task.Run(() => GroundLoader.Compile(ground, world.water.level, world.water.waveHeight)); //TODO this might not be necessary anymore await CacheGroundTextures(world, compiledGround); return compiledGround; } private RSM[] LoadModels(List<RSW.ModelDescriptor> modelDescriptors) { HashSet<RSM> objectsSet = new HashSet<RSM>(); foreach (var descriptor in modelDescriptors) { RSM model = FileManager.Load("data/model/" + descriptor.filename) as RSM; if (model != null) { model.CreateInstance(descriptor); model.filename = descriptor.filename; lock (objectsSet) { objectsSet.Add(model); } } } FileCache.ClearAllWithExt("rsm"); RSM[] models = new RSM[objectsSet.Count]; objectsSet.CopyTo(models); return models; } private async Task<RSM.CompiledModel[]> CompileModels(RSM[] objects) { List<Task<RSM.CompiledModel>> tasks = new List<Task<RSM.CompiledModel>>(); foreach (var model in objects) { var t = Task.Run(() => ModelLoader.Compile(model)); tasks.Add(t); } return await Task.WhenAll(tasks); } private async Task CacheGroundTextures(RSW world, GND.Mesh ground) { LinkedList<string> textures = new LinkedList<string>(); FileManager.InitBatch(); //queue water textures if (ground.waterVertCount > 0) { var path = "data/texture/\xbf\xf6\xc5\xcd/water" + world.water.type; for (int i = 0; i < 32; i++) { string num = i < 10 ? "0" + i : "" + i; textures.AddLast(path + num + ".jpg"); FileManager.Load(textures.Last.Value); } } //queue ground textures for (int i = 0; i < ground.textures.Length; i++) { textures.AddLast("data/texture/" + ground.textures[i]); FileManager.Load(textures.Last.Value); } await Task.Run(() => FileManager.EndBatch()); //splice water textures from ground textures List<string> waterTextures = new List<string>(); if (ground.waterVertCount > 0) { for (int i = 0; i < 32; i++) { waterTextures.Add(textures.First.Value); textures.RemoveFirst(); } } waterTextures.CopyTo(world.water.images); ground.textures = new string[textures.Count]; textures.CopyTo(ground.textures, 0); } private string GetFilePath(string path) { if (Tables.ResNameTable.ContainsKey(path)) { return Convert.ToString(Tables.ResNameTable[path]); } return path; } } /// <summary> /// Loaders for a ro map /// /// @author Guilherme Hernandez /// Based on ROBrowser by Vincent Thibault (robrowser.com) /// </summary> public class MapLoader { public async Task Load(string mapname, Action<string, string, object> callback) { await LoadWorld(mapname, callback); } private async Task LoadWorld(string mapname, Action<string, string, object> callback) { string rswPath = "data/" + GetFilePath(mapname); RSW world = await Task.Run(() => FileManager.Load(rswPath) as RSW); if (world == null) { throw new Exception("Could not load rsw for " + mapname); } callback.Invoke(mapname, "MAP_WORLD", world); LoadAltitude(mapname, callback); await LoadGround(mapname, world, callback); } private async void LoadAltitude(string mapname, Action<string, string, object> callback) { string gatPath = "data/" + GetFilePath(WorldLoader.files.gat); GAT altitude = await Task.Run(() => FileManager.Load(gatPath) as GAT); if (altitude == null) { throw new Exception("Could not load gat for " + mapname); } callback.Invoke(mapname, "MAP_ALTITUDE", altitude); } private async Task LoadGround(string mapname, RSW world, Action<string, string, object> callback) { string gndPath = "data/" + GetFilePath(WorldLoader.files.gnd); GND ground = await Task.Run(() => FileManager.Load(gndPath) as GND); if (ground == null) { throw new Exception("Could not load gnd for " + mapname); } callback.Invoke(mapname, "MAP_GROUND_SIZE", new UnityEngine.Vector2(ground.width, ground.height)); LoadModels(mapname, world.modelDescriptors, callback); GND.Mesh compiledGround = await CompileGroundMesh(mapname, ground, world, callback); callback.Invoke(mapname, "MAP_GROUND", compiledGround); } private async Task<GND.Mesh> CompileGroundMesh(string mapname, GND ground, RSW world, Action<string, string, object> callback) { GND.Mesh compiledGround = await Task.Run(() => GroundLoader.Compile(ground, world.water.level, world.water.waveHeight)); await LoadGroundTexture(world, compiledGround); return compiledGround; } private void LoadModels(string mapname, List<RSW.ModelDescriptor> modelDescriptors, Action<string, string, object> callback) { HashSet<RSM> objectsSet = new HashSet<RSM>(); for (int i = 0; i < modelDescriptors.Count; i++) { RSM model = FileManager.Load("data/model/" + modelDescriptors[i].filename) as RSM; if (model != null) { model.CreateInstance(modelDescriptors[i]); model.filename = modelDescriptors[i].filename; objectsSet.Add(model); } } FileCache.ClearAllWithExt("rsm"); RSM[] models = new RSM[objectsSet.Count]; objectsSet.CopyTo(models); CompileModels(mapname, models, callback); } private async void CompileModels(string mapname, RSM[] objects, Action<string, string, object> callback) { List<Task<RSM.CompiledModel>> tasks = new List<Task<RSM.CompiledModel>>(); foreach (var model in objects) { var t = Task.Run(() => ModelLoader.Compile(model)); tasks.Add(t); } RSM.CompiledModel[] compiledModels = await Task.WhenAll(tasks); callback.Invoke(mapname, "MAP_MODELS", compiledModels); } private async Task LoadGroundTexture(RSW world, GND.Mesh ground) { LinkedList<string> textures = new LinkedList<string>(); FileManager.InitBatch(); //queue water textures if (ground.waterVertCount > 0) { var path = "data/texture/\xbf\xf6\xc5\xcd/water" + world.water.type; for (int i = 0; i < 32; i++) { string num = i < 10 ? "0" + i : "" + i; textures.AddLast(path + num + ".jpg"); FileManager.Load(textures.Last.Value); } } //queue ground textures for (int i = 0; i < ground.textures.Length; i++) { textures.AddLast("data/texture/" + ground.textures[i]); FileManager.Load(textures.Last.Value); } await Task.Run(() => FileManager.EndBatch()); //splice water textures from ground textures List<string> waterTextures = new List<string>(); if (ground.waterVertCount > 0) { for (int i = 0; i < 32; i++) { waterTextures.Add(textures.First.Value); textures.RemoveFirst(); } } waterTextures.CopyTo(world.water.images); ground.textures = new string[textures.Count]; textures.CopyTo(ground.textures, 0); } private string GetFilePath(string path) { if (Tables.ResNameTable.ContainsKey(path)) { return Convert.ToString(Tables.ResNameTable[path]); } return path; } } }
1
0.896017
1
0.896017
game-dev
MEDIA
0.649397
game-dev
0.976308
1
0.976308
magefree/mage
1,469
Mage.Sets/src/mage/cards/e/ExperimentOne.java
package mage.cards.e; import mage.MageInt; import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.costs.common.RemoveCountersSourceCost; import mage.abilities.effects.common.RegenerateSourceEffect; import mage.abilities.keyword.EvolveAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.counters.CounterType; import java.util.UUID; /** * @author Plopman */ public final class ExperimentOne extends CardImpl { public ExperimentOne(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{G}"); this.subtype.add(SubType.HUMAN); this.subtype.add(SubType.OOZE); this.power = new MageInt(1); this.toughness = new MageInt(1); // Evolve (Whenever a creature you control enters, if that creature // has greater power or toughness than this creature, put a +1/+1 counter on this creature.) this.addAbility(new EvolveAbility()); //Remove two +1/+1 counters from Experiment One: Regenerate Experiment One. this.addAbility(new SimpleActivatedAbility(new RegenerateSourceEffect("it"), new RemoveCountersSourceCost(CounterType.P1P1.createInstance(2)))); } private ExperimentOne(final ExperimentOne card) { super(card); } @Override public ExperimentOne copy() { return new ExperimentOne(this); } }
1
0.961379
1
0.961379
game-dev
MEDIA
0.928742
game-dev
0.978762
1
0.978762
knightnemo/nlp-proj
29,894
text-simulator/data/games/conductivity.py
# conductivity.py # based on balance-scale-heaviest.py # ruoyao wang (feb 13/2023) # Task Description: Create a micro-simulation that simulates an experiment which tests the conductivity of a fork by putting the fork into a circuit. # Environment: room # Task-critical Objects: Battery, LightBulb, Wire, ElectricalObject, Container # High-level object classes: ElectricalObject (battery, light bulb, wire) # Critical properties: connects (ElectricalObject), on (LightBulb), conductivity (ElectricalObject) # Actions: look, inventory, take/put objects, connect X terminal A to Y terminal B # Distractor Items: None # Distractor Actions: None # High-level solution procedure: connect the light bulb, the fork, and battery into a circuit with wires, observe the light bulb, if the light bulb is on, put the fork into the red box, otherwise, put it into the black box import random UUID = 0 randomSeed = 1 # # Abstract class for all game objects # class GameObject(): def __init__(self, name): # Prevent this constructor from running if it's already been run during multiple inheritance if hasattr(self, "constructorsRun"): return # Otherwise, keep a list of constructors that have already been run self.constructorsRun = ["GameObject"] global UUID self.uuid = UUID UUID += 1 self.name = f"{name} (ID: {self.uuid})" self.parentContainer = None self.contains = [] self.properties = {} # Set critical properties self.properties["isContainer"] = False # By default, objects are not containers self.properties["isMoveable"] = True # By default, objects are moveable # Get a property of the object (safely), returning None if the property doesn't exist def getProperty(self, propertyName): if propertyName in self.properties: return self.properties[propertyName] else: return None # Add an object to this container, removing it from its previous container def addObject(self, obj): obj.removeSelfFromContainer() self.contains.append(obj) obj.parentContainer = self # Remove an object from this container def removeObject(self, obj): self.contains.remove(obj) obj.parentContainer = None # Remove the current object from whatever container it's currently in def removeSelfFromContainer(self): if self.parentContainer != None: self.parentContainer.removeObject(self) # Get all contained objects, recursively def getAllContainedObjectsRecursive(self): outList = [] for obj in self.contains: # Add self outList.append(obj) # Add all contained objects outList.extend(obj.getAllContainedObjectsRecursive()) return outList # Get all contained objects that have a specific name (not recursively) def containsItemWithName(self, name): foundObjects = [] for obj in self.contains: if obj.name == name: foundObjects.append(obj) return foundObjects # Game tick: Perform any internal updates that need to be performed at each step of the game. def tick(self): pass # Get a list of referents (i.e. names that this object can be called by) def getReferents(self): return [self.name] # Make a human-readable string that describes this object def makeDescriptionStr(self, makeDetailed=False): return self.name # # Abstract Game-object Classes # # Abstract class for things that can be considered 'containers' (e.g. a drawer, a box, a table, a shelf, etc.) class Container(GameObject): def __init__(self, name): # Prevent this constructor from running if it's already been run during multiple inheritance if hasattr(self, "constructorsRun"): if "Container" in self.constructorsRun: return GameObject.__init__(self, name) # Otherwise, mark this constructor as having been run self.constructorsRun.append("Container") # Set critical properties self.properties["isContainer"] = True self.properties["isOpenable"] = False # Can the container be opened (e.g. a drawer, a door, a box, etc.), or is it always 'open' (e.g. a table, a shelf, etc.) self.properties["isOpen"] = True # Is the container open or closed (if it is openable) self.properties["containerPrefix"] = "in" # The prefix to use when referring to the container (e.g. "in the drawer", "on the table", etc.) # Try to open the container # Returns an observation string, and a success flag (boolean) def openContainer(self): # First, check to see if this object is openable if not self.getProperty("isOpenable"): # If not, then it can't be opened return ("The " + self.name + " can't be opened.", False) # If this object is openable, then check to see if it is already open if self.getProperty("isOpen"): # If so, then it can't be opened return ("The " + self.name + " is already open.", False) # If this object is openable and it is closed, then open it self.properties["isOpen"] = True return ("The " + self.name + " is now open.", True) # Try to close the container # Returns an observation string, and a success flag (boolean) def closeContainer(self): # First, check to see if this object is openable if not (self.getProperty("isOpenable") == True): # If not, then it can't be closed return ("The " + self.name + " can't be closed.", False) # If this object is openable, then check to see if it is already closed if not (self.getProperty("isOpen") == True): # If so, then it can't be closed return ("The " + self.name + " is already closed.", False) # If this object is openable and it is open, then close it self.properties["isOpen"] = False return ("The " + self.name + " is now closed.", True) # Try to place the object in a container. # Returns an observation string, and a success flag (boolean) def placeObjectInContainer(self, obj): # First, check to see if this object is a container if not (self.getProperty("isContainer") == True): # If not, then it can't be placed in a container return ("The " + self.name + " is not a container, so things can't be placed there.", False) # Check to see if the object is moveable if not (obj.getProperty("isMoveable") == True): # If not, then it can't be removed from a container return ("The " + obj.name + " is not moveable.", None, False) # If this object is a container, then check to see if it is open if not (self.getProperty("isOpen") == True): # If not, then it can't be placed in a container return ("The " + self.name + " is closed, so things can't be placed there.", False) # If this object is a container and it is open, then place the object in the container self.addObject(obj) return ("The " + obj.getReferents()[0] + " is placed in the " + self.name + ".", True) # Try to remove the object from a container. # Returns an observation string, a reference to the object being taken, and a success flag (boolean) def takeObjectFromContainer(self, obj): # First, check to see if this object is a container if not (self.getProperty("isContainer") == True): # If not, then it can't be removed from a container return ("The " + self.name + " is not a container, so things can't be removed from it.", None, False) # Check to see if the object is moveable if not (obj.getProperty("isMoveable") == True): # If not, then it can't be removed from a container return ("The " + obj.name + " is not moveable.", None, False) # If this object is a container, then check to see if it is open if not (self.getProperty("isOpen") == True): # If not, then it can't be removed from a container return ("The " + self.name + " is closed, so things can't be removed from it.", None, False) # Check to make sure that the object is contained in this container if obj not in self.contains: return ("The " + obj.name + " is not contained in the " + self.name + ".", None, False) # If this object is a container and it is open, then remove the object from the container obj.removeSelfFromContainer() return ("The " + obj.getReferents()[0] + " is removed from the " + self.name + ".", obj, True) # Make a human-readable string that describes this object def makeDescriptionStr(self, makeDetailed=False): return "the " + self.name # A game object with electrical terminals class ElectricalObject(GameObject): def __init__(self, name, conductive=True): GameObject.__init__(self, name) self.connects = {"terminal1": (None, None), "terminal2": (None, None)} # Set critical properties self.properties["is_electrical_object"] = True self.properties["conductive"] = conductive self.properties["connects"] = {"terminal1": (None, None), "terminal2": (None, None)} def disconnect(self, terminal): if self.connects[terminal][0] is not None: obj_connects_to, connected_terminal = self.connects[terminal] obj_connects_to.connects[connected_terminal] = (None, None) obj_connects_to.properties["connects"][connected_terminal] = (None, None) self.connects[terminal] = (None, None) self.properties['connects'][terminal] = (None, None) def makeDescriptionStr(self, makeDetailed=False): terminal1, terminal2 = self.connects.keys() if self.connects[terminal1][0] is None and self.connects[terminal2][0] is None: return f"a {self.name}" elif self.connects[terminal1][0] is None and self.connects[terminal2][0]: return f"a {self.name} connecting to {self.connects[terminal2][0].name} {self.connects[terminal2][1]}" elif self.connects[terminal1][0] and self.connects[terminal2][0] is None: return f"a {self.name} connecting to {self.connects[terminal1][0].name} {self.connects[terminal1][1]}" else: return f"a {self.name} connecting to {self.connects[terminal1][0].name} {self.connects[terminal1][1]} and {self.connects[terminal2][0].name} {self.connects[terminal2][1]}" # A battery class Battery(ElectricalObject): def __init__(self, name): ElectricalObject.__init__(self, name, True) self.connects = {"cathode": (None, None), "anode": (None, None)} # Set critical properties self.properties["connects"] = {"cathode": (None, None), "anode": (None, None)} # A lightbulb class LightBulb(ElectricalObject): def __init__(self, name): ElectricalObject.__init__(self, name, True) # Set critical properties self.properties['on'] = False def connectsToBattery(self): # check if the bulb is in a conductive circuit with at least one battery in it found_battery = False is_good_circuit = True current_obj = self current_terminal = 'terminal1' while True: next_obj, next_terminal = current_obj.connects[current_terminal] # ends if the connected object is not conductive # ends if does not connect to anything if next_obj is None: is_good_circuit = False break elif not next_obj.getProperty("conductive"): is_good_circuit = False break # ends when find the bulb itself in a loop elif next_obj == self: break else: if type(next_obj) == Battery: found_battery = True for key in next_obj.connects: if key != next_terminal: next_terminal = key break # update current objects and terminal name current_obj = next_obj current_terminal = next_terminal if found_battery and is_good_circuit: return True else: return False def tick(self): if self.connectsToBattery(): self.properties['on'] = True else: self.properties['on'] = False def makeDescriptionStr(self, makeDetailed=False): if self.properties["on"]: state_desc = f"a {self.name} which is on" else: state_desc = f"a {self.name} which is off" terminal1, terminal2 = self.connects.keys() if self.connects[terminal1][0] is None and self.connects[terminal2][0] is None: return f"{state_desc}" elif self.connects[terminal1][0] is None and self.connects[terminal2][0]: return f"{state_desc} and connects to {self.connects[terminal2][0].name} {self.connects[terminal2][1]}" elif self.connects[terminal1][0] and self.connects[terminal2][0] is None: return f"{state_desc} and connects to {self.connects[terminal1][0].name} {self.connects[terminal1][1]}" else: return f"{state_desc} and connects to {self.connects[terminal1][0].name} {self.connects[terminal1][1]} and {self.connects[terminal2][0].name} {self.connects[terminal2][1]}" # wires that can connects electrical devices class Wire(ElectricalObject): def __init__(self, name): ElectricalObject.__init__(self, name, True) # Set critical properties self.properties["is_wire"] = True # The world is the root object of the game object tree. In single room environments, it's where all the objects are located. class World(Container): def __init__(self): Container.__init__(self, "room") def makeDescriptionStr(self, makeDetailed=False): outStr = "You find yourself in a room. In the room, you see: \n" for obj in self.contains: outStr += "\t" + obj.makeDescriptionStr() + "\n" return outStr # The agent (just a placeholder for a container for the inventory) class Agent(Container): def __init__(self): GameObject.__init__(self, "agent") Container.__init__(self, "agent") def getReferents(self): return ["yourself"] def makeDescriptionStr(self, makeDetailed=False): return "yourself" class TextGame: def __init__(self, randomSeed): # Random number generator, initialized with a seed passed as an argument self.random = random.Random(randomSeed) # Reset global UUID global UUID UUID = 0 # The agent/player self.agent = Agent() # Game Object Tree self.rootObject = self.initializeWorld() # Game score self.score = 0 self.numSteps = 0 # Game over flag self.gameOver = False self.gameWon = False # Last game observation self.observationStr = self.rootObject.makeDescriptionStr() # Do calculate initial scoring self.calculateScore() # Create/initialize the world/environment for this game def initializeWorld(self): world = World() # Add the agent world.addObject(self.agent) # Add a light bulb bulb = LightBulb("light bulb") world.addObject(bulb) # Add three wires wire1 = Wire("red wire") wire2 = Wire("black wire") wire3 = Wire("blue wire") world.addObject(wire1) world.addObject(wire2) world.addObject(wire3) # Add a battery battery = Battery("battery") world.addObject(battery) # # Add a fork to test # # randomly generate if the fork is conductive or not self.conductive = self.random.choice([True, False]) fork = ElectricalObject("fork", conductive=self.conductive) world.addObject(fork) self.test_obj = fork # Add two answer boxes red_box = Container("red box") world.addObject(red_box) black_box = Container("black box") world.addObject(black_box) # Return the world return world # Get the task description for this game def getTaskDescription(self): return "Your task is to figure out if the fork is conductive or not. If the fork is conductive, put it in the red box. Otherwise, put it in the black box." # Make a dictionary whose keys are object names (strings), and whose values are lists of object references with those names. # This is useful for generating valid actions, and parsing user input. def makeNameToObjectDict(self): # Get a list of all game objects allObjects = self.rootObject.getAllContainedObjectsRecursive() # Make a dictionary whose keys are object names (strings), and whose values are lists of object references with those names. nameToObjectDict = {} for obj in allObjects: for name in obj.getReferents(): #print("Object referent: " + name) if name in nameToObjectDict: nameToObjectDict[name].append(obj) else: nameToObjectDict[name] = [obj] return nameToObjectDict # # Action generation # def addAction(self, actionStr, actionArgs): # Check whether the action string key already exists -- if not, add a blank list if not (actionStr in self.possibleActions): self.possibleActions[actionStr] = [] # Add the action arguments to the list self.possibleActions[actionStr].append(actionArgs) # Returns a list of valid actions at the current time step def generatePossibleActions(self): # Get a list of all game objects that could serve as arguments to actions allObjects = self.makeNameToObjectDict() # Make a dictionary whose keys are possible action strings, and whose values are lists that contain the arguments. self.possibleActions = {} # Actions with zero arguments # (0-arg) Look around the environment self.addAction("look around", ["look around"]) self.addAction("look", ["look around"]) # (0-arg) Look at the agent's current inventory self.addAction("inventory", ["inventory"]) # Actions with one object argument # (1-arg) Take for objReferent, objs in allObjects.items(): for obj in objs: self.addAction("take " + objReferent, ["take", obj]) self.addAction("take " + objReferent + " from " + obj.parentContainer.getReferents()[0], ["take", obj]) # Actions with two object arguments # (2-arg) Put for objReferent1, objs1 in allObjects.items(): for objReferent2, objs2 in allObjects.items(): for obj1 in objs1: for obj2 in objs2: if (obj1 != obj2): containerPrefix = "in" if obj2.properties["isContainer"]: containerPrefix = obj2.properties["containerPrefix"] self.addAction("put " + objReferent1 + " " + containerPrefix + " " + objReferent2, ["put", obj1, obj2]) # Actions with four object arguments for objReferent1, objs1 in allObjects.items(): for objReferent2, objs2 in allObjects.items(): for obj1 in objs1: for obj2 in objs2: if (obj1 != obj2 and obj1.getProperty("is_electrical_object") and obj2.getProperty("is_electrical_object")): for terminal_1 in obj1.connects: for terminal_2 in obj2.connects: self.addAction(f"connect {objReferent1} {terminal_1} to {objReferent2} {terminal_2}", ["connect", obj1, terminal_1, obj2, terminal_2]) return self.possibleActions # # Interpret actions # # Describe the room that the agent is currently in def actionLook(self): return self.agent.parentContainer.makeDescriptionStr() # Take an object from a container def actionTake(self, obj): # If the object doesn't have a parent container, then it's dangling and something has gone wrong if (obj.parentContainer == None): return "Something has gone wrong -- that object is dangling in the void. You can't take that." # Cannot take the agent if type(obj) == Agent: return "You cannot take yourself." # Take the object from the parent container, and put it in the inventory obsStr, objRef, success = obj.parentContainer.takeObjectFromContainer(obj) if (success == False): return obsStr # if an electrical object is taken, remove all its connections if obj.getProperty("is_electrical_object"): for key in obj.connects: obj.disconnect(key) # Add the object to the inventory self.agent.addObject(obj) return obsStr + " You put the " + obj.getReferents()[0] + " in your inventory." # Put an object in a container def actionPut(self, objToMove, newContainer): # Check that the destination container is a container if (newContainer.getProperty("isContainer") == False): return "You can't put things in the " + newContainer.getReferents()[0] + "." # Enforce that the object must be in the inventory to do anything with it if (objToMove.parentContainer != self.agent): return "You don't currently have the " + objToMove.getReferents()[0] + " in your inventory." # Take the object from it's current container, and put it in the new container. # Deep copy the reference to the original parent container, because the object's parent container will be changed when it's taken from the original container originalContainer = objToMove.parentContainer obsStr1, objRef, success = objToMove.parentContainer.takeObjectFromContainer(objToMove) if (success == False): return obsStr1 # Put the object in the new container obsStr2, success = newContainer.placeObjectInContainer(objToMove) if (success == False): # For whatever reason, the object can't be moved into the new container. Put the object back into the original container originalContainer.addObject(objToMove) return obsStr2 # Success -- show both take and put observations return obsStr1 + "\n" + obsStr2 # Display agent inventory def actionInventory(self): # Get the inventory inventory = self.agent.contains # If the inventory is empty, return a message if (len(inventory) == 0): return "Your inventory is empty." # Otherwise, return a list of the inventory items else: obsStr = "You have the following items in your inventory:\n" for obj in inventory: obsStr += "\t" + obj.makeDescriptionStr() + "\n" return obsStr # Connects two electrical objects def actionConnect(self, obj1, terminal_1, obj2, terminal_2): # at least one of the two objects should be a wire if not (obj1.getProperty("is_wire") or (obj2.getProperty("is_wire"))): return "You cannot connect to devices directly without a wire." # disconnect the terminal if the terminal is already connected to other objects if obj1.connects[terminal_1]: obj1.disconnect(terminal_1) if obj2.connects[terminal_2]: obj2.disconnect(terminal_2) obj1.connects[terminal_1] = (obj2, terminal_2) obj1.properties["connects"][terminal_1] = (obj2.name, terminal_2) obj2.connects[terminal_2] = (obj1, terminal_1) obj2.properties["connects"][terminal_2] = (obj1.name, terminal_1) return f"Successfully connect {obj1.name} {terminal_1} to {obj2.name} {terminal_2}" # Performs an action in the environment, returns the result (a string observation, the reward, and whether the game is completed). def step_action(self, actionStr): self.observationStr = "" reward = 0 # Check to make sure the action is in the possible actions dictionary if actionStr not in self.possibleActions: self.observationStr = "I don't understand that." return (self.observationStr, self.score, reward, self.gameOver, self.gameWon) self.numSteps += 1 # Find the action in the possible actions dictionary actions = self.possibleActions[actionStr] action = None # Check for an ambiguous action (i.e. one that has multiple possible arguments) if (len(actions) > 1): # If there are multiple possible arguments, for now just choose the first one action = actions[0] else: # Otherwise, also just take the first action in the list of possible actions action = actions[0] # Interpret the action actionVerb = action[0] if (actionVerb == "look around"): # Look around the environment -- i.e. show the description of the world. self.observationStr = self.rootObject.makeDescriptionStr() elif (actionVerb == "inventory"): # Display the agent's inventory self.observationStr = self.actionInventory() elif (actionVerb == "take"): # Take an object from a container thingToTake = action[1] self.observationStr = self.actionTake(thingToTake) elif (actionVerb == "put"): # Put an object in a container thingToMove = action[1] newContainer = action[2] self.observationStr = self.actionPut(thingToMove, newContainer) elif (actionVerb == "connect"): obj1, terminal_1, obj2, terminal_2 = action[1:] self.observationStr = self.actionConnect(obj1, terminal_1, obj2, terminal_2) # Catch-all else: self.observationStr = "ERROR: Unknown action." def step_tick(self): # Do one tick of the environment self.doWorldTick() def step_calculate_score(self): # Calculate the score lastScore = self.score self.calculateScore() reward = self.score - lastScore return reward def step(self, actionStr): self.step_action(actionStr) self.step_tick() reward = self.step_calculate_score() return (self.observationStr, self.score, reward, self.gameOver, self.gameWon) # Call the object update for each object in the environment def doWorldTick(self): # Get a list of all objects in the environment allObjects = self.rootObject.getAllContainedObjectsRecursive() # Loop through all objects, and call their tick() for obj in allObjects: obj.tick() # Calculate the game score def calculateScore(self): # Baseline score self.score = 0 # Check if the folk is put into the correct box. allObjects = self.rootObject.getAllContainedObjectsRecursive() if ('red box' in self.test_obj.parentContainer.name and self.conductive) \ or ('black box' in self.test_obj.parentContainer.name and not self.conductive): self.score += 1 self.gameOver = True self.gameWon = True elif ('red box' in self.test_obj.parentContainer.name and not self.conductive) \ or ('black box' in self.test_obj.parentContainer.name and self.conductive): self.score = 0 self.gameOver = True self.gameWon = False # Main Program def main(): # Create a new game game = TextGame(randomSeed = randomSeed) # Get a list of valid actions possibleActions = game.generatePossibleActions() #print("Possible actions: " + str(possibleActions.keys())) print("Task Description: " + game.getTaskDescription()) print("") print("Initial Observation: " + game.observationStr) print("") print("Type 'help' for a list of possible actions.") print("") # Main game loop #while not game.gameOver: while True: # Get the player's action actionStr = "" while ((len(actionStr) == 0) or (actionStr == "help")): actionStr = input("> ") if (actionStr == "help"): print("Possible actions: " + str(possibleActions.keys())) print("") actionStr = "" elif (actionStr == "exit") or (actionStr == "quit"): return # Perform the action observationStr, score, reward, gameOver, gameWon = game.step(actionStr) # Get a list of valid actions possibleActions = game.generatePossibleActions() # Print the current game state print("Observation: " + observationStr) print("") print("Current step: " + str(game.numSteps)) print("Score: " + str(score)) print("Reward: " + str(reward)) print("Game Over: " + str(gameOver)) print("Game Won: " + str(gameWon)) print("") print("----------------------------------------") # Run the main program if __name__ == "__main__": main()
1
0.805469
1
0.805469
game-dev
MEDIA
0.234023
game-dev
0.77335
1
0.77335
roboserg/RoboLeague
1,492
Assets/ML-Agents/HomingMissile.cs
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using Random = UnityEngine.Random; /// <summary> /// An object that will move towards an object marked with the tag 'targetTag'. /// </summary> public class HomingMissile : MonoBehaviour { public Transform target; public float turnSpeed; public int distance; public float timeInterval = 5; private float _nextActionTime = 2; public Vector2 rocketVelocity= new Vector2(50, 100); Rigidbody _rb; private void Start() { _rb = GetComponent<Rigidbody>(); InitPosition(target.position); } private void FixedUpdate() { if (Time.time > _nextActionTime ) { _nextActionTime += timeInterval; InitPosition(target.position); } _rb.velocity = transform.forward * (Random.Range(rocketVelocity.x, rocketVelocity.y)); var rocketTargetRotation = Quaternion.LookRotation(target.position - transform.position); _rb.MoveRotation(Quaternion.RotateTowards(transform.rotation, rocketTargetRotation, turnSpeed)); } public void InitPosition(Vector3 pos) { transform.position = pos + Random.onUnitSphere * distance; if(transform.position.y < 1) transform.position = new Vector3(transform.position.x, 1.5f, transform.position.z); } private void OnCollisionEnter(Collision other) { InitPosition(target.position); } }
1
0.930648
1
0.930648
game-dev
MEDIA
0.953484
game-dev
0.972383
1
0.972383
requarks/wiki
4,149
server/models/searchEngines.js
const Model = require('objection').Model const path = require('path') const fs = require('fs-extra') const _ = require('lodash') const yaml = require('js-yaml') const commonHelper = require('../helpers/common') /* global WIKI */ /** * SearchEngine model */ module.exports = class SearchEngine extends Model { static get tableName() { return 'searchEngines' } static get idColumn() { return 'key' } static get jsonSchema () { return { type: 'object', required: ['key', 'isEnabled'], properties: { key: {type: 'string'}, isEnabled: {type: 'boolean'}, level: {type: 'string'} } } } static get jsonAttributes() { return ['config'] } static async getSearchEngines() { return WIKI.models.searchEngines.query() } static async refreshSearchEnginesFromDisk() { let trx try { const dbSearchEngines = await WIKI.models.searchEngines.query() // -> Fetch definitions from disk const searchEnginesDirs = await fs.readdir(path.join(WIKI.SERVERPATH, 'modules/search')) let diskSearchEngines = [] for (let dir of searchEnginesDirs) { const def = await fs.readFile(path.join(WIKI.SERVERPATH, 'modules/search', dir, 'definition.yml'), 'utf8') diskSearchEngines.push(yaml.safeLoad(def)) } WIKI.data.searchEngines = diskSearchEngines.map(searchEngine => ({ ...searchEngine, props: commonHelper.parseModuleProps(searchEngine.props) })) // -> Insert new searchEngines let newSearchEngines = [] for (let searchEngine of WIKI.data.searchEngines) { if (!_.some(dbSearchEngines, ['key', searchEngine.key])) { newSearchEngines.push({ key: searchEngine.key, isEnabled: false, config: _.transform(searchEngine.props, (result, value, key) => { _.set(result, key, value.default) return result }, {}) }) } else { const searchEngineConfig = _.get(_.find(dbSearchEngines, ['key', searchEngine.key]), 'config', {}) await WIKI.models.searchEngines.query().patch({ config: _.transform(searchEngine.props, (result, value, key) => { if (!_.has(result, key)) { _.set(result, key, value.default) } return result }, searchEngineConfig) }).where('key', searchEngine.key) } } if (newSearchEngines.length > 0) { trx = await WIKI.models.Objection.transaction.start(WIKI.models.knex) for (let searchEngine of newSearchEngines) { await WIKI.models.searchEngines.query(trx).insert(searchEngine) } await trx.commit() WIKI.logger.info(`Loaded ${newSearchEngines.length} new search engines: [ OK ]`) } else { WIKI.logger.info(`No new search engines found: [ SKIPPED ]`) } } catch (err) { WIKI.logger.error(`Failed to scan or load new search engines: [ FAILED ]`) WIKI.logger.error(err) if (trx) { trx.rollback() } } } static async initEngine({ activate = false } = {}) { const searchEngine = await WIKI.models.searchEngines.query().findOne('isEnabled', true) if (searchEngine) { WIKI.data.searchEngine = require(`../modules/search/${searchEngine.key}/engine`) WIKI.data.searchEngine.key = searchEngine.key WIKI.data.searchEngine.config = searchEngine.config if (activate) { try { await WIKI.data.searchEngine.activate() } catch (err) { // -> Revert to basic engine if (err instanceof WIKI.Error.SearchActivationFailed) { await WIKI.models.searchEngines.query().patch({ isEnabled: false }).where('key', searchEngine.key) await WIKI.models.searchEngines.query().patch({ isEnabled: true }).where('key', 'db') await WIKI.models.searchEngines.initEngine() } throw err } } try { await WIKI.data.searchEngine.init() } catch (err) { WIKI.logger.warn(err) } } } }
1
0.76217
1
0.76217
game-dev
MEDIA
0.156059
game-dev
0.915113
1
0.915113
Railcraft/Railcraft
11,264
src/main/java/mods/railcraft/common/blocks/structures/StructurePattern.java
/*------------------------------------------------------------------------------ Copyright (c) CovertJaguar, 2011-2022 http://railcraft.info This code is the property of CovertJaguar and may only be used with explicit written permission unless otherwise specified on the license page at http://railcraft.info/wiki/info:license. -----------------------------------------------------------------------------*/ package mods.railcraft.common.blocks.structures; import it.unimi.dsi.fastutil.chars.Char2ObjectMap; import mods.railcraft.common.blocks.TileLogic; import mods.railcraft.common.blocks.logic.StructureLogic; import mods.railcraft.common.plugins.forge.WorldPlugin; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.EntityLivingBase; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3i; import net.minecraft.world.World; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; import java.util.Optional; import static com.google.common.base.Preconditions.checkArgument; /** * @author CovertJaguar <http://www.railcraft.info> */ public final class StructurePattern { public static final char EMPTY_MARKER = 'O'; private final char[][][] pattern; private final BlockPos masterOffset; private final @Nullable AxisAlignedBB entityCheckBounds; private final Object[] attachedData; /** * Creates a multiblock pattern builder. * * @return The created builder */ public static Builder builder() { return new Builder(); } public StructurePattern(char[][][] pattern) { this(pattern, 1, 1, 1); } public StructurePattern(char[][][] pattern, Object... attachedData) { this(pattern, new BlockPos(1, 1, 1), null, attachedData); } public StructurePattern(char[][][] pattern, int offsetX, int offsetY, int offsetZ) { this(pattern, offsetX, offsetY, offsetZ, null); } public StructurePattern(char[][][] pattern, int offsetX, int offsetY, int offsetZ, @Nullable AxisAlignedBB entityCheckBounds) { this(pattern, new BlockPos(offsetX, offsetY, offsetZ), entityCheckBounds); } StructurePattern(char[][][] pattern, BlockPos offset, @Nullable AxisAlignedBB entityCheckBounds, Object... attachedData) { this.pattern = pattern; this.masterOffset = offset; this.entityCheckBounds = entityCheckBounds; this.attachedData = attachedData; } public @Nullable AxisAlignedBB getEntityCheckBounds(BlockPos masterPos) { if (entityCheckBounds == null) return null; return entityCheckBounds.offset(masterPos.getX(), masterPos.getY(), masterPos.getZ()); } // @Deprecated // public char getPatternMarkerChecked(BlockPos posInPattern) { // int x = posInPattern.getX(); // int y = posInPattern.getY(); // int z = posInPattern.getZ(); // if (x < 0 || y < 0 || z < 0) // return EMPTY_MARKER; // if (x >= getPatternWidthX() || y >= getPatternHeight() || z >= getPatternWidthZ()) // return EMPTY_MARKER; // return getPatternMarker(posInPattern); // } public char getPatternMarker(BlockPos posInPattern) { return getPatternMarker(posInPattern.getX(), posInPattern.getY(), posInPattern.getZ()); } public char getPatternMarker(int x, int y, int z) { return pattern[y][x][z]; } public char getPatternMarker(Vec3i vec) { return pattern[vec.getY()][vec.getX()][vec.getZ()]; } public BlockPos getMasterOffset() { return masterOffset; } public int getPatternHeight() { return pattern.length; } public int getPatternWidthX() { return pattern[0].length; } public int getPatternWidthZ() { return pattern[0][0].length; } public int getPatternSize() { return getPatternHeight() * getPatternWidthX() * getPatternWidthZ(); } public BlockPos getMasterPosition(BlockPos myPos, BlockPos posInPattern) { return masterOffset.subtract(posInPattern).add(myPos); } public boolean isMasterPosition(BlockPos posInPattern) { return masterOffset.equals(posInPattern); } public Object[] getAttachedData() { return attachedData; } @SuppressWarnings("unchecked") public <T> T getAttachedData(int index) { return (T) attachedData[index]; } // Why is this needed?? @Contract("_, !null -> !null") @SuppressWarnings("unchecked") public @Nullable <T> T getAttachedDataOr(int index, @Nullable T backup) { return attachedData.length <= index ? backup : (T) attachedData[index]; } public State testPattern(StructureLogic logic) { int xWidth = getPatternWidthX(); int zWidth = getPatternWidthZ(); int height = getPatternHeight(); BlockPos offset = logic.getPos().subtract(getMasterOffset()); BlockPos.PooledMutableBlockPos now = BlockPos.PooledMutableBlockPos.retain(); for (int patX = 0; patX < xWidth; patX++) { for (int patY = 0; patY < height; patY++) { for (int patZ = 0; patZ < zWidth; patZ++) { int x = patX + offset.getX(); int y = patY + offset.getY(); int z = patZ + offset.getZ(); now.setPos(x, y, z); if (!logic.theWorldAsserted().isBlockLoaded(now)) return State.NOT_LOADED; if (!logic.isMapPositionValid(now, getPatternMarker(patX, patY, patZ))) return State.PATTERN_DOES_NOT_MATCH; } } } now.release(); AxisAlignedBB entityCheckBounds = getEntityCheckBounds(logic.getPos()); // if(entityCheckBounds != null) { // System.out.println("test entities: " + entityCheckBounds.toString()); // } if (entityCheckBounds != null && !logic.theWorldAsserted().getEntitiesWithinAABB(EntityLivingBase.class, entityCheckBounds).isEmpty()) return State.ENTITY_IN_WAY; return State.VALID; } public Optional<TileLogic> placeStructure(World world, BlockPos pos, Char2ObjectMap<IBlockState> blockMapping) { int xWidth = getPatternWidthX(); int zWidth = getPatternWidthZ(); int height = getPatternHeight(); BlockPos offset = pos.subtract(getMasterOffset()); Optional<TileLogic> master = Optional.empty(); for (byte px = 0; px < xWidth; px++) { for (byte py = 0; py < height; py++) { for (byte pz = 0; pz < zWidth; pz++) { char marker = getPatternMarker(px, py, pz); IBlockState blockState = blockMapping.get(marker); if (blockState == null) continue; BlockPos p = new BlockPos(px, py, pz).add(offset); world.setBlockState(p, blockState, 3); if (px == masterOffset.getX() && py == masterOffset.getY() && pz == masterOffset.getZ()) master = WorldPlugin.getTileEntity(world, pos, TileLogic.class); } } } return master; } @Override public String toString() { StringBuilder builder = new StringBuilder(); for (int i = 0; i < pattern.length; i++) { builder.append("Level ").append(i).append(":\n"); char[][] level = pattern[i]; for (char[] line : level) { builder.append(line).append('\n'); } } return builder.toString(); } public enum State { VALID("railcraft.multiblock.state.valid"), // TODO map to untested? ENTITY_IN_WAY("railcraft.multiblock.state.invalid.entity"), PATTERN_DOES_NOT_MATCH("railcraft.multiblock.state.invalid.pattern"), NOT_LOADED("railcraft.multiblock.state.unknown.unloaded"); public final String message; State(String msg) { this.message = msg; } } public static final class Builder { private int widthX = -1; private int widthZ = -1; private BlockPos masterOffset = new BlockPos(1, 1, 1); private final List<char[][]> levels = new ArrayList<>(); private @Nullable AxisAlignedBB box; private final List<Object> attachedData = new ArrayList<>(); Builder() { } /** * Sets the master position relative to the corner. * * @param x The x position * @param y The y position * @param z The z position * @return This builder, for chaining */ public Builder master(int x, int y, int z) { masterOffset = new BlockPos(x, y, z); return this; } /** * Sets the master position relative to the corner. * * @param pos The position * @return This builder, for chaining */ public Builder master(BlockPos pos) { masterOffset = pos.toImmutable(); return this; } /** * Adds a level at top. * * @param level The pattern on this level * @return This builder, for chaining */ public Builder level(char[][] level) { checkArgument(level.length > 0, "The level can't be empty"); checkArgument(level[0].length > 0, "The level can't be empty"); for (int i = 1; i < level.length; i++) { checkArgument(level[i].length == level[0].length, "The level must be a rectangle"); } if (levels.isEmpty()) { widthX = level.length; widthZ = level[0].length; } else { checkArgument(level.length == widthX, "A level of different dimension added"); checkArgument(level[0].length == widthZ, "A level of different dimension added"); } levels.add(level); return this; } /** * Sets the entity check bounds. * * @param box The check bounds * @return This builder, for chaining */ public Builder entityCheckBounds(@Nullable AxisAlignedBB box) { this.box = box; return this; } /** * Sets the attached data of this pattern/ * * @param data The attached data * @param <T> The data type * @return This builder, for chaining */ public <T> Builder attachedData(@Nullable T data) { attachedData.add(data); return this; } /** * Creates a multiblock pattern. * * @return The created multiblock pattern */ public StructurePattern build() { char[][][] chars = levels.toArray(new char[0][][]); return new StructurePattern(chars, masterOffset, box, attachedData.toArray()); } } }
1
0.842189
1
0.842189
game-dev
MEDIA
0.450519
game-dev,graphics-rendering
0.902561
1
0.902561
SupinePandora43/UltralightNet
2,318
gpu/libs/UltralightNet.Veldrid/SlottingList.cs
/* from SilkNetSandbox */ using System; using System.Collections; using System.Collections.Generic; namespace UltralightNet.Veldrid { internal readonly struct SlottingList<T> : IList<T> where T : class { private readonly List<T> _slots; private readonly Queue<int> _vacancies; public SlottingList(int initialItemCapacity, int freeListCapacity) { _slots = new List<T>(initialItemCapacity); _vacancies = new Queue<int>(freeListCapacity); } public IEnumerator<T> GetEnumerator() { for (var i = 0; i < Allocated; ++i) { var item = _slots[i]; if (item != null) yield return item; } } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public int Add(T item) { if (_vacancies.TryDequeue(out var index)) { _slots[index] = item; } else { index = Allocated; _slots.Add(item); } return index; } void ICollection<T>.Add(T item) => Add(item); public void Clear() { _slots.Clear(); _vacancies.Clear(); } public bool Contains(T item) => _slots.Contains(item); public void CopyTo(T[] array, int arrayIndex) => _slots.CopyTo(array, arrayIndex); public bool Remove(T item) { var index = _slots.IndexOf(item); if (index == -1) return false; _slots[index] = null!; _vacancies.Enqueue(index); return true; } public int Count => _slots.Count - _vacancies.Count; public int Allocated => _slots.Count; public int Free => _vacancies.Count; public int Capacity => _slots.Capacity; public bool IsReadOnly => false; public int IndexOf(T item) => _slots.IndexOf(item); public void Insert(int index, T item) => throw new NotSupportedException(); public T RemoveAt(int index) { if (index < 0 || index > Allocated) throw new ArgumentOutOfRangeException(nameof(index)); var v = _slots[index]; _slots[index] = null!; _vacancies.Enqueue(index); return v; } void IList<T>.RemoveAt(int index) => RemoveAt(index); public T this[int index] { get => _slots[index]; set => _slots[index] = value; } #nullable enable public bool TryGet(int index, out T? item) { if (index >= Allocated) { item = null; return false; } item = this[index]; return item != null; } } }
1
0.949271
1
0.949271
game-dev
MEDIA
0.580899
game-dev,uncategorized
0.929039
1
0.929039
cphxj123/Dol-BJX-Ex
2,219
源码/overworld-town/loc-bunker-bjx/events.twee
:: Bunker Rat <<if $molestationstart is 1>> <<set $molestationstart to 0>> <<controlloss>> <<violence 1>> <<neutral 1>> <<molested>> <<beastCombatInit>> <</if>> <<effects>> <<effectsman>> <br> <<beast $enemyno>> <br><br> <<stateman>> <br><br> <<actionsman>> <<if $finish is 1>> <span id="next"><<link [[继续|Bunker Rat Finish]]>><</link>></span><<nexttext>> <<elseif $enemyhealth lte 0>> <span id="next"><<link [[继续|Bunker Rat Finish]]>><</link>></span><<nexttext>> <<elseif $enemyarousal gte $enemyarousalmax>> <span id="next"><<link [[继续|Bunker Rat Finish]]>><</link>></span><<nexttext>> <<else>> <span id="next"><<link [[继续|Bunker Rat]]>><</link>></span><<nexttext>> <</if>> :: Bunker Rat Finish <<effects>> <<if $enemyhealth lte 0>> 你成功地击败了<<beasttype>>,<<bHe>>逃入了地堡深处。 <br><br> <<tearful>>你重新振作了起来。 <br><br> <<clotheson>> <<endcombat>> <<link [[继续|Bunker]]>><<set $eventskip to 1>><</link>> <br> <<elseif $enemyarousal gte $enemyarousalmax>> <<beastejaculation>> 在得到满足之后,这只<<beasttype>>离开了你。 <br><br> <<clotheson>> <<endcombat>> <<link [[继续|Bunker]]>><<set $eventskip to 1>><</link>> <<else>> <<tearful>>你重新振作了起来。 <br><br> <<clotheson>> <<endcombat>> <<link [[继续|Bunker]]>><<set $eventskip to 1>><</link>> <</if>> :: Bunker Spider <<effects>> <<if $molestationstart is 1>> <<set $molestationstart to 0>> <<molested>> <<controlloss>> <<set $combat to 1>> <<set $enemytype to "swarm">> <<swarminit "spiders" "蜘囊" "爬行着" "破开" "稳定" 1 9>> <<set $timer to 30>> <</if>> <<if $timer gte 25>> 上方那些满是蜘蛛网的老旧铁链正在吱呀作响,这样下去的话,它们一定会断开的。 <<elseif $timer gte 20>> 伴随着轰的一声,天花板骤然碎裂,碎片散落的满地都是。 <<elseif $timer gte 10>> 那些铁制的东西正在被继续腐蚀着。 <<elseif $timer gte 1>> 天花板上正在发出不妙的嘎吱声。 <<else>> 天花板上的一根钢梁骤然断裂,蜘蛛网也随之塌落到了地面上。 <</if>> <br><br> <<swarmeffects>> <<swarm>> <<swarmactions>> <<if $timer lte 0>> <span id="next"><<link [[继续|Bunker Spider Finish]]>><</link>></span><<nexttext>> <<else>> <span id="next"><<link [[继续|Bunker Spider]]>><</link>></span><<nexttext>> <</if>> :: Bunker Spider Finish <<effects>> 被这次塌方吓坏的蜘蛛逃回了来时的地方,<<tearful>>你努力站了起来,然后把身上还挂着的蛛网扯了下去。 <br><br> <<clotheson>> <<pass 1 hour>> <<endcombat>> <<link [[继续|Bunker]]>><<set $eventskip to 1>><</link>>
1
0.926383
1
0.926383
game-dev
MEDIA
0.864058
game-dev
0.786742
1
0.786742
qiayuanl/DArm
63,393
Arduino/ArduinoAddons/Arduino_1.5.x/hardware/marlin/avr/libraries/U8glib/utility/chessengine.c
/* chessengine.c "Little Rook Chess" (lrc) Port to u8g library chess for embedded 8-Bit controllers Copyright (c) 2012, olikraus@gmail.com All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Note: UNIX_MAIN --> unix console executable Current Rule Limitation - no minor promotion, only "Queening" of the pawn - threefold repetition is not detected (same board situation appears three times) Note: Could be implemented, but requires tracking of the complete game - Fifty-move rule is not checked (no pawn move, no capture within last 50 moves) Words Ply a half move General Links http://chessprogramming.wikispaces.com/ Arduino specific http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1260055596 Prefixes chess_ Generic Chess Application Interface ce_ Chess engine, used internally, these function should not be called directly cu_ Chess utility function stack_ Internal function for stack handling Issues 10.01.2011 - castling to the right does not move the rook --> done - castling to the left: King can only move two squares --> done 11.01.2011 Next Steps: - replace stack_NextCurrentPos with cu_NextPos, cleanup code according to the loop variable --> done - Castling: Need to check for fields under attack --> done - Check for WIN / LOSE situation, perhaps call ce_Eval() once on the top-level board setup just after the real move - cleanup cu_Move --> almost done - add some heuristics to the eval procedure - add right side menu --> done - clean up chess_ManualMove --> done - finish menu (consider is_game_end, undo move) - end condition: if KING is under attack and if KING can not move to a field which is under attack... then the game is lost. What will be returned by the Eval procedure? is it -INF? --> finished - reduce the use of variable color, all should be reduced to board_orientation and ply&1 - chess_GetNextMarked shoud make use of cu_NextPos --> done - chess_ManualMove: again cleanup, solve draw issue (KING is not in check and no legal moves are available) --> done 22.01.2011 - simplify eval_t ce_Eval(void) - position eval does not work, still moves side pawn :-( maybe because all pieces are considered --> done */ #include "u8g.h" //#ifndef __unix__ //#else //#include <assert.h> //#define U8G_NOINLINE //#endif /* SAN identifies each piece by a single upper case letter. The standard English values: pawn = "P", knight = "N", bishop = "B", rook = "R", queen = "Q", and king = "K". */ /* numbers for the various pieces */ #define PIECE_NONE 0 #define PIECE_PAWN 1 #define PIECE_KNIGHT 2 #define PIECE_BISHOP 3 #define PIECE_ROOK 4 #define PIECE_QUEEN 5 #define PIECE_KING 6 /* color definitions */ #define COLOR_WHITE 0 #define COLOR_BLACK 1 /* a mask, which includes COLOR and PIECE number */ #define COLOR_PIECE_MASK 0x01f #define CP_MARK_MASK 0x20 #define ILLEGAL_POSITION 255 /* This is the build in upper limit of the search stack */ /* This value defines the amount of memory allocated for the search stack */ /* The search depth of this chess engine can never exceed this value */ #define STACK_MAX_SIZE 5 /* chess half move stack: twice the number of undo's, a user can do */ #define CHM_USER_SIZE 6 /* the CHM_LIST_SIZE must be larger than the maximum search depth */ /* the overall size of ste half move stack */ #define CHM_LIST_SIZE (STACK_MAX_SIZE+CHM_USER_SIZE+2) typedef int16_t eval_t; /* a variable type to store results from the evaluation */ //#define EVAL_T_LOST -32768 #define EVAL_T_MIN -32767 #define EVAL_T_MAX 32767 //#define EVAL_T_WIN 32767 /* for maintainance of our own stack: this is the definition of one element on the stack */ struct _stack_element_struct { /* the current source position which is investigated */ uint8_t current_pos; uint8_t current_cp; uint8_t current_color; /* COLOR_WHITE or COLOR_BLACK: must be predefines */ /* the move which belongs to that value, both values are game positions */ uint8_t best_from_pos; uint8_t best_to_pos; /* the best value, which has been dicovered so far */ eval_t best_eval; }; typedef struct _stack_element_struct stack_element_t; typedef struct _stack_element_struct *stack_element_p; /* chess half move history */ struct _chm_struct { uint8_t main_cp; /* the main piece, which is moved */ uint8_t main_src; /* the source position of the main piece */ uint8_t main_dest; /* the destination of the main piece */ uint8_t other_cp; /* another piece: the captured one, the ROOK in case of castling or PIECE_NONE */ uint8_t other_src; /* the delete position of other_cp. Often identical to main_dest except for e.p. and castling */ uint8_t other_dest; /* only used for castling: ROOK destination pos */ /* the position of the last pawn, which did a double move forward */ /* this is required to check en passant conditions */ /* this array can be indexed by the color of the current player */ /* this is the condition BEFORE the move was done */ uint8_t pawn_dbl_move[2]; /* flags for the movement of rook and king; required for castling */ /* a 1 means: castling is (still) possible */ /* a 0 means: castling not possible */ /* bit 0 left side white */ /* bit 1 right side white */ /* bit 2 left side black */ /* bit 3 right side black */ /* this is the condition BEFORE the move was done */ uint8_t castling_possible; }; typedef struct _chm_struct chm_t; typedef struct _chm_struct *chm_p; /* little rook chess, main structure */ struct _lrc_struct { /* half-move (ply) counter: Counts the number of half-moves so far. Starts with 0 */ /* the lowest bit is used to derive the color of the current player */ /* will be set to zero in chess_SetupBoard() */ uint8_t ply_count; /* the half move stack position counter, counts the number of elements in chm_list */ uint8_t chm_pos; /* each element contains a colored piece, empty fields have value 0 */ /* the field with index 0 is black (lower left) */ uint8_t board[64]; /* the position of the last pawn, which did a double move forward */ /* this is required to check en passant conditions */ /* this array can be indexed by the color of the current player */ uint8_t pawn_dbl_move[2]; /* flags for the movement of rook and king; required for castling */ /* a 1 means: castling is (still) possible */ /* a 0 means: castling not possible */ /* bit 0 left side white */ /* bit 1 right side white */ /* bit 2 left side black */ /* bit 3 right side black */ uint8_t castling_possible; /* board orientation */ /* 0: white is below COLOR_WHITE */ /* 1: black is below COLOR_BLACK */ /* bascially, this can be used as a color */ uint8_t orientation; /* exchange colors of the pieces */ /* 0: white has an empty body, use this for bright background color */ /* 1: black has an empty body, use this for dark backround color */ uint8_t strike_out_color; /* 0, when the game is ongoing */ /* 1, when the game is stopped (lost or draw) */ uint8_t is_game_end; /* the color of the side which lost the game */ /* this value is only valid, when is_game_end is not 0 */ /* values 0 and 1 represent WHITE and BLACK, 2 means a draw */ uint8_t lost_side_color; /* checks are executed in ce_LoopRecur */ /* these checks will put some marks on the board */ /* this will be used by the interface to find out */ /* legal moves */ uint8_t check_src_pos; uint8_t check_mode; /* CHECK_MODE_NONE, CHECK_MODE_MOVEABLE, CHECK_MODE_TARGET_MOVE */ /* count of the attacking pieces, indexed by color */ uint8_t find_piece_cnt[2]; /* sum of the attacking pieces, indexed by color */ uint8_t find_piece_weight[2]; /* points to the current element of the search stack */ /* this stack is NEVER empty. The value 0 points to the first element of the stack */ /* actually "curr_depth" represent half-moves (plies) */ uint8_t curr_depth; uint8_t max_depth; stack_element_p curr_element; /* allocated memory for the search stack */ stack_element_t stack_memory[STACK_MAX_SIZE]; /* the half move stack, used for move undo and depth search, size is stored in chm_pos */ chm_t chm_list[CHM_LIST_SIZE]; }; typedef struct _lrc_struct lrc_t; #define CHECK_MODE_NONE 0 #define CHECK_MODE_MOVEABLE 1 #define CHECK_MODE_TARGET_MOVE 2 /*==============================================================*/ /* global variables */ /*==============================================================*/ u8g_t *lrc_u8g; lrc_t lrc_obj; /*==============================================================*/ /* forward declarations */ /*==============================================================*/ /* apply no inline to some of the functions: avr-gcc very often inlines functions, however not inline saves a lot of program memory! On the other hand there are some really short procedures which should be inlined (like cp_GetColor) These procedures are marked static to prevent the generation of the expanded procedure, which also saves space. */ uint8_t stack_Push(uint8_t color) U8G_NOINLINE; void stack_Pop(void) U8G_NOINLINE; void stack_InitCurrElement(void) U8G_NOINLINE; void stack_Init(uint8_t max) U8G_NOINLINE; void stack_SetMove(eval_t val, uint8_t to_pos) U8G_NOINLINE; uint8_t cu_NextPos(uint8_t pos) U8G_NOINLINE; static uint8_t cu_gpos2bpos(uint8_t gpos); static uint8_t cp_Construct(uint8_t color, uint8_t piece); static uint8_t cp_GetPiece(uint8_t cp); static uint8_t cp_GetColor(uint8_t cp); uint8_t cp_GetFromBoard(uint8_t pos) U8G_NOINLINE; void cp_SetOnBoard(uint8_t pos, uint8_t cp) U8G_NOINLINE; void cu_ClearBoard(void) U8G_NOINLINE; void chess_SetupBoard(void) U8G_NOINLINE; eval_t ce_Eval(void); void cu_ClearMoveHistory(void) U8G_NOINLINE; void cu_ReduceHistoryByFullMove(void) U8G_NOINLINE; void cu_UndoHalfMove(void) U8G_NOINLINE; chm_p cu_PushHalfMove(void) U8G_NOINLINE; void ce_CalculatePositionWeight(uint8_t pos); uint8_t ce_GetPositionAttackWeight(uint8_t pos, uint8_t color); void chess_Thinking(void); void ce_LoopPieces(void); /*==============================================================*/ /* search stack */ /*==============================================================*/ /* get current element from stack */ stack_element_p stack_GetCurrElement(void) { return lrc_obj.curr_element; } uint8_t stack_Push(uint8_t color) { if ( lrc_obj.curr_depth == lrc_obj.max_depth ) return 0; lrc_obj.curr_depth++; lrc_obj.curr_element = lrc_obj.stack_memory+lrc_obj.curr_depth; /* change view for the evaluation */ color ^= 1; stack_GetCurrElement()->current_color = color; return 1; } void stack_Pop(void) { lrc_obj.curr_depth--; lrc_obj.curr_element = lrc_obj.stack_memory+lrc_obj.curr_depth; } /* reset the current element on the stack */ void stack_InitCurrElement(void) { stack_element_p e = stack_GetCurrElement(); e->best_eval = EVAL_T_MIN; e->best_from_pos = ILLEGAL_POSITION; e->best_to_pos = ILLEGAL_POSITION; } /* resets the search stack (and the check mode) */ void stack_Init(uint8_t max) { lrc_obj.curr_depth = 0; lrc_obj.curr_element = lrc_obj.stack_memory; lrc_obj.max_depth = max; lrc_obj.check_mode = CHECK_MODE_NONE; stack_InitCurrElement(); stack_GetCurrElement()->current_color = lrc_obj.ply_count; stack_GetCurrElement()->current_color &= 1; } /* assign evaluation value and store the move, if this is the best move */ /* assumes, that current_pos contains the source position */ void stack_SetMove(eval_t val, uint8_t to_pos) { stack_element_p e = stack_GetCurrElement(); if ( e->best_eval < val ) { e->best_eval = val; e->best_from_pos = e->current_pos; e->best_to_pos = to_pos; } } /* calculate next position on a 0x88 board loop is constructed in this way: i = 0; do { ... i = cu_NextPos(i); } while( i != 0 ); next pos might be started with an illegal position like 255 */ uint8_t cu_NextPos(uint8_t pos) { /* calculate next gpos */ pos++; if ( ( pos & 0x08 ) != 0 ) { pos+= 0x10; pos&= 0xf0; } if ( ( pos & 0x80 ) != 0 ) pos = 0; return pos; } uint8_t cu_PrevPos(uint8_t pos) { /* calculate prev gpos */ pos--; if ( ( pos & 0x80 ) != 0 ) pos = 0x077; else if ( ( pos & 0x08 ) != 0 ) { pos &= 0xf0; pos |= 0x07; } return pos; } /*==============================================================*/ /* position transltion */ /*==============================================================*/ /* there are two positions 1. game position (gpos): BCD encoded x-y values 2. board position (bpos): a number between 0 and 63, only used to access the board. */ /* gpos: game position value returns: board position note: does not do any checks */ static uint8_t cu_gpos2bpos(uint8_t gpos) { uint8_t bpos = gpos; bpos &= 0xf0; bpos >>= 1; gpos &= 0x0f; bpos |= gpos; return bpos; } #define gpos_IsIllegal(gpos) ((gpos) & 0x088) /*==============================================================*/ /* colored piece handling */ /*==============================================================*/ #define cp_IsMarked(cp) ((cp) & CP_MARK_MASK) /* piece: one of PIECE_xxx color: COLOR_WHITE or COLOR_BLACK returns: A colored piece */ static uint8_t cp_Construct(uint8_t color, uint8_t piece) { color <<= 4; color |= piece; return color; } /* inline is better than a macro */ static uint8_t cp_GetPiece(uint8_t cp) { cp &= 0x0f; return cp; } /* we could use a macro: #define cp_GetColor(cp) (((cp) >> 4)&1) however, inlined functions are sometimes much better */ static uint8_t cp_GetColor(uint8_t cp) { cp >>= 4; cp &= 1; return cp; } /* pos: game position returns the colored piece at the given position */ uint8_t cp_GetFromBoard(uint8_t pos) { return lrc_obj.board[cu_gpos2bpos(pos)]; } /* pos: game position cp: colored piece */ void cp_SetOnBoard(uint8_t pos, uint8_t cp) { /*printf("cp_SetOnBoard gpos:%02x cp:%02x\n", pos, cp);*/ lrc_obj.board[cu_gpos2bpos(pos)] = cp; } /*==============================================================*/ /* global board access */ /*==============================================================*/ void cu_ClearBoard(void) { uint8_t i; /* clear the board */ for( i = 0; i < 64; i++ ) lrc_obj.board[i] = PIECE_NONE; lrc_obj.ply_count = 0; lrc_obj.orientation = COLOR_WHITE; lrc_obj.pawn_dbl_move[0] = ILLEGAL_POSITION; lrc_obj.pawn_dbl_move[1] = ILLEGAL_POSITION; lrc_obj.castling_possible = 0x0f; lrc_obj.is_game_end = 0; lrc_obj.lost_side_color = 0; /* clear half move history */ cu_ClearMoveHistory(); } /* test setup white wins in one move */ void chess_SetupBoardTest01(void) { cu_ClearBoard(); lrc_obj.board[7+7*8] = cp_Construct(COLOR_BLACK, PIECE_KING); lrc_obj.board[7+5*8] = cp_Construct(COLOR_WHITE, PIECE_PAWN); lrc_obj.board[3] = cp_Construct(COLOR_WHITE, PIECE_KING); lrc_obj.board[0+7*8] = cp_Construct(COLOR_BLACK, PIECE_ROOK); lrc_obj.board[6] = cp_Construct(COLOR_WHITE, PIECE_QUEEN); } /* setup the global board */ void chess_SetupBoard(void) { uint8_t i; register uint8_t bp, wp; /* clear the board */ cu_ClearBoard(); /* precronstruct pawns */ wp = cp_Construct(COLOR_WHITE, PIECE_PAWN); bp = cp_Construct(COLOR_BLACK, PIECE_PAWN); /* setup pawn */ for( i = 0; i < 8; i++ ) { lrc_obj.board[i+8] = wp; lrc_obj.board[i+6*8] = bp; } /* assign remaining pieces */ lrc_obj.board[0] = cp_Construct(COLOR_WHITE, PIECE_ROOK); lrc_obj.board[1] = cp_Construct(COLOR_WHITE, PIECE_KNIGHT); lrc_obj.board[2] = cp_Construct(COLOR_WHITE, PIECE_BISHOP); lrc_obj.board[3] = cp_Construct(COLOR_WHITE, PIECE_QUEEN); lrc_obj.board[4] = cp_Construct(COLOR_WHITE, PIECE_KING); lrc_obj.board[5] = cp_Construct(COLOR_WHITE, PIECE_BISHOP); lrc_obj.board[6] = cp_Construct(COLOR_WHITE, PIECE_KNIGHT); lrc_obj.board[7] = cp_Construct(COLOR_WHITE, PIECE_ROOK); lrc_obj.board[0+7*8] = cp_Construct(COLOR_BLACK, PIECE_ROOK); lrc_obj.board[1+7*8] = cp_Construct(COLOR_BLACK, PIECE_KNIGHT); lrc_obj.board[2+7*8] = cp_Construct(COLOR_BLACK, PIECE_BISHOP); lrc_obj.board[3+7*8] = cp_Construct(COLOR_BLACK, PIECE_QUEEN); lrc_obj.board[4+7*8] = cp_Construct(COLOR_BLACK, PIECE_KING); lrc_obj.board[5+7*8] = cp_Construct(COLOR_BLACK, PIECE_BISHOP); lrc_obj.board[6+7*8] = cp_Construct(COLOR_BLACK, PIECE_KNIGHT); lrc_obj.board[7+7*8] = cp_Construct(COLOR_BLACK, PIECE_ROOK); //chess_SetupBoardTest01(); } /*==============================================================*/ /* checks */ /*==============================================================*/ /* checks if the position is somehow illegal */ uint8_t cu_IsIllegalPosition(uint8_t pos, uint8_t my_color) { uint8_t board_cp; /* check, if the position is offboard */ if ( gpos_IsIllegal(pos) != 0 ) return 1; /* get the piece from the board */ board_cp = cp_GetFromBoard(pos); /* check if hit our own pieces */ if ( board_cp != 0 ) if ( cp_GetColor(board_cp) == my_color ) return 1; /* all ok, we could go to this position */ return 0; } /*==============================================================*/ /* evaluation procedure */ /*==============================================================*/ /* basic idea is to return a value between EVAL_T_MIN and EVAL_T_MAX */ /* the weight table uses the PIECE number as index: #define PIECE_NONE 0 #define PIECE_PAWN 1 #define PIECE_KNIGHT 2 #define PIECE_BISHOP 3 #define PIECE_ROOK 4 #define PIECE_QUEEN 5 #define PIECE_KING 6 the king itself is not counted */ uint8_t ce_piece_weight[] = { 0, 1, 3, 3, 5, 9, 0 }; uint8_t ce_pos_weight[] = { 0, 1, 1, 2, 2, 1, 1, 0}; /* evaluate the current situation on the global board */ eval_t ce_Eval(void) { uint8_t cp; uint8_t is_my_king_present = 0; uint8_t is_opposit_king_present = 0; eval_t material_my_color = 0; eval_t material_opposit_color = 0; eval_t position_my_color = 0; eval_t position_opposit_color = 0; eval_t result; uint8_t pos; pos = 0; do { /* get colored piece from the board */ cp = cp_GetFromBoard(pos); if ( cp_GetPiece(cp) != PIECE_NONE ) { if ( stack_GetCurrElement()->current_color == cp_GetColor(cp) ) { /* this is our color */ /* check if we found our king */ if ( cp_GetPiece(cp) == PIECE_KING ) is_my_king_present = 1; material_my_color += ce_piece_weight[cp_GetPiece(cp)]; if ( cp_GetPiece(cp) == PIECE_PAWN || cp_GetPiece(cp) == PIECE_KNIGHT ) { position_my_color += ce_pos_weight[pos&7]*ce_pos_weight[(pos>>4)&7]; } } else { /* this is the opposit color */ if ( cp_GetPiece(cp) == PIECE_KING ) is_opposit_king_present = 1; material_opposit_color += ce_piece_weight[cp_GetPiece(cp)]; if ( cp_GetPiece(cp) == PIECE_PAWN || cp_GetPiece(cp) == PIECE_KNIGHT ) { position_opposit_color += ce_pos_weight[pos&7]*ce_pos_weight[(pos>>4)&7]; } } } pos = cu_NextPos(pos); } while( pos != 0 ); /* decide if we lost or won the game */ if ( is_my_king_present == 0 ) return EVAL_T_MIN; /*_LOST*/ if ( is_opposit_king_present == 0 ) return EVAL_T_MAX; /*_WIN*/ /* here is the evaluation function */ result = material_my_color - material_opposit_color; result <<= 3; result += position_my_color - position_opposit_color; return result; } /*==============================================================*/ /* move backup and restore */ /*==============================================================*/ /* this procedure must be called to keep the size as low as possible */ /* if the chm_list is large enough, it could hold the complete history */ /* but for an embedded controler... it is deleted for every engine search */ void cu_ClearMoveHistory(void) { lrc_obj.chm_pos = 0; } void cu_ReduceHistoryByFullMove(void) { uint8_t i; while( lrc_obj.chm_pos > CHM_USER_SIZE ) { i = 0; for(;;) { if ( i+2 >= lrc_obj.chm_pos ) break; lrc_obj.chm_list[i] = lrc_obj.chm_list[i+2]; i++; } lrc_obj.chm_pos -= 2; } } void cu_UndoHalfMove(void) { chm_p chm; if ( lrc_obj.chm_pos == 0 ) return; lrc_obj.chm_pos--; chm = lrc_obj.chm_list+lrc_obj.chm_pos; lrc_obj.pawn_dbl_move[0] = chm->pawn_dbl_move[0]; lrc_obj.pawn_dbl_move[1] = chm->pawn_dbl_move[1]; lrc_obj.castling_possible = chm->castling_possible; cp_SetOnBoard(chm->main_src, chm->main_cp); cp_SetOnBoard(chm->main_dest, PIECE_NONE); if ( chm->other_src != ILLEGAL_POSITION ) cp_SetOnBoard(chm->other_src, chm->other_cp); if ( chm->other_dest != ILLEGAL_POSITION ) cp_SetOnBoard(chm->other_dest, PIECE_NONE); } /* assumes, that the following members of the returned chm structure are filled uint8_t main_cp; the main piece, which is moved uint8_t main_src; the source position of the main piece uint8_t main_dest; the destination of the main piece uint8_t other_cp; another piece: the captured one, the ROOK in case of castling or PIECE_NONE uint8_t other_src; the delete position of other_cp. Often identical to main_dest except for e.p. and castling uint8_t other_dest; only used for castling: ROOK destination pos */ chm_p cu_PushHalfMove(void) { chm_p chm; chm = lrc_obj.chm_list+lrc_obj.chm_pos; if ( lrc_obj.chm_pos < CHM_LIST_SIZE-1) lrc_obj.chm_pos++; chm->pawn_dbl_move[0] = lrc_obj.pawn_dbl_move[0]; chm->pawn_dbl_move[1] = lrc_obj.pawn_dbl_move[1]; chm->castling_possible = lrc_obj.castling_possible; return chm; } char chess_piece_to_char[] = "NBRQK"; /* simple moves on empty field: Ka1-b2 capture moves: Ka1xb2 castling: 0-0 or 0-0-0 */ static void cu_add_pos(char *s, uint8_t pos) U8G_NOINLINE; static void cu_add_pos(char *s, uint8_t pos) { *s = pos; *s >>= 4; *s += 'a'; s++; *s = pos; *s &= 15; *s += '1'; } const char *cu_GetHalfMoveStr(uint8_t idx) { chm_p chm; static char buf[7]; /*Ka1-b2*/ char *p = buf; chm = lrc_obj.chm_list+idx; if ( cp_GetPiece(chm->main_cp) != PIECE_NONE ) { if ( cp_GetPiece(chm->main_cp) > PIECE_PAWN ) { *p++ = chess_piece_to_char[cp_GetPiece(chm->main_cp)-2]; } cu_add_pos(p, chm->main_src); p+=2; if ( cp_GetPiece(chm->other_cp) == PIECE_NONE ) *p++ = '-'; else *p++ = 'x'; cu_add_pos(p, chm->main_dest); p+=2; } *p = '\0'; return buf; } /*==============================================================*/ /* move */ /*==============================================================*/ /* Move a piece from source position to a destination on the board This function - does not perform any checking - however it processes "en passant" and casteling - backup the move and allow 1x undo 2011-02-05: - fill pawn_dbl_move[] for double pawn moves --> done - Implement casteling --> done - en passant --> done - pawn conversion/promotion --> done - half-move backup --> done - cleanup everything, minimize variables --> done */ void cu_Move(uint8_t src, uint8_t dest) { /* start backup structure */ chm_p chm = cu_PushHalfMove(); /* these are the values from the board at the positions, provided as arguments to this function */ uint8_t cp_src, cp_dest; /* Maybe a second position is cleared and one additional location is set */ uint8_t clr_pos2; uint8_t set_pos2; uint8_t set_cp2; /* get values from board */ cp_src = cp_GetFromBoard(src); cp_dest = cp_GetFromBoard(dest); /* fill backup structure */ chm->main_cp = cp_src; chm->main_src = src; chm->main_dest = dest; chm->other_cp = cp_dest; /* prepace capture backup */ chm->other_src = dest; chm->other_dest = ILLEGAL_POSITION; /* setup results as far as possible with some suitable values */ clr_pos2 = ILLEGAL_POSITION; /* for en passant and castling, two positions might be cleared */ set_pos2 = ILLEGAL_POSITION; /* only used for castling */ set_cp2 = PIECE_NONE; /* ROOK for castling */ /* check for PAWN */ if ( cp_GetPiece(cp_src) == PIECE_PAWN ) { /* double step: is the distance 2 rows */ if ( (src - dest == 32) || ( dest - src == 32 ) ) { /* remember the destination position */ lrc_obj.pawn_dbl_move[cp_GetColor(cp_src)] = dest; } /* check if the PAWN is able to promote */ else if ( (dest>>4) == 0 || (dest>>4) == 7 ) { /* do simple "queening" */ cp_src &= ~PIECE_PAWN; cp_src |= PIECE_QUEEN; } /* is it en passant capture? */ /* check for side move */ else if ( ((src + dest) & 1) != 0 ) { /* check, if target field is empty */ if ( cp_GetPiece(cp_dest) == PIECE_NONE ) { /* this is en passant */ /* no further checking required, because legal moves are assumed here */ /* however... the captured pawn position must be valid */ clr_pos2 = lrc_obj.pawn_dbl_move[cp_GetColor(cp_src) ^ 1]; chm->other_src = clr_pos2; chm->other_cp = cp_GetFromBoard(clr_pos2); } } } /* check for the KING */ else if ( cp_GetPiece(cp_src) == PIECE_KING ) { /* disallow castling, if the KING has moved */ if ( cp_GetColor(cp_src) == COLOR_WHITE ) { /* if white KING has moved, disallow castling for white */ lrc_obj.castling_possible &= 0x0c; } else { /* if black KING has moved, disallow castling for black */ lrc_obj.castling_possible &= 0x03; } /* has it been castling to the left? */ if ( src - dest == 2 ) { /* let the ROOK move to pos2 */ set_pos2 = src-1; set_cp2 = cp_GetFromBoard(src-4); /* the ROOK must be cleared from the original position */ clr_pos2 = src-4; chm->other_cp = set_cp2; chm->other_src = clr_pos2; chm->other_dest = set_pos2; } /* has it been castling to the right? */ else if ( dest - src == 2 ) { /* let the ROOK move to pos2 */ set_pos2 = src+1; set_cp2 = cp_GetFromBoard(src+3); /* the ROOK must be cleared from the original position */ clr_pos2 = src+3; chm->other_cp = set_cp2; chm->other_src = clr_pos2; chm->other_dest = set_pos2; } } /* check for the ROOK */ else if ( cp_GetPiece(cp_src) == PIECE_ROOK ) { /* disallow white left castling */ if ( src == 0x00 ) lrc_obj.castling_possible &= ~0x01; /* disallow white right castling */ if ( src == 0x07 ) lrc_obj.castling_possible &= ~0x02; /* disallow black left castling */ if ( src == 0x70 ) lrc_obj.castling_possible &= ~0x04; /* disallow black right castling */ if ( src == 0x77 ) lrc_obj.castling_possible &= ~0x08; } /* apply new board situation */ cp_SetOnBoard(dest, cp_src); if ( set_pos2 != ILLEGAL_POSITION ) cp_SetOnBoard(set_pos2, set_cp2); cp_SetOnBoard(src, PIECE_NONE); if ( clr_pos2 != ILLEGAL_POSITION ) cp_SetOnBoard(clr_pos2, PIECE_NONE); } /* this subprocedure decides for evaluation of the current board situation or further (deeper) investigation Argument pos is the new target position if the current piece */ uint8_t ce_LoopRecur(uint8_t pos) { eval_t eval; /* 1. check if target position is occupied by the same player (my_color) */ /* of if pos is somehow illegal or not valid */ if ( cu_IsIllegalPosition(pos, stack_GetCurrElement()->current_color) != 0 ) return 0; /* 2. move piece to the specified position, capture opponent piece if required */ cu_Move(stack_GetCurrElement()->current_pos, pos); /* 3. */ /* if depth reached: evaluate */ /* else: go down next level */ /* no eval if there had been any valid half-moves, so the default value (MIN) will be returned. */ if ( stack_Push(stack_GetCurrElement()->current_color) == 0 ) { eval = ce_Eval(); } else { /* init the element, which has been pushed */ stack_InitCurrElement(); /* start over with ntext level */ ce_LoopPieces(); /* get the best move from opponents view, so invert the result */ eval = -stack_GetCurrElement()->best_eval; stack_Pop(); } /* 4. store result */ stack_SetMove(eval, pos); /* 5. undo the move */ cu_UndoHalfMove(); /* 6. check special modes */ /* the purpose of these checks is to mark special pieces and positions on the board */ /* these marks can be checked by the user interface to highlight special positions */ if ( lrc_obj.check_mode != 0 ) { stack_element_p e = stack_GetCurrElement(); if ( lrc_obj.check_mode == CHECK_MODE_MOVEABLE ) { cp_SetOnBoard(e->current_pos, e->current_cp | CP_MARK_MASK ); } else if ( lrc_obj.check_mode == CHECK_MODE_TARGET_MOVE ) { if ( e->current_pos == lrc_obj.check_src_pos ) { cp_SetOnBoard(pos, cp_GetFromBoard(pos) | CP_MARK_MASK ); } } } return 1; } /*==============================================================*/ /* move pieces which can move one or more steps into a direction */ /*==============================================================*/ /* subprocedure to generate various target positions for some pieces special cases are handled in the piece specific sub-procedure Arguments: d: a list of potential directions is_multi_step: if the piece can only do one step (zero for KING and KNIGHT) */ static const uint8_t ce_dir_offset_rook[] PROGMEM = { 1, 16, -16, -1, 0 }; static const uint8_t ce_dir_offset_bishop[] PROGMEM = { 15, 17, -17, -15, 0 }; static const uint8_t ce_dir_offset_queen[] PROGMEM = { 1, 16, -16, -1, 15, 17, -17, -15, 0 }; static const uint8_t ce_dir_offset_knight[] PROGMEM = {14, -14, 18, -18, 31, -31, 33, -33, 0}; void ce_LoopDirsSingleMultiStep(const uint8_t *d, uint8_t is_multi_step) { uint8_t loop_pos; /* with all directions */ for(;;) { if ( u8g_pgm_read(d) == 0 ) break; /* start again from the initial position */ loop_pos = stack_GetCurrElement()->current_pos; /* check direction */ do { /* check next position into one direction */ loop_pos += u8g_pgm_read(d); /* go further to ce_LoopRecur() 0 will be returned if the target position is illegal or a piece of the own color this is used to stop walking into one direction */ if ( ce_LoopRecur(loop_pos) == 0 ) break; /* stop if we had hit another piece */ if ( cp_GetPiece(cp_GetFromBoard(loop_pos)) != PIECE_NONE ) break; } while( is_multi_step ); d++; } } void ce_LoopRook(void) { ce_LoopDirsSingleMultiStep(ce_dir_offset_rook, 1); } void ce_LoopBishop(void) { ce_LoopDirsSingleMultiStep(ce_dir_offset_bishop, 1); } void ce_LoopQueen(void) { ce_LoopDirsSingleMultiStep(ce_dir_offset_queen, 1); } void ce_LoopKnight(void) { ce_LoopDirsSingleMultiStep(ce_dir_offset_knight, 0); } /*==============================================================*/ /* move king */ /*==============================================================*/ uint8_t cu_IsKingCastling(uint8_t mask, int8_t direction, uint8_t cnt) U8G_NOINLINE; /* checks, if the king can do castling Arguments: mask: the bit-mask for the global "castling possible" flag direction: left castling: -1, right castling 1 cnt: number of fields to be checked: 3 or 2 */ uint8_t cu_IsKingCastling(uint8_t mask, int8_t direction, uint8_t cnt) { uint8_t pos; uint8_t opponent_color; /* check if the current board state allows castling */ if ( (lrc_obj.castling_possible & mask) == 0 ) return 0; /* castling not allowed */ /* get the position of the KING, could be white or black king */ pos = stack_GetCurrElement()->current_pos; /* calculate the color of the opponent */ opponent_color = 1; opponent_color -= stack_GetCurrElement()->current_color; /* if the KING itself is given check... */ if ( ce_GetPositionAttackWeight(pos, opponent_color) > 0 ) return 0; /* check if fields in the desired direction are emtpy */ for(;;) { /* go to the next field */ pos += direction; /* check for a piece */ if ( cp_GetPiece(cp_GetFromBoard(pos)) != PIECE_NONE ) return 0; /* castling not allowed */ /* if some of the fields are under attack */ if ( ce_GetPositionAttackWeight(pos, opponent_color) > 0 ) return 0; cnt--; if ( cnt == 0 ) break; } return 1; /* castling allowed */ } void ce_LoopKing(void) { /* there is an interessting timing problem in this procedure it must be checked for castling first and as second step the normal KING movement. If we would first check for normal moves, than any marks might be overwritten by the ROOK in the case of castling. */ /* castling (this must be done before checking normal moves (see above) */ if ( stack_GetCurrElement()->current_color == COLOR_WHITE ) { /* white left castling */ if ( cu_IsKingCastling(1, -1, 3) != 0 ) { /* check for attacked fields */ ce_LoopRecur(stack_GetCurrElement()->current_pos-2); } /* white right castling */ if ( cu_IsKingCastling(2, 1, 2) != 0 ) { /* check for attacked fields */ ce_LoopRecur(stack_GetCurrElement()->current_pos+2); } } else { /* black left castling */ if ( cu_IsKingCastling(4, -1, 3) != 0 ) { /* check for attacked fields */ ce_LoopRecur(stack_GetCurrElement()->current_pos-2); } /* black right castling */ if ( cu_IsKingCastling(8, 1, 2) != 0 ) { /* check for attacked fields */ ce_LoopRecur(stack_GetCurrElement()->current_pos+2); } } /* reuse queen directions */ ce_LoopDirsSingleMultiStep(ce_dir_offset_queen, 0); } /*==============================================================*/ /* move pawn */ /*==============================================================*/ /* doppelschritt: nur von der grundlinie aus, beide (!) felder vor dem bauern mssen frei sein en passant: nur unmittelbar nachdem ein doppelschritt ausgefhrt wurde. */ void ce_LoopPawnSideCapture(uint8_t loop_pos) { if ( gpos_IsIllegal(loop_pos) == 0 ) { /* get the piece from the board */ /* if the field is NOT empty */ if ( cp_GetPiece(cp_GetFromBoard(loop_pos)) != PIECE_NONE ) { /* normal capture */ ce_LoopRecur(loop_pos); /* TODO: check for pawn conversion/promotion */ } else { /* check conditions for en passant capture */ if ( stack_GetCurrElement()->current_color == COLOR_WHITE ) { if ( lrc_obj.pawn_dbl_move[COLOR_BLACK]+16 == loop_pos ) { ce_LoopRecur(loop_pos); /* note: pawn conversion/promotion can not occur */ } } else { if ( lrc_obj.pawn_dbl_move[COLOR_WHITE] == loop_pos+16 ) { ce_LoopRecur(loop_pos); /* note: pawn conversion/promotion can not occur */ } } } } } void ce_LoopPawn(void) { uint8_t initial_pos = stack_GetCurrElement()->current_pos; uint8_t my_color = stack_GetCurrElement()->current_color; uint8_t loop_pos; uint8_t line; /* one step forward */ loop_pos = initial_pos; line = initial_pos; line >>= 4; if ( my_color == COLOR_WHITE ) loop_pos += 16; else loop_pos -= 16; if ( gpos_IsIllegal(loop_pos) == 0 ) { /* if the field is empty */ if ( cp_GetPiece(cp_GetFromBoard(loop_pos)) == PIECE_NONE ) { /* TODO: check for and loop through piece conversion/promotion */ ce_LoopRecur(loop_pos); /* second step forward */ /* if pawn is on his starting line */ if ( (my_color == COLOR_WHITE && line == 1) || (my_color == COLOR_BLACK && line == 6 ) ) { /* the place before the pawn is not occupied, so we can do double moves, see above */ if ( my_color == COLOR_WHITE ) loop_pos += 16; else loop_pos -= 16; if ( cp_GetPiece(cp_GetFromBoard(loop_pos)) == PIECE_NONE ) { /* this is a special case, other promotions of the pawn can not occur */ ce_LoopRecur(loop_pos); } } } } /* capture */ loop_pos = initial_pos; if ( my_color == COLOR_WHITE ) loop_pos += 15; else loop_pos -= 15; ce_LoopPawnSideCapture(loop_pos); loop_pos = initial_pos; if ( my_color == COLOR_WHITE ) loop_pos += 17; else loop_pos -= 17; ce_LoopPawnSideCapture(loop_pos); } /*==============================================================*/ /* attacked */ /*==============================================================*/ /* from a starting position, search for a piece, that might jump to that postion. return: the two global variables lrc_obj.find_piece_weight[0]; lrc_obj.find_piece_weight[1]; will be increased by the weight of the attacked pieces of that color. it is usually required to reset these global variables to zero, before using this function. */ void ce_FindPieceByStep(uint8_t start_pos, uint8_t piece, const uint8_t *d, uint8_t is_multi_step) { uint8_t loop_pos, cp; /* with all directions */ for(;;) { if ( u8g_pgm_read(d) == 0 ) break; /* start again from the initial position */ loop_pos = start_pos; /* check direction */ do { /* check next position into one direction */ loop_pos += u8g_pgm_read(d); /* check if the board boundary has been crossed */ if ( (loop_pos & 0x088) != 0 ) break; /* get the colored piece from the board */ cp = cp_GetFromBoard(loop_pos); /* stop if we had hit another piece */ if ( cp_GetPiece(cp) != PIECE_NONE ) { /* if it is the piece we are looking for, then add the weight */ if ( cp_GetPiece(cp) == piece ) { lrc_obj.find_piece_weight[cp_GetColor(cp)] += ce_piece_weight[piece]; lrc_obj.find_piece_cnt[cp_GetColor(cp)]++; } /* in any case, break out of the inner loop */ break; } } while( is_multi_step ); d++; } } void ce_FindPawnPiece(uint8_t dest_pos, uint8_t color) { uint8_t cp; /* check if the board boundary has been crossed */ if ( (dest_pos & 0x088) == 0 ) { /* get the colored piece from the board */ cp = cp_GetFromBoard(dest_pos); /* only if there is a pawn of the matching color */ if ( cp_GetPiece(cp) == PIECE_PAWN ) { if ( cp_GetColor(cp) == color ) { /* the weight of the PAWN */ lrc_obj.find_piece_weight[color] += 1; lrc_obj.find_piece_cnt[color]++; } } } } /* find out, which pieces do attack a specified field used to - check if the KING can do castling - check if the KING must move may be used in the eval procedure ... once... the result is stored in the global array uint8_t lrc_obj.find_piece_weight[2]; which is indexed with the color. lrc_obj.find_piece_weight[COLOR_WHITE] is the sum of all white pieces which can directly move to this field. example: if the black KING is at "pos" and lrc_obj.find_piece_weight[COLOR_WHITE] is not zero (after executing ce_CalculatePositionWeight(pos)) then the KING must be protected or moveed, because the KING was given check. */ void ce_CalculatePositionWeight(uint8_t pos) { lrc_obj.find_piece_weight[0] = 0; lrc_obj.find_piece_weight[1] = 0; lrc_obj.find_piece_cnt[0] = 0; lrc_obj.find_piece_cnt[1] = 0; if ( (pos & 0x088) != 0 ) return; ce_FindPieceByStep(pos, PIECE_ROOK, ce_dir_offset_rook, 1); ce_FindPieceByStep(pos, PIECE_BISHOP, ce_dir_offset_bishop, 1); ce_FindPieceByStep(pos, PIECE_QUEEN, ce_dir_offset_queen, 1); ce_FindPieceByStep(pos, PIECE_KNIGHT, ce_dir_offset_knight, 0); ce_FindPieceByStep(pos, PIECE_KING, ce_dir_offset_queen, 0); ce_FindPawnPiece(pos+17, COLOR_BLACK); ce_FindPawnPiece(pos+15, COLOR_BLACK); ce_FindPawnPiece(pos-17, COLOR_WHITE); ce_FindPawnPiece(pos-15, COLOR_WHITE); } /* calculate the summed weight of pieces with specified color which can move to a specified position argument: pos: the position which should be analysed color: the color of those pieces which should be analysed e.g. if a black piece is at 'pos' and 'color' is white then this procedure returns the white atting count */ uint8_t ce_GetPositionAttackWeight(uint8_t pos, uint8_t color) { ce_CalculatePositionWeight(pos); return lrc_obj.find_piece_weight[color]; } uint8_t ce_GetPositionAttackCount(uint8_t pos, uint8_t color) { ce_CalculatePositionWeight(pos); return lrc_obj.find_piece_cnt[color]; } /*==============================================================*/ /* depth search starts here: loop over all pieces of the current color on the board */ /*==============================================================*/ void ce_LoopPieces(void) { stack_element_p e = stack_GetCurrElement(); /* start with lower left position (A1) */ e->current_pos = 0; do { e->current_cp = cp_GetFromBoard(e->current_pos); /* check if the position on the board is empty */ if ( e->current_cp != 0 ) { /* only generate moves for the current color */ if ( e->current_color == cp_GetColor(e->current_cp) ) { chess_Thinking(); /* find out which piece is used */ switch(cp_GetPiece(e->current_cp)) { case PIECE_NONE: break; case PIECE_PAWN: ce_LoopPawn(); break; case PIECE_KNIGHT: ce_LoopKnight(); break; case PIECE_BISHOP: ce_LoopBishop(); break; case PIECE_ROOK: ce_LoopRook(); break; case PIECE_QUEEN: ce_LoopQueen(); break; case PIECE_KING: ce_LoopKing(); break; } } } e->current_pos = cu_NextPos(e->current_pos); } while( e->current_pos != 0 ); } /*==============================================================*/ /* user interface */ /*==============================================================*/ /* eval_t chess_EvalCurrBoard(uint8_t color) { stack_Init(0); stack_GetCurrElement()->current_color = color; ce_LoopPieces(); return stack_GetCurrElement()->best_eval; } */ /* clear any marks on the board */ void chess_ClearMarks(void) { uint8_t i; for( i = 0; i < 64; i++ ) lrc_obj.board[i] &= ~CP_MARK_MASK; } /* Mark all pieces which can do moves. This is done by setting flags on the global board */ void chess_MarkMovable(void) { stack_Init(0); //stack_GetCurrElement()->current_color = color; lrc_obj.check_mode = CHECK_MODE_MOVEABLE; ce_LoopPieces(); } /* Checks, if the piece can move from src_pos to dest_pos src_pos: The game position of a piece on the chess board */ void chess_MarkTargetMoves(uint8_t src_pos) { stack_Init(0); stack_GetCurrElement()->current_color = cp_GetColor(cp_GetFromBoard(src_pos)); lrc_obj.check_src_pos = src_pos; lrc_obj.check_mode = CHECK_MODE_TARGET_MOVE; ce_LoopPieces(); } /* first call should start with 255 this procedure will return 255 if - there are no marks at all - it has looped over all marks once */ uint8_t chess_GetNextMarked(uint8_t arg, uint8_t is_prev) { uint8_t i; uint8_t pos = arg; for(i = 0; i < 64; i++) { if ( is_prev != 0 ) pos = cu_PrevPos(pos); else pos = cu_NextPos(pos); if ( arg != 255 && pos == 0 ) return 255; if ( cp_IsMarked(cp_GetFromBoard(pos)) ) return pos; } return 255; } /* make a manual move: this is a little bit more than cu_Move() */ void chess_ManualMove(uint8_t src, uint8_t dest) { uint8_t cp; /* printf("chess_ManualMove %02x -> %02x\n", src, dest); */ /* if all other things fail, this is the place where the game is to be decided: */ /* ... if the KING is captured */ cp = cp_GetFromBoard(dest); if ( cp_GetPiece(cp) == PIECE_KING ) { lrc_obj.is_game_end = 1; lrc_obj.lost_side_color = cp_GetColor(cp); } /* clear ply history here, to avoid memory overflow */ /* may be the last X moves can be kept here */ cu_ReduceHistoryByFullMove(); /* perform the move on the board */ cu_Move(src, dest); /* update en passant double move positions: en passant position is removed after two half moves */ lrc_obj.pawn_dbl_move[lrc_obj.ply_count&1] = ILLEGAL_POSITION; /* update the global half move counter */ lrc_obj.ply_count++; /* make a small check about the end of the game */ /* use at least depth 1, because we must know if the king can still move */ /* this is: King moves at level 0 and will be captured at level 1 */ /* so we check if the king can move and will not be captured at search level 1 */ stack_Init(1); ce_LoopPieces(); /* printf("chess_ManualMove/analysis best_from_pos %02x -> best_to_pos %02x\n", stack_GetCurrElement()->best_from_pos, stack_GetCurrElement()->best_to_pos); */ /* analyse the eval result */ /* check if the other player has any moves left */ if ( stack_GetCurrElement()->best_from_pos == ILLEGAL_POSITION ) { uint8_t color; /* conditions: */ /* 1. no King, should never happen, opposite color has won */ /* this is already checked above at the beginning if this procedure */ /* 2. King is under attack, opposite color has won */ /* 3. King is not under attack, game is a draw */ uint8_t i = 0; color = lrc_obj.ply_count; color &= 1; do { cp = cp_GetFromBoard(i); /* look for the King */ if ( cp_GetPiece(cp) == PIECE_KING ) { if ( cp_GetColor(cp) == color ) { /* check if KING is attacked */ if ( ce_GetPositionAttackCount(i, color^1) != 0 ) { /* KING is under attack (check) and can not move: Game is lost */ lrc_obj.is_game_end = 1; lrc_obj.lost_side_color = color; } else { /* KING is NOT under attack (check) but can not move: Game is a draw */ lrc_obj.is_game_end = 1; lrc_obj.lost_side_color = 2; } /* break out of the loop */ break; } } i = cu_NextPos(i); } while( i != 0 ); } } /* let the computer do a move */ void chess_ComputerMove(uint8_t depth) { stack_Init(depth); //stack_GetCurrElement()->current_color = lrc_obj.ply_count; //stack_GetCurrElement()->current_color &= 1; cu_ReduceHistoryByFullMove(); ce_LoopPieces(); chess_ManualMove(stack_GetCurrElement()->best_from_pos, stack_GetCurrElement()->best_to_pos); } /*==============================================================*/ /* unix code */ /*==============================================================*/ #ifdef UNIX_MAIN #include <stdio.h> #include <string.h> char *piece_str[] = { /* 0x00 */ " ", "wP", "wN", "wB", /* 0x04 */ "wR", "wQ", "wK", "w?", /* 0x08 */ "w?", "w?", "w?", "w?", /* 0x0c */ "w?", "w?", "w?", "w?", /* 0x10 */ "b ", "bP", "bN", "bB", "bR", "bQ", "bK", "b?", "b?", "b?", "b?", "b?", "b?", "b?", "b?", "b?" }; void chess_Thinking(void) { uint8_t i; uint8_t cp = cp_GetPiece(stack_GetCurrElement()->current_cp); printf("Thinking: ", piece_str[cp], stack_GetCurrElement()->current_pos); for( i = 0; i <= lrc_obj.curr_depth; i++ ) printf("%s ", piece_str[(lrc_obj.stack_memory+i)->current_cp]); printf(" \r"); } void board_Show(void) { uint8_t i, j, cp; char buf[10]; for ( i = 0; i < 8; i++ ) { printf("%1d ", 7-i); for ( j = 0; j < 8; j++ ) { /* get piece from global board */ cp = lrc_obj.board[(7-i)*8+j]; strcpy(buf, piece_str[cp&COLOR_PIECE_MASK]); if ( (cp & CP_MARK_MASK) != 0 ) { buf[0] = '#'; } /* mask out any bits except color and piece index */ cp &= COLOR_PIECE_MASK; printf("%s %02x ", buf, cp); } printf("\n"); } } int main(void) { uint8_t depth = 3; chess_SetupBoard(); board_Show(); puts(""); /* chess_ClearMarks(); chess_MarkMovable(COLOR_WHITE); board_Show(); */ chess_ManualMove(0x006, 0x066); printf("lrc_obj.is_game_end: %d\n" , lrc_obj.is_game_end); printf("lrc_obj.lost_side_color: %d\n" , lrc_obj.lost_side_color); chess_ComputerMove(2); printf("lrc_obj.is_game_end: %d\n" , lrc_obj.is_game_end); printf("lrc_obj.lost_side_color: %d\n" , lrc_obj.lost_side_color); board_Show(); } #else /*==============================================================*/ /* display menu */ /*==============================================================*/ //#define MNU_FONT font_5x7 #define MNU_FONT u8g_font_5x8r //#define MNU_FONT font_6x9 #define MNU_ENTRY_HEIGHT 9 char *mnu_title = "Little Rook Chess"; char *mnu_list[] = { "New Game (White)", "New Game (Black)", "Undo Move", "Return" }; uint8_t mnu_pos = 0; uint8_t mnu_max = 4; void mnu_DrawHome(uint8_t is_highlight) { uint8_t x = lrc_u8g->width - 35; uint8_t y = (lrc_u8g->height-1); uint8_t t; u8g_SetFont(lrc_u8g, u8g_font_5x7r); u8g_SetDefaultForegroundColor(lrc_u8g); t = u8g_DrawStrP(lrc_u8g, x, y -1, U8G_PSTR("Options")); if ( is_highlight ) u8g_DrawFrame(lrc_u8g, x-1, y - MNU_ENTRY_HEIGHT +1, t, MNU_ENTRY_HEIGHT); } void mnu_DrawEntry(uint8_t y, char *str, uint8_t is_clr_background, uint8_t is_highlight) { uint8_t t, x; u8g_SetFont(lrc_u8g, MNU_FONT); t = u8g_GetStrWidth(lrc_u8g, str); x = u8g_GetWidth(lrc_u8g); x -= t; x >>= 1; if ( is_clr_background ) { u8g_SetDefaultBackgroundColor(lrc_u8g); u8g_DrawBox(lrc_u8g, x-3, (lrc_u8g->height-1) - (y+MNU_ENTRY_HEIGHT-1+2), t+5, MNU_ENTRY_HEIGHT+4); } u8g_SetDefaultForegroundColor(lrc_u8g); u8g_DrawStr(lrc_u8g, x, (lrc_u8g->height-1) - y, str); if ( is_highlight ) { u8g_DrawFrame(lrc_u8g, x-1, (lrc_u8g->height-1) - y -MNU_ENTRY_HEIGHT +1, t, MNU_ENTRY_HEIGHT); } } void mnu_Draw(void) { uint8_t i; uint8_t t,y; /* calculate hight of the complete menu */ y = mnu_max; y++; /* consider also some space for the title */ y++; /* consider also some space for the title */ y *= MNU_ENTRY_HEIGHT; /* calculate how much space will be left */ t = u8g_GetHeight(lrc_u8g); t -= y; /* topmost pos start half of that empty space from the top */ t >>= 1; y = u8g_GetHeight(lrc_u8g); y -= t; y -= MNU_ENTRY_HEIGHT; mnu_DrawEntry(y, mnu_title, 0, 0); y -= MNU_ENTRY_HEIGHT; for( i = 0; i < mnu_max; i++ ) { y -= MNU_ENTRY_HEIGHT; mnu_DrawEntry(y, mnu_list[i], 0, i == mnu_pos); } } void mnu_Step(uint8_t key_cmd) { if ( key_cmd == CHESS_KEY_NEXT ) { if ( mnu_pos+1 < mnu_max ) mnu_pos++; } else if ( key_cmd == CHESS_KEY_PREV ) { if ( mnu_pos > 0 ) mnu_pos--; } } uint8_t chess_key_code = 0; uint8_t chess_key_cmd = 0; #define CHESS_STATE_MENU 0 #define CHESS_STATE_SELECT_START 1 #define CHESS_STATE_SELECT_PIECE 2 #define CHESS_STATE_SELECT_TARGET_POS 3 #define CHESS_STATE_THINKING 4 #define CHESS_STATE_GAME_END 5 uint8_t chess_state = CHESS_STATE_MENU; uint8_t chess_source_pos = 255; uint8_t chess_target_pos = 255; const uint8_t chess_pieces_body_bm[] PROGMEM = { /* PAWN */ 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, /* 0x00, 0x00, 0x00, 0x0c, 0x0c, 0x00, 0x00, 0x00, */ /* KNIGHT */ 0x00, 0x00, 0x1c, 0x2c, 0x04, 0x04, 0x0e, 0x00, /* BISHOP */ 0x00, 0x00, 0x1c, 0x1c, 0x1c, 0x08, 0x00, 0x00, /* 0x00, 0x00, 0x08, 0x1c, 0x1c, 0x08, 0x00, 0x00, */ /* ROOK */ 0x00, 0x00, 0x00, 0x1c, 0x1c, 0x1c, 0x1c, 0x00, /* QUEEN */ 0x00, 0x00, 0x14, 0x1c, 0x08, 0x1c, 0x08, 0x00, /* KING */ 0x00, 0x00, 0x00, 0x08, 0x3e, 0x1c, 0x08, 0x00, }; #ifdef NOT_REQUIRED /* white pieces are constructed by painting black pieces and cutting out the white area */ const uint8_t chess_white_pieces_bm[] PROGMEM = { /* PAWN */ 0x00, 0x00, 0x0c, 0x12, 0x12, 0x0c, 0x1e, 0x00, /* KNIGHT */ 0x00, 0x1c, 0x22, 0x52, 0x6a, 0x0a, 0x11, 0x1f, /* BISHOP */ 0x00, 0x08, 0x14, 0x22, 0x22, 0x14, 0x08, 0x7f, /* ROOK */ 0x00, 0x55, 0x7f, 0x22, 0x22, 0x22, 0x22, 0x7f, /* QUEEN */ 0x00, 0x55, 0x2a, 0x22, 0x14, 0x22, 0x14, 0x7f, /* KING */ 0x08, 0x1c, 0x49, 0x77, 0x41, 0x22, 0x14, 0x7f, }; #endif const uint8_t chess_black_pieces_bm[] PROGMEM = { /* PAWN */ 0x00, 0x00, 0x18, 0x3c, 0x3c, 0x18, 0x3c, 0x00, /* 0x00, 0x00, 0x0c, 0x1e, 0x1e, 0x0c, 0x1e, 0x00, */ /* KNIGHT */ 0x00, 0x1c, 0x3e, 0x7e, 0x6e, 0x0e, 0x1f, 0x1f, /* BISHOP */ 0x00, 0x1c, 0x2e, 0x3e, 0x3e, 0x1c, 0x08, 0x7f, /*0x00, 0x08, 0x1c, 0x3e, 0x3e, 0x1c, 0x08, 0x7f,*/ /* ROOK */ 0x00, 0x55, 0x7f, 0x3e, 0x3e, 0x3e, 0x3e, 0x7f, /* QUEEN */ 0x00, 0x55, 0x3e, 0x3e, 0x1c, 0x3e, 0x1c, 0x7f, /* KING -*/ 0x08, 0x1c, 0x49, 0x7f, 0x7f, 0x3e, 0x1c, 0x7f, }; #if defined(DOGXL160_HW_GR) #define BOXSIZE 13 #define BOXOFFSET 3 #else #define BOXSIZE 8 #define BOXOFFSET 1 #endif u8g_uint_t chess_low_edge; uint8_t chess_boxsize = 8; uint8_t chess_boxoffset = 1; void chess_DrawFrame(uint8_t pos, uint8_t is_bold) { u8g_uint_t x0, y0; x0 = pos; x0 &= 15; if ( lrc_obj.orientation != COLOR_WHITE ) x0 ^= 7; y0 = pos; y0>>= 4; if ( lrc_obj.orientation != COLOR_WHITE ) y0 ^= 7; x0 *= chess_boxsize; y0 *= chess_boxsize; u8g_SetDefaultForegroundColor(lrc_u8g); u8g_DrawFrame(lrc_u8g, x0, chess_low_edge - y0 - chess_boxsize+1, chess_boxsize, chess_boxsize); if ( is_bold ) { x0--; y0++; u8g_DrawFrame(lrc_u8g, x0, chess_low_edge - y0 - chess_boxsize +1, chess_boxsize+2, chess_boxsize+2); } } void chess_DrawBoard(void) { uint8_t i, j, cp; const uint8_t *ptr; /* pointer into PROGMEM */ if ( U8G_MODE_GET_BITS_PER_PIXEL(u8g_GetMode(lrc_u8g)) > 1 ) { for( i = 0; i < 8; i++ ) for( j = 0; j < 8; j++ ) { uint8_t x,y; x = i; x*=chess_boxsize; y = j; y*=chess_boxsize; if ( ((i^j) & 1) == 0 ) u8g_SetDefaultMidColor(lrc_u8g); else u8g_SetDefaultBackgroundColor(lrc_u8g); u8g_DrawBox(lrc_u8g, x,chess_low_edge-y-chess_boxsize+1,chess_boxsize,chess_boxsize); } //u8g_SetDefaultForegroundColor(lrc_u8g); } else { uint8_t x_offset = 1; u8g_SetDefaultForegroundColor(lrc_u8g); for( i = 0; i < 8*8; i+=8 ) { for( j = 0; j < 8*8; j+=8 ) { if ( ((i^j) & 8) == 0 ) { u8g_DrawPixel(lrc_u8g, j+0+x_offset, chess_low_edge - i-0); u8g_DrawPixel(lrc_u8g, j+0+x_offset, chess_low_edge - i-2); u8g_DrawPixel(lrc_u8g, j+0+x_offset, chess_low_edge - i-4); u8g_DrawPixel(lrc_u8g, j+0+x_offset, chess_low_edge - i-6); u8g_DrawPixel(lrc_u8g, j+2+x_offset, chess_low_edge - i-0); u8g_DrawPixel(lrc_u8g, j+2+x_offset, chess_low_edge - i-6); u8g_DrawPixel(lrc_u8g, j+4+x_offset, chess_low_edge - i-0); u8g_DrawPixel(lrc_u8g, j+4+x_offset, chess_low_edge - i-6); u8g_DrawPixel(lrc_u8g, j+6+x_offset, chess_low_edge - i-0); u8g_DrawPixel(lrc_u8g, j+6+x_offset, chess_low_edge - i-2); u8g_DrawPixel(lrc_u8g, j+6+x_offset, chess_low_edge - i-4); u8g_DrawPixel(lrc_u8g, j+6+x_offset, chess_low_edge - i-6); } } } } for ( i = 0; i < 8; i++ ) { for ( j = 0; j < 8; j++ ) { /* get piece from global board */ if ( lrc_obj.orientation == COLOR_WHITE ) { cp = lrc_obj.board[i*8+j]; } else { cp = lrc_obj.board[(7-i)*8+7-j]; } if ( cp_GetPiece(cp) != PIECE_NONE ) { ptr = chess_black_pieces_bm; ptr += (cp_GetPiece(cp)-1)*8; u8g_SetDefaultForegroundColor(lrc_u8g); u8g_DrawBitmapP(lrc_u8g, j*chess_boxsize+chess_boxoffset-1, chess_low_edge - (i*chess_boxsize+chess_boxsize-chess_boxoffset), 1, 8, ptr); if ( cp_GetColor(cp) == lrc_obj.strike_out_color ) { ptr = chess_pieces_body_bm; ptr += (cp_GetPiece(cp)-1)*8; u8g_SetDefaultBackgroundColor(lrc_u8g); u8g_DrawBitmapP(lrc_u8g, j*chess_boxsize+chess_boxoffset-1, chess_low_edge - (i*chess_boxsize+chess_boxsize-chess_boxoffset), 1, 8, ptr); } } } } if ( (chess_source_pos & 0x88) == 0 ) { chess_DrawFrame(chess_source_pos, 1); } if ( (chess_target_pos & 0x88) == 0 ) { chess_DrawFrame(chess_target_pos, 0); } } void chess_Thinking(void) { } void chess_Init(u8g_t *u8g, uint8_t body_color) { lrc_u8g = u8g; chess_low_edge = u8g_GetHeight(lrc_u8g); chess_low_edge--; if ( U8G_MODE_GET_BITS_PER_PIXEL(u8g_GetMode(lrc_u8g)) == 1 ) { chess_boxsize = 8; chess_boxoffset = 1; } else { /* if ( u8g_GetHeight(lrc_u8g) >= 12*8 ) { chess_boxsize = 12; chess_boxoffset = 3; } else */ if ( u8g_GetHeight(lrc_u8g) >= 11*8 ) { chess_boxsize = 10; chess_boxoffset = 2; } else { chess_boxsize = 8; chess_boxoffset = 1; } if ( u8g_GetHeight(lrc_u8g) > 64 ) chess_low_edge -= (u8g_GetHeight(lrc_u8g)-chess_boxsize*8) / 2; } lrc_obj.strike_out_color = body_color; chess_SetupBoard(); } void chess_Draw(void) { if ( chess_state == CHESS_STATE_MENU ) { if ( lrc_obj.ply_count == 0) mnu_max = 2; else mnu_max = 4; mnu_Draw(); } else { chess_DrawBoard(); { uint8_t i; uint8_t entries = lrc_obj.chm_pos; if ( entries > 4 ) entries = 4; u8g_SetFont(lrc_u8g, u8g_font_5x7); u8g_SetDefaultForegroundColor(lrc_u8g); for( i = 0; i < entries; i++ ) { #if defined(DOGXL160_HW_GR) || defined(DOGXL160_HW_BW) dog_DrawStr(u8g_GetWidth(lrc_u8g)-35, u8g_GetHeight(lrc_u8g)-8*(i+1), font_5x7, cu_GetHalfMoveStr(lrc_obj.chm_pos-entries+i)); #else u8g_DrawStr(lrc_u8g, u8g_GetWidth(lrc_u8g)-35, 8*(i+1), cu_GetHalfMoveStr(lrc_obj.chm_pos-entries+i)); #endif } } if ( chess_state == CHESS_STATE_SELECT_PIECE ) mnu_DrawHome(chess_source_pos == 255); else if ( chess_state == CHESS_STATE_SELECT_TARGET_POS ) mnu_DrawHome(chess_target_pos == 255); else mnu_DrawHome(0); if ( chess_state == CHESS_STATE_GAME_END ) { switch( lrc_obj.lost_side_color ) { case COLOR_WHITE: mnu_DrawEntry(u8g_GetHeight(lrc_u8g) / 2-2, "Black wins", 1, 1); break; case COLOR_BLACK: mnu_DrawEntry(u8g_GetHeight(lrc_u8g) / 2-2, "White wins", 1, 1); break; default: mnu_DrawEntry(u8g_GetHeight(lrc_u8g) / 2-2, "Stalemate", 1, 1); break; } } } } void chess_Step(uint8_t keycode) { if ( keycode == CHESS_KEY_NONE ) { chess_key_cmd = chess_key_code; chess_key_code = CHESS_KEY_NONE; } else { chess_key_cmd = CHESS_KEY_NONE; chess_key_code = keycode; } //chess_ComputerMove(2); switch(chess_state) { case CHESS_STATE_MENU: mnu_Step(chess_key_cmd); if ( chess_key_cmd == CHESS_KEY_SELECT ) { if ( mnu_pos == 0 ) { chess_SetupBoard(); lrc_obj.orientation = 0; chess_state = CHESS_STATE_SELECT_START; } else if ( mnu_pos == 1 ) { chess_SetupBoard(); lrc_obj.orientation = 1; chess_state = CHESS_STATE_THINKING; } else if ( mnu_pos == 2 ) { if ( lrc_obj.ply_count >= 2 ) { cu_UndoHalfMove(); cu_UndoHalfMove(); lrc_obj.ply_count-=2; if ( lrc_obj.ply_count == 0 ) mnu_pos = 0; } chess_state = CHESS_STATE_SELECT_START; } else if ( mnu_pos == 3 ) { chess_state = CHESS_STATE_SELECT_START; } } break; case CHESS_STATE_SELECT_START: chess_ClearMarks(); chess_MarkMovable(); chess_source_pos = chess_GetNextMarked(255, 0); chess_target_pos = ILLEGAL_POSITION; chess_state = CHESS_STATE_SELECT_PIECE; break; case CHESS_STATE_SELECT_PIECE: if ( chess_key_cmd == CHESS_KEY_NEXT ) { chess_source_pos = chess_GetNextMarked(chess_source_pos, 0); } else if ( chess_key_cmd == CHESS_KEY_PREV ) { chess_source_pos = chess_GetNextMarked(chess_source_pos, 1); } else if ( chess_key_cmd == CHESS_KEY_SELECT ) { if ( chess_source_pos == 255 ) { chess_state = CHESS_STATE_MENU; } else { chess_ClearMarks(); chess_MarkTargetMoves(chess_source_pos); chess_target_pos = chess_GetNextMarked(255, 0); chess_state = CHESS_STATE_SELECT_TARGET_POS; } } break; case CHESS_STATE_SELECT_TARGET_POS: if ( chess_key_cmd == CHESS_KEY_NEXT ) { chess_target_pos = chess_GetNextMarked(chess_target_pos, 0); } else if ( chess_key_cmd == CHESS_KEY_PREV ) { chess_target_pos = chess_GetNextMarked(chess_target_pos, 1); } else if ( chess_key_cmd == CHESS_KEY_BACK ) { chess_ClearMarks(); chess_MarkMovable(); chess_target_pos = ILLEGAL_POSITION; chess_state = CHESS_STATE_SELECT_PIECE; } else if ( chess_key_cmd == CHESS_KEY_SELECT ) { chess_ManualMove(chess_source_pos, chess_target_pos); if ( lrc_obj.is_game_end != 0 ) chess_state = CHESS_STATE_GAME_END; else chess_state = CHESS_STATE_THINKING; /* clear marks as some kind of feedback to the user... it simply looks better */ chess_source_pos = ILLEGAL_POSITION; chess_target_pos = ILLEGAL_POSITION; chess_ClearMarks(); } break; case CHESS_STATE_THINKING: chess_ComputerMove(2); if ( lrc_obj.is_game_end != 0 ) chess_state = CHESS_STATE_GAME_END; else chess_state = CHESS_STATE_SELECT_START; break; case CHESS_STATE_GAME_END: if ( chess_key_cmd != CHESS_KEY_NONE ) { chess_state = CHESS_STATE_MENU; chess_SetupBoard(); } break; } } #endif
1
0.945495
1
0.945495
game-dev
MEDIA
0.447648
game-dev
0.926252
1
0.926252
L2Miko/L2FileEdit
1,242
data/l2asm-disasm/DAT_defs/CT2_6/npcgrp.ddf
FS = "\t"; HEADER = 1; RECCNT = OFF; MTXCNT_OUT = 1; MATCNT_OUT = 1; ORD_IGNORE = 0; { UINT tag; UNICODE class; UNICODE mesh; UINT cnt_tex1; UNICODE tex1[cnt_tex1]; UINT cnt_tex2; UNICODE tex1[cnt_tex2]; CNTR cnt_dtab1; UINT dtab1[cnt_dtab1]; FLOAT npc_speed; // UINT UNK_0; UINT unk0_cnt; UNICODE unk0_tab[unk0_cnt]; UINT cnt_snd1; UNICODE snd1[cnt_snd1]; UINT cnt_snd2; UNICODE snd2[cnt_snd2]; UINT cnt_snd3; UNICODE snd3[cnt_snd3]; UINT rb_effect_on; UNICODE rb_effect; ENBBY = [(rb_effect_on,1)]; FLOAT rb_effect_fl; ENBBY = [(rb_effect_on,1)]; CNTR unk1_cnt; UINT unk1_tab[unk1_cnt]; CNTR unk2_cnt; UINT unk2_tab[unk2_cnt]; // UINT level_lim_dn; // UINT level_lim_up; UNICODE effect; UINT UNK_3; FLOAT sound_rad; FLOAT sound_vol; FLOAT sound_rnd; UINT quest_be; UINT class_lim_?; UINT npcend_cnt; ASCF npcend[npcend_cnt]; } /* npcgrp from c5 seems to be more simple than c4's one wtf that unk_0 is just a gamble - counter or value is always 0 Interlude added something that look like a structure containing one UNICODE and one FLOAT. As it looks like enable / disable type of field only, simple on/off with enbby suffices, for now. Hard to tell what will happen in later times. */
1
0.598995
1
0.598995
game-dev
MEDIA
0.215137
game-dev
0.766269
1
0.766269
m5stack/StackFlow
1,285
projects/llm_framework/include/sherpa/sherpa-onnx/csrc/voice-activity-detector.h
// sherpa-onnx/csrc/voice-activity-detector.h // // Copyright (c) 2023 Xiaomi Corporation #ifndef SHERPA_ONNX_CSRC_VOICE_ACTIVITY_DETECTOR_H_ #define SHERPA_ONNX_CSRC_VOICE_ACTIVITY_DETECTOR_H_ #include <memory> #include <vector> #include "sherpa-onnx/csrc/vad-model-config.h" namespace sherpa_onnx { struct SpeechSegment { int32_t start; // in samples std::vector<float> samples; }; class VoiceActivityDetector { public: explicit VoiceActivityDetector(const VadModelConfig &config, float buffer_size_in_seconds = 60); template <typename Manager> VoiceActivityDetector(Manager *mgr, const VadModelConfig &config, float buffer_size_in_seconds = 60); ~VoiceActivityDetector(); void AcceptWaveform(const float *samples, int32_t n); bool Empty() const; void Pop(); void Clear(); const SpeechSegment &Front() const; bool IsSpeechDetected() const; void Reset() const; // At the end of the utterance, you can invoke this method so that // the last speech segment can be detected. void Flush() const; const VadModelConfig &GetConfig() const; private: class Impl; std::unique_ptr<Impl> impl_; }; } // namespace sherpa_onnx #endif // SHERPA_ONNX_CSRC_VOICE_ACTIVITY_DETECTOR_H_
1
0.69555
1
0.69555
game-dev
MEDIA
0.496267
game-dev
0.521041
1
0.521041
vite-pwa/vite-plugin-pwa
4,974
src/plugins/pwa-assets.ts
import type { ModuleNode, Plugin, ViteDevServer } from 'vite' import type { PWAPluginContext } from '../context' import { exactRegex } from '@rolldown/pluginutils' import { DEV_PWA_ASSETS_NAME, DEV_READY_NAME, PWA_ASSETS_HEAD_VIRTUAL, PWA_ASSETS_ICONS_VIRTUAL, RESOLVED_PWA_ASSETS_HEAD_VIRTUAL, RESOLVED_PWA_ASSETS_ICONS_VIRTUAL, } from '../constants' import { extractIcons } from '../pwa-assets/utils' export function AssetsPlugin(ctx: PWAPluginContext) { return <Plugin>{ name: 'vite-plugin-pwa:pwa-assets', enforce: 'post', transformIndexHtml: { order: 'post', async handler(html) { return await transformIndexHtmlHandler(html, ctx) }, enforce: 'post', // deprecated since Vite 4 async transform(html) { // deprecated since Vite 4 return await transformIndexHtmlHandler(html, ctx) }, }, resolveId: { filter: { id: [exactRegex(PWA_ASSETS_HEAD_VIRTUAL), exactRegex(PWA_ASSETS_ICONS_VIRTUAL)] }, handler(id) { // condition is kept for backward compatibility for below Vite v6.3 switch (true) { case id === PWA_ASSETS_HEAD_VIRTUAL: return RESOLVED_PWA_ASSETS_HEAD_VIRTUAL case id === PWA_ASSETS_ICONS_VIRTUAL: return RESOLVED_PWA_ASSETS_ICONS_VIRTUAL default: return undefined } }, }, load: { filter: { id: [exactRegex(RESOLVED_PWA_ASSETS_HEAD_VIRTUAL), exactRegex(RESOLVED_PWA_ASSETS_ICONS_VIRTUAL)] }, async handler(id) { // conditions are kept for backward compatibility for below Vite v6.3 if (id === RESOLVED_PWA_ASSETS_HEAD_VIRTUAL) { const pwaAssetsGenerator = await ctx.pwaAssetsGenerator const head = pwaAssetsGenerator?.resolveHtmlAssets() ?? { links: [], themeColor: undefined } return `export const pwaAssetsHead = ${JSON.stringify(head)}` } if (id === RESOLVED_PWA_ASSETS_ICONS_VIRTUAL) { const pwaAssetsGenerator = await ctx.pwaAssetsGenerator const icons = extractIcons(pwaAssetsGenerator?.instructions()) return `export const pwaAssetsIcons = ${JSON.stringify(icons)}` } }, }, async handleHotUpdate({ file, server }) { const pwaAssetsGenerator = await ctx.pwaAssetsGenerator if (await pwaAssetsGenerator?.checkHotUpdate(file)) { const modules: ModuleNode[] = [] const head = server.moduleGraph.getModuleById(RESOLVED_PWA_ASSETS_HEAD_VIRTUAL) head && modules.push(head) const icons = server.moduleGraph.getModuleById(RESOLVED_PWA_ASSETS_ICONS_VIRTUAL) icons && modules.push(icons) if (modules) return modules server.ws.send({ type: 'full-reload' }) return [] } }, configureServer(server) { server.ws.on(DEV_READY_NAME, createWSResponseHandler(ctx, server)) server.middlewares.use(async (req, res, next) => { const url = req.url if (!url) return next() if (!/\.(?:ico|png|svg|webp)$/.test(url)) return next() const pwaAssetsGenerator = await ctx.pwaAssetsGenerator if (!pwaAssetsGenerator) return next() const icon = await pwaAssetsGenerator.findIconAsset(url) if (!icon) return next() if (icon.age > 0) { const ifModifiedSince = req.headers['if-modified-since'] ?? req.headers['If-Modified-Since'] const useIfModifiedSince = ifModifiedSince ? Array.isArray(ifModifiedSince) ? ifModifiedSince[0] : ifModifiedSince : undefined if (useIfModifiedSince && new Date(icon.lastModified).getTime() / 1000 >= new Date(useIfModifiedSince).getTime() / 1000) { res.statusCode = 304 res.end() return } } const buffer = await icon.buffer res.setHeader('Age', icon.age / 1000) res.setHeader('Content-Type', icon.mimeType) res.setHeader('Content-Length', buffer.length) res.setHeader('Last-Modified', new Date(icon.lastModified).toUTCString()) res.statusCode = 200 res.end(buffer) }) }, } } async function transformIndexHtmlHandler(html: string, ctx: PWAPluginContext) { // dev: color-theme and icon links injected using createWSResponseHandler if (ctx.devEnvironment && ctx.options.devOptions.enabled) return html const pwaAssetsGenerator = await ctx.pwaAssetsGenerator if (!pwaAssetsGenerator) return html return pwaAssetsGenerator.transformIndexHtml(html) } function createWSResponseHandler(ctx: PWAPluginContext, server: ViteDevServer): () => Promise<void> { return async () => { const pwaAssetsGenerator = await ctx.pwaAssetsGenerator if (pwaAssetsGenerator) { const data = pwaAssetsGenerator.resolveHtmlAssets() server.ws.send({ type: 'custom', event: DEV_PWA_ASSETS_NAME, data, }) } } }
1
0.621323
1
0.621323
game-dev
MEDIA
0.610298
game-dev
0.750391
1
0.750391
Minestom/Minestom
17,657
src/main/java/net/minestom/server/ServerProcessImpl.java
package net.minestom.server; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import net.minestom.server.advancements.AdvancementManager; import net.minestom.server.adventure.bossbar.BossBarManager; import net.minestom.server.codec.StructCodec; import net.minestom.server.command.CommandManager; import net.minestom.server.component.DataComponents; import net.minestom.server.dialog.Dialog; import net.minestom.server.entity.Entity; import net.minestom.server.entity.damage.DamageType; import net.minestom.server.entity.metadata.animal.ChickenVariant; import net.minestom.server.entity.metadata.animal.CowVariant; import net.minestom.server.entity.metadata.animal.FrogVariant; import net.minestom.server.entity.metadata.animal.PigVariant; import net.minestom.server.entity.metadata.animal.tameable.CatVariant; import net.minestom.server.entity.metadata.animal.tameable.WolfSoundVariant; import net.minestom.server.entity.metadata.animal.tameable.WolfVariant; import net.minestom.server.entity.metadata.other.PaintingVariant; import net.minestom.server.event.EventDispatcher; import net.minestom.server.event.GlobalEventHandler; import net.minestom.server.event.server.ServerTickMonitorEvent; import net.minestom.server.exception.ExceptionManager; import net.minestom.server.instance.Chunk; import net.minestom.server.instance.Instance; import net.minestom.server.instance.InstanceManager; import net.minestom.server.instance.block.BlockManager; import net.minestom.server.instance.block.banner.BannerPattern; import net.minestom.server.instance.block.jukebox.JukeboxSong; import net.minestom.server.item.armor.TrimMaterial; import net.minestom.server.item.armor.TrimPattern; import net.minestom.server.item.enchant.*; import net.minestom.server.item.instrument.Instrument; import net.minestom.server.listener.manager.PacketListenerManager; import net.minestom.server.message.ChatType; import net.minestom.server.monitoring.BenchmarkManager; import net.minestom.server.monitoring.EventsJFR; import net.minestom.server.monitoring.TickMonitor; import net.minestom.server.network.ConnectionManager; import net.minestom.server.network.packet.PacketParser; import net.minestom.server.network.packet.PacketVanilla; import net.minestom.server.network.packet.client.ClientPacket; import net.minestom.server.network.socket.Server; import net.minestom.server.recipe.RecipeManager; import net.minestom.server.registry.DynamicRegistry; import net.minestom.server.scoreboard.TeamManager; import net.minestom.server.snapshot.*; import net.minestom.server.thread.Acquirable; import net.minestom.server.thread.ThreadDispatcher; import net.minestom.server.thread.ThreadProvider; import net.minestom.server.timer.SchedulerManager; import net.minestom.server.utils.PacketViewableUtils; import net.minestom.server.utils.collection.MappedCollection; import net.minestom.server.utils.time.Tick; import net.minestom.server.world.DimensionType; import net.minestom.server.world.biome.Biome; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.SocketAddress; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; final class ServerProcessImpl implements ServerProcess { private static final Logger LOGGER = LoggerFactory.getLogger(ServerProcessImpl.class); private final Auth auth; private final ExceptionManager exception; private final DynamicRegistry<StructCodec<? extends LevelBasedValue>> enchantmentLevelBasedValues; private final DynamicRegistry<StructCodec<? extends ValueEffect>> enchantmentValueEffects; private final DynamicRegistry<StructCodec<? extends EntityEffect>> enchantmentEntityEffects; private final DynamicRegistry<StructCodec<? extends LocationEffect>> enchantmentLocationEffects; private final DynamicRegistry<ChatType> chatType; private final DynamicRegistry<Dialog> dialog; private final DynamicRegistry<DimensionType> dimensionType; private final DynamicRegistry<Biome> biome; private final DynamicRegistry<DamageType> damageType; private final DynamicRegistry<TrimMaterial> trimMaterial; private final DynamicRegistry<TrimPattern> trimPattern; private final DynamicRegistry<BannerPattern> bannerPattern; private final DynamicRegistry<Enchantment> enchantment; private final DynamicRegistry<PaintingVariant> paintingVariant; private final DynamicRegistry<JukeboxSong> jukeboxSong; private final DynamicRegistry<Instrument> instrument; private final DynamicRegistry<WolfVariant> wolfVariant; private final DynamicRegistry<WolfSoundVariant> wolfSoundVariant; private final DynamicRegistry<CatVariant> catVariant; private final DynamicRegistry<ChickenVariant> chickenVariant; private final DynamicRegistry<CowVariant> cowVariant; private final DynamicRegistry<FrogVariant> frogVariant; private final DynamicRegistry<PigVariant> pigVariant; private final ConnectionManager connection; private final PacketListenerManager packetListener; private final PacketParser<ClientPacket> packetParser; private final InstanceManager instance; private final BlockManager block; private final CommandManager command; private final RecipeManager recipe; private final TeamManager team; private final GlobalEventHandler eventHandler; private final SchedulerManager scheduler; private final BenchmarkManager benchmark; private final AdvancementManager advancement; private final BossBarManager bossBar; private final Server server; private final ThreadDispatcher<Chunk, Entity> dispatcher; private final Ticker ticker; private final AtomicBoolean started = new AtomicBoolean(); private final AtomicBoolean stopped = new AtomicBoolean(); public ServerProcessImpl(Auth auth) { this.auth = auth; this.exception = new ExceptionManager(); // The order of initialization here is relevant, we must load the enchantment util registries before the vanilla data is loaded. var ignoredForInit = DataComponents.ITEM_NAME; this.enchantmentLevelBasedValues = LevelBasedValue.createDefaultRegistry(); this.enchantmentValueEffects = ValueEffect.createDefaultRegistry(); this.enchantmentEntityEffects = EntityEffect.createDefaultRegistry(); this.enchantmentLocationEffects = LocationEffect.createDefaultRegistry(); this.chatType = ChatType.createDefaultRegistry(); this.dialog = Dialog.createDefaultRegistry(this); this.dimensionType = DimensionType.createDefaultRegistry(); this.biome = Biome.createDefaultRegistry(); this.damageType = DamageType.createDefaultRegistry(); this.trimMaterial = TrimMaterial.createDefaultRegistry(); this.trimPattern = TrimPattern.createDefaultRegistry(); this.bannerPattern = BannerPattern.createDefaultRegistry(); this.enchantment = Enchantment.createDefaultRegistry(this); this.paintingVariant = PaintingVariant.createDefaultRegistry(); this.jukeboxSong = JukeboxSong.createDefaultRegistry(); this.instrument = Instrument.createDefaultRegistry(); this.wolfVariant = WolfVariant.createDefaultRegistry(); this.wolfSoundVariant = WolfSoundVariant.createDefaultRegistry(); this.catVariant = CatVariant.createDefaultRegistry(); this.chickenVariant = ChickenVariant.createDefaultRegistry(); this.cowVariant = CowVariant.createDefaultRegistry(); this.frogVariant = FrogVariant.createDefaultRegistry(); this.pigVariant = PigVariant.createDefaultRegistry(); this.connection = new ConnectionManager(); this.packetListener = new PacketListenerManager(); this.packetParser = PacketVanilla.CLIENT_PACKET_PARSER; this.instance = new InstanceManager(this); this.block = new BlockManager(); this.command = new CommandManager(); this.recipe = new RecipeManager(); this.team = new TeamManager(); this.eventHandler = new GlobalEventHandler(); this.scheduler = new SchedulerManager(); this.benchmark = new BenchmarkManager(); this.advancement = new AdvancementManager(); this.bossBar = new BossBarManager(); this.server = new Server(packetParser); this.dispatcher = ThreadDispatcher.dispatcher(ThreadProvider.counter(), ServerFlag.DISPATCHER_THREADS); this.ticker = new TickerImpl(); } @Override public Auth auth() { return auth; } @Override public ExceptionManager exception() { return exception; } @Override public DynamicRegistry<Dialog> dialog() { return dialog; } @Override public DynamicRegistry<DamageType> damageType() { return damageType; } @Override public DynamicRegistry<TrimMaterial> trimMaterial() { return trimMaterial; } @Override public DynamicRegistry<TrimPattern> trimPattern() { return trimPattern; } @Override public DynamicRegistry<BannerPattern> bannerPattern() { return bannerPattern; } @Override public DynamicRegistry<Enchantment> enchantment() { return enchantment; } @Override public DynamicRegistry<PaintingVariant> paintingVariant() { return paintingVariant; } @Override public DynamicRegistry<JukeboxSong> jukeboxSong() { return jukeboxSong; } @Override public DynamicRegistry<Instrument> instrument() { return instrument; } @Override public DynamicRegistry<WolfVariant> wolfVariant() { return wolfVariant; } @Override public DynamicRegistry<WolfSoundVariant> wolfSoundVariant() { return wolfSoundVariant; } @Override public DynamicRegistry<CatVariant> catVariant() { return catVariant; } @Override public DynamicRegistry<ChickenVariant> chickenVariant() { return chickenVariant; } @Override public DynamicRegistry<CowVariant> cowVariant() { return cowVariant; } @Override public DynamicRegistry<FrogVariant> frogVariant() { return frogVariant; } @Override public DynamicRegistry<PigVariant> pigVariant() { return pigVariant; } @Override public DynamicRegistry<StructCodec<? extends LevelBasedValue>> enchantmentLevelBasedValues() { return enchantmentLevelBasedValues; } @Override public DynamicRegistry<StructCodec<? extends ValueEffect>> enchantmentValueEffects() { return enchantmentValueEffects; } @Override public DynamicRegistry<StructCodec<? extends EntityEffect>> enchantmentEntityEffects() { return enchantmentEntityEffects; } @Override public DynamicRegistry<StructCodec<? extends LocationEffect>> enchantmentLocationEffects() { return enchantmentLocationEffects; } @Override public ConnectionManager connection() { return connection; } @Override public InstanceManager instance() { return instance; } @Override public BlockManager block() { return block; } @Override public CommandManager command() { return command; } @Override public RecipeManager recipe() { return recipe; } @Override public TeamManager team() { return team; } @Override public GlobalEventHandler eventHandler() { return eventHandler; } @Override public SchedulerManager scheduler() { return scheduler; } @Override public BenchmarkManager benchmark() { return benchmark; } @Override public AdvancementManager advancement() { return advancement; } @Override public BossBarManager bossBar() { return bossBar; } @Override public DynamicRegistry<ChatType> chatType() { return chatType; } @Override public DynamicRegistry<DimensionType> dimensionType() { return dimensionType; } @Override public DynamicRegistry<Biome> biome() { return biome; } @Override public PacketListenerManager packetListener() { return packetListener; } @Override public PacketParser<ClientPacket> packetParser() { return packetParser; } @Override public Server server() { return server; } @Override public ThreadDispatcher<Chunk, Entity> dispatcher() { return dispatcher; } @Override public Ticker ticker() { return ticker; } @Override public void start(SocketAddress socketAddress) { if (!started.compareAndSet(false, true)) { throw new IllegalStateException("Server already started"); } final String brand = MinecraftServer.getBrandName(); LOGGER.info("Starting {} ({}) server.", brand, Git.version()); switch (auth) { case Auth.Offline ignored -> LOGGER.info("Running in offline mode. Beware that this is not secure and players can impersonate each other."); case Auth.Online ignored -> LOGGER.info("Running in online mode with Mojang's authentication."); case Auth.Velocity ignored -> LOGGER.info("Running in Velocity mode with modern IP forwarding."); case Auth.Bungee bungee -> { if (bungee.guard()) { LOGGER.info("Running in BungeeCord mode, using legacy IP forwarding with Guard enabled."); } else { LOGGER.info("Running in BungeeCord mode without BungeeGuard. Be sure to configure your firewall to prevent direct connections."); } } } // Init server try { server.init(socketAddress); } catch (IOException e) { exception.handleException(e); throw new RuntimeException(e); } // Start server server.start(); LOGGER.info("{} server started successfully.", brand); // Stop the server on SIGINT if (ServerFlag.SHUTDOWN_ON_SIGNAL) Runtime.getRuntime().addShutdownHook(new Thread(this::stop)); } @Override public void stop() { if (!stopped.compareAndSet(false, true)) return; final String brand = MinecraftServer.getBrandName(); LOGGER.info("Stopping {} server.", brand); scheduler.shutdown(); connection.shutdown(); server.stop(); LOGGER.info("Shutting down all thread pools."); benchmark.disable(); dispatcher.shutdown(); LOGGER.info("{} server stopped successfully.", brand); } @Override public boolean isAlive() { return started.get() && !stopped.get(); } @Override public ServerSnapshot updateSnapshot(SnapshotUpdater updater) { List<AtomicReference<InstanceSnapshot>> instanceRefs = new ArrayList<>(); Int2ObjectOpenHashMap<AtomicReference<EntitySnapshot>> entityRefs = new Int2ObjectOpenHashMap<>(); for (Instance instance : instance.getInstances()) { instanceRefs.add(updater.reference(instance)); for (Entity entity : instance.getEntities()) { entityRefs.put(entity.getEntityId(), updater.reference(entity)); } } return new SnapshotImpl.Server(MappedCollection.plainReferences(instanceRefs), entityRefs); } private final class TickerImpl implements Ticker { @Override public void tick(long nanoTime) { var serverTickEvent = EventsJFR.newServerTick(); serverTickEvent.begin(); scheduler().processTick(); // Connection tick (let waiting clients in, send keep alives, handle configuration players packets) connection().tick(nanoTime); // Server tick (chunks/entities) serverTick(nanoTime); scheduler().processTickEnd(); // Flush all waiting packets PacketViewableUtils.flush(); // Monitoring { final double acquisitionTimeMs = Acquirable.resetAcquiringTime() / 1e6D; final double tickTimeMs = (System.nanoTime() - nanoTime) / 1e6D; final TickMonitor tickMonitor = new TickMonitor(tickTimeMs, acquisitionTimeMs); EventDispatcher.call(new ServerTickMonitorEvent(tickMonitor)); } serverTickEvent.commit(); } private void serverTick(long nanoStart) { long milliStart = TimeUnit.NANOSECONDS.toMillis(nanoStart); // Tick all instances for (Instance instance : instance().getInstances()) { try { instance.tick(milliStart); } catch (Exception e) { exception().handleException(e); } } // Tick all chunks (and entities inside) dispatcher().updateAndAwait(nanoStart); // Clear removed entities & update threads final long tickDuration = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - nanoStart); final long remainingTickDuration = Tick.SERVER_TICKS.getDuration().toNanos() - tickDuration; // the nanoTimeout for refreshThreads is the remaining tick duration dispatcher().refreshThreads(remainingTickDuration); } } }
1
0.862339
1
0.862339
game-dev
MEDIA
0.920825
game-dev
0.632371
1
0.632371
sifteo/thundercracker
29,279
emulator/src/Box2D/Dynamics/b2World.cpp
/* * Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include <Box2D/Dynamics/b2World.h> #include <Box2D/Dynamics/b2Body.h> #include <Box2D/Dynamics/b2Fixture.h> #include <Box2D/Dynamics/b2Island.h> #include <Box2D/Dynamics/Joints/b2PulleyJoint.h> #include <Box2D/Dynamics/Contacts/b2Contact.h> #include <Box2D/Dynamics/Contacts/b2ContactSolver.h> #include <Box2D/Collision/b2Collision.h> #include <Box2D/Collision/b2BroadPhase.h> #include <Box2D/Collision/Shapes/b2CircleShape.h> #include <Box2D/Collision/Shapes/b2EdgeShape.h> #include <Box2D/Collision/Shapes/b2ChainShape.h> #include <Box2D/Collision/Shapes/b2PolygonShape.h> #include <Box2D/Collision/b2TimeOfImpact.h> #include <Box2D/Common/b2Draw.h> #include <Box2D/Common/b2Timer.h> #include <new> b2World::b2World(const b2Vec2& gravity) { m_destructionListener = NULL; m_debugDraw = NULL; m_bodyList = NULL; m_jointList = NULL; m_bodyCount = 0; m_jointCount = 0; m_warmStarting = true; m_continuousPhysics = true; m_subStepping = false; m_stepComplete = true; m_allowSleep = true; m_gravity = gravity; m_flags = e_clearForces; m_inv_dt0 = 0.0f; m_contactManager.m_allocator = &m_blockAllocator; memset(&m_profile, 0, sizeof(b2Profile)); } b2World::~b2World() { // Some shapes allocate using b2Alloc. b2Body* b = m_bodyList; while (b) { b2Body* bNext = b->m_next; b2Fixture* f = b->m_fixtureList; while (f) { b2Fixture* fNext = f->m_next; f->m_proxyCount = 0; f->Destroy(&m_blockAllocator); f = fNext; } b = bNext; } } void b2World::SetDestructionListener(b2DestructionListener* listener) { m_destructionListener = listener; } void b2World::SetContactFilter(b2ContactFilter* filter) { m_contactManager.m_contactFilter = filter; } void b2World::SetContactListener(b2ContactListener* listener) { m_contactManager.m_contactListener = listener; } void b2World::SetDebugDraw(b2Draw* debugDraw) { m_debugDraw = debugDraw; } b2Body* b2World::CreateBody(const b2BodyDef* def) { b2Assert(IsLocked() == false); if (IsLocked()) { return NULL; } void* mem = m_blockAllocator.Allocate(sizeof(b2Body)); b2Body* b = new (mem) b2Body(def, this); // Add to world doubly linked list. b->m_prev = NULL; b->m_next = m_bodyList; if (m_bodyList) { m_bodyList->m_prev = b; } m_bodyList = b; ++m_bodyCount; return b; } void b2World::DestroyBody(b2Body* b) { b2Assert(m_bodyCount > 0); b2Assert(IsLocked() == false); if (IsLocked()) { return; } // Delete the attached joints. b2JointEdge* je = b->m_jointList; while (je) { b2JointEdge* je0 = je; je = je->next; if (m_destructionListener) { m_destructionListener->SayGoodbye(je0->joint); } DestroyJoint(je0->joint); b->m_jointList = je; } b->m_jointList = NULL; // Delete the attached contacts. b2ContactEdge* ce = b->m_contactList; while (ce) { b2ContactEdge* ce0 = ce; ce = ce->next; m_contactManager.Destroy(ce0->contact); } b->m_contactList = NULL; // Delete the attached fixtures. This destroys broad-phase proxies. b2Fixture* f = b->m_fixtureList; while (f) { b2Fixture* f0 = f; f = f->m_next; if (m_destructionListener) { m_destructionListener->SayGoodbye(f0); } f0->DestroyProxies(&m_contactManager.m_broadPhase); f0->Destroy(&m_blockAllocator); f0->~b2Fixture(); m_blockAllocator.Free(f0, sizeof(b2Fixture)); b->m_fixtureList = f; b->m_fixtureCount -= 1; } b->m_fixtureList = NULL; b->m_fixtureCount = 0; // Remove world body list. if (b->m_prev) { b->m_prev->m_next = b->m_next; } if (b->m_next) { b->m_next->m_prev = b->m_prev; } if (b == m_bodyList) { m_bodyList = b->m_next; } --m_bodyCount; b->~b2Body(); m_blockAllocator.Free(b, sizeof(b2Body)); } b2Joint* b2World::CreateJoint(const b2JointDef* def) { b2Assert(IsLocked() == false); if (IsLocked()) { return NULL; } b2Joint* j = b2Joint::Create(def, &m_blockAllocator); // Connect to the world list. j->m_prev = NULL; j->m_next = m_jointList; if (m_jointList) { m_jointList->m_prev = j; } m_jointList = j; ++m_jointCount; // Connect to the bodies' doubly linked lists. j->m_edgeA.joint = j; j->m_edgeA.other = j->m_bodyB; j->m_edgeA.prev = NULL; j->m_edgeA.next = j->m_bodyA->m_jointList; if (j->m_bodyA->m_jointList) j->m_bodyA->m_jointList->prev = &j->m_edgeA; j->m_bodyA->m_jointList = &j->m_edgeA; j->m_edgeB.joint = j; j->m_edgeB.other = j->m_bodyA; j->m_edgeB.prev = NULL; j->m_edgeB.next = j->m_bodyB->m_jointList; if (j->m_bodyB->m_jointList) j->m_bodyB->m_jointList->prev = &j->m_edgeB; j->m_bodyB->m_jointList = &j->m_edgeB; b2Body* bodyA = def->bodyA; b2Body* bodyB = def->bodyB; // If the joint prevents collisions, then flag any contacts for filtering. if (def->collideConnected == false) { b2ContactEdge* edge = bodyB->GetContactList(); while (edge) { if (edge->other == bodyA) { // Flag the contact for filtering at the next time step (where either // body is awake). edge->contact->FlagForFiltering(); } edge = edge->next; } } // Note: creating a joint doesn't wake the bodies. return j; } void b2World::DestroyJoint(b2Joint* j) { b2Assert(IsLocked() == false); if (IsLocked()) { return; } bool collideConnected = j->m_collideConnected; // Remove from the doubly linked list. if (j->m_prev) { j->m_prev->m_next = j->m_next; } if (j->m_next) { j->m_next->m_prev = j->m_prev; } if (j == m_jointList) { m_jointList = j->m_next; } // Disconnect from island graph. b2Body* bodyA = j->m_bodyA; b2Body* bodyB = j->m_bodyB; // Wake up connected bodies. bodyA->SetAwake(true); bodyB->SetAwake(true); // Remove from body 1. if (j->m_edgeA.prev) { j->m_edgeA.prev->next = j->m_edgeA.next; } if (j->m_edgeA.next) { j->m_edgeA.next->prev = j->m_edgeA.prev; } if (&j->m_edgeA == bodyA->m_jointList) { bodyA->m_jointList = j->m_edgeA.next; } j->m_edgeA.prev = NULL; j->m_edgeA.next = NULL; // Remove from body 2 if (j->m_edgeB.prev) { j->m_edgeB.prev->next = j->m_edgeB.next; } if (j->m_edgeB.next) { j->m_edgeB.next->prev = j->m_edgeB.prev; } if (&j->m_edgeB == bodyB->m_jointList) { bodyB->m_jointList = j->m_edgeB.next; } j->m_edgeB.prev = NULL; j->m_edgeB.next = NULL; b2Joint::Destroy(j, &m_blockAllocator); b2Assert(m_jointCount > 0); --m_jointCount; // If the joint prevents collisions, then flag any contacts for filtering. if (collideConnected == false) { b2ContactEdge* edge = bodyB->GetContactList(); while (edge) { if (edge->other == bodyA) { // Flag the contact for filtering at the next time step (where either // body is awake). edge->contact->FlagForFiltering(); } edge = edge->next; } } } // void b2World::SetAllowSleeping(bool flag) { if (flag == m_allowSleep) { return; } m_allowSleep = flag; if (m_allowSleep == false) { for (b2Body* b = m_bodyList; b; b = b->m_next) { b->SetAwake(true); } } } // Find islands, integrate and solve constraints, solve position constraints void b2World::Solve(const b2TimeStep& step) { m_profile.solveInit = 0.0f; m_profile.solveVelocity = 0.0f; m_profile.solvePosition = 0.0f; // Size the island for the worst case. b2Island island(m_bodyCount, m_contactManager.m_contactCount, m_jointCount, &m_stackAllocator, m_contactManager.m_contactListener); // Clear all the island flags. for (b2Body* b = m_bodyList; b; b = b->m_next) { b->m_flags &= ~b2Body::e_islandFlag; } for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next) { c->m_flags &= ~b2Contact::e_islandFlag; } for (b2Joint* j = m_jointList; j; j = j->m_next) { j->m_islandFlag = false; } // Build and simulate all awake islands. int32 stackSize = m_bodyCount; b2Body** stack = (b2Body**)m_stackAllocator.Allocate(stackSize * sizeof(b2Body*)); for (b2Body* seed = m_bodyList; seed; seed = seed->m_next) { if (seed->m_flags & b2Body::e_islandFlag) { continue; } if (seed->IsAwake() == false || seed->IsActive() == false) { continue; } // The seed can be dynamic or kinematic. if (seed->GetType() == b2_staticBody) { continue; } // Reset island and stack. island.Clear(); int32 stackCount = 0; stack[stackCount++] = seed; seed->m_flags |= b2Body::e_islandFlag; // Perform a depth first search (DFS) on the constraint graph. while (stackCount > 0) { // Grab the next body off the stack and add it to the island. b2Body* b = stack[--stackCount]; b2Assert(b->IsActive() == true); island.Add(b); // Make sure the body is awake. b->SetAwake(true); // To keep islands as small as possible, we don't // propagate islands across static bodies. if (b->GetType() == b2_staticBody) { continue; } // Search all contacts connected to this body. for (b2ContactEdge* ce = b->m_contactList; ce; ce = ce->next) { b2Contact* contact = ce->contact; // Has this contact already been added to an island? if (contact->m_flags & b2Contact::e_islandFlag) { continue; } // Is this contact solid and touching? if (contact->IsEnabled() == false || contact->IsTouching() == false) { continue; } // Skip sensors. bool sensorA = contact->m_fixtureA->m_isSensor; bool sensorB = contact->m_fixtureB->m_isSensor; if (sensorA || sensorB) { continue; } island.Add(contact); contact->m_flags |= b2Contact::e_islandFlag; b2Body* other = ce->other; // Was the other body already added to this island? if (other->m_flags & b2Body::e_islandFlag) { continue; } b2Assert(stackCount < stackSize); stack[stackCount++] = other; other->m_flags |= b2Body::e_islandFlag; } // Search all joints connect to this body. for (b2JointEdge* je = b->m_jointList; je; je = je->next) { if (je->joint->m_islandFlag == true) { continue; } b2Body* other = je->other; // Don't simulate joints connected to inactive bodies. if (other->IsActive() == false) { continue; } island.Add(je->joint); je->joint->m_islandFlag = true; if (other->m_flags & b2Body::e_islandFlag) { continue; } b2Assert(stackCount < stackSize); stack[stackCount++] = other; other->m_flags |= b2Body::e_islandFlag; } } b2Profile profile; island.Solve(&profile, step, m_gravity, m_allowSleep); m_profile.solveInit += profile.solveInit; m_profile.solveVelocity += profile.solveVelocity; m_profile.solvePosition += profile.solvePosition; // Post solve cleanup. for (int32 i = 0; i < island.m_bodyCount; ++i) { // Allow static bodies to participate in other islands. b2Body* b = island.m_bodies[i]; if (b->GetType() == b2_staticBody) { b->m_flags &= ~b2Body::e_islandFlag; } } } m_stackAllocator.Free(stack); { b2Timer timer; // Synchronize fixtures, check for out of range bodies. for (b2Body* b = m_bodyList; b; b = b->GetNext()) { // If a body was not in an island then it did not move. if ((b->m_flags & b2Body::e_islandFlag) == 0) { continue; } if (b->GetType() == b2_staticBody) { continue; } // Update fixtures (for broad-phase). b->SynchronizeFixtures(); } // Look for new contacts. m_contactManager.FindNewContacts(); m_profile.broadphase = timer.GetMilliseconds(); } } // Find TOI contacts and solve them. void b2World::SolveTOI(const b2TimeStep& step) { b2Island island(2 * b2_maxTOIContacts, b2_maxTOIContacts, 0, &m_stackAllocator, m_contactManager.m_contactListener); if (m_stepComplete) { for (b2Body* b = m_bodyList; b; b = b->m_next) { b->m_flags &= ~b2Body::e_islandFlag; b->m_sweep.alpha0 = 0.0f; } for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next) { // Invalidate TOI c->m_flags &= ~(b2Contact::e_toiFlag | b2Contact::e_islandFlag); c->m_toiCount = 0; c->m_toi = 1.0f; } } // Find TOI events and solve them. for (;;) { // Find the first TOI. b2Contact* minContact = NULL; float32 minAlpha = 1.0f; for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next) { // Is this contact disabled? if (c->IsEnabled() == false) { continue; } // Prevent excessive sub-stepping. if (c->m_toiCount > b2_maxSubSteps) { continue; } float32 alpha = 1.0f; if (c->m_flags & b2Contact::e_toiFlag) { // This contact has a valid cached TOI. alpha = c->m_toi; } else { b2Fixture* fA = c->GetFixtureA(); b2Fixture* fB = c->GetFixtureB(); // Is there a sensor? if (fA->IsSensor() || fB->IsSensor()) { continue; } b2Body* bA = fA->GetBody(); b2Body* bB = fB->GetBody(); b2BodyType typeA = bA->m_type; b2BodyType typeB = bB->m_type; b2Assert(typeA == b2_dynamicBody || typeB == b2_dynamicBody); bool activeA = bA->IsAwake() && typeA != b2_staticBody; bool activeB = bB->IsAwake() && typeB != b2_staticBody; // Is at least one body active (awake and dynamic or kinematic)? if (activeA == false && activeB == false) { continue; } bool collideA = bA->IsBullet() || typeA != b2_dynamicBody; bool collideB = bB->IsBullet() || typeB != b2_dynamicBody; // Are these two non-bullet dynamic bodies? if (collideA == false && collideB == false) { continue; } // Compute the TOI for this contact. // Put the sweeps onto the same time interval. float32 alpha0 = bA->m_sweep.alpha0; if (bA->m_sweep.alpha0 < bB->m_sweep.alpha0) { alpha0 = bB->m_sweep.alpha0; bA->m_sweep.Advance(alpha0); } else if (bB->m_sweep.alpha0 < bA->m_sweep.alpha0) { alpha0 = bA->m_sweep.alpha0; bB->m_sweep.Advance(alpha0); } b2Assert(alpha0 < 1.0f); int32 indexA = c->GetChildIndexA(); int32 indexB = c->GetChildIndexB(); // Compute the time of impact in interval [0, minTOI] b2TOIInput input; input.proxyA.Set(fA->GetShape(), indexA); input.proxyB.Set(fB->GetShape(), indexB); input.sweepA = bA->m_sweep; input.sweepB = bB->m_sweep; input.tMax = 1.0f; b2TOIOutput output; b2TimeOfImpact(&output, &input); // Beta is the fraction of the remaining portion of the . float32 beta = output.t; if (output.state == b2TOIOutput::e_touching) { alpha = b2Min(alpha0 + (1.0f - alpha0) * beta, 1.0f); } else { alpha = 1.0f; } c->m_toi = alpha; c->m_flags |= b2Contact::e_toiFlag; } if (alpha < minAlpha) { // This is the minimum TOI found so far. minContact = c; minAlpha = alpha; } } if (minContact == NULL || 1.0f - 10.0f * b2_epsilon < minAlpha) { // No more TOI events. Done! m_stepComplete = true; break; } // Advance the bodies to the TOI. b2Fixture* fA = minContact->GetFixtureA(); b2Fixture* fB = minContact->GetFixtureB(); b2Body* bA = fA->GetBody(); b2Body* bB = fB->GetBody(); b2Sweep backup1 = bA->m_sweep; b2Sweep backup2 = bB->m_sweep; bA->Advance(minAlpha); bB->Advance(minAlpha); // The TOI contact likely has some new contact points. minContact->Update(m_contactManager.m_contactListener); minContact->m_flags &= ~b2Contact::e_toiFlag; ++minContact->m_toiCount; // Is the contact solid? if (minContact->IsEnabled() == false || minContact->IsTouching() == false) { // Restore the sweeps. minContact->SetEnabled(false); bA->m_sweep = backup1; bB->m_sweep = backup2; bA->SynchronizeTransform(); bB->SynchronizeTransform(); continue; } bA->SetAwake(true); bB->SetAwake(true); // Build the island island.Clear(); island.Add(bA); island.Add(bB); island.Add(minContact); bA->m_flags |= b2Body::e_islandFlag; bB->m_flags |= b2Body::e_islandFlag; minContact->m_flags |= b2Contact::e_islandFlag; // Get contacts on bodyA and bodyB. b2Body* bodies[2] = {bA, bB}; for (int32 i = 0; i < 2; ++i) { b2Body* body = bodies[i]; if (body->m_type == b2_dynamicBody) { for (b2ContactEdge* ce = body->m_contactList; ce; ce = ce->next) { if (island.m_bodyCount == island.m_bodyCapacity) { break; } if (island.m_contactCount == island.m_contactCapacity) { break; } b2Contact* contact = ce->contact; // Has this contact already been added to the island? if (contact->m_flags & b2Contact::e_islandFlag) { continue; } // Only add static, kinematic, or bullet bodies. b2Body* other = ce->other; if (other->m_type == b2_dynamicBody && body->IsBullet() == false && other->IsBullet() == false) { continue; } // Skip sensors. bool sensorA = contact->m_fixtureA->m_isSensor; bool sensorB = contact->m_fixtureB->m_isSensor; if (sensorA || sensorB) { continue; } // Tentatively advance the body to the TOI. b2Sweep backup = other->m_sweep; if ((other->m_flags & b2Body::e_islandFlag) == 0) { other->Advance(minAlpha); } // Update the contact points contact->Update(m_contactManager.m_contactListener); // Was the contact disabled by the user? if (contact->IsEnabled() == false) { other->m_sweep = backup; other->SynchronizeTransform(); continue; } // Are there contact points? if (contact->IsTouching() == false) { other->m_sweep = backup; other->SynchronizeTransform(); continue; } // Add the contact to the island contact->m_flags |= b2Contact::e_islandFlag; island.Add(contact); // Has the other body already been added to the island? if (other->m_flags & b2Body::e_islandFlag) { continue; } // Add the other body to the island. other->m_flags |= b2Body::e_islandFlag; if (other->m_type != b2_staticBody) { other->SetAwake(true); } island.Add(other); } } } b2TimeStep subStep; subStep.dt = (1.0f - minAlpha) * step.dt; subStep.inv_dt = 1.0f / subStep.dt; subStep.dtRatio = 1.0f; subStep.positionIterations = 20; subStep.velocityIterations = step.velocityIterations; subStep.warmStarting = false; island.SolveTOI(subStep, bA->m_islandIndex, bB->m_islandIndex); // Reset island flags and synchronize broad-phase proxies. for (int32 i = 0; i < island.m_bodyCount; ++i) { b2Body* body = island.m_bodies[i]; body->m_flags &= ~b2Body::e_islandFlag; if (body->m_type != b2_dynamicBody) { continue; } body->SynchronizeFixtures(); // Invalidate all contact TOIs on this displaced body. for (b2ContactEdge* ce = body->m_contactList; ce; ce = ce->next) { ce->contact->m_flags &= ~(b2Contact::e_toiFlag | b2Contact::e_islandFlag); } } // Commit fixture proxy movements to the broad-phase so that new contacts are created. // Also, some contacts can be destroyed. m_contactManager.FindNewContacts(); if (m_subStepping) { m_stepComplete = false; break; } } } void b2World::Step(float32 dt, int32 velocityIterations, int32 positionIterations) { b2Timer stepTimer; // If new fixtures were added, we need to find the new contacts. if (m_flags & e_newFixture) { m_contactManager.FindNewContacts(); m_flags &= ~e_newFixture; } m_flags |= e_locked; b2TimeStep step; step.dt = dt; step.velocityIterations = velocityIterations; step.positionIterations = positionIterations; if (dt > 0.0f) { step.inv_dt = 1.0f / dt; } else { step.inv_dt = 0.0f; } step.dtRatio = m_inv_dt0 * dt; step.warmStarting = m_warmStarting; // Update contacts. This is where some contacts are destroyed. { b2Timer timer; m_contactManager.Collide(); m_profile.collide = timer.GetMilliseconds(); } // Integrate velocities, solve velocity constraints, and integrate positions. if (m_stepComplete && step.dt > 0.0f) { b2Timer timer; Solve(step); m_profile.solve = timer.GetMilliseconds(); } // Handle TOI events. if (m_continuousPhysics && step.dt > 0.0f) { b2Timer timer; SolveTOI(step); m_profile.solveTOI = timer.GetMilliseconds(); } if (step.dt > 0.0f) { m_inv_dt0 = step.inv_dt; } if (m_flags & e_clearForces) { ClearForces(); } m_flags &= ~e_locked; m_profile.step = stepTimer.GetMilliseconds(); } void b2World::ClearForces() { for (b2Body* body = m_bodyList; body; body = body->GetNext()) { body->m_force.SetZero(); body->m_torque = 0.0f; } } struct b2WorldQueryWrapper { bool QueryCallback(int32 proxyId) { b2FixtureProxy* proxy = (b2FixtureProxy*)broadPhase->GetUserData(proxyId); return callback->ReportFixture(proxy->fixture); } const b2BroadPhase* broadPhase; b2QueryCallback* callback; }; void b2World::QueryAABB(b2QueryCallback* callback, const b2AABB& aabb) const { b2WorldQueryWrapper wrapper; wrapper.broadPhase = &m_contactManager.m_broadPhase; wrapper.callback = callback; m_contactManager.m_broadPhase.Query(&wrapper, aabb); } struct b2WorldRayCastWrapper { float32 RayCastCallback(const b2RayCastInput& input, int32 proxyId) { void* userData = broadPhase->GetUserData(proxyId); b2FixtureProxy* proxy = (b2FixtureProxy*)userData; b2Fixture* fixture = proxy->fixture; int32 index = proxy->childIndex; b2RayCastOutput output; bool hit = fixture->RayCast(&output, input, index); if (hit) { float32 fraction = output.fraction; b2Vec2 point = (1.0f - fraction) * input.p1 + fraction * input.p2; return callback->ReportFixture(fixture, point, output.normal, fraction); } return input.maxFraction; } const b2BroadPhase* broadPhase; b2RayCastCallback* callback; }; void b2World::RayCast(b2RayCastCallback* callback, const b2Vec2& point1, const b2Vec2& point2) const { b2WorldRayCastWrapper wrapper; wrapper.broadPhase = &m_contactManager.m_broadPhase; wrapper.callback = callback; b2RayCastInput input; input.maxFraction = 1.0f; input.p1 = point1; input.p2 = point2; m_contactManager.m_broadPhase.RayCast(&wrapper, input); } void b2World::DrawShape(b2Fixture* fixture, const b2Transform& xf, const b2Color& color) { switch (fixture->GetType()) { case b2Shape::e_circle: { b2CircleShape* circle = (b2CircleShape*)fixture->GetShape(); b2Vec2 center = b2Mul(xf, circle->m_p); float32 radius = circle->m_radius; b2Vec2 axis = b2Mul(xf.q, b2Vec2(1.0f, 0.0f)); m_debugDraw->DrawSolidCircle(center, radius, axis, color); } break; case b2Shape::e_edge: { b2EdgeShape* edge = (b2EdgeShape*)fixture->GetShape(); b2Vec2 v1 = b2Mul(xf, edge->m_vertex1); b2Vec2 v2 = b2Mul(xf, edge->m_vertex2); m_debugDraw->DrawSegment(v1, v2, color); } break; case b2Shape::e_chain: { b2ChainShape* chain = (b2ChainShape*)fixture->GetShape(); int32 count = chain->m_count; const b2Vec2* vertices = chain->m_vertices; b2Vec2 v1 = b2Mul(xf, vertices[0]); for (int32 i = 1; i < count; ++i) { b2Vec2 v2 = b2Mul(xf, vertices[i]); m_debugDraw->DrawSegment(v1, v2, color); m_debugDraw->DrawCircle(v1, 0.05f, color); v1 = v2; } } break; case b2Shape::e_polygon: { b2PolygonShape* poly = (b2PolygonShape*)fixture->GetShape(); int32 vertexCount = poly->m_vertexCount; b2Assert(vertexCount <= b2_maxPolygonVertices); b2Vec2 vertices[b2_maxPolygonVertices]; for (int32 i = 0; i < vertexCount; ++i) { vertices[i] = b2Mul(xf, poly->m_vertices[i]); } m_debugDraw->DrawSolidPolygon(vertices, vertexCount, color); } break; default: break; } } void b2World::DrawJoint(b2Joint* joint) { b2Body* bodyA = joint->GetBodyA(); b2Body* bodyB = joint->GetBodyB(); const b2Transform& xf1 = bodyA->GetTransform(); const b2Transform& xf2 = bodyB->GetTransform(); b2Vec2 x1 = xf1.p; b2Vec2 x2 = xf2.p; b2Vec2 p1 = joint->GetAnchorA(); b2Vec2 p2 = joint->GetAnchorB(); b2Color color(0.5f, 0.8f, 0.8f); switch (joint->GetType()) { case e_distanceJoint: m_debugDraw->DrawSegment(p1, p2, color); break; case e_pulleyJoint: { b2PulleyJoint* pulley = (b2PulleyJoint*)joint; b2Vec2 s1 = pulley->GetGroundAnchorA(); b2Vec2 s2 = pulley->GetGroundAnchorB(); m_debugDraw->DrawSegment(s1, p1, color); m_debugDraw->DrawSegment(s2, p2, color); m_debugDraw->DrawSegment(s1, s2, color); } break; case e_mouseJoint: // don't draw this break; default: m_debugDraw->DrawSegment(x1, p1, color); m_debugDraw->DrawSegment(p1, p2, color); m_debugDraw->DrawSegment(x2, p2, color); } } void b2World::DrawDebugData() { if (m_debugDraw == NULL) { return; } uint32 flags = m_debugDraw->GetFlags(); if (flags & b2Draw::e_shapeBit) { for (b2Body* b = m_bodyList; b; b = b->GetNext()) { const b2Transform& xf = b->GetTransform(); for (b2Fixture* f = b->GetFixtureList(); f; f = f->GetNext()) { if (b->IsActive() == false) { DrawShape(f, xf, b2Color(0.5f, 0.5f, 0.3f)); } else if (b->GetType() == b2_staticBody) { DrawShape(f, xf, b2Color(0.5f, 0.9f, 0.5f)); } else if (b->GetType() == b2_kinematicBody) { DrawShape(f, xf, b2Color(0.5f, 0.5f, 0.9f)); } else if (b->IsAwake() == false) { DrawShape(f, xf, b2Color(0.6f, 0.6f, 0.6f)); } else { DrawShape(f, xf, b2Color(0.9f, 0.7f, 0.7f)); } } } } if (flags & b2Draw::e_jointBit) { for (b2Joint* j = m_jointList; j; j = j->GetNext()) { DrawJoint(j); } } if (flags & b2Draw::e_pairBit) { b2Color color(0.3f, 0.9f, 0.9f); for (b2Contact* c = m_contactManager.m_contactList; c; c = c->GetNext()) { //b2Fixture* fixtureA = c->GetFixtureA(); //b2Fixture* fixtureB = c->GetFixtureB(); //b2Vec2 cA = fixtureA->GetAABB().GetCenter(); //b2Vec2 cB = fixtureB->GetAABB().GetCenter(); //m_debugDraw->DrawSegment(cA, cB, color); } } if (flags & b2Draw::e_aabbBit) { b2Color color(0.9f, 0.3f, 0.9f); b2BroadPhase* bp = &m_contactManager.m_broadPhase; for (b2Body* b = m_bodyList; b; b = b->GetNext()) { if (b->IsActive() == false) { continue; } for (b2Fixture* f = b->GetFixtureList(); f; f = f->GetNext()) { for (int32 i = 0; i < f->m_proxyCount; ++i) { b2FixtureProxy* proxy = f->m_proxies + i; b2AABB aabb = bp->GetFatAABB(proxy->proxyId); b2Vec2 vs[4]; vs[0].Set(aabb.lowerBound.x, aabb.lowerBound.y); vs[1].Set(aabb.upperBound.x, aabb.lowerBound.y); vs[2].Set(aabb.upperBound.x, aabb.upperBound.y); vs[3].Set(aabb.lowerBound.x, aabb.upperBound.y); m_debugDraw->DrawPolygon(vs, 4, color); } } } } if (flags & b2Draw::e_centerOfMassBit) { for (b2Body* b = m_bodyList; b; b = b->GetNext()) { b2Transform xf = b->GetTransform(); xf.p = b->GetWorldCenter(); m_debugDraw->DrawTransform(xf); } } } int32 b2World::GetProxyCount() const { return m_contactManager.m_broadPhase.GetProxyCount(); } int32 b2World::GetTreeHeight() const { return m_contactManager.m_broadPhase.GetTreeHeight(); } int32 b2World::GetTreeBalance() const { return m_contactManager.m_broadPhase.GetTreeBalance(); } float32 b2World::GetTreeQuality() const { return m_contactManager.m_broadPhase.GetTreeQuality(); } void b2World::Dump() { if ((m_flags & e_locked) == e_locked) { return; } b2Log("b2Vec2 g(%.15lef, %.15lef);\n", m_gravity.x, m_gravity.y); b2Log("m_world->SetGravity(g);\n"); b2Log("b2Body** bodies = (b2Body**)b2Alloc(%d * sizeof(b2Body*));\n", m_bodyCount); b2Log("b2Joint** joints = (b2Joint**)b2Alloc(%d * sizeof(b2Joint*));\n", m_jointCount); int32 i = 0; for (b2Body* b = m_bodyList; b; b = b->m_next) { b->m_islandIndex = i; b->Dump(); ++i; } i = 0; for (b2Joint* j = m_jointList; j; j = j->m_next) { j->m_index = i; ++i; } // First pass on joints, skip gear joints. for (b2Joint* j = m_jointList; j; j = j->m_next) { if (j->m_type == e_gearJoint) { continue; } b2Log("{\n"); j->Dump(); b2Log("}\n"); } // Second pass on joints, only gear joints. for (b2Joint* j = m_jointList; j; j = j->m_next) { if (j->m_type != e_gearJoint) { continue; } b2Log("{\n"); j->Dump(); b2Log("}\n"); } b2Log("b2Free(joints);\n"); b2Log("b2Free(bodies);\n"); b2Log("joints = NULL;\n"); b2Log("bodies = NULL;\n"); }
1
0.972467
1
0.972467
game-dev
MEDIA
0.87244
game-dev
0.988085
1
0.988085
folgerwang/UnrealEngine
5,022
Engine/Source/Editor/HierarchicalLODOutliner/Private/HLODOutlinerDragDrop.cpp
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. #include "HLODOutlinerDragDrop.h" #include "Widgets/DeclarativeSyntaxSupport.h" #include "Engine/GameViewportClient.h" #include "Modules/ModuleManager.h" #include "Widgets/SBoxPanel.h" #include "Widgets/Layout/SBorder.h" #include "Widgets/Images/SImage.h" #include "Widgets/Text/STextBlock.h" #include "EditorStyleSet.h" #include "DragAndDrop/ActorDragDropOp.h" #include "DragAndDrop/ActorDragDropGraphEdOp.h" #include "IHierarchicalLODUtilities.h" #include "HierarchicalLODUtilitiesModule.h" #include "ITreeItem.h" HLODOutliner::FDragDropPayload::FDragDropPayload() { LODActors = TArray<TWeakObjectPtr<AActor>>(); StaticMeshActors = TArray<TWeakObjectPtr<AActor>>(); bSceneOutliner = false; } EClusterGenerationError HLODOutliner::FDragDropPayload::ParseDrag(const FDragDropOperation& Operation) { EClusterGenerationError ErrorValue = EClusterGenerationError::None; if (Operation.IsOfType<FHLODOutlinerDragDropOp>()) { bSceneOutliner = false; const auto& OutlinerOp = static_cast<const FHLODOutlinerDragDropOp&>(Operation); if (OutlinerOp.StaticMeshActorOp.IsValid()) { StaticMeshActors = OutlinerOp.StaticMeshActorOp->Actors; } if (OutlinerOp.LODActorOp.IsValid()) { LODActors = OutlinerOp.LODActorOp->Actors; } ErrorValue |= EClusterGenerationError::ValidActor; } else if (Operation.IsOfType<FActorDragDropGraphEdOp>()) { bSceneOutliner = true; int32 NumInvalidActors = 0; const auto& ActorOp = static_cast<const FActorDragDropGraphEdOp&>(Operation); for (auto& ActorPtr : ActorOp.Actors) { AActor* Actor = ActorPtr.Get(); FHierarchicalLODUtilitiesModule& Module = FModuleManager::LoadModuleChecked<FHierarchicalLODUtilitiesModule>("HierarchicalLODUtilities"); IHierarchicalLODUtilities* Utilities = Module.GetUtilities(); EClusterGenerationError ClusterGenerationResult = Utilities->ShouldGenerateCluster(Actor, INDEX_NONE); ErrorValue |= ClusterGenerationResult; if ((ClusterGenerationResult & EClusterGenerationError::ValidActor) != EClusterGenerationError::None) { if (!StaticMeshActors.IsSet()) { StaticMeshActors = TArray<TWeakObjectPtr<AActor>>(); } StaticMeshActors->Add(Actor); } else { ++NumInvalidActors; } } } return ErrorValue; } TSharedPtr<FDragDropOperation> HLODOutliner::CreateDragDropOperation(const TArray<FTreeItemPtr>& InTreeItems) { FDragDropPayload DraggedObjects; for (const auto& Item : InTreeItems) { Item->PopulateDragDropPayload(DraggedObjects); } if (DraggedObjects.LODActors.IsSet() || DraggedObjects.StaticMeshActors.IsSet()) { TSharedPtr<FHLODOutlinerDragDropOp> OutlinerOp = MakeShareable(new FHLODOutlinerDragDropOp(DraggedObjects)); OutlinerOp->Construct(); return OutlinerOp; } return nullptr; } HLODOutliner::FHLODOutlinerDragDropOp::FHLODOutlinerDragDropOp(const FDragDropPayload& DraggedObjects) : OverrideText() , OverrideIcon(nullptr) { if (DraggedObjects.StaticMeshActors) { StaticMeshActorOp = MakeShareable(new FActorDragDropOp); StaticMeshActorOp->Init(DraggedObjects.StaticMeshActors.GetValue()); } if (DraggedObjects.LODActors) { LODActorOp = MakeShareable(new FActorDragDropOp); LODActorOp->Init(DraggedObjects.LODActors.GetValue()); } } TSharedPtr<SWidget> HLODOutliner::FHLODOutlinerDragDropOp::GetDefaultDecorator() const { TSharedRef<SVerticalBox> VerticalBox = SNew(SVerticalBox); VerticalBox->AddSlot() [ SNew(SBorder) .BorderImage(FEditorStyle::GetBrush("Graph.ConnectorFeedback.Border")) .Visibility(this, &FHLODOutlinerDragDropOp::GetOverrideVisibility) .Content() [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .AutoWidth() .Padding(0.0f, 0.0f, 3.0f, 0.0f) [ SNew(SImage) .Image(this, &FHLODOutlinerDragDropOp::GetOverrideIcon) ] + SHorizontalBox::Slot() .AutoWidth() .VAlign(VAlign_Center) [ SNew(STextBlock) .Text(this, &FHLODOutlinerDragDropOp::GetOverrideText) ] ] ]; if (LODActorOp.IsValid()) { auto Content = LODActorOp->GetDefaultDecorator(); if (Content.IsValid()) { Content->SetVisibility(TAttribute<EVisibility>(this, &FHLODOutlinerDragDropOp::GetDefaultVisibility)); VerticalBox->AddSlot()[Content.ToSharedRef()]; } } if (StaticMeshActorOp.IsValid()) { auto Content = StaticMeshActorOp->GetDefaultDecorator(); if (Content.IsValid()) { Content->SetVisibility(TAttribute<EVisibility>(this, &FHLODOutlinerDragDropOp::GetDefaultVisibility)); VerticalBox->AddSlot()[Content.ToSharedRef()]; } } return VerticalBox; } EVisibility HLODOutliner::FHLODOutlinerDragDropOp::GetOverrideVisibility() const { return OverrideText.IsEmpty() && OverrideIcon == nullptr ? EVisibility::Collapsed : EVisibility::Visible; } EVisibility HLODOutliner::FHLODOutlinerDragDropOp::GetDefaultVisibility() const { return OverrideText.IsEmpty() && OverrideIcon == nullptr ? EVisibility::Visible : EVisibility::Collapsed; }
1
0.92879
1
0.92879
game-dev
MEDIA
0.790842
game-dev
0.925368
1
0.925368
DarkstarProject/darkstar
1,039
scripts/globals/mobskills/gravity_wheel.lua
--------------------------------------------- -- Gravity Wheel -- -- Description: Deals heavy damage to players in an area of effect. Additional effect: Weight -- Type: Physical -- 2-3 Shadows -- Range: Unknown --------------------------------------------- require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/monstertpmoves") --------------------------------------------- function onMobSkillCheck(target,mob,skill) if (mob:AnimationSub() == 2) then return 0 end return 1 end function onMobWeaponSkill(target, mob, skill) local numhits = 1 local accmod = 1 local dmgmod = 3 local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT) local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.PHYSICAL,dsp.damageType.SLASHING,MOBPARAM_2_SHADOW) target:takeDamage(dmg, mob, dsp.attackType.PHYSICAL, dsp.damageType.SLASHING) MobStatusEffectMove(mob, target, dsp.effect.WEIGHT, 1, 0, 30) return dmg end
1
0.812791
1
0.812791
game-dev
MEDIA
0.987838
game-dev
0.896859
1
0.896859
steviegt6/terraclient
1,528
patches/Terraclient/Terraria/GameContent/UI/Elements/UICharacterListItem.cs.patch
--- src/Terraria/Terraria/GameContent/UI/Elements/UICharacterListItem.cs +++ src/Terraclient/Terraria/GameContent/UI/Elements/UICharacterListItem.cs @@ -88,6 +_,14 @@ uIImageButton4.OnMouseOut += ButtonMouseOut; Append(uIImageButton4); num += 24f; + uIImageButton4 = new UIImageButton(_buttonRenameTexture); + uIImageButton4.VAlign = 1f; + uIImageButton4.Left.Set(num, 0f); + uIImageButton4.OnClick += CycleDifficulty; + uIImageButton4.OnMouseOver += CycleMouseOver; + uIImageButton4.OnMouseOut += ButtonMouseOut; + Append(uIImageButton4); + num += 24f; UIImageButton uIImageButton5 = new UIImageButton(_buttonDeleteTexture) { VAlign = 1f, HAlign = 1f @@ -162,6 +_,31 @@ uIVirtualKeyboard.SetMaxInputLength(20); Main.MenuUI.SetState(uIVirtualKeyboard); (base.Parent.Parent as UIList)?.UpdateOrder(); + } + + // TODO: move to partial + private void CycleMouseOver(UIMouseEvent evt, UIElement listeningElement) { + _buttonLabel.SetText(Language.GetTextValue("UI.CyclePlayerDifficulty")); + } + + private void CycleDifficulty(UIMouseEvent mouseEvent, UIElement element) { + SoundEngine.PlaySound(10); + + switch (_data.Player.difficulty) { + case 0: + case 1: + case 2: + _data.Player.difficulty++; + break; + + case 3: + _data.Player.difficulty = 0; + break; + } + + Player.SavePlayer(_data); + Main.OpenCharacterSelectUI(); + (Parent.Parent as UIList)?.UpdateOrder(); } private void OnFinishedSettingName(string name) {
1
0.870927
1
0.870927
game-dev
MEDIA
0.855135
game-dev
0.964074
1
0.964074
valence-rs/valence
4,908
crates/valence_server/src/client_command.rs
use bevy_app::prelude::*; use bevy_ecs::prelude::*; use valence_entity::entity::Flags; use valence_entity::{entity, Pose}; pub use valence_protocol::packets::play::client_command_c2s::ClientCommand; use valence_protocol::packets::play::ClientCommandC2s; use crate::event_loop::{EventLoopPreUpdate, PacketEvent}; pub struct ClientCommandPlugin; impl Plugin for ClientCommandPlugin { fn build(&self, app: &mut App) { app.add_event::<SprintEvent>() .add_event::<SneakEvent>() .add_event::<JumpWithHorseEvent>() .add_event::<LeaveBedEvent>() .add_systems(EventLoopPreUpdate, handle_client_command); } } #[derive(Event, Copy, Clone, PartialEq, Eq, Debug)] pub struct SprintEvent { pub client: Entity, pub state: SprintState, } #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub enum SprintState { Start, Stop, } #[derive(Event, Copy, Clone, PartialEq, Eq, Debug)] pub struct SneakEvent { pub client: Entity, pub state: SneakState, } #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub enum SneakState { Start, Stop, } #[derive(Event, Copy, Clone, PartialEq, Eq, Debug)] pub struct JumpWithHorseEvent { pub client: Entity, pub state: JumpWithHorseState, } #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub enum JumpWithHorseState { Start { /// The power of the horse jump in `0..=100`. power: u8, }, Stop, } #[derive(Event, Copy, Clone, PartialEq, Eq, Debug)] pub struct LeaveBedEvent { pub client: Entity, } fn handle_client_command( mut packets: EventReader<PacketEvent>, mut clients: Query<(&mut entity::Pose, &mut Flags)>, mut sprinting_events: EventWriter<SprintEvent>, mut sneaking_events: EventWriter<SneakEvent>, mut jump_with_horse_events: EventWriter<JumpWithHorseEvent>, mut leave_bed_events: EventWriter<LeaveBedEvent>, ) { for packet in packets.read() { if let Some(pkt) = packet.decode::<ClientCommandC2s>() { match pkt.action { ClientCommand::StartSneaking => { if let Ok((mut pose, mut flags)) = clients.get_mut(packet.client) { pose.0 = Pose::Sneaking; flags.set_sneaking(true); } sneaking_events.send(SneakEvent { client: packet.client, state: SneakState::Start, }); } ClientCommand::StopSneaking => { if let Ok((mut pose, mut flags)) = clients.get_mut(packet.client) { pose.0 = Pose::Standing; flags.set_sneaking(false); } sneaking_events.send(SneakEvent { client: packet.client, state: SneakState::Stop, }); } ClientCommand::LeaveBed => { leave_bed_events.send(LeaveBedEvent { client: packet.client, }); } ClientCommand::StartSprinting => { if let Ok((_, mut flags)) = clients.get_mut(packet.client) { flags.set_sprinting(true); } sprinting_events.send(SprintEvent { client: packet.client, state: SprintState::Start, }); } ClientCommand::StopSprinting => { if let Ok((_, mut flags)) = clients.get_mut(packet.client) { flags.set_sprinting(false); } sprinting_events.send(SprintEvent { client: packet.client, state: SprintState::Stop, }); } ClientCommand::StartJumpWithHorse => { jump_with_horse_events.send(JumpWithHorseEvent { client: packet.client, state: JumpWithHorseState::Start { power: pkt.jump_boost.0 as u8, }, }); } ClientCommand::StopJumpWithHorse => { jump_with_horse_events.send(JumpWithHorseEvent { client: packet.client, state: JumpWithHorseState::Stop, }); } ClientCommand::OpenHorseInventory => {} // TODO ClientCommand::StartFlyingWithElytra => { if let Ok((mut pose, _)) = clients.get_mut(packet.client) { pose.0 = Pose::FallFlying; } // TODO. } } } } }
1
0.812946
1
0.812946
game-dev
MEDIA
0.228919
game-dev
0.69478
1
0.69478
EB-wilson/Helium
8,004
src/main/kotlin/helium/ui/dialogs/ConfigLayouts.kt
package helium.ui.dialogs import arc.Core import arc.func.* import arc.graphics.Color import arc.input.KeyCode import arc.math.Mathf import arc.scene.event.HandCursorListener import arc.scene.event.InputEvent import arc.scene.event.InputListener import arc.scene.event.Touchable import arc.scene.ui.* import arc.scene.ui.layout.Cell import arc.scene.ui.layout.Table import arc.util.Strings import arc.util.Time import helium.invoke import helium.ui.UIUtils.line import helium.ui.dialogs.ModConfigDialog.ConfigLayout import helium.util.binds.CombinedKeys import mindustry.graphics.Pal import mindustry.ui.Styles import kotlin.reflect.KMutableProperty0 class ConfigSepLine( name: String, private var string: String, private var lineColor: Color = Pal.accent, private var lineColorBack: Color = Pal.accentBack ): ConfigLayout(name) { override fun build(table: Table) { table.stack( Table { t -> t.image().color(lineColor).pad(0f).grow() t.row() t.line(lineColorBack, true, 4f) }, Table { t: Table -> t.left().add(string, Styles.outlineLabel).fill().left().padLeft(5f) } ).grow().pad(-5f).padBottom(4f).padTop(4f) table.row() } } abstract class ConfigEntry(name: String) : ConfigLayout(name) { protected var str: Prov<String>? = null protected var tip: Prov<String>? = null protected var disabled = Boolp { false } init { if (Core.bundle.has("settings.tip.$name")) { tip = Prov { Core.bundle["settings.tip.$name"] } } } override fun build(table: Table) { table.left().add(Core.bundle["settings.item.$name"]).left().padLeft(4f) table.table { t: Table -> t.clip = false t.right().defaults().right().padRight(0f) if (str != null) t.add("").update { l -> l.setText(str!!.get()) } buildCfg(t) }.growX().height(60f).padRight(4f).right() if (tip != null) { table.addListener(Tooltip { ta -> ta.add( tip!!.get() ).update { l: Label -> l.setText(tip!!.get()) } }.apply { allowMobile = true }) } } abstract fun buildCfg(table: Table) } class ConfigButton( name: String, private var button: Prov<Button> ): ConfigEntry(name) { override fun buildCfg(table: Table) { table.add(button.get()).width(180f).growY().pad(4f).get().setDisabled(disabled) } } class ConfigTable( name: String, private var table: Cons<Table>, private var handler: Cons<Cell<Table>> ): ConfigEntry(name) { override fun buildCfg(table: Table) { handler[table.table { t: Table -> t.clip = false this.table[t] }] } } class ConfigKeyBind( name: String, private var getBindKey: Prov<KeyCode>, private var bindingKey: Cons<KeyCode>, ): ConfigEntry(name) { val def = getBindKey.get()!! constructor(name: String, baindField: KMutableProperty0<KeyCode>): this( name, { baindField.get() }, { baindField.set(it) } ) override fun buildCfg(table: Table) { createKeybindTable(table, getBindKey, bindingKey) { bindingKey.get(def) } } private fun createKeybindTable( table: Table, getBindKey: Prov<KeyCode>, hotKeyMethod: Cons<KeyCode>, resetMethod: Runnable ) { table.label{ getBindKey().toString() }.color(Pal.accent).left().minWidth(160f).padRight(20f) table.button("@settings.rebind", Styles.defaultt) { openDialog(false){ hotKeyMethod(it.first()) } }.width(130f) table.button("@settings.resetKey", Styles.defaultt) { resetMethod.run() }.width(130f).pad(2f).padLeft(4f) table.row() } } private fun openDialog(isCombine: Boolean, callBack: Cons<Array<KeyCode>>) { val rebindDialog = Dialog() val res = linkedSetOf<KeyCode>() var show = "" rebindDialog.cont.table{ it.add(Core.bundle["misc.pressAnyKeys".takeIf { isCombine }?:"keybind.press"]) .color(Pal.accent) if (!isCombine) return@table it.row() it.label{ show.ifBlank { Core.bundle["misc.requireInput"] } } .padTop(8f) } rebindDialog.titleTable.cells.first().pad(4f) rebindDialog.addListener(object : InputListener() { override fun touchDown(event: InputEvent, x: Float, y: Float, pointer: Int, button: KeyCode): Boolean { if (Core.app.isAndroid) { rebindDialog.hide() return false } keySet(button) return true } override fun keyDown(event: InputEvent, keycode: KeyCode): Boolean { if (keycode == KeyCode.escape) { rebindDialog.hide() return false } keySet(keycode) return true } private fun keySet(button: KeyCode) { if (!isCombine) { callBack(arrayOf(button)) rebindDialog.hide() return } if (button != KeyCode.enter) { res.add(button) show = CombinedKeys.toString(res) } else { callBack(res.toTypedArray()) rebindDialog.hide() } } override fun keyUp(event: InputEvent?, keycode: KeyCode?): Boolean { res.remove(keycode) show = CombinedKeys.toString(res) return true } }) rebindDialog.show() Time.runTask(1f) { Core.scene.setScrollFocus(rebindDialog) } } class ConfigCheck( name: String, private var click: Boolc, private var checked: Boolp ): ConfigEntry(name) { constructor(name: String, field: KMutableProperty0<Boolean>): this(name, { field.set(it) }, { field.get() }) override fun buildCfg(table: Table) { table.check("", checked.get(), click) .update { c -> c.isChecked = checked.get() } .get().also { it.setDisabled(disabled) table.touchable = Touchable.enabled table.addListener(it.clickListener) table.addListener(HandCursorListener()) it.removeListener(it.clickListener) } } } class ConfigSlider : ConfigEntry { private var slided: Floatc private var curr: Floatp private var show: Func<Float, String> private var min: Float private var max: Float private var step: Float constructor( name: String, slided: Floatc, curr: Floatp, min: Float, max: Float, step: Float ) : super(name) { var s = step this.slided = slided this.curr = curr this.min = min this.max = max this.step = s val fix: Int s %= 1f var i = 0 while (true) { if (Mathf.zero(s)) { fix = i break } s *= 10f s %= 1f i++ } this.show = Func { f -> Strings.autoFixed(f, fix) } } constructor( name: String, field: KMutableProperty0<Float>, min: Float, max: Float, step: Float ) : this(name, { field.set(it) }, { field.get() }, min, max, step) constructor( name: String, field: KMutableProperty0<Int>, min: Int, max: Int, step: Int ) : this(name, { field.set(it.toInt()) }, { field.get().toFloat() }, min.toFloat(), max.toFloat(), step.toFloat()) constructor( name: String, field: KMutableProperty0<Int>, min: Int, max: Int, step: Int, show: Func<Int, String>, ) : this( name, { field.set(it.toInt()) }, { field.get().toFloat() }, min.toFloat(), max.toFloat(), step.toFloat(), { f -> show(f.toInt()) } ) constructor( name: String, slided: Floatc, curr: Floatp, min: Float, max: Float, step: Float, show: Func<Float, String>, ) : super(name) { this.show = show this.slided = slided this.curr = curr this.min = min this.max = max this.step = step } constructor( name: String, field: KMutableProperty0<Float>, min: Float, max: Float, step: Float, show: Func<Float, String>, ) : this(name, { field.set(it) }, { field.get() }, min, max, step, show) override fun buildCfg(table: Table) { if (str == null) { table.add("").update { l: Label -> l.setText(show[curr.get()]) }.padRight(0f) } table.slider(min, max, step, curr.get(), slided).width(360f).padLeft(4f).update { s: Slider -> s.setValue(curr.get()) s.isDisabled = disabled.get() } } }
1
0.933317
1
0.933317
game-dev
MEDIA
0.626692
game-dev,desktop-app
0.960402
1
0.960402
emileb/OpenGames
4,946
opengames/src/main/jni/Doom/crispy-doom-crispy-doom-1.0/src/strife/p_telept.c
// Emacs style mode select -*- C++ -*- //----------------------------------------------------------------------------- // // Copyright(C) 1993-1996 Id Software, Inc. // Copyright(C) 2005 Simon Howard // // 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. // // DESCRIPTION: // Teleportation. // //----------------------------------------------------------------------------- #include "doomdef.h" #include "doomstat.h" #include "s_sound.h" #include "p_local.h" // Data. #include "sounds.h" // State. #include "r_state.h" // // TELEPORTATION // // haleyjd 09/22/10: [STRIFE] Modified to take a flags parameter to control // silent teleportation. Rogue also removed the check for missiles, and the // z-set was replaced with one in P_TeleportMove. // int EV_Teleport ( line_t* line, int side, mobj_t* thing, teleflags_e flags) { int i; int tag; mobj_t* m; mobj_t* fog = NULL; unsigned an; thinker_t* thinker; sector_t* sector; fixed_t oldx; fixed_t oldy; fixed_t oldz; // haleyjd 20110205 [STRIFE]: this is not checked here // don't teleport missiles //if (thing->flags & MF_MISSILE) // return 0; // Don't teleport if hit back of line, // so you can get out of teleporter. if (side == 1) return 0; tag = line->tag; for (i = 0; i < numsectors; i++) { if (sectors[ i ].tag == tag ) { thinker = thinkercap.next; for (thinker = thinkercap.next; thinker != &thinkercap; thinker = thinker->next) { // not a mobj if (thinker->function.acp1 != (actionf_p1)P_MobjThinker) continue; m = (mobj_t *)thinker; // not a teleportman if (m->type != MT_TELEPORTMAN ) continue; sector = m->subsector->sector; // wrong sector if (sector-sectors != i ) continue; oldx = thing->x; oldy = thing->y; oldz = thing->z; if (!P_TeleportMove (thing, m->x, m->y)) return 0; // fraggle: this was changed in final doom, // problem between normal doom2 1.9 and final doom // // Note that although chex.exe is based on Final Doom, // it does not have this quirk. // // haleyjd 20110205 [STRIFE] This code is *not* present, // because of a z-set which Rogue added to P_TeleportMove. /* if (gameversion < exe_final || gameversion == exe_chex) thing->z = thing->floorz; */ if (thing->player) thing->player->viewz = thing->z+thing->player->viewheight; // spawn teleport fog at source and destination // haleyjd 09/22/10: [STRIFE] controlled by teleport flags // BUG: Behavior would be undefined if this function were passed // any combination of teleflags that has the NO*FOG but not the // corresponding NO*SND flag - fortunately this is never done // anywhere in the code. if(!(flags & TF_NOSRCFOG)) fog = P_SpawnMobj (oldx, oldy, oldz, MT_TFOG); if(!(flags & TF_NOSRCSND)) S_StartSound (fog, sfx_telept); an = m->angle >> ANGLETOFINESHIFT; if(!(flags & TF_NODSTFOG)) fog = P_SpawnMobj (m->x+20*finecosine[an], m->y+20*finesine[an], thing->z, MT_TFOG); if(!(flags & TF_NODSTSND)) S_StartSound (fog, sfx_telept); // don't move for a bit if (thing->player) thing->reactiontime = 18; thing->angle = m->angle; thing->momx = thing->momy = thing->momz = 0; return 1; } } } return 0; }
1
0.67726
1
0.67726
game-dev
MEDIA
0.957235
game-dev
0.963188
1
0.963188
blurite/rsprot
1,381
protocol/osrs-232/osrs-232-model/src/main/kotlin/net/rsprot/protocol/game/incoming/messaging/MessagePrivate.kt
package net.rsprot.protocol.game.incoming.messaging import net.rsprot.protocol.ClientProtCategory import net.rsprot.protocol.game.incoming.GameClientProtCategory import net.rsprot.protocol.message.IncomingGameMessage /** * Message private events are sent when a player writes a private * message to the target player. The server is responsible for looking * up the target player and forwarding the message to them, if possible. * @property name the name of the recipient of this private message * @property message the message forwarded to the recipient */ public class MessagePrivate( public val name: String, public val message: String, ) : IncomingGameMessage { override val category: ClientProtCategory get() = GameClientProtCategory.USER_EVENT override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as MessagePrivate if (name != other.name) return false if (message != other.message) return false return true } override fun hashCode(): Int { var result = name.hashCode() result = 31 * result + message.hashCode() return result } override fun toString(): String = "MessagePrivate(" + "name='$name', " + "message='$message'" + ")" }
1
0.665564
1
0.665564
game-dev
MEDIA
0.362788
game-dev
0.643046
1
0.643046
ProjectIgnis/CardScripts
4,628
unofficial/c95000023.lua
--Numeron Network local s,id=GetID() function s.initial_effect(c) --activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) c:RegisterEffect(e1) -- local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetCode(EFFECT_INDESTRUCTABLE_COUNT) e2:SetRange(LOCATION_SZONE) e2:SetCountLimit(2) e2:SetValue(s.valcon) c:RegisterEffect(e2) --activate 2 local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(id,0)) e3:SetType(EFFECT_TYPE_QUICK_O) e3:SetCode(EVENT_FREE_CHAIN) e3:SetRange(LOCATION_SZONE) e3:SetCondition(s.accon) e3:SetCost(s.accost) e3:SetOperation(s.acop) c:RegisterEffect(e3) local e6=Effect.CreateEffect(c) e6:SetDescription(aux.Stringid(93016201,0)) e6:SetType(EFFECT_TYPE_QUICK_O) e6:SetCode(EVENT_SUMMON) e6:SetRange(LOCATION_SZONE) e6:SetCondition(s.accon) e6:SetTarget(s.accost) e6:SetOperation(s.acop) c:RegisterEffect(e6) local e7=e6:Clone() e7:SetCode(EVENT_SPSUMMON) c:RegisterEffect(e7) local e8=e6:Clone() e8:SetCode(EVENT_FLIP_SUMMON) c:RegisterEffect(e8) local chain=Duel.GetCurrentChain copychain=0 Duel.GetCurrentChain=function() if copychain==1 then copychain=0 return chain()-1 else return chain() end end end s.mark=0 function s.valcon(e,re,r,rp) return (r&REASON_EFFECT)~=0 end function s.accon(e,tp,eg,ep,ev,re,r,rp) return Duel.GetFieldGroupCount(tp,LOCATION_ONFIELD,0)<=1 end function s.cfilter(c,e,tp,eg,ep,ev,re,r,rp,chain,chk) local te=c:GetActivateEffect() if not te or not c:IsSpellTrap() or not c:IsAbleToGraveAsCost() then return false end local condition=te:GetCondition() local cost=te:GetCost() local target=te:GetTarget() if te:GetCode()==EVENT_CHAINING then if chain<=0 then return false end local te2=Duel.GetChainInfo(chain,CHAININFO_TRIGGERING_EFFECT) local tc=te2:GetHandler() local g=Group.FromCards(tc) local p=tc:GetControler() return (not condition or condition(e,tp,g,p,chain,te2,REASON_EFFECT,p)) and (not cost or cost(e,tp,g,p,chain,te2,REASON_EFFECT,p,0)) and (not target or target(e,tp,g,p,chain,te2,REASON_EFFECT,p,0)) elseif (te:GetCode()==EVENT_SPSUMMON or te:GetCode()==EVENT_SUMMON or te:GetCode()==EVENT_FLIP_SUMMON or te:GetCode()==EVENT_FREE_CHAIN) and te:GetCode()==e:GetCode() then if chk then copychain=1 end return (not condition or condition(e,tp,eg,ep,ev,re,r,rp)) and (not cost or cost(e,tp,eg,ep,ev,re,r,rp,0)) and (not target or target(e,tp,eg,ep,ev,re,r,rp,0)) else local res,teg,tep,tev,tre,tr,trp=Duel.CheckEvent(te:GetCode(),true) return res and (not condition or condition(e,tp,teg,tep,tev,tre,tr,trp)) and (not cost or cost(e,tp,teg,tep,tev,tre,tr,trp,0)) and (not target or target(e,tp,teg,tep,tev,tre,tr,trp,0)) end end function s.accost(e,tp,eg,ep,ev,re,r,rp,chk) local chain=Duel.GetCurrentChain() if chk==0 then return Duel.IsExistingMatchingCard(s.cfilter,tp,LOCATION_HAND|LOCATION_DECK,0,1,nil,e,tp,eg,ep,ev,re,r,rp,chain) end chain=chain-1 Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE) local g=Duel.SelectMatchingCard(tp,s.cfilter,tp,LOCATION_HAND|LOCATION_DECK,0,1,1,nil,e,tp,eg,ep,ev,re,r,rp,chain,true) copychain=0 Duel.SendtoGrave(g,REASON_COST) Duel.SetTargetCard(g:GetFirst()) end function s.acop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc then local te=tc:GetActivateEffect() if not te then return end e:SetCategory(te:GetCategory()) e:SetProperty(te:GetProperty()) local co=te:GetCost() local tg=te:GetTarget() local op=te:GetOperation() local res,teg,tep,tev,tre,tr,trp if te:GetCode()==EVENT_CHAINING then local chain=Duel.GetCurrentChain()-1 local te2=Duel.GetChainInfo(chain,CHAININFO_TRIGGERING_EFFECT) local tc=te2:GetHandler() local g=Group.FromCards(tc) local p=tc:GetControler() teg,tep,tev,tre,tr,trp=g,p,chain,te2,REASON_EFFECT,p elseif te:GetCode()==EVENT_SUMMON or te:GetCode()==EVENT_FLIP_SUMMON or te:GetCode()==EVENT_SPSUMMON or te:GetCode()==EVENT_FREE_CHAIN then teg,tep,tev,tre,tr,trp=eg,ep,ev,re,r,rp else res,teg,tep,tev,tre,tr,trp=Duel.CheckEvent(te:GetCode(),true) end e:GetHandler():CreateEffectRelation(te) if co then co(e,tp,teg,tep,tev,tre,tr,trp,1) end if tg then tg(e,tp,teg,tep,tev,tre,tr,trp,1) end Duel.BreakEffect() local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS) local etc=g:GetFirst() while etc do etc:CreateEffectRelation(te) etc=g:GetNext() end if op then op(e,tp,teg,tep,tev,tre,tr,trp) end e:GetHandler():ReleaseEffectRelation(te) etc=g:GetFirst() while etc do etc:ReleaseEffectRelation(te) etc=g:GetNext() end end end
1
0.821177
1
0.821177
game-dev
MEDIA
0.870605
game-dev
0.925329
1
0.925329
orts/server
5,197
data/actions/scripts/tools/skinning.lua
local config = { [5908] = { -- Minotaurs [2830] = {value = 25000, newItem = 5878}, [2871] = {value = 25000, newItem = 5878}, [2866] = {value = 25000, newItem = 5878}, [2876] = {value = 25000, newItem = 5878}, [3090] = {value = 25000, newItem = 5878}, [23463] = {value = 25000, newItem = 5878}, [23467] = {value = 25000, newItem = 5878}, [23471] = {value = 25000, newItem = 5878}, -- Low Class Lizards [4259] = {value = 25000, newItem = 5876}, [4262] = {value = 25000, newItem = 5876}, [4256] = {value = 25000, newItem = 5876}, -- High Class Lizards [11288] = {value = 25000, newItem = 5876}, [11280] = {value = 25000, newItem = 5876}, [11272] = {value = 25000, newItem = 5876}, [11284] = {value = 25000, newItem = 5876}, -- Dragons [3104] = {value = 25000, newItem = 5877}, [2844] = {value = 25000, newItem = 5877}, -- Dragon Lords [2881] = {value = 25000, newItem = 5948}, -- Behemoths [2931] = {value = 35000, newItem = 5893}, -- Bone Beasts [3031] = {value = 25000, newItem = 5925}, -- The Mutated Pumpkin [8961] = { { value = 5000, newItem = 7487 }, { value = 10000, newItem = 7737 }, { value = 20000, 6492 }, { value = 30000, newItem = 8860 }, { value = 45000, newItem = 2683 }, { value = 60000, newItem = 2096 }, { value = 90000, newItem = 9005, amount = 50 } }, -- Marble [11343] = { {value = 10000, newItem = 11345, desc = "This shoddy work was made by |PLAYERNAME|." }, {value = 35000, newItem = 11345, desc = "This little figurine made by |PLAYERNAME| has some room for improvement." }, { value = 60000, newItem = 11346, desc = "This little figurine of Tibiasula was masterfully sculpted by |PLAYERNAME|." } }, -- Ice Cube [7441] = {value = 25000, newItem = 7442}, [7442] = {value = 25000, newItem = 7444}, [7444] = {value = 25000, newItem = 7445}, [7445] = {value = 25000, newItem = 7446}, }, [5942] = { -- Demon [2916] = {value = 25000, newItem = 5906}, -- Vampires [2956] = {value = 25000, newItem = 5905}, [9654] = {value = 25000, newItem = 5905, after = 9658}, [8938] = {value = 25000, newItem = 5905}, [21275] = {value = 25000, newItem= 5905} } } function onUse(player, item, fromPosition, target, toPosition, isHotkey) local skin = config[item.itemid][target.itemid] -- Wrath of the emperor quest if item.itemid == 5908 and target.itemid == 12295 then target:transform(12287) player:say("You carve a solid bowl of the chunk of wood.", TALKTYPE_MONSTER_SAY) -- An Interest In Botany Quest elseif item.itemid == 5908 and target.itemid == 11691 and player:getItemCount(12655) > 0 and player:getStorageValue(Storage.TibiaTales.AnInterestInBotany) == 1 then player:say("The plant feels cold but dry and very soft. You streak the plant gently with your knife and put a fragment in the almanach.", TALKTYPE_MONSTER_SAY) player:setStorageValue(Storage.TibiaTales.AnInterestInBotany, 2) elseif item.itemid == 5908 and target.itemid == 11653 and player:getItemCount(12655) > 0 and player:getStorageValue(Storage.TibiaTales.AnInterestInBotany) == 2 then player:say("You cut a leaf from a branch and put it in the almanach. It smells strangely sweet and awfully bitter at the same time.", TALKTYPE_MONSTER_SAY) player:setStorageValue(Storage.TibiaTales.AnInterestInBotany, 3) end if not skin then player:sendCancelMessage(RETURNVALUE_NOTPOSSIBLE) return true end local random, effect, transform = math.random(1, 100000), CONST_ME_MAGIC_GREEN, true if type(skin[1]) == 'table' then local added = false local _skin for i = 1, #skin do _skin = skin[i] if random <= _skin.value then if target.itemid == 11343 then effect = CONST_ME_ICEAREA local gobletItem = player:addItem(_skin.newItem, _skin.amount or 1) if gobletItem then gobletItem:setDescription(_skin.desc:gsub('|PLAYERNAME|', player:getName())) end added = true elseif isInArray({7441, 7442, 7444, 7445}, target.itemid) then player:addItem(_skin.newItem, _skin.amount or 1) effect = CONST_ME_HITAREA added = true else player:addItem(_skin.newItem, _skin.amount or 1) added = true end break end end if not added and target.itemid == 8961 then effect = CONST_ME_POFF transform = false end elseif random <= skin.value then if target.itemid == 11343 then effect = CONST_ME_ICEAREA local gobletItem = player:addItem(skin.newItem, skin.amount or 1) if gobletItem then gobletItem:setDescription(skin.desc:gsub('|PLAYERNAME|', player:getName())) end elseif isInArray({7441, 7442, 7444, 7445}, target.itemid) then if skin.newItem == 7446 then player:addAchievement('Ice Sculptor') end player:addItem(skin.newItem, skin.amount or 1) effect = CONST_ME_HITAREA else player:addItem(skin.newItem, skin.amount or 1) end else if isInArray({7441, 7442, 7444, 7445}, target.itemid) then player:say('The attempt of sculpting failed miserably.', TALKTYPE_MONSTER_SAY) effect = CONST_ME_HITAREA else effect = CONST_ME_POFF end end toPosition:sendMagicEffect(effect) if transform then target:transform(skin.after or target.itemid + 1) end return true end
1
0.636334
1
0.636334
game-dev
MEDIA
0.938398
game-dev
0.919883
1
0.919883
ProjectTSB/TheSkyBlessing
3,166
TheSkyBlessing/data/mob_manager/functions/entity_finder/player_hurt_entity/fetch_entity.mcfunction
#> mob_manager:entity_finder/player_hurt_entity/fetch_entity # # 多分このfunctionの実行者は攻撃したEntityであるはず # # @within function mob_manager:entity_finder/player_hurt_entity/filters/0 #> Private # @within function # mob_manager:entity_finder/player_hurt_entity/fetch_entity # mob_manager:entity_finder/player_hurt_entity/make_attack_event_data #declare score_holder $Damage # ダメージ種別取得 execute if entity @p[tag=AttackedPlayer,advancements={mob_manager:entity_finder/check_player_hurt_entity={type-melee=true}}] run data modify storage mob_manager:entity_finder DamageType set value "vanilla_melee" execute if entity @p[tag=AttackedPlayer,advancements={mob_manager:entity_finder/check_player_hurt_entity={type-projectile=true}}] run data modify storage mob_manager:entity_finder DamageType set value "vanilla_projectile" execute if entity @p[tag=AttackedPlayer,advancements={mob_manager:entity_finder/check_player_hurt_entity={type-explosion=true}}] run data modify storage mob_manager:entity_finder DamageType set value "vanilla_explosion" execute if entity @p[tag=AttackedPlayer,advancements={mob_manager:entity_finder/check_player_hurt_entity={type-other=true}}] run data modify storage mob_manager:entity_finder DamageType set value "vanilla_other" # ダメージ取得 execute store result score $Damage Temporary run data get entity @s Health 100 scoreboard players remove $Damage Temporary 51200 scoreboard players operation $Damage Temporary *= $-1 Const # ArtifactEvents にデータ追加 data modify storage mob_manager:entity_finder AttackEventData set from storage oh_my_dat: _[-4][-4][-4][-4][-4][-4][-4][-4].ArtifactEvents.Attack[{IsVanilla:true}] data remove storage oh_my_dat: _[-4][-4][-4][-4][-4][-4][-4][-4].ArtifactEvents.Attack[{IsVanilla:true}] execute unless data storage mob_manager:entity_finder AttackEventData run data modify storage mob_manager:entity_finder AttackEventData set value {IsVanilla:true} data modify storage mob_manager:entity_finder AttackEventData.Type set from storage mob_manager:entity_finder DamageType data modify storage mob_manager:entity_finder AttackEventData.Amounts append value -1d execute store result storage mob_manager:entity_finder AttackEventData.Amounts[-1] double 0.01 run scoreboard players get $Damage Temporary data modify storage mob_manager:entity_finder AttackEventData.To append value -1 execute store result storage mob_manager:entity_finder AttackEventData.To[-1] int 1 run scoreboard players get @s MobUUID data modify storage oh_my_dat: _[-4][-4][-4][-4][-4][-4][-4][-4].ArtifactEvents.Attack append from storage mob_manager:entity_finder AttackEventData # 攻撃された Entity に hurt イベントを push する function api:mob/apply_to_forward_target/with_non-idempotent.m {CB:"mob_manager:entity_finder/player_hurt_entity/push_hurt_event",Key:"mob_manager:entity_finder/player_hurt_entity/fetch_entity",IsForwardedOnly:false} # 体力をもとに戻す data modify entity @s Health set value 512f # リセット data remove storage mob_manager:entity_finder AttackEventData data remove storage mob_manager:entity_finder DamageType scoreboard players reset $Damage Temporary
1
0.9595
1
0.9595
game-dev
MEDIA
0.993692
game-dev
0.861984
1
0.861984
PaperMC/Paper
2,050
paper-api/src/main/java/com/destroystokyo/paper/event/entity/WitchThrowPotionEvent.java
package com.destroystokyo.paper.event.entity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Witch; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; import org.bukkit.event.entity.EntityEvent; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.ApiStatus; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; /** * Fired when a witch throws a potion at a player */ @NullMarked public class WitchThrowPotionEvent extends EntityEvent implements Cancellable { private static final HandlerList HANDLER_LIST = new HandlerList(); private final LivingEntity target; private @Nullable ItemStack potion; private boolean cancelled; @ApiStatus.Internal public WitchThrowPotionEvent(final Witch witch, final LivingEntity target, final @Nullable ItemStack potion) { super(witch); this.target = target; this.potion = potion; } @Override public Witch getEntity() { return (Witch) super.getEntity(); } /** * @return The target of the potion */ public LivingEntity getTarget() { return this.target; } /** * @return The potion the witch will throw at a player */ public @Nullable ItemStack getPotion() { return this.potion; } /** * Sets the potion to be thrown at a player * * @param potion The potion */ public void setPotion(final @Nullable ItemStack potion) { this.potion = potion != null ? potion.clone() : null; } /** * @return Event was cancelled or potion was {@code null} */ @Override public boolean isCancelled() { return this.cancelled || this.potion == null; } @Override public void setCancelled(final boolean cancel) { this.cancelled = cancel; } @Override public HandlerList getHandlers() { return HANDLER_LIST; } public static HandlerList getHandlerList() { return HANDLER_LIST; } }
1
0.820197
1
0.820197
game-dev
MEDIA
0.959833
game-dev
0.925807
1
0.925807
magefree/mage
1,237
Mage.Sets/src/mage/cards/h/HyraxTowerScout.java
package mage.cards.h; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.EntersBattlefieldTriggeredAbility; import mage.abilities.effects.common.UntapTargetEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.target.common.TargetCreaturePermanent; import java.util.UUID; /** * @author TheElk801 */ public final class HyraxTowerScout extends CardImpl { public HyraxTowerScout(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{2}{G}"); this.subtype.add(SubType.HUMAN); this.subtype.add(SubType.SCOUT); this.power = new MageInt(3); this.toughness = new MageInt(3); // When Hyrax Tower Scout enters the battlefield, untap target creature. Ability ability = new EntersBattlefieldTriggeredAbility(new UntapTargetEffect()); ability.addTarget(new TargetCreaturePermanent()); this.addAbility(ability); } private HyraxTowerScout(final HyraxTowerScout card) { super(card); } @Override public HyraxTowerScout copy() { return new HyraxTowerScout(this); } }
1
0.832707
1
0.832707
game-dev
MEDIA
0.858797
game-dev
0.990769
1
0.990769
smart-fm/simmobility-prod
1,811
dev/Basic/medium/entities/roles/waitTaxiActivity/WaitTaxiActivityFacets.cpp
/* * WaitTaxiActivityFacets.cpp * * Created on: Nov 28, 2016 * Author: zhang huai peng */ #include "WaitTaxiActivityFacets.hpp" #include "WaitTaxiActivity.hpp" #include "conf/ConfigManager.hpp" #include "conf/ConfigParams.hpp" namespace sim_mob { namespace medium { WaitTaxiActivityBehavior::WaitTaxiActivityBehavior() : BehaviorFacet(), waitTaxiActivity(nullptr) { } WaitTaxiActivityBehavior::~WaitTaxiActivityBehavior() { } WaitTaxiActivityMovement::WaitTaxiActivityMovement() : MovementFacet(), waitTaxiActivity(nullptr) { } WaitTaxiActivityMovement::~WaitTaxiActivityMovement() { } void WaitTaxiActivityMovement::setWaitTaxiActivity(WaitTaxiActivity* activity) { waitTaxiActivity = activity; } void WaitTaxiActivityBehavior::setWaitTaxiActivity(WaitTaxiActivity* activity) { waitTaxiActivity = activity; } void WaitTaxiActivityMovement::frame_init() { if(waitTaxiActivity) { UpdateParams& params = waitTaxiActivity->getParams(); Person* person = waitTaxiActivity->parent; person->setStartTime(params.now.ms()); } } void WaitTaxiActivityMovement::frame_tick() { unsigned int tickMS = ConfigManager::GetInstance().FullConfig().baseGranMS(); if(waitTaxiActivity) { waitTaxiActivity->increaseWaitingTime(tickMS); waitTaxiActivity->setTravelTime(waitTaxiActivity->getWaitingTime()); } waitTaxiActivity->parent->setRemainingTimeThisTick(0); } std::string WaitTaxiActivityMovement::frame_tick_output() { return std::string(); } Conflux* WaitTaxiActivityMovement::getStartingConflux() const { return nullptr; } TravelMetric& WaitTaxiActivityMovement::startTravelTimeMetric() { return travelMetric; } TravelMetric& WaitTaxiActivityMovement::finalizeTravelTimeMetric() { return travelMetric; } } }
1
0.724487
1
0.724487
game-dev
MEDIA
0.255041
game-dev
0.638123
1
0.638123
Dwarf-Therapist/Dwarf-Therapist
9,937
src/uniform.cpp
/* Dwarf Therapist Copyright (c) 2009 Trey Stout (chmod) 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 "uniform.h" #include "item.h" #include "itemuniform.h" #include "itemdefuniform.h" Uniform::Uniform(DFInstance *df, QObject *parent) : QObject(parent) , m_df(df) , m_first_check(true) { } Uniform::~Uniform() { foreach (const QList<ItemDefUniform*> &list, m_uniform_items) { foreach (ItemDefUniform* def, list) { delete def; } } } void Uniform::add_uniform_item(ITEM_TYPE itype, short sub_type, short job_skill, int count){ ItemDefUniform *uItem = new ItemDefUniform(itype,sub_type,job_skill,this); add_uniform_item(itype,uItem,count); } void Uniform::add_uniform_item(ITEM_TYPE itype, short sub_type, QList<int> job_skills, int count){ ItemDefUniform *uItem = new ItemDefUniform(itype,sub_type,job_skills,this); add_uniform_item(itype,uItem,count); } void Uniform::add_uniform_item(VIRTADDR addr, ITEM_TYPE itype, int count){ ItemDefUniform *uItem; //backpacks, quivers and flasks are assigned specific items, so pass the id number rather than an address if(!Item::is_supplies(itype) && !Item::is_ranged_equipment(itype)){ uItem = new ItemDefUniform(m_df,addr,this); }else{ uItem = new ItemDefUniform(itype,m_df->read_int(addr),this); } add_uniform_item(itype,uItem,count); } void Uniform::add_uniform_item(ITEM_TYPE itype, ItemDefUniform *uItem, int count){ //if there's no item type, this indicates that it's a specifically chosen item, so reset the item type so we can find it later if(uItem->item_type() == NONE) uItem->item_type(itype); uItem->add_to_stack(count-1); //uniform item stack size start at 1 m_uniform_items[itype].append(uItem); //assigning boots to a uniform only lists one item, but if (uItem->id() <= 0 && (itype == SHOES || itype == GLOVES)) m_uniform_items[itype].append(new ItemDefUniform(*uItem)); if (count > 0) add_equip_count(itype,count); uItem = 0; } void Uniform::add_equip_count(ITEM_TYPE itype, int count){ int current_count = m_equip_counts.value(itype); if(itype == SHOES || itype == GLOVES) count *=2; m_equip_counts.insert(itype,current_count+count); //add group counts as well if(Item::is_melee_equipment(itype)) add_equip_count(MELEE_EQUIPMENT,count); else if(Item::is_supplies(itype)) add_equip_count(SUPPLIES,count); else if(Item::is_ranged_equipment(itype)) add_equip_count(RANGED_EQUIPMENT,count); } void Uniform::clear(){ m_equip_counts.clear(); m_missing_items.clear(); m_first_check = true; } int Uniform::get_remaining_required(ITEM_TYPE itype){ int count = 0; foreach(ITEM_TYPE key, m_uniform_items.uniqueKeys()){ QList<ItemDefUniform*> items = m_uniform_items.value(key); foreach(ItemDefUniform *u, items){ if(u->get_stack_size() > 0 && (u->item_type() == itype || Item::type_in_group(itype,u->item_type()))) count += u->get_stack_size(); } } return count; } int Uniform::get_missing_equip_count(ITEM_TYPE itype){ int count = 0; if(m_missing_items.count() == 0) return count; if(m_missing_counts.count() <= 0){ load_missing_counts(); } return m_missing_counts.value(itype); } void Uniform::load_missing_counts(){ //ensure we have a NONE and group counts m_missing_counts.insert(NONE,0); m_missing_counts.insert(MELEE_EQUIPMENT,0); m_missing_counts.insert(RANGED_EQUIPMENT,0); m_missing_counts.insert(SUPPLIES,0); foreach(ITEM_TYPE itype, m_missing_items.uniqueKeys()){ foreach(ItemDefUniform *item_miss, m_missing_items.value(itype)){ int missing_count = m_missing_counts.value(itype,0); int item_qty = item_miss->get_stack_size(); if(item_qty > 0){ missing_count += item_qty; m_missing_counts[NONE] += item_qty; //add group counts as well if(Item::is_melee_equipment(itype)) m_missing_counts[MELEE_EQUIPMENT] += item_qty; else if(Item::is_supplies(itype)) m_missing_counts[SUPPLIES] += item_qty; else if(Item::is_ranged_equipment(itype)) m_missing_counts[RANGED_EQUIPMENT] += item_qty; } m_missing_counts.insert(itype,missing_count); } } } float Uniform::get_uniform_rating(ITEM_TYPE itype){ float rating = 100; if(m_first_check) return rating; float required = 0; float missing = get_missing_equip_count(itype); if(itype != NONE){ required = (float)m_equip_counts.value(itype); }else{ foreach(ITEM_TYPE i,m_equip_counts.uniqueKeys()){ if(i < NUM_OF_ITEM_TYPES) required += m_equip_counts.value(i,0); } } if(required <= 0) required = 1; rating = (required-missing) / required * 100.0f; if(rating > 100) rating = 100.0f; return rating; } void Uniform::check_uniform(QString category_name, Item *item_inv){ if(m_uniform_items.count() <= 0) return; //make a copy of our full uniform list to a missing list to remove items from if(m_first_check){ m_missing_items = m_uniform_items; m_first_check = false; } ITEM_TYPE itype = item_inv->item_type(); //no address indicates a placeholder item for uncovered/missing stuff if(item_inv->address() != 0 && category_name != Item::missing_group_name() && category_name != Item::uncovered_group_name()){ //check our uniform's item list if(m_missing_items.value(itype).count() > 0){ int idx = 0; //get the qty of this item type still required, based on the stack size int req_count = get_remaining_required(item_inv->item_type()); int inv_qty = item_inv->get_stack_size(); for(idx = m_missing_items.value(itype).count()-1; idx >= 0; idx--){ //if the inventory quantity has been used up, or the required item count for the uniform met, quit if(inv_qty <= 0 || req_count <= 0) break; ItemDefUniform *item_uni_miss = m_missing_items.value(itype).at(idx); //get a missing item of the same type Item *item_miss = new ItemUniform(m_df,item_uni_miss,this); bool match = false; //check for a specific item id if(item_miss->id() > -1){ if(item_miss->id() == item_inv->id()){ match = true; }else{ continue; } }else{ match = (item_uni_miss->indv_choice() || ( (item_uni_miss->item_subtype() < 0 || item_uni_miss->item_subtype() == item_inv->item_subtype()) && ( (item_uni_miss->mat_flag() == MAT_NONE && item_miss->mat_type() < 0 && item_miss->mat_index() < 0) || (item_miss->mat_type() < 0 && item_miss->mat_index() < 0 && item_inv->mat_flags().has_flag(item_uni_miss->mat_flag())) || //QString::compare(item_miss->get_material_name(),item_inv->get_material_name_base(),Qt::CaseInsensitive)==0) || ((item_miss->mat_type() >= 0 || item_miss->mat_index() >= 0) && item_miss->mat_type() == item_inv->mat_type() && item_miss->mat_index() == item_inv->mat_index()) ) && (item_uni_miss->job_skills().count() == 0 || (item_uni_miss->job_skills().contains(item_inv->melee_skill()) || item_uni_miss->job_skills().contains(item_inv->ranged_skill()))) ) ); } delete item_miss; if(match){ QList<ItemDefUniform*> missing_items = m_missing_items.take(itype); req_count -= inv_qty; //reduce the required count missing_items.at(idx)->add_to_stack(-inv_qty); //reduce the uniform item's stack int curr_qty = missing_items.at(idx)->get_stack_size(); //after applying the inventory quantity if(curr_qty <= 0){ inv_qty = abs(curr_qty); //update the leftover inventory quantity missing_items.removeAt(idx); //item isn't missing, remove it } if(missing_items.count() > 0) m_missing_items.insert(itype,missing_items); } } } } }
1
0.964114
1
0.964114
game-dev
MEDIA
0.690012
game-dev
0.990613
1
0.990613
R2NorthstarTools/VTOL
1,082
VTOL_2.0.0/Scripts/Titanfall2_Requisite/PilotData/Normal Pilot/Jack/Jack.cs
using System; namespace Titanfall2_SkinTool.Titanfall2.PilotData.Normal_Pilot.Jack { class Jack { public string Seek { get; private set; } public string Length { get; private set; } public string SeekLength { get; private set; } //Jack Cooper Hands LOL public Jack(String PilotPart, int imagecheck) { String str = PilotPart.Substring(1, PilotPart.Length - 5); if (str.Contains("gauntlet")) { Part.gauntlet ga = new Part.gauntlet(str, imagecheck); Seek = ga.Seek; Length = ga.Length; SeekLength = ga.SeekLength; } else if (str.Contains("gauntletr")) { Part.gauntletr gar = new Part.gauntletr(str, imagecheck); Seek = gar.Seek; Length = gar.Length; SeekLength = gar.SeekLength; } else { throw new Exception("BUG!" + "\n" + "In Pilot Part."); } } } }
1
0.539524
1
0.539524
game-dev
MEDIA
0.783443
game-dev
0.576054
1
0.576054
FTL13/FTL13
19,176
code/modules/surgery/organs/vocal_cords.dm
#define COOLDOWN_STUN 1200 #define COOLDOWN_DAMAGE 600 #define COOLDOWN_MEME 300 #define COOLDOWN_NONE 100 /obj/item/organ/vocal_cords //organs that are activated through speech with the :x channel name = "vocal cords" icon_state = "appendix" zone = "mouth" slot = "vocal_cords" gender = PLURAL var/list/spans = null /obj/item/organ/vocal_cords/proc/can_speak_with() //if there is any limitation to speaking with these cords return TRUE /obj/item/organ/vocal_cords/proc/speak_with(message) //do what the organ does return /obj/item/organ/vocal_cords/proc/handle_speech(message) //actually say the message owner.say(message, spans = spans, sanitize = FALSE) /obj/item/organ/adamantine_resonator name = "adamantine resonator" desc = "Fragments of adamantine exists in all golems, stemming from their origins as purely magical constructs. These are used to \"hear\" messages from their leaders." zone = "head" slot = "adamantine_resonator" icon_state = "adamantine_resonator" /obj/item/organ/vocal_cords/adamantine name = "adamantine vocal cords" desc = "When adamantine resonates, it causes all nearby pieces of adamantine to resonate as well. Adamantine golems use this to broadcast messages to nearby golems." actions_types = list(/datum/action/item_action/organ_action/use/adamantine_vocal_cords) zone = "mouth" slot = "vocal_cords" icon_state = "adamantine_cords" /datum/action/item_action/organ_action/use/adamantine_vocal_cords/Trigger() if(!IsAvailable()) return var/message = input(owner, "Resonate a message to all nearby golems.", "Resonate") if(QDELETED(src) || QDELETED(owner) || !message) return owner.say(".x[message]") /obj/item/organ/vocal_cords/adamantine/handle_speech(message) var/msg = "<span class='resonate'><span class='name'>[owner.real_name]</span> <span class='message'>resonates, \"[message]\"</span></span>" for(var/m in GLOB.player_list) if(iscarbon(m)) var/mob/living/carbon/C = m if(C.getorganslot("adamantine_resonator")) to_chat(C, msg) if(isobserver(m)) var/link = FOLLOW_LINK(m, owner) to_chat(m, "[link] [msg]") //Colossus drop, forces the listeners to obey certain commands /obj/item/organ/vocal_cords/colossus name = "divine vocal cords" desc = "They carry the voice of an ancient god." icon_state = "voice_of_god" zone = "mouth" slot = "vocal_cords" actions_types = list(/datum/action/item_action/organ_action/colossus) var/next_command = 0 var/cooldown_mod = 1 var/base_multiplier = 1 spans = list("colossus","yell") /datum/action/item_action/organ_action/colossus name = "Voice of God" var/obj/item/organ/vocal_cords/colossus/cords = null /datum/action/item_action/organ_action/colossus/New() ..() cords = target /datum/action/item_action/organ_action/colossus/IsAvailable() if(world.time < cords.next_command) return FALSE if(!owner) return FALSE if(!owner.can_speak()) return FALSE if(check_flags & AB_CHECK_CONSCIOUS) if(owner.stat) return FALSE return TRUE /datum/action/item_action/organ_action/colossus/Trigger() . = ..() if(!IsAvailable()) if(world.time < cords.next_command) to_chat(owner, "<span class='notice'>You must wait [(cords.next_command - world.time)/10] seconds before Speaking again.</span>") return var/command = input(owner, "Speak with the Voice of God", "Command") if(QDELETED(src) || QDELETED(owner)) return if(!command) return owner.say(".x[command]") /obj/item/organ/vocal_cords/colossus/can_speak_with() if(world.time < next_command) to_chat(owner, "<span class='notice'>You must wait [(next_command - world.time)/10] seconds before Speaking again.</span>") return FALSE if(!owner) return FALSE if(!owner.can_speak()) to_chat(owner, "<span class='warning'>You are unable to speak!</span>") return FALSE return TRUE /obj/item/organ/vocal_cords/colossus/handle_speech(message) owner.say(uppertext(message), spans = spans, sanitize = FALSE) playsound(get_turf(owner), 'sound/magic/clockwork/invoke_general.ogg', 300, 1, 5) return //voice of god speaks for us /obj/item/organ/vocal_cords/colossus/speak_with(message) var/cooldown = voice_of_god(message, owner, spans, base_multiplier) next_command = world.time + (cooldown * cooldown_mod) ////////////////////////////////////// ///////////VOICE OF GOD/////////////// ////////////////////////////////////// /proc/voice_of_god(message, mob/living/user, list/span_list, base_multiplier = 1) var/cooldown = 0 if(!user || !user.can_speak() || user.stat) return 0 //no cooldown var/log_message = uppertext(message) if(!span_list || !span_list.len) if(iscultist(user)) span_list = list("narsiesmall") else if (is_servant_of_ratvar(user)) span_list = list("ratvar") else span_list = list() message = lowertext(message) var/mob/living/list/listeners = list() for(var/mob/living/L in get_hearers_in_view(8, user)) if(L.can_hear() && !L.null_rod_check() && L != user && L.stat != DEAD) if(ishuman(L)) var/mob/living/carbon/human/H = L if(istype(H.ears, /obj/item/clothing/ears/earmuffs)) continue listeners += L if(!listeners.len) cooldown = COOLDOWN_NONE return cooldown var/power_multiplier = base_multiplier if(user.mind) //Chaplains are very good at speaking with the voice of god if(user.mind.assigned_role == "Chaplain") power_multiplier *= 2 //Command staff has authority if(user.mind.assigned_role in GLOB.command_positions) power_multiplier *= 1.4 //Why are you speaking if(user.mind.assigned_role == "Mime") power_multiplier *= 0.5 //Cultists are closer to their gods and are more powerful, but they'll give themselves away if(iscultist(user)) power_multiplier *= 2 else if (is_servant_of_ratvar(user)) power_multiplier *= 2 //Try to check if the speaker specified a name or a job to focus on var/list/specific_listeners = list() var/found_string = null //Get the proper job titles message = get_full_job_name(message) for(var/V in listeners) var/mob/living/L = V var/datum/antagonist/devil/devilinfo = is_devil(L) if(devilinfo && findtext(message, devilinfo.truename)) var/start = findtext(message, devilinfo.truename) listeners = list(L) //Devil names are unique. power_multiplier *= 5 //if you're a devil and god himself addressed you, you fucked up //Cut out the name so it doesn't trigger commands message = copytext(message, 0, start)+copytext(message, start + length(devilinfo.truename), length(message) + 1) break else if(dd_hasprefix(message, L.real_name)) specific_listeners += L //focus on those with the specified name //Cut out the name so it doesn't trigger commands found_string = L.real_name else if(dd_hasprefix(message, L.first_name())) specific_listeners += L //focus on those with the specified name //Cut out the name so it doesn't trigger commands found_string = L.first_name() else if(L.mind && L.mind.assigned_role && dd_hasprefix(message, L.mind.assigned_role)) specific_listeners += L //focus on those with the specified job //Cut out the job so it doesn't trigger commands found_string = L.mind.assigned_role if(specific_listeners.len) listeners = specific_listeners power_multiplier *= (1 + (1/specific_listeners.len)) //2x on a single guy, 1.5x on two and so on message = copytext(message, 0, 1)+copytext(message, 1 + length(found_string), length(message) + 1) var/static/regex/stun_words = regex("stop|wait|stand still|hold on|halt") var/static/regex/knockdown_words = regex("drop|fall|trip|knockdown") var/static/regex/sleep_words = regex("sleep|slumber|rest") var/static/regex/vomit_words = regex("vomit|throw up") var/static/regex/silence_words = regex("shut up|silence|ssh|quiet|hush") var/static/regex/hallucinate_words = regex("see the truth|hallucinate") var/static/regex/wakeup_words = regex("wake up|awaken") var/static/regex/heal_words = regex("live|heal|survive|mend|heroes never die") var/static/regex/hurt_words = regex("die|suffer|hurt|pain") var/static/regex/bleed_words = regex("bleed|there will be blood") var/static/regex/burn_words = regex("burn|ignite") var/static/regex/hot_words = regex("heat|hot|hell") var/static/regex/cold_words = regex("cold|cool down|chill|freeze") var/static/regex/repulse_words = regex("shoo|go away|leave me alone|begone|flee|fus ro dah|get away|repulse") var/static/regex/attract_words = regex("come here|come to me|get over here|attract") var/static/regex/whoareyou_words = regex("who are you|say your name|state your name|identify") var/static/regex/saymyname_words = regex("say my name|who am i|whoami") var/static/regex/knockknock_words = regex("knock knock") var/static/regex/statelaws_words = regex("state laws|state your laws") var/static/regex/move_words = regex("move|walk") var/static/regex/left_words = regex("left|west|port") var/static/regex/right_words = regex("right|east|starboard") var/static/regex/up_words = regex("up|north|fore") var/static/regex/down_words = regex("down|south|aft") var/static/regex/walk_words = regex("slow down") var/static/regex/run_words = regex("run") var/static/regex/helpintent_words = regex("help|hug") var/static/regex/disarmintent_words = regex("disarm") var/static/regex/grabintent_words = regex("grab") var/static/regex/harmintent_words = regex("harm|fight|punch") var/static/regex/throwmode_words = regex("throw|catch") var/static/regex/flip_words = regex("flip|rotate|revolve|roll|somersault") var/static/regex/speak_words = regex("speak|say something") var/static/regex/getup_words = regex("get up") var/static/regex/sit_words = regex("sit") var/static/regex/stand_words = regex("stand") var/static/regex/dance_words = regex("dance") var/static/regex/jump_words = regex("jump") var/static/regex/salute_words = regex("salute") var/static/regex/deathgasp_words = regex("play dead") var/static/regex/clap_words = regex("clap|applaud") var/static/regex/honk_words = regex("ho+nk") //hooooooonk var/static/regex/multispin_words = regex("like a record baby|right round") //STUN if(findtext(message, stun_words)) cooldown = COOLDOWN_STUN for(var/V in listeners) var/mob/living/L = V L.Stun(60 * power_multiplier) //KNOCKDOWN else if(findtext(message, knockdown_words)) cooldown = COOLDOWN_STUN for(var/V in listeners) var/mob/living/L = V L.Knockdown(60 * power_multiplier) //SLEEP else if((findtext(message, sleep_words))) cooldown = COOLDOWN_STUN for(var/mob/living/carbon/C in listeners) C.Sleeping(40 * power_multiplier) //VOMIT else if((findtext(message, vomit_words))) cooldown = COOLDOWN_STUN for(var/mob/living/carbon/C in listeners) C.vomit(10 * power_multiplier, distance = power_multiplier) //SILENCE else if((findtext(message, silence_words))) cooldown = COOLDOWN_STUN for(var/mob/living/carbon/C in listeners) if(user.mind && (user.mind.assigned_role == "Curator" || user.mind.assigned_role == "Mime")) power_multiplier *= 3 C.silent += (10 * power_multiplier) //HALLUCINATE else if((findtext(message, hallucinate_words))) cooldown = COOLDOWN_MEME for(var/mob/living/carbon/C in listeners) new /datum/hallucination/delusion(C, TRUE, null,150 * power_multiplier,0) //WAKE UP else if((findtext(message, wakeup_words))) cooldown = COOLDOWN_DAMAGE for(var/V in listeners) var/mob/living/L = V L.SetSleeping(0) //HEAL else if((findtext(message, heal_words))) cooldown = COOLDOWN_DAMAGE for(var/V in listeners) var/mob/living/L = V L.heal_overall_damage(10 * power_multiplier, 10 * power_multiplier, 0, 0) //BRUTE DAMAGE else if((findtext(message, hurt_words))) cooldown = COOLDOWN_DAMAGE for(var/V in listeners) var/mob/living/L = V L.apply_damage(15 * power_multiplier, def_zone = "chest") //BLEED else if((findtext(message, bleed_words))) cooldown = COOLDOWN_DAMAGE for(var/mob/living/carbon/human/H in listeners) H.bleed_rate += (5 * power_multiplier) //FIRE else if((findtext(message, burn_words))) cooldown = COOLDOWN_DAMAGE for(var/V in listeners) var/mob/living/L = V L.adjust_fire_stacks(1 * power_multiplier) L.IgniteMob() //HOT else if((findtext(message, hot_words))) cooldown = COOLDOWN_DAMAGE for(var/V in listeners) var/mob/living/L = V L.bodytemperature += (50 * power_multiplier) //COLD else if((findtext(message, cold_words))) cooldown = COOLDOWN_DAMAGE for(var/V in listeners) var/mob/living/L = V L.bodytemperature -= (50 * power_multiplier) //REPULSE else if((findtext(message, repulse_words))) cooldown = COOLDOWN_DAMAGE for(var/V in listeners) var/mob/living/L = V var/throwtarget = get_edge_target_turf(user, get_dir(user, get_step_away(L, user))) L.throw_at(throwtarget, 3 * power_multiplier, 1 * power_multiplier) //ATTRACT else if((findtext(message, attract_words))) cooldown = COOLDOWN_DAMAGE for(var/V in listeners) var/mob/living/L = V L.throw_at(get_step_towards(user,L), 3 * power_multiplier, 1 * power_multiplier) //WHO ARE YOU? else if((findtext(message, whoareyou_words))) cooldown = COOLDOWN_MEME for(var/V in listeners) var/mob/living/L = V if(is_devil(L)) var/datum/antagonist/devil/devilinfo = is_devil(L) L.say("[devilinfo.truename]") else L.say("[L.real_name]") sleep(5) //So the chat flows more naturally //SAY MY NAME else if((findtext(message, saymyname_words))) cooldown = COOLDOWN_MEME for(var/V in listeners) var/mob/living/L = V L.say("[user.name]!") //"Unknown!" sleep(5) //So the chat flows more naturally //KNOCK KNOCK else if((findtext(message, knockknock_words))) cooldown = COOLDOWN_MEME for(var/V in listeners) var/mob/living/L = V L.say("Who's there?") sleep(5) //So the chat flows more naturally //STATE LAWS else if((findtext(message, statelaws_words))) cooldown = COOLDOWN_STUN for(var/mob/living/silicon/S in listeners) S.statelaws(force = 1) //MOVE else if((findtext(message, move_words))) cooldown = COOLDOWN_MEME var/direction if(findtext(message, up_words)) direction = NORTH else if(findtext(message, down_words)) direction = SOUTH else if(findtext(message, left_words)) direction = WEST else if(findtext(message, right_words)) direction = EAST for(var/i=1, i<=(5*power_multiplier), i++) for(var/V in listeners) var/mob/living/L = V step(L, direction ? direction : pick(GLOB.cardinals)) sleep(10) //WALK else if((findtext(message, walk_words))) cooldown = COOLDOWN_MEME for(var/V in listeners) var/mob/living/L = V if(L.m_intent != MOVE_INTENT_WALK) L.toggle_move_intent() //RUN else if((findtext(message, run_words))) cooldown = COOLDOWN_MEME for(var/V in listeners) var/mob/living/L = V if(L.m_intent != MOVE_INTENT_RUN) L.toggle_move_intent() //HELP INTENT else if((findtext(message, helpintent_words))) cooldown = COOLDOWN_MEME for(var/mob/living/carbon/human/H in listeners) H.a_intent_change(INTENT_HELP) H.click_random_mob() sleep(2) //delay to make it feel more natural //DISARM INTENT else if((findtext(message, disarmintent_words))) cooldown = COOLDOWN_MEME for(var/mob/living/carbon/human/H in listeners) H.a_intent_change(INTENT_DISARM) H.click_random_mob() sleep(2) //delay to make it feel more natural //GRAB INTENT else if((findtext(message, grabintent_words))) cooldown = COOLDOWN_MEME for(var/mob/living/carbon/human/H in listeners) H.a_intent_change(INTENT_GRAB) H.click_random_mob() sleep(2) //delay to make it feel more natural //HARM INTENT else if((findtext(message, harmintent_words))) cooldown = COOLDOWN_MEME for(var/mob/living/carbon/human/H in listeners) H.a_intent_change(INTENT_HARM) H.click_random_mob() sleep(2) //delay to make it feel more natural //THROW/CATCH else if((findtext(message, throwmode_words))) cooldown = COOLDOWN_MEME for(var/mob/living/carbon/C in listeners) C.throw_mode_on() //FLIP else if((findtext(message, flip_words))) cooldown = COOLDOWN_MEME for(var/V in listeners) var/mob/living/L = V L.emote("flip") //SPEAK else if((findtext(message, speak_words))) cooldown = COOLDOWN_MEME for(var/V in listeners) var/mob/living/L = V L.say(pick_list_replacements(BRAIN_DAMAGE_FILE, "brain_damage")) sleep(5) //So the chat flows more naturally //GET UP else if((findtext(message, getup_words))) cooldown = COOLDOWN_DAMAGE //because stun removal for(var/V in listeners) var/mob/living/L = V if(L.resting) L.lay_down() //aka get up L.SetStun(0) L.SetKnockdown(0) L.SetUnconscious(0) //i said get up i don't care if you're being tazed //SIT else if((findtext(message, sit_words))) cooldown = COOLDOWN_MEME for(var/V in listeners) var/mob/living/L = V for(var/obj/structure/chair/chair in get_turf(L)) chair.buckle_mob(L) break //STAND UP else if((findtext(message, stand_words))) cooldown = COOLDOWN_MEME for(var/V in listeners) var/mob/living/L = V if(L.buckled && istype(L.buckled, /obj/structure/chair)) L.buckled.unbuckle_mob(L) //DANCE else if((findtext(message, dance_words))) cooldown = COOLDOWN_MEME for(var/V in listeners) var/mob/living/L = V L.emote("dance") sleep(5) //So the chat flows more naturally //JUMP else if((findtext(message, jump_words))) cooldown = COOLDOWN_MEME for(var/V in listeners) var/mob/living/L = V if(prob(25)) L.say("HOW HIGH?!!") L.emote("jump") sleep(5) //So the chat flows more naturally //SALUTE else if((findtext(message, salute_words))) cooldown = COOLDOWN_MEME for(var/V in listeners) var/mob/living/L = V L.emote("salute") sleep(5) //So the chat flows more naturally //PLAY DEAD else if((findtext(message, deathgasp_words))) cooldown = COOLDOWN_MEME for(var/V in listeners) var/mob/living/L = V L.emote("deathgasp") sleep(5) //So the chat flows more naturally //PLEASE CLAP else if((findtext(message, clap_words))) cooldown = COOLDOWN_MEME for(var/V in listeners) var/mob/living/L = V L.emote("clap") sleep(5) //So the chat flows more naturally //HONK else if((findtext(message, honk_words))) cooldown = COOLDOWN_MEME addtimer(CALLBACK(GLOBAL_PROC, .proc/playsound, get_turf(user), 'sound/items/bikehorn.ogg', 300, 1), 25) if(user.mind && user.mind.assigned_role == "Clown") for(var/mob/living/carbon/C in listeners) C.slip(140 * power_multiplier) cooldown = COOLDOWN_MEME //RIGHT ROUND else if((findtext(message, multispin_words))) cooldown = COOLDOWN_MEME for(var/V in listeners) var/mob/living/L = V L.SpinAnimation(speed = 10, loops = 5) else cooldown = COOLDOWN_NONE message_admins("[key_name_admin(user)] has said '[log_message]' with a Voice of God, affecting [english_list(listeners)], with a power multiplier of [power_multiplier].") log_game("[key_name(user)] has said '[log_message]' with a Voice of God, affecting [english_list(listeners)], with a power multiplier of [power_multiplier].") return cooldown #undef COOLDOWN_STUN #undef COOLDOWN_DAMAGE #undef COOLDOWN_MEME #undef COOLDOWN_NONE
1
0.909392
1
0.909392
game-dev
MEDIA
0.168434
game-dev
0.906289
1
0.906289
cc-tweaked/CC-Tweaked
9,009
projects/common/src/main/java/dan200/computercraft/shared/computer/core/ServerContext.java
// SPDX-FileCopyrightText: 2022 The CC: Tweaked Developers // // SPDX-License-Identifier: MPL-2.0 package dan200.computercraft.shared.computer.core; import com.google.common.annotations.VisibleForTesting; import dan200.computercraft.api.ComputerCraftAPI; import dan200.computercraft.api.filesystem.Mount; import dan200.computercraft.api.network.PacketNetwork; import dan200.computercraft.core.ComputerContext; import dan200.computercraft.core.computer.GlobalEnvironment; import dan200.computercraft.core.computer.mainthread.MainThread; import dan200.computercraft.core.computer.mainthread.MainThreadConfig; import dan200.computercraft.core.lua.CobaltLuaMachine; import dan200.computercraft.core.lua.ILuaMachine; import dan200.computercraft.core.methods.MethodSupplier; import dan200.computercraft.core.methods.PeripheralMethod; import dan200.computercraft.impl.AbstractComputerCraftAPI; import dan200.computercraft.impl.GenericSources; import dan200.computercraft.shared.CommonHooks; import dan200.computercraft.shared.computer.metrics.GlobalMetrics; import dan200.computercraft.shared.config.ConfigSpec; import dan200.computercraft.shared.peripheral.modem.wireless.WirelessNetwork; import dan200.computercraft.shared.util.IDAssigner; import net.minecraft.SharedConstants; import net.minecraft.server.MinecraftServer; import net.minecraft.world.level.storage.LevelResource; import org.jspecify.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.InputStream; import java.nio.file.Path; import java.util.Objects; import java.util.concurrent.TimeUnit; /** * Stores ComputerCraft's server-side state for the lifetime of a {@link MinecraftServer}. * <p> * This is effectively a glorified singleton, holding references to most global state ComputerCraft stores * (for instance, {@linkplain IDAssigner ID assignment} and {@linkplain ServerComputerRegistry running computers}. Its * main purpose is to offer a single point of resetting the state ({@link ServerContext#close()} and ensure disciplined * access to the current state, by ensuring callers have a {@link MinecraftServer} to hand. * * @see CommonHooks for where the context is created and torn down. */ public final class ServerContext { private static final Logger LOG = LoggerFactory.getLogger(ServerContext.class); private static final LevelResource FOLDER = new LevelResource(ComputerCraftAPI.MOD_ID); @VisibleForTesting public static ILuaMachine.Factory luaMachine = CobaltLuaMachine::new; private static @Nullable ServerContext instance; private final MinecraftServer server; private final ServerComputerRegistry registry = new ServerComputerRegistry(); private final GlobalMetrics metrics = new GlobalMetrics(); private final ComputerContext context; private final MainThread mainThread; private final IDAssigner idAssigner; private final WirelessNetwork wirelessNetwork = new WirelessNetwork(); private final Path storageDir; private ServerContext(MinecraftServer server) { this.server = server; storageDir = server.getWorldPath(FOLDER); mainThread = new MainThread(mainThreadConfig); context = ComputerContext.builder(new Environment(server)) .computerThreads(ConfigSpec.computerThreads.get()) .mainThreadScheduler(mainThread) .luaFactory(luaMachine) .genericMethods(GenericSources.getAllMethods()) .build(); idAssigner = new IDAssigner(storageDir.resolve("ids.json")); } /** * Start a new server context from the currently running Minecraft server. * * @param server The currently running Minecraft server. * @throws IllegalStateException If a context is already present. */ public static void create(MinecraftServer server) { if (ServerContext.instance != null) throw new IllegalStateException("ServerContext already exists!"); ServerContext.instance = new ServerContext(server); } /** * Stops the current server context, resetting any state and terminating all computers. */ public static void close() { var instance = ServerContext.instance; if (instance == null) return; instance.registry.close(); try { if (!instance.context.close(1, TimeUnit.SECONDS)) { LOG.error("Failed to stop computers under deadline."); } } catch (InterruptedException e) { LOG.error("Failed to stop computers.", e); Thread.currentThread().interrupt(); } ServerContext.instance = null; } /** * Get the {@link ServerContext} instance for the currently running Minecraft server. * * @param server The current server. * @return The current server context. */ public static ServerContext get(MinecraftServer server) { Objects.requireNonNull(server, "Server cannot be null"); var instance = ServerContext.instance; if (instance == null) throw new IllegalStateException("ServerContext has not been started yet"); if (instance.server != server) { throw new IllegalStateException("Incorrect server given. Did ServerContext shutdown correctly?"); } return instance; } /** * Get the current {@link ComputerContext} computers should run under. * * @return The current {@link ComputerContext}. */ ComputerContext computerContext() { return context; } /** * Get the {@link MethodSupplier} used to find methods on peripherals. * * @return The {@link PeripheralMethod} method supplier. * @see ComputerContext#peripheralMethods() */ public MethodSupplier<PeripheralMethod> peripheralMethods() { return context.peripheralMethods(); } /** * Tick all components of this server context. This should <em>NOT</em> be called outside of {@link CommonHooks}. */ public void tick() { registry.update(); mainThread.tick(); } /** * Get the current {@link ServerComputerRegistry}. * * @return The global computer registry. */ public ServerComputerRegistry registry() { return registry; } /** * Return the next available ID for a particular kind (for instance, a computer or particular peripheral type). * <p> * IDs are assigned incrementally, with the last assigned ID being stored in {@code ids.json} in our root * {@linkplain #storageDir() storage folder}. * * @param kind The kind we're assigning an ID for, for instance {@code "computer"} or {@code "peripheral.monitor"}. * @return The next available ID. * @see ComputerCraftAPI#createUniqueNumberedSaveDir(MinecraftServer, String) */ public int getNextId(String kind) { return idAssigner.getNextId(kind); } /** * Get the directory used for all ComputerCraft related information. This includes the computer/peripheral id store, * and all computer data. * * @return The storge directory for ComputerCraft. */ public Path storageDir() { return storageDir; } /** * Get the current global metrics store. * * @return The current metrics store. */ public GlobalMetrics metrics() { return metrics; } /** * Get the global wireless network. * <p> * Use {@link ComputerCraftAPI#getWirelessNetwork(MinecraftServer)} instead of this method. * * @return The wireless network. */ public PacketNetwork wirelessNetwork() { return wirelessNetwork; } private record Environment(MinecraftServer server) implements GlobalEnvironment { @Override public @Nullable Mount createResourceMount(String domain, String subPath) { return ComputerCraftAPI.createResourceMount(server, domain, subPath); } @Override public @Nullable InputStream createResourceFile(String domain, String subPath) { return AbstractComputerCraftAPI.getResourceFile(server, domain, subPath); } @Override public String getHostString() { var version = SharedConstants.getCurrentVersion().getName(); return String.format("ComputerCraft %s (Minecraft %s)", ComputerCraftAPI.getInstalledVersion(), version); } @Override public String getUserAgent() { return ComputerCraftAPI.MOD_ID + "/" + ComputerCraftAPI.getInstalledVersion(); } } private static final MainThreadConfig mainThreadConfig = new MainThreadConfig() { @Override public long maxGlobalTime() { return TimeUnit.MILLISECONDS.toNanos(ConfigSpec.maxMainGlobalTime.get()); } @Override public long maxComputerTime() { return TimeUnit.MILLISECONDS.toNanos(ConfigSpec.maxMainComputerTime.get()); } }; }
1
0.890114
1
0.890114
game-dev
MEDIA
0.87411
game-dev,networking
0.932164
1
0.932164
CleanroomMC/GroovyScript
1,032
src/main/java/com/cleanroommc/groovyscript/helper/ingredient/itemstack/ItemStackHashStrategy.java
package com.cleanroommc.groovyscript.helper.ingredient.itemstack; import it.unimi.dsi.fastutil.Hash; import net.minecraft.item.ItemStack; /** * Hash strategy for fastutils that checks item and metadata. * Note that in many cases, metadata equal to {@link Short#MAX_VALUE} * (aka {@link net.minecraftforge.oredict.OreDictionary#WILDCARD_VALUE OreDictionary.WILDCARD_VALUE}) * has special logic, and will need to be handled separately from the other ItemStacks. * <br> * This cannot be part of the hash strategy, as doing so would require * violating {@link Object#hashCode()}. */ public class ItemStackHashStrategy implements Hash.Strategy<ItemStack> { public static final ItemStackHashStrategy STRATEGY = new ItemStackHashStrategy(); @Override public int hashCode(ItemStack o) { return 31 * o.getItem().hashCode() + o.getMetadata(); } @Override public boolean equals(ItemStack a, ItemStack b) { return a == b || (a != null && b != null && ItemStack.areItemsEqual(a, b)); } }
1
0.714227
1
0.714227
game-dev
MEDIA
0.969489
game-dev
0.765791
1
0.765791
opentomb/OpenTomb
2,848
src/script/script.h
#ifndef ENGINE_SCRIPT_H #define ENGINE_SCRIPT_H struct screen_info_s; struct entity_s; struct lua_State; #define CVAR_LUA_TABLE_NAME "cvars" // character state flags constants #define CHARACTER_STATE_DEAD (0) #define CHARACTER_STATE_WEAPON (1) // Entity timer constants #define TICK_IDLE (0) #define TICK_STOPPED (1) #define TICK_ACTIVE (2) extern lua_State *engine_lua; void Script_LoadConstants(lua_State *lua); bool Script_LuaInit(); int Script_DoLuaFile(lua_State *lua, const char *local_path); void Script_LuaClearTasks(); void Script_LuaRegisterFuncs(lua_State *lua); char *SC_ParseToken(char *data, char *token, size_t token_size); float SC_ParseFloat(char **ch); int SC_ParseInt(char **ch); int lua_print(lua_State *lua); int lua_Bind(lua_State *lua); #define lua_CallAndLog(L,n,r,f) lua_CallWithError(L, n, r, f, __FILE__, __LINE__) bool lua_CallWithError(lua_State *lua, int nargs, int nresults, int errfunc, const char *cfile, int cline); void Script_LuaRegisterConfigFuncs(lua_State *lua); void Script_ExportConfig(const char *path); int Script_ParseScreen(lua_State *lua, struct screen_info_s *sc); int Script_ParseRender(lua_State *lua, struct render_settings_s *rs); int Script_ParseAudio(lua_State *lua, struct audio_settings_s *as); int Script_ParseConsole(lua_State *lua, struct console_params_s *cp); int Script_ParseControls(lua_State *lua, struct control_settings_s *cs); bool Script_GetOverridedSamplesInfo(lua_State *lua, int *num_samples, int *num_sounds, char *sample_name_mask); bool Script_GetOverridedSample(lua_State *lua, int sound_id, int *first_sample_number, int *samples_count); int Script_GetGlobalSound(lua_State *lua, int global_sound_id); int Script_GetSecretTrackNumber(lua_State *lua); int Script_GetNumTracks(lua_State *lua); bool Script_GetSoundtrack(lua_State *lua, int track_index, char *track_path, int file_path_len, int *load_method, int *stream_type); bool Script_GetString(lua_State *lua, int string_index, size_t string_size, char *buffer); void Script_LoopEntity(lua_State *lua, struct entity_s *ent); int Script_UseItem(lua_State *lua, int item_id, int activator_id); int Script_ExecEntity(lua_State *lua, int id_callback, int id_object, int id_activator = -1); int Script_EntityUpdateCollisionInfo(lua_State *lua, int id, struct collision_node_s *cn); size_t Script_GetEntitySaveData(lua_State *lua, int id_entity, char *buf, size_t buf_size); void Script_DoFlipEffect(lua_State *lua, int id_effect, int id_object, int param); size_t Script_GetFlipEffectsSaveData(lua_State *lua, char *buf, size_t buf_size); int Script_DoTasks(lua_State *lua, float time); bool Script_CallVoidFunc(lua_State *lua, const char *func_name, bool destroy_after_call = false); void Script_AddKey(lua_State *lua, int keycode, int state); #endif
1
0.763037
1
0.763037
game-dev
MEDIA
0.785099
game-dev
0.571776
1
0.571776
WesCook/Nutrition
3,079
src/main/java/ca/wescook/nutrition/Nutrition.java
package ca.wescook.nutrition; import ca.wescook.nutrition.capabilities.CapabilityManager; import ca.wescook.nutrition.events.*; import ca.wescook.nutrition.gui.ModGuiHandler; import ca.wescook.nutrition.network.ModPacketHandler; import ca.wescook.nutrition.potions.ModPotions; import ca.wescook.nutrition.proxy.IProxy; import ca.wescook.nutrition.utility.ChatCommand; import ca.wescook.nutrition.utility.Config; import ca.wescook.nutrition.utility.DataImporter; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.event.FMLServerStartingEvent; import net.minecraftforge.fml.common.network.NetworkRegistry; import static ca.wescook.nutrition.Nutrition.*; @Mod( modid = MODID, name = MODNAME, version = "@VERSION@", acceptedMinecraftVersions = FORGE_VERSIONS, acceptableRemoteVersions = "*" ) public class Nutrition { public static final String MODID = "nutrition"; public static final String MODNAME = "Nutrition"; public static final String FORGE_VERSIONS = "[1.12,1.13)"; // Create instance of mod @Mod.Instance public static Nutrition instance; // Create instance of proxy // This will vary depending on if the client or server is running @SidedProxy( clientSide="ca.wescook.nutrition.proxy.ClientProxy", serverSide="ca.wescook.nutrition.proxy.ServerProxy" ) public static IProxy proxy; // Events @EventHandler public void preInit(FMLPreInitializationEvent event) { Config.registerConfigs(event.getModConfigurationDirectory()); // Load Config file ModPacketHandler.registerMessages(); // Register network messages CapabilityManager.register(); // Register capability ModPotions.createPotions(); // Register custom potions MinecraftForge.EVENT_BUS.register(new EventRegistry()); // Register custom potions MinecraftForge.EVENT_BUS.register(new EventPlayerJoinWorld()); // Attach capability to player MinecraftForge.EVENT_BUS.register(new EventPlayerDeath()); // Player death and warping MinecraftForge.EVENT_BUS.register(new EventEatFood()); // Register use item event MinecraftForge.EVENT_BUS.register(new EventWorldTick()); // Register update event for nutrition decay and potion effects Nutrition.proxy.preInit(event); } @EventHandler public void init(FMLInitializationEvent event) { NetworkRegistry.INSTANCE.registerGuiHandler(Nutrition.instance, new ModGuiHandler()); // Register GUI handler Nutrition.proxy.init(event); } @EventHandler public void postInit(FMLPostInitializationEvent event) { DataImporter.reload(); // Load nutrients and effects Nutrition.proxy.postInit(event); } @Mod.EventHandler public void serverStart(FMLServerStartingEvent event) { event.registerServerCommand(new ChatCommand()); } }
1
0.695363
1
0.695363
game-dev
MEDIA
0.982342
game-dev
0.688833
1
0.688833
PlayFab/UnrealMarketplacePlugin
142,743
4.27/PlayFabPlugin/PlayFab/Source/PlayFabCpp/Public/Core/PlayFabServerInstanceAPI.h
////////////////////////////////////////////////////// // Copyright (C) Microsoft. 2018. All rights reserved. ////////////////////////////////////////////////////// // This is automatically generated by PlayFab SDKGenerator. DO NOT modify this manually! #pragma once #include "CoreMinimal.h" #include "Core/PlayFabError.h" #include "Core/PlayFabServerDataModels.h" #include "Core/PlayFabSettings.h" #include "PlayFabAPISettings.h" #include "Interfaces/IHttpRequest.h" #include "Interfaces/IHttpResponse.h" namespace PlayFab { /** * Main interface for PlayFab Sdk, specifically all Server APIs */ class PLAYFABCPP_API UPlayFabServerInstanceAPI { public: DECLARE_DELEGATE_OneParam(FAddCharacterVirtualCurrencyDelegate, const ServerModels::FModifyCharacterVirtualCurrencyResult&); DECLARE_DELEGATE_OneParam(FAddFriendDelegate, const ServerModels::FEmptyResponse&); DECLARE_DELEGATE_OneParam(FAddGenericIDDelegate, const ServerModels::FEmptyResult&); DECLARE_DELEGATE_OneParam(FAddPlayerTagDelegate, const ServerModels::FAddPlayerTagResult&); DECLARE_DELEGATE_OneParam(FAddSharedGroupMembersDelegate, const ServerModels::FAddSharedGroupMembersResult&); DECLARE_DELEGATE_OneParam(FAddUserVirtualCurrencyDelegate, const ServerModels::FModifyUserVirtualCurrencyResult&); DECLARE_DELEGATE_OneParam(FAuthenticateSessionTicketDelegate, const ServerModels::FAuthenticateSessionTicketResult&); DECLARE_DELEGATE_OneParam(FAwardSteamAchievementDelegate, const ServerModels::FAwardSteamAchievementResult&); DECLARE_DELEGATE_OneParam(FBanUsersDelegate, const ServerModels::FBanUsersResult&); DECLARE_DELEGATE_OneParam(FConsumeItemDelegate, const ServerModels::FConsumeItemResult&); DECLARE_DELEGATE_OneParam(FCreateSharedGroupDelegate, const ServerModels::FCreateSharedGroupResult&); DECLARE_DELEGATE_OneParam(FDeleteCharacterFromUserDelegate, const ServerModels::FDeleteCharacterFromUserResult&); DECLARE_DELEGATE_OneParam(FDeletePlayerDelegate, const ServerModels::FDeletePlayerResult&); DECLARE_DELEGATE_OneParam(FDeletePlayerCustomPropertiesDelegate, const ServerModels::FDeletePlayerCustomPropertiesResult&); DECLARE_DELEGATE_OneParam(FDeletePushNotificationTemplateDelegate, const ServerModels::FDeletePushNotificationTemplateResult&); DECLARE_DELEGATE_OneParam(FDeleteSharedGroupDelegate, const ServerModels::FEmptyResponse&); DECLARE_DELEGATE_OneParam(FEvaluateRandomResultTableDelegate, const ServerModels::FEvaluateRandomResultTableResult&); DECLARE_DELEGATE_OneParam(FExecuteCloudScriptDelegate, const ServerModels::FExecuteCloudScriptResult&); DECLARE_DELEGATE_OneParam(FGetAllSegmentsDelegate, const ServerModels::FGetAllSegmentsResult&); DECLARE_DELEGATE_OneParam(FGetAllUsersCharactersDelegate, const ServerModels::FListUsersCharactersResult&); DECLARE_DELEGATE_OneParam(FGetCatalogItemsDelegate, const ServerModels::FGetCatalogItemsResult&); DECLARE_DELEGATE_OneParam(FGetCharacterDataDelegate, const ServerModels::FGetCharacterDataResult&); DECLARE_DELEGATE_OneParam(FGetCharacterInternalDataDelegate, const ServerModels::FGetCharacterDataResult&); DECLARE_DELEGATE_OneParam(FGetCharacterInventoryDelegate, const ServerModels::FGetCharacterInventoryResult&); DECLARE_DELEGATE_OneParam(FGetCharacterLeaderboardDelegate, const ServerModels::FGetCharacterLeaderboardResult&); DECLARE_DELEGATE_OneParam(FGetCharacterReadOnlyDataDelegate, const ServerModels::FGetCharacterDataResult&); DECLARE_DELEGATE_OneParam(FGetCharacterStatisticsDelegate, const ServerModels::FGetCharacterStatisticsResult&); DECLARE_DELEGATE_OneParam(FGetContentDownloadUrlDelegate, const ServerModels::FGetContentDownloadUrlResult&); DECLARE_DELEGATE_OneParam(FGetFriendLeaderboardDelegate, const ServerModels::FGetLeaderboardResult&); DECLARE_DELEGATE_OneParam(FGetFriendsListDelegate, const ServerModels::FGetFriendsListResult&); DECLARE_DELEGATE_OneParam(FGetLeaderboardDelegate, const ServerModels::FGetLeaderboardResult&); DECLARE_DELEGATE_OneParam(FGetLeaderboardAroundCharacterDelegate, const ServerModels::FGetLeaderboardAroundCharacterResult&); DECLARE_DELEGATE_OneParam(FGetLeaderboardAroundUserDelegate, const ServerModels::FGetLeaderboardAroundUserResult&); DECLARE_DELEGATE_OneParam(FGetLeaderboardForUserCharactersDelegate, const ServerModels::FGetLeaderboardForUsersCharactersResult&); DECLARE_DELEGATE_OneParam(FGetPlayerCombinedInfoDelegate, const ServerModels::FGetPlayerCombinedInfoResult&); DECLARE_DELEGATE_OneParam(FGetPlayerCustomPropertyDelegate, const ServerModels::FGetPlayerCustomPropertyResult&); DECLARE_DELEGATE_OneParam(FGetPlayerProfileDelegate, const ServerModels::FGetPlayerProfileResult&); DECLARE_DELEGATE_OneParam(FGetPlayerSegmentsDelegate, const ServerModels::FGetPlayerSegmentsResult&); DECLARE_DELEGATE_OneParam(FGetPlayersInSegmentDelegate, const ServerModels::FGetPlayersInSegmentResult&); DECLARE_DELEGATE_OneParam(FGetPlayerStatisticsDelegate, const ServerModels::FGetPlayerStatisticsResult&); DECLARE_DELEGATE_OneParam(FGetPlayerStatisticVersionsDelegate, const ServerModels::FGetPlayerStatisticVersionsResult&); DECLARE_DELEGATE_OneParam(FGetPlayerTagsDelegate, const ServerModels::FGetPlayerTagsResult&); DECLARE_DELEGATE_OneParam(FGetPlayFabIDsFromBattleNetAccountIdsDelegate, const ServerModels::FGetPlayFabIDsFromBattleNetAccountIdsResult&); DECLARE_DELEGATE_OneParam(FGetPlayFabIDsFromFacebookIDsDelegate, const ServerModels::FGetPlayFabIDsFromFacebookIDsResult&); DECLARE_DELEGATE_OneParam(FGetPlayFabIDsFromFacebookInstantGamesIdsDelegate, const ServerModels::FGetPlayFabIDsFromFacebookInstantGamesIdsResult&); DECLARE_DELEGATE_OneParam(FGetPlayFabIDsFromGenericIDsDelegate, const ServerModels::FGetPlayFabIDsFromGenericIDsResult&); DECLARE_DELEGATE_OneParam(FGetPlayFabIDsFromNintendoServiceAccountIdsDelegate, const ServerModels::FGetPlayFabIDsFromNintendoServiceAccountIdsResult&); DECLARE_DELEGATE_OneParam(FGetPlayFabIDsFromNintendoSwitchDeviceIdsDelegate, const ServerModels::FGetPlayFabIDsFromNintendoSwitchDeviceIdsResult&); DECLARE_DELEGATE_OneParam(FGetPlayFabIDsFromPSNAccountIDsDelegate, const ServerModels::FGetPlayFabIDsFromPSNAccountIDsResult&); DECLARE_DELEGATE_OneParam(FGetPlayFabIDsFromPSNOnlineIDsDelegate, const ServerModels::FGetPlayFabIDsFromPSNOnlineIDsResult&); DECLARE_DELEGATE_OneParam(FGetPlayFabIDsFromSteamIDsDelegate, const ServerModels::FGetPlayFabIDsFromSteamIDsResult&); DECLARE_DELEGATE_OneParam(FGetPlayFabIDsFromSteamNamesDelegate, const ServerModels::FGetPlayFabIDsFromSteamNamesResult&); DECLARE_DELEGATE_OneParam(FGetPlayFabIDsFromTwitchIDsDelegate, const ServerModels::FGetPlayFabIDsFromTwitchIDsResult&); DECLARE_DELEGATE_OneParam(FGetPlayFabIDsFromXboxLiveIDsDelegate, const ServerModels::FGetPlayFabIDsFromXboxLiveIDsResult&); DECLARE_DELEGATE_OneParam(FGetPublisherDataDelegate, const ServerModels::FGetPublisherDataResult&); DECLARE_DELEGATE_OneParam(FGetRandomResultTablesDelegate, const ServerModels::FGetRandomResultTablesResult&); DECLARE_DELEGATE_OneParam(FGetServerCustomIDsFromPlayFabIDsDelegate, const ServerModels::FGetServerCustomIDsFromPlayFabIDsResult&); DECLARE_DELEGATE_OneParam(FGetSharedGroupDataDelegate, const ServerModels::FGetSharedGroupDataResult&); DECLARE_DELEGATE_OneParam(FGetStoreItemsDelegate, const ServerModels::FGetStoreItemsResult&); DECLARE_DELEGATE_OneParam(FGetTimeDelegate, const ServerModels::FGetTimeResult&); DECLARE_DELEGATE_OneParam(FGetTitleDataDelegate, const ServerModels::FGetTitleDataResult&); DECLARE_DELEGATE_OneParam(FGetTitleInternalDataDelegate, const ServerModels::FGetTitleDataResult&); DECLARE_DELEGATE_OneParam(FGetTitleNewsDelegate, const ServerModels::FGetTitleNewsResult&); DECLARE_DELEGATE_OneParam(FGetUserAccountInfoDelegate, const ServerModels::FGetUserAccountInfoResult&); DECLARE_DELEGATE_OneParam(FGetUserBansDelegate, const ServerModels::FGetUserBansResult&); DECLARE_DELEGATE_OneParam(FGetUserDataDelegate, const ServerModels::FGetUserDataResult&); DECLARE_DELEGATE_OneParam(FGetUserInternalDataDelegate, const ServerModels::FGetUserDataResult&); DECLARE_DELEGATE_OneParam(FGetUserInventoryDelegate, const ServerModels::FGetUserInventoryResult&); DECLARE_DELEGATE_OneParam(FGetUserPublisherDataDelegate, const ServerModels::FGetUserDataResult&); DECLARE_DELEGATE_OneParam(FGetUserPublisherInternalDataDelegate, const ServerModels::FGetUserDataResult&); DECLARE_DELEGATE_OneParam(FGetUserPublisherReadOnlyDataDelegate, const ServerModels::FGetUserDataResult&); DECLARE_DELEGATE_OneParam(FGetUserReadOnlyDataDelegate, const ServerModels::FGetUserDataResult&); DECLARE_DELEGATE_OneParam(FGrantCharacterToUserDelegate, const ServerModels::FGrantCharacterToUserResult&); DECLARE_DELEGATE_OneParam(FGrantItemsToCharacterDelegate, const ServerModels::FGrantItemsToCharacterResult&); DECLARE_DELEGATE_OneParam(FGrantItemsToUserDelegate, const ServerModels::FGrantItemsToUserResult&); DECLARE_DELEGATE_OneParam(FGrantItemsToUsersDelegate, const ServerModels::FGrantItemsToUsersResult&); DECLARE_DELEGATE_OneParam(FLinkBattleNetAccountDelegate, const ServerModels::FEmptyResult&); DECLARE_DELEGATE_OneParam(FLinkNintendoServiceAccountDelegate, const ServerModels::FEmptyResult&); DECLARE_DELEGATE_OneParam(FLinkNintendoServiceAccountSubjectDelegate, const ServerModels::FEmptyResult&); DECLARE_DELEGATE_OneParam(FLinkNintendoSwitchDeviceIdDelegate, const ServerModels::FLinkNintendoSwitchDeviceIdResult&); DECLARE_DELEGATE_OneParam(FLinkPSNAccountDelegate, const ServerModels::FLinkPSNAccountResult&); DECLARE_DELEGATE_OneParam(FLinkPSNIdDelegate, const ServerModels::FLinkPSNIdResponse&); DECLARE_DELEGATE_OneParam(FLinkServerCustomIdDelegate, const ServerModels::FLinkServerCustomIdResult&); DECLARE_DELEGATE_OneParam(FLinkSteamIdDelegate, const ServerModels::FLinkSteamIdResult&); DECLARE_DELEGATE_OneParam(FLinkXboxAccountDelegate, const ServerModels::FLinkXboxAccountResult&); DECLARE_DELEGATE_OneParam(FLinkXboxIdDelegate, const ServerModels::FLinkXboxAccountResult&); DECLARE_DELEGATE_OneParam(FListPlayerCustomPropertiesDelegate, const ServerModels::FListPlayerCustomPropertiesResult&); DECLARE_DELEGATE_OneParam(FLoginWithAndroidDeviceIDDelegate, const ServerModels::FServerLoginResult&); DECLARE_DELEGATE_OneParam(FLoginWithBattleNetDelegate, const ServerModels::FServerLoginResult&); DECLARE_DELEGATE_OneParam(FLoginWithCustomIDDelegate, const ServerModels::FServerLoginResult&); DECLARE_DELEGATE_OneParam(FLoginWithIOSDeviceIDDelegate, const ServerModels::FServerLoginResult&); DECLARE_DELEGATE_OneParam(FLoginWithPSNDelegate, const ServerModels::FServerLoginResult&); DECLARE_DELEGATE_OneParam(FLoginWithServerCustomIdDelegate, const ServerModels::FServerLoginResult&); DECLARE_DELEGATE_OneParam(FLoginWithSteamIdDelegate, const ServerModels::FServerLoginResult&); DECLARE_DELEGATE_OneParam(FLoginWithXboxDelegate, const ServerModels::FServerLoginResult&); DECLARE_DELEGATE_OneParam(FLoginWithXboxIdDelegate, const ServerModels::FServerLoginResult&); DECLARE_DELEGATE_OneParam(FModifyItemUsesDelegate, const ServerModels::FModifyItemUsesResult&); DECLARE_DELEGATE_OneParam(FMoveItemToCharacterFromCharacterDelegate, const ServerModels::FMoveItemToCharacterFromCharacterResult&); DECLARE_DELEGATE_OneParam(FMoveItemToCharacterFromUserDelegate, const ServerModels::FMoveItemToCharacterFromUserResult&); DECLARE_DELEGATE_OneParam(FMoveItemToUserFromCharacterDelegate, const ServerModels::FMoveItemToUserFromCharacterResult&); DECLARE_DELEGATE_OneParam(FRedeemCouponDelegate, const ServerModels::FRedeemCouponResult&); DECLARE_DELEGATE_OneParam(FRemoveFriendDelegate, const ServerModels::FEmptyResponse&); DECLARE_DELEGATE_OneParam(FRemoveGenericIDDelegate, const ServerModels::FEmptyResult&); DECLARE_DELEGATE_OneParam(FRemovePlayerTagDelegate, const ServerModels::FRemovePlayerTagResult&); DECLARE_DELEGATE_OneParam(FRemoveSharedGroupMembersDelegate, const ServerModels::FRemoveSharedGroupMembersResult&); DECLARE_DELEGATE_OneParam(FReportPlayerDelegate, const ServerModels::FReportPlayerServerResult&); DECLARE_DELEGATE_OneParam(FRevokeAllBansForUserDelegate, const ServerModels::FRevokeAllBansForUserResult&); DECLARE_DELEGATE_OneParam(FRevokeBansDelegate, const ServerModels::FRevokeBansResult&); DECLARE_DELEGATE_OneParam(FRevokeInventoryItemDelegate, const ServerModels::FRevokeInventoryResult&); DECLARE_DELEGATE_OneParam(FRevokeInventoryItemsDelegate, const ServerModels::FRevokeInventoryItemsResult&); DECLARE_DELEGATE_OneParam(FSavePushNotificationTemplateDelegate, const ServerModels::FSavePushNotificationTemplateResult&); DECLARE_DELEGATE_OneParam(FSendCustomAccountRecoveryEmailDelegate, const ServerModels::FSendCustomAccountRecoveryEmailResult&); DECLARE_DELEGATE_OneParam(FSendEmailFromTemplateDelegate, const ServerModels::FSendEmailFromTemplateResult&); DECLARE_DELEGATE_OneParam(FSendPushNotificationDelegate, const ServerModels::FSendPushNotificationResult&); DECLARE_DELEGATE_OneParam(FSendPushNotificationFromTemplateDelegate, const ServerModels::FSendPushNotificationResult&); DECLARE_DELEGATE_OneParam(FSetFriendTagsDelegate, const ServerModels::FEmptyResponse&); DECLARE_DELEGATE_OneParam(FSetPlayerSecretDelegate, const ServerModels::FSetPlayerSecretResult&); DECLARE_DELEGATE_OneParam(FSetPublisherDataDelegate, const ServerModels::FSetPublisherDataResult&); DECLARE_DELEGATE_OneParam(FSetTitleDataDelegate, const ServerModels::FSetTitleDataResult&); DECLARE_DELEGATE_OneParam(FSetTitleInternalDataDelegate, const ServerModels::FSetTitleDataResult&); DECLARE_DELEGATE_OneParam(FSubtractCharacterVirtualCurrencyDelegate, const ServerModels::FModifyCharacterVirtualCurrencyResult&); DECLARE_DELEGATE_OneParam(FSubtractUserVirtualCurrencyDelegate, const ServerModels::FModifyUserVirtualCurrencyResult&); DECLARE_DELEGATE_OneParam(FUnlinkBattleNetAccountDelegate, const ServerModels::FEmptyResponse&); DECLARE_DELEGATE_OneParam(FUnlinkNintendoServiceAccountDelegate, const ServerModels::FEmptyResponse&); DECLARE_DELEGATE_OneParam(FUnlinkNintendoSwitchDeviceIdDelegate, const ServerModels::FUnlinkNintendoSwitchDeviceIdResult&); DECLARE_DELEGATE_OneParam(FUnlinkPSNAccountDelegate, const ServerModels::FUnlinkPSNAccountResult&); DECLARE_DELEGATE_OneParam(FUnlinkServerCustomIdDelegate, const ServerModels::FUnlinkServerCustomIdResult&); DECLARE_DELEGATE_OneParam(FUnlinkSteamIdDelegate, const ServerModels::FUnlinkSteamIdResult&); DECLARE_DELEGATE_OneParam(FUnlinkXboxAccountDelegate, const ServerModels::FUnlinkXboxAccountResult&); DECLARE_DELEGATE_OneParam(FUnlockContainerInstanceDelegate, const ServerModels::FUnlockContainerItemResult&); DECLARE_DELEGATE_OneParam(FUnlockContainerItemDelegate, const ServerModels::FUnlockContainerItemResult&); DECLARE_DELEGATE_OneParam(FUpdateAvatarUrlDelegate, const ServerModels::FEmptyResponse&); DECLARE_DELEGATE_OneParam(FUpdateBansDelegate, const ServerModels::FUpdateBansResult&); DECLARE_DELEGATE_OneParam(FUpdateCharacterDataDelegate, const ServerModels::FUpdateCharacterDataResult&); DECLARE_DELEGATE_OneParam(FUpdateCharacterInternalDataDelegate, const ServerModels::FUpdateCharacterDataResult&); DECLARE_DELEGATE_OneParam(FUpdateCharacterReadOnlyDataDelegate, const ServerModels::FUpdateCharacterDataResult&); DECLARE_DELEGATE_OneParam(FUpdateCharacterStatisticsDelegate, const ServerModels::FUpdateCharacterStatisticsResult&); DECLARE_DELEGATE_OneParam(FUpdatePlayerCustomPropertiesDelegate, const ServerModels::FUpdatePlayerCustomPropertiesResult&); DECLARE_DELEGATE_OneParam(FUpdatePlayerStatisticsDelegate, const ServerModels::FUpdatePlayerStatisticsResult&); DECLARE_DELEGATE_OneParam(FUpdateSharedGroupDataDelegate, const ServerModels::FUpdateSharedGroupDataResult&); DECLARE_DELEGATE_OneParam(FUpdateUserDataDelegate, const ServerModels::FUpdateUserDataResult&); DECLARE_DELEGATE_OneParam(FUpdateUserInternalDataDelegate, const ServerModels::FUpdateUserDataResult&); DECLARE_DELEGATE_OneParam(FUpdateUserInventoryItemCustomDataDelegate, const ServerModels::FEmptyResponse&); DECLARE_DELEGATE_OneParam(FUpdateUserPublisherDataDelegate, const ServerModels::FUpdateUserDataResult&); DECLARE_DELEGATE_OneParam(FUpdateUserPublisherInternalDataDelegate, const ServerModels::FUpdateUserDataResult&); DECLARE_DELEGATE_OneParam(FUpdateUserPublisherReadOnlyDataDelegate, const ServerModels::FUpdateUserDataResult&); DECLARE_DELEGATE_OneParam(FUpdateUserReadOnlyDataDelegate, const ServerModels::FUpdateUserDataResult&); DECLARE_DELEGATE_OneParam(FWriteCharacterEventDelegate, const ServerModels::FWriteEventResponse&); DECLARE_DELEGATE_OneParam(FWritePlayerEventDelegate, const ServerModels::FWriteEventResponse&); DECLARE_DELEGATE_OneParam(FWriteTitleEventDelegate, const ServerModels::FWriteEventResponse&); private: TSharedPtr<UPlayFabAPISettings> settings; TSharedPtr<UPlayFabAuthenticationContext> authContext; public: UPlayFabServerInstanceAPI(); explicit UPlayFabServerInstanceAPI(TSharedPtr<UPlayFabAPISettings> apiSettings); explicit UPlayFabServerInstanceAPI(TSharedPtr<UPlayFabAuthenticationContext> authenticationContext); UPlayFabServerInstanceAPI(TSharedPtr<UPlayFabAPISettings> apiSettings, TSharedPtr<UPlayFabAuthenticationContext> authenticationContext); ~UPlayFabServerInstanceAPI(); UPlayFabServerInstanceAPI(const UPlayFabServerInstanceAPI& source) = delete; // disable copy UPlayFabServerInstanceAPI(UPlayFabServerInstanceAPI&&) = delete; // disable move UPlayFabServerInstanceAPI& operator=(const UPlayFabServerInstanceAPI& source) = delete; // disable assignment UPlayFabServerInstanceAPI& operator=(UPlayFabServerInstanceAPI&& other) = delete; // disable move assignment int GetPendingCalls() const; TSharedPtr<UPlayFabAPISettings> GetSettings() const; void SetSettings(TSharedPtr<UPlayFabAPISettings> apiSettings); TSharedPtr<UPlayFabAuthenticationContext> GetAuthenticationContext() const; void SetAuthenticationContext(TSharedPtr<UPlayFabAuthenticationContext> authenticationContext); void ForgetAllCredentials(); private: TSharedPtr<UPlayFabAuthenticationContext> GetOrCreateAuthenticationContext(); public: // ------------ Generated API calls /** * _NOTE: This is a Legacy Economy API, and is in bugfix-only mode. All new Economy features are being developed only for * version 2._ Increments the character's balance of the specified virtual currency by the stated amount */ bool AddCharacterVirtualCurrency(ServerModels::FAddCharacterVirtualCurrencyRequest& request, const FAddCharacterVirtualCurrencyDelegate& SuccessDelegate = FAddCharacterVirtualCurrencyDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Adds the Friend user to the friendlist of the user with PlayFabId. At least one of * FriendPlayFabId,FriendUsername,FriendEmail, or FriendTitleDisplayName should be initialized. */ bool AddFriend(ServerModels::FAddFriendRequest& request, const FAddFriendDelegate& SuccessDelegate = FAddFriendDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Adds the specified generic service identifier to the player's PlayFab account. This is designed to allow for a PlayFab * ID lookup of any arbitrary service identifier a title wants to add. This identifier should never be used as * authentication credentials, as the intent is that it is easily accessible by other players. */ bool AddGenericID(ServerModels::FAddGenericIDRequest& request, const FAddGenericIDDelegate& SuccessDelegate = FAddGenericIDDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Adds a given tag to a player profile. The tag's namespace is automatically generated based on the source of the tag. * This API will trigger a player_tag_added event and add a tag with the given TagName and PlayFabID to the corresponding player profile. TagName can be used for segmentation and it is limited to 256 characters. Also there is a limit on the number of tags a title can have. */ bool AddPlayerTag(ServerModels::FAddPlayerTagRequest& request, const FAddPlayerTagDelegate& SuccessDelegate = FAddPlayerTagDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Adds users to the set of those able to update both the shared data, as well as the set of users in the group. Only users * in the group (and the server) can add new members. Shared Groups are designed for sharing data between a very small * number of players, please see our guide: * https://docs.microsoft.com/gaming/playfab/features/social/groups/using-shared-group-data */ bool AddSharedGroupMembers(ServerModels::FAddSharedGroupMembersRequest& request, const FAddSharedGroupMembersDelegate& SuccessDelegate = FAddSharedGroupMembersDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * _NOTE: This is a Legacy Economy API, and is in bugfix-only mode. All new Economy features are being developed only for * version 2._ Increments the user's balance of the specified virtual currency by the stated amount */ bool AddUserVirtualCurrency(ServerModels::FAddUserVirtualCurrencyRequest& request, const FAddUserVirtualCurrencyDelegate& SuccessDelegate = FAddUserVirtualCurrencyDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Validated a client's session ticket, and if successful, returns details for that user * Note that data returned may be Personally Identifying Information (PII), such as email address, and so care should be taken in how this data is stored and managed. Since this call will always return the relevant information for users who have accessed the title, the recommendation is to not store this data locally. */ bool AuthenticateSessionTicket(ServerModels::FAuthenticateSessionTicketRequest& request, const FAuthenticateSessionTicketDelegate& SuccessDelegate = FAuthenticateSessionTicketDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Awards the specified users the specified Steam achievements bool AwardSteamAchievement(ServerModels::FAwardSteamAchievementRequest& request, const FAwardSteamAchievementDelegate& SuccessDelegate = FAwardSteamAchievementDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Bans users by PlayFab ID with optional IP address, or MAC address for the provided game. * The existence of each user will not be verified. When banning by IP or MAC address, multiple players may be affected, so use this feature with caution. Returns information about the new bans. */ bool BanUsers(ServerModels::FBanUsersRequest& request, const FBanUsersDelegate& SuccessDelegate = FBanUsersDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * _NOTE: This is a Legacy Economy API, and is in bugfix-only mode. All new Economy features are being developed only for * version 2._ Consume uses of a consumable item. When all uses are consumed, it will be removed from the player's * inventory. */ bool ConsumeItem(ServerModels::FConsumeItemRequest& request, const FConsumeItemDelegate& SuccessDelegate = FConsumeItemDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Requests the creation of a shared group object, containing key/value pairs which may be updated by all members of the * group. When created by a server, the group will initially have no members. Shared Groups are designed for sharing data * between a very small number of players, please see our guide: * https://docs.microsoft.com/gaming/playfab/features/social/groups/using-shared-group-data * If SharedGroupId is specified, the service will attempt to create a group with that identifier, and will return an error if it is already in use. If no SharedGroupId is specified, a random identifier will be assigned. */ bool CreateSharedGroup(ServerModels::FCreateSharedGroupRequest& request, const FCreateSharedGroupDelegate& SuccessDelegate = FCreateSharedGroupDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Deletes the specific character ID from the specified user. * This function will delete the specified character from the list allowed by the user, and will also delete any inventory or VC currently held by that character. It will NOT delete any statistics associated for this character, in order to preserve leaderboard integrity. */ bool DeleteCharacterFromUser(ServerModels::FDeleteCharacterFromUserRequest& request, const FDeleteCharacterFromUserDelegate& SuccessDelegate = FDeleteCharacterFromUserDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Removes a user's player account from a title and deletes all associated data * Deletes all data associated with the player, including statistics, custom data, inventory, purchases, virtual currency balances, characters and shared group memberships. Removes the player from all leaderboards and player search indexes. Does not delete PlayStream event history associated with the player. Does not delete the publisher user account that created the player in the title nor associated data such as username, password, email address, account linkages, or friends list. Note, this API queues the player for deletion and returns immediately. It may take several minutes or more before all player data is fully deleted. Until the player data is fully deleted, attempts to recreate the player with the same user account in the same title will fail with the 'AccountDeleted' error. This API must be enabled for use as an option in the game manager website. It is disabled by default. */ bool DeletePlayer(ServerModels::FDeletePlayerRequest& request, const FDeletePlayerDelegate& SuccessDelegate = FDeletePlayerDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Deletes title-specific custom properties for a player * Deletes custom properties for the specified player. The list of provided property names must be non-empty. */ bool DeletePlayerCustomProperties(ServerModels::FDeletePlayerCustomPropertiesRequest& request, const FDeletePlayerCustomPropertiesDelegate& SuccessDelegate = FDeletePlayerCustomPropertiesDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Deletes push notification template for title bool DeletePushNotificationTemplate(ServerModels::FDeletePushNotificationTemplateRequest& request, const FDeletePushNotificationTemplateDelegate& SuccessDelegate = FDeletePushNotificationTemplateDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Deletes a shared group, freeing up the shared group ID to be reused for a new group. Shared Groups are designed for * sharing data between a very small number of players, please see our guide: * https://docs.microsoft.com/gaming/playfab/features/social/groups/using-shared-group-data */ bool DeleteSharedGroup(ServerModels::FDeleteSharedGroupRequest& request, const FDeleteSharedGroupDelegate& SuccessDelegate = FDeleteSharedGroupDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * _NOTE: This is a Legacy Economy API, and is in bugfix-only mode. All new Economy features are being developed only for * version 2._ Returns the result of an evaluation of a Random Result Table - the ItemId from the game Catalog which would * have been added to the player inventory, if the Random Result Table were added via a Bundle or a call to * UnlockContainer. */ bool EvaluateRandomResultTable(ServerModels::FEvaluateRandomResultTableRequest& request, const FEvaluateRandomResultTableDelegate& SuccessDelegate = FEvaluateRandomResultTableDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Executes a CloudScript function, with the 'currentPlayerId' set to the PlayFab ID of the authenticated player. The * PlayFab ID is the entity ID of the player's master_player_account entity. */ bool ExecuteCloudScript(ServerModels::FExecuteCloudScriptServerRequest& request, const FExecuteCloudScriptDelegate& SuccessDelegate = FExecuteCloudScriptDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Retrieves an array of player segment definitions. Results from this can be used in subsequent API calls such as * GetPlayersInSegment which requires a Segment ID. While segment names can change the ID for that segment will not change. * Request has no paramaters. */ bool GetAllSegments(const FGetAllSegmentsDelegate& SuccessDelegate = FGetAllSegmentsDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Retrieves an array of player segment definitions. Results from this can be used in subsequent API calls such as * GetPlayersInSegment which requires a Segment ID. While segment names can change the ID for that segment will not change. * Request has no paramaters. */ bool GetAllSegments(ServerModels::FGetAllSegmentsRequest& request, const FGetAllSegmentsDelegate& SuccessDelegate = FGetAllSegmentsDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Lists all of the characters that belong to a specific user. CharacterIds are not globally unique; characterId must be * evaluated with the parent PlayFabId to guarantee uniqueness. * Returns a list of every character that currently belongs to a user. */ bool GetAllUsersCharacters(ServerModels::FListUsersCharactersRequest& request, const FGetAllUsersCharactersDelegate& SuccessDelegate = FGetAllUsersCharactersDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * _NOTE: This is a Legacy Economy API, and is in bugfix-only mode. All new Economy features are being developed only for * version 2._ Retrieves the specified version of the title's catalog of virtual goods, including all defined properties */ bool GetCatalogItems(ServerModels::FGetCatalogItemsRequest& request, const FGetCatalogItemsDelegate& SuccessDelegate = FGetCatalogItemsDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Retrieves the title-specific custom data for the user which is readable and writable by the client * Data is stored as JSON key-value pairs. If the Keys parameter is provided, the data object returned will only contain the data specific to the indicated Keys. Otherwise, the full set of custom user data will be returned. */ bool GetCharacterData(ServerModels::FGetCharacterDataRequest& request, const FGetCharacterDataDelegate& SuccessDelegate = FGetCharacterDataDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Retrieves the title-specific custom data for the user's character which cannot be accessed by the client * Data is stored as JSON key-value pairs. If the Keys parameter is provided, the data object returned will only contain the data specific to the indicated Keys. Otherwise, the full set of custom user data will be returned. */ bool GetCharacterInternalData(ServerModels::FGetCharacterDataRequest& request, const FGetCharacterInternalDataDelegate& SuccessDelegate = FGetCharacterInternalDataDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * _NOTE: This is a Legacy Economy API, and is in bugfix-only mode. All new Economy features are being developed only for * version 2._ Retrieves the specified character's current inventory of virtual goods * All items currently in the character inventory will be returned, irrespective of how they were acquired (via purchasing, grants, coupons, etc.). Items that are expired, fully consumed, or are no longer valid are not considered to be in the user's current inventory, and so will not be not included. Also returns their virtual currency balances. */ bool GetCharacterInventory(ServerModels::FGetCharacterInventoryRequest& request, const FGetCharacterInventoryDelegate& SuccessDelegate = FGetCharacterInventoryDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Retrieves a list of ranked characters for the given statistic, starting from the indicated point in the leaderboard bool GetCharacterLeaderboard(ServerModels::FGetCharacterLeaderboardRequest& request, const FGetCharacterLeaderboardDelegate& SuccessDelegate = FGetCharacterLeaderboardDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Retrieves the title-specific custom data for the user's character which can only be read by the client * Data is stored as JSON key-value pairs. If the Keys parameter is provided, the data object returned will only contain the data specific to the indicated Keys. Otherwise, the full set of custom data will be returned. */ bool GetCharacterReadOnlyData(ServerModels::FGetCharacterDataRequest& request, const FGetCharacterReadOnlyDataDelegate& SuccessDelegate = FGetCharacterReadOnlyDataDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Retrieves the details of all title-specific statistics for the specific character * Character statistics are similar to user statistics in that they are numeric values which may only be updated by a server operation, in order to minimize the opportunity for unauthorized changes. In addition to being available for use by the title, the statistics are used for all leaderboard operations in PlayFab. */ bool GetCharacterStatistics(ServerModels::FGetCharacterStatisticsRequest& request, const FGetCharacterStatisticsDelegate& SuccessDelegate = FGetCharacterStatisticsDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * This API retrieves a pre-signed URL for accessing a content file for the title. A subsequent HTTP GET to the returned * URL will attempt to download the content. A HEAD query to the returned URL will attempt to retrieve the metadata of the * content. Note that a successful result does not guarantee the existence of this content - if it has not been uploaded, * the query to retrieve the data will fail. See this post for more information: * https://community.playfab.com/hc/community/posts/205469488-How-to-upload-files-to-PlayFab-s-Content-Service. Also, * please be aware that the Content service is specifically PlayFab's CDN offering, for which standard CDN rates apply. */ bool GetContentDownloadUrl(ServerModels::FGetContentDownloadUrlRequest& request, const FGetContentDownloadUrlDelegate& SuccessDelegate = FGetContentDownloadUrlDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Retrieves a list of ranked friends of the given player for the given statistic, starting from the indicated point in the * leaderboard */ bool GetFriendLeaderboard(ServerModels::FGetFriendLeaderboardRequest& request, const FGetFriendLeaderboardDelegate& SuccessDelegate = FGetFriendLeaderboardDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Retrieves the current friends for the user with PlayFabId, constrained to users who have PlayFab accounts. Friends from * linked accounts (Facebook, Steam) are also included. You may optionally exclude some linked services' friends. */ bool GetFriendsList(ServerModels::FGetFriendsListRequest& request, const FGetFriendsListDelegate& SuccessDelegate = FGetFriendsListDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Retrieves a list of ranked users for the given statistic, starting from the indicated point in the leaderboard bool GetLeaderboard(ServerModels::FGetLeaderboardRequest& request, const FGetLeaderboardDelegate& SuccessDelegate = FGetLeaderboardDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Retrieves a list of ranked characters for the given statistic, centered on the requested user bool GetLeaderboardAroundCharacter(ServerModels::FGetLeaderboardAroundCharacterRequest& request, const FGetLeaderboardAroundCharacterDelegate& SuccessDelegate = FGetLeaderboardAroundCharacterDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Retrieves a list of ranked users for the given statistic, centered on the currently signed-in user bool GetLeaderboardAroundUser(ServerModels::FGetLeaderboardAroundUserRequest& request, const FGetLeaderboardAroundUserDelegate& SuccessDelegate = FGetLeaderboardAroundUserDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Retrieves a list of all of the user's characters for the given statistic. bool GetLeaderboardForUserCharacters(ServerModels::FGetLeaderboardForUsersCharactersRequest& request, const FGetLeaderboardForUserCharactersDelegate& SuccessDelegate = FGetLeaderboardForUserCharactersDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Returns whatever info is requested in the response for the user. Note that PII (like email address, facebook id) may be * returned. All parameters default to false. */ bool GetPlayerCombinedInfo(ServerModels::FGetPlayerCombinedInfoRequest& request, const FGetPlayerCombinedInfoDelegate& SuccessDelegate = FGetPlayerCombinedInfoDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Retrieves a title-specific custom property value for a player. bool GetPlayerCustomProperty(ServerModels::FGetPlayerCustomPropertyRequest& request, const FGetPlayerCustomPropertyDelegate& SuccessDelegate = FGetPlayerCustomPropertyDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Retrieves the player's profile * This API allows for access to details regarding a user in the PlayFab service, usually for purposes of customer support. Note that data returned may be Personally Identifying Information (PII), such as email address, and so care should be taken in how this data is stored and managed. Since this call will always return the relevant information for users who have accessed the title, the recommendation is to not store this data locally. */ bool GetPlayerProfile(ServerModels::FGetPlayerProfileRequest& request, const FGetPlayerProfileDelegate& SuccessDelegate = FGetPlayerProfileDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // List all segments that a player currently belongs to at this moment in time. bool GetPlayerSegments(ServerModels::FGetPlayersSegmentsRequest& request, const FGetPlayerSegmentsDelegate& SuccessDelegate = FGetPlayerSegmentsDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Allows for paging through all players in a given segment. This API creates a snapshot of all player profiles that match * the segment definition at the time of its creation and lives through the Total Seconds to Live, refreshing its life span * on each subsequent use of the Continuation Token. Profiles that change during the course of paging will not be reflected * in the results. AB Test segments are currently not supported by this operation. NOTE: This API is limited to being * called 30 times in one minute. You will be returned an error if you exceed this threshold. * Initial request must contain at least a Segment ID. Subsequent requests must contain the Segment ID as well as the Continuation Token. Failure to send the Continuation Token will result in a new player segment list being generated. Each time the Continuation Token is passed in the length of the Total Seconds to Live is refreshed. If too much time passes between requests to the point that a subsequent request is past the Total Seconds to Live an error will be returned and paging will be terminated. This API is resource intensive and should not be used in scenarios which might generate high request volumes. Only one request to this API at a time should be made per title. Concurrent requests to the API may be rejected with the APIConcurrentRequestLimitExceeded error. */ bool GetPlayersInSegment(ServerModels::FGetPlayersInSegmentRequest& request, const FGetPlayersInSegmentDelegate& SuccessDelegate = FGetPlayersInSegmentDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Retrieves the current version and values for the indicated statistics, for the local player. bool GetPlayerStatistics(ServerModels::FGetPlayerStatisticsRequest& request, const FGetPlayerStatisticsDelegate& SuccessDelegate = FGetPlayerStatisticsDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Retrieves the information on the available versions of the specified statistic. bool GetPlayerStatisticVersions(ServerModels::FGetPlayerStatisticVersionsRequest& request, const FGetPlayerStatisticVersionsDelegate& SuccessDelegate = FGetPlayerStatisticVersionsDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Get all tags with a given Namespace (optional) from a player profile. * This API will return a list of canonical tags which includes both namespace and tag's name. If namespace is not provided, the result is a list of all canonical tags. TagName can be used for segmentation and Namespace is limited to 128 characters. */ bool GetPlayerTags(ServerModels::FGetPlayerTagsRequest& request, const FGetPlayerTagsDelegate& SuccessDelegate = FGetPlayerTagsDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Retrieves the unique PlayFab identifiers for the given set of Battle.net account identifiers. bool GetPlayFabIDsFromBattleNetAccountIds(ServerModels::FGetPlayFabIDsFromBattleNetAccountIdsRequest& request, const FGetPlayFabIDsFromBattleNetAccountIdsDelegate& SuccessDelegate = FGetPlayFabIDsFromBattleNetAccountIdsDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Retrieves the unique PlayFab identifiers for the given set of Facebook identifiers. bool GetPlayFabIDsFromFacebookIDs(ServerModels::FGetPlayFabIDsFromFacebookIDsRequest& request, const FGetPlayFabIDsFromFacebookIDsDelegate& SuccessDelegate = FGetPlayFabIDsFromFacebookIDsDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Retrieves the unique PlayFab identifiers for the given set of Facebook Instant Games identifiers. bool GetPlayFabIDsFromFacebookInstantGamesIds(ServerModels::FGetPlayFabIDsFromFacebookInstantGamesIdsRequest& request, const FGetPlayFabIDsFromFacebookInstantGamesIdsDelegate& SuccessDelegate = FGetPlayFabIDsFromFacebookInstantGamesIdsDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Retrieves the unique PlayFab identifiers for the given set of generic service identifiers. A generic identifier is the * service name plus the service-specific ID for the player, as specified by the title when the generic identifier was * added to the player account. */ bool GetPlayFabIDsFromGenericIDs(ServerModels::FGetPlayFabIDsFromGenericIDsRequest& request, const FGetPlayFabIDsFromGenericIDsDelegate& SuccessDelegate = FGetPlayFabIDsFromGenericIDsDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Retrieves the unique PlayFab identifiers for the given set of Nintendo Service Account identifiers. bool GetPlayFabIDsFromNintendoServiceAccountIds(ServerModels::FGetPlayFabIDsFromNintendoServiceAccountIdsRequest& request, const FGetPlayFabIDsFromNintendoServiceAccountIdsDelegate& SuccessDelegate = FGetPlayFabIDsFromNintendoServiceAccountIdsDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Retrieves the unique PlayFab identifiers for the given set of Nintendo Switch Device identifiers. bool GetPlayFabIDsFromNintendoSwitchDeviceIds(ServerModels::FGetPlayFabIDsFromNintendoSwitchDeviceIdsRequest& request, const FGetPlayFabIDsFromNintendoSwitchDeviceIdsDelegate& SuccessDelegate = FGetPlayFabIDsFromNintendoSwitchDeviceIdsDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Retrieves the unique PlayFab identifiers for the given set of PlayStation :tm: Network identifiers. bool GetPlayFabIDsFromPSNAccountIDs(ServerModels::FGetPlayFabIDsFromPSNAccountIDsRequest& request, const FGetPlayFabIDsFromPSNAccountIDsDelegate& SuccessDelegate = FGetPlayFabIDsFromPSNAccountIDsDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Retrieves the unique PlayFab identifiers for the given set of PlayStation :tm: Network identifiers. bool GetPlayFabIDsFromPSNOnlineIDs(ServerModels::FGetPlayFabIDsFromPSNOnlineIDsRequest& request, const FGetPlayFabIDsFromPSNOnlineIDsDelegate& SuccessDelegate = FGetPlayFabIDsFromPSNOnlineIDsDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Retrieves the unique PlayFab identifiers for the given set of Steam identifiers. The Steam identifiers are the profile * IDs for the user accounts, available as SteamId in the Steamworks Community API calls. */ bool GetPlayFabIDsFromSteamIDs(ServerModels::FGetPlayFabIDsFromSteamIDsRequest& request, const FGetPlayFabIDsFromSteamIDsDelegate& SuccessDelegate = FGetPlayFabIDsFromSteamIDsDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Retrieves the unique PlayFab identifiers for the given set of Steam identifiers. The Steam identifiers are persona * names. */ bool GetPlayFabIDsFromSteamNames(ServerModels::FGetPlayFabIDsFromSteamNamesRequest& request, const FGetPlayFabIDsFromSteamNamesDelegate& SuccessDelegate = FGetPlayFabIDsFromSteamNamesDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Retrieves the unique PlayFab identifiers for the given set of Twitch identifiers. The Twitch identifiers are the IDs for * the user accounts, available as "_id" from the Twitch API methods (ex: * https://github.com/justintv/Twitch-API/blob/master/v3_resources/users.md#get-usersuser). */ bool GetPlayFabIDsFromTwitchIDs(ServerModels::FGetPlayFabIDsFromTwitchIDsRequest& request, const FGetPlayFabIDsFromTwitchIDsDelegate& SuccessDelegate = FGetPlayFabIDsFromTwitchIDsDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Retrieves the unique PlayFab identifiers for the given set of XboxLive identifiers. bool GetPlayFabIDsFromXboxLiveIDs(ServerModels::FGetPlayFabIDsFromXboxLiveIDsRequest& request, const FGetPlayFabIDsFromXboxLiveIDsDelegate& SuccessDelegate = FGetPlayFabIDsFromXboxLiveIDsDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Retrieves the key-value store of custom publisher settings * This API is designed to return publisher-specific values which can be read, but not written to, by the client. This data is shared across all titles assigned to a particular publisher, and can be used for cross-game coordination. Only titles assigned to a publisher can use this API. For more information email helloplayfab@microsoft.com. Note that there may up to a minute delay in between updating title data and this API call returning the newest value. */ bool GetPublisherData(ServerModels::FGetPublisherDataRequest& request, const FGetPublisherDataDelegate& SuccessDelegate = FGetPublisherDataDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * _NOTE: This is a Legacy Economy API, and is in bugfix-only mode. All new Economy features are being developed only for * version 2._ Retrieves the configuration information for the specified random results tables for the title, including all * ItemId values and weights */ bool GetRandomResultTables(ServerModels::FGetRandomResultTablesRequest& request, const FGetRandomResultTablesDelegate& SuccessDelegate = FGetRandomResultTablesDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Retrieves the associated PlayFab account identifiers for the given set of server custom identifiers. bool GetServerCustomIDsFromPlayFabIDs(ServerModels::FGetServerCustomIDsFromPlayFabIDsRequest& request, const FGetServerCustomIDsFromPlayFabIDsDelegate& SuccessDelegate = FGetServerCustomIDsFromPlayFabIDsDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Retrieves data stored in a shared group object, as well as the list of members in the group. The server can access all * public and private group data. Shared Groups are designed for sharing data between a very small number of players, * please see our guide: https://docs.microsoft.com/gaming/playfab/features/social/groups/using-shared-group-data */ bool GetSharedGroupData(ServerModels::FGetSharedGroupDataRequest& request, const FGetSharedGroupDataDelegate& SuccessDelegate = FGetSharedGroupDataDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * _NOTE: This is a Legacy Economy API, and is in bugfix-only mode. All new Economy features are being developed only for * version 2._ Retrieves the set of items defined for the specified store, including all prices defined, for the specified * player * A store contains an array of references to items defined in one or more catalog versions of the game, along with the prices for the item, in both real world and virtual currencies. These prices act as an override to any prices defined in the catalog. In this way, the base definitions of the items may be defined in the catalog, with all associated properties, while the pricing can be set for each store, as needed. This allows for subsets of goods to be defined for different purposes (in order to simplify showing some, but not all catalog items to users, based upon different characteristics), along with unique prices. Note that all prices defined in the catalog and store definitions for the item are considered valid, and that a compromised client can be made to send a request for an item based upon any of these definitions. If no price is specified in the store for an item, the price set in the catalog should be displayed to the user. */ bool GetStoreItems(ServerModels::FGetStoreItemsServerRequest& request, const FGetStoreItemsDelegate& SuccessDelegate = FGetStoreItemsDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Retrieves the current server time * This query retrieves the current time from one of the servers in PlayFab. Please note that due to clock drift between servers, there is a potential variance of up to 5 seconds. */ bool GetTime(const FGetTimeDelegate& SuccessDelegate = FGetTimeDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Retrieves the current server time * This query retrieves the current time from one of the servers in PlayFab. Please note that due to clock drift between servers, there is a potential variance of up to 5 seconds. */ bool GetTime(ServerModels::FGetTimeRequest& request, const FGetTimeDelegate& SuccessDelegate = FGetTimeDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Retrieves the key-value store of custom title settings * This API is designed to return title specific values which can be read, but not written to, by the client. For example, a developer could choose to store values which modify the user experience, such as enemy spawn rates, weapon strengths, movement speeds, etc. This allows a developer to update the title without the need to create, test, and ship a new build. If an override label is specified in the request, the overrides are applied automatically and returned with the title data. Note that there may up to a minute delay in between updating title data and this API call returning the newest value. */ bool GetTitleData(ServerModels::FGetTitleDataRequest& request, const FGetTitleDataDelegate& SuccessDelegate = FGetTitleDataDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Retrieves the key-value store of custom internal title settings * This API is designed to return title specific values which are accessible only to the server. This can be used to tweak settings on game servers and Cloud Scripts without needed to update and re-deploy them. Note that there may up to a minute delay in between updating title data and this API call returning the newest value. */ bool GetTitleInternalData(ServerModels::FGetTitleDataRequest& request, const FGetTitleInternalDataDelegate& SuccessDelegate = FGetTitleInternalDataDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Retrieves the title news feed, as configured in the developer portal bool GetTitleNews(ServerModels::FGetTitleNewsRequest& request, const FGetTitleNewsDelegate& SuccessDelegate = FGetTitleNewsDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Retrieves the relevant details for a specified user * This API allows for access to details regarding a user in the PlayFab service, usually for purposes of customer support. Note that data returned may be Personally Identifying Information (PII), such as email address, and so care should be taken in how this data is stored and managed. Since this call will always return the relevant information for users who have accessed the title, the recommendation is to not store this data locally. */ bool GetUserAccountInfo(ServerModels::FGetUserAccountInfoRequest& request, const FGetUserAccountInfoDelegate& SuccessDelegate = FGetUserAccountInfoDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Gets all bans for a user. * Get all bans for a user, including inactive and expired bans. */ bool GetUserBans(ServerModels::FGetUserBansRequest& request, const FGetUserBansDelegate& SuccessDelegate = FGetUserBansDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Retrieves the title-specific custom data for the user which is readable and writable by the client * Data is stored as JSON key-value pairs. If the Keys parameter is provided, the data object returned will only contain the data specific to the indicated Keys. Otherwise, the full set of custom user data will be returned. */ bool GetUserData(ServerModels::FGetUserDataRequest& request, const FGetUserDataDelegate& SuccessDelegate = FGetUserDataDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Retrieves the title-specific custom data for the user which cannot be accessed by the client * Data is stored as JSON key-value pairs. If the Keys parameter is provided, the data object returned will only contain the data specific to the indicated Keys. Otherwise, the full set of custom user data will be returned. */ bool GetUserInternalData(ServerModels::FGetUserDataRequest& request, const FGetUserInternalDataDelegate& SuccessDelegate = FGetUserInternalDataDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * _NOTE: This is a Legacy Economy API, and is in bugfix-only mode. All new Economy features are being developed only for * version 2._ Retrieves the specified user's current inventory of virtual goods * All items currently in the user inventory will be returned, irrespective of how they were acquired (via purchasing, grants, coupons, etc.). Items that are expired, fully consumed, or are no longer valid are not considered to be in the user's current inventory, and so will not be not included. */ bool GetUserInventory(ServerModels::FGetUserInventoryRequest& request, const FGetUserInventoryDelegate& SuccessDelegate = FGetUserInventoryDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Retrieves the publisher-specific custom data for the user which is readable and writable by the client * Data is stored as JSON key-value pairs. If the Keys parameter is provided, the data object returned will only contain the data specific to the indicated Keys. Otherwise, the full set of custom user data will be returned. */ bool GetUserPublisherData(ServerModels::FGetUserDataRequest& request, const FGetUserPublisherDataDelegate& SuccessDelegate = FGetUserPublisherDataDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Retrieves the publisher-specific custom data for the user which cannot be accessed by the client * Data is stored as JSON key-value pairs. If the Keys parameter is provided, the data object returned will only contain the data specific to the indicated Keys. Otherwise, the full set of custom user data will be returned. */ bool GetUserPublisherInternalData(ServerModels::FGetUserDataRequest& request, const FGetUserPublisherInternalDataDelegate& SuccessDelegate = FGetUserPublisherInternalDataDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Retrieves the publisher-specific custom data for the user which can only be read by the client * Data is stored as JSON key-value pairs. If the Keys parameter is provided, the data object returned will only contain the data specific to the indicated Keys. Otherwise, the full set of custom user data will be returned. */ bool GetUserPublisherReadOnlyData(ServerModels::FGetUserDataRequest& request, const FGetUserPublisherReadOnlyDataDelegate& SuccessDelegate = FGetUserPublisherReadOnlyDataDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Retrieves the title-specific custom data for the user which can only be read by the client * Data is stored as JSON key-value pairs. If the Keys parameter is provided, the data object returned will only contain the data specific to the indicated Keys. Otherwise, the full set of custom user data will be returned. */ bool GetUserReadOnlyData(ServerModels::FGetUserDataRequest& request, const FGetUserReadOnlyDataDelegate& SuccessDelegate = FGetUserReadOnlyDataDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Grants the specified character type to the user. CharacterIds are not globally unique; characterId must be evaluated * with the parent PlayFabId to guarantee uniqueness. * Grants a character to the user of the type and name specified in the request. */ bool GrantCharacterToUser(ServerModels::FGrantCharacterToUserRequest& request, const FGrantCharacterToUserDelegate& SuccessDelegate = FGrantCharacterToUserDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * _NOTE: This is a Legacy Economy API, and is in bugfix-only mode. All new Economy features are being developed only for * version 2._ Adds the specified items to the specified character's inventory * This function directly adds inventory items to the character's inventories. As a result of this operations, the user will not be charged any transaction fee, regardless of the inventory item catalog definition. Please note that the processing time for inventory grants and purchases increases fractionally the more items are in the inventory, and the more items are in the grant/purchase operation. */ bool GrantItemsToCharacter(ServerModels::FGrantItemsToCharacterRequest& request, const FGrantItemsToCharacterDelegate& SuccessDelegate = FGrantItemsToCharacterDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * _NOTE: This is a Legacy Economy API, and is in bugfix-only mode. All new Economy features are being developed only for * version 2._ Adds the specified items to the specified user's inventory * This function directly adds inventory items to the user's inventories. As a result of this operations, the user will not be charged any transaction fee, regardless of the inventory item catalog definition. Please note that the processing time for inventory grants and purchases increases fractionally the more items are in the inventory, and the more items are in the grant/purchase operation. */ bool GrantItemsToUser(ServerModels::FGrantItemsToUserRequest& request, const FGrantItemsToUserDelegate& SuccessDelegate = FGrantItemsToUserDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * _NOTE: This is a Legacy Economy API, and is in bugfix-only mode. All new Economy features are being developed only for * version 2._ Adds the specified items to the specified user inventories * This function directly adds inventory items to user inventories. As a result of this operations, the user will not be charged any transaction fee, regardless of the inventory item catalog definition. Please note that the processing time for inventory grants and purchases increases fractionally the more items are in the inventory, and the more items are in the grant/purchase operation. */ bool GrantItemsToUsers(ServerModels::FGrantItemsToUsersRequest& request, const FGrantItemsToUsersDelegate& SuccessDelegate = FGrantItemsToUsersDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Links the Battle.net account associated with the token to the user's PlayFab account. bool LinkBattleNetAccount(ServerModels::FLinkBattleNetAccountRequest& request, const FLinkBattleNetAccountDelegate& SuccessDelegate = FLinkBattleNetAccountDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Links the Nintendo account associated with the token to the user's PlayFab account bool LinkNintendoServiceAccount(ServerModels::FLinkNintendoServiceAccountRequest& request, const FLinkNintendoServiceAccountDelegate& SuccessDelegate = FLinkNintendoServiceAccountDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Links the Nintendo account associated with the Nintendo Service Account subject or id to the user's PlayFab account bool LinkNintendoServiceAccountSubject(ServerModels::FLinkNintendoServiceAccountSubjectRequest& request, const FLinkNintendoServiceAccountSubjectDelegate& SuccessDelegate = FLinkNintendoServiceAccountSubjectDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Links the NintendoSwitchDeviceId to the user's PlayFab account bool LinkNintendoSwitchDeviceId(ServerModels::FLinkNintendoSwitchDeviceIdRequest& request, const FLinkNintendoSwitchDeviceIdDelegate& SuccessDelegate = FLinkNintendoSwitchDeviceIdDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Links the PlayStation :tm: Network account associated with the provided access code to the user's PlayFab account bool LinkPSNAccount(ServerModels::FLinkPSNAccountRequest& request, const FLinkPSNAccountDelegate& SuccessDelegate = FLinkPSNAccountDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Links the PlayStation :tm: Network account associated with the provided user id to the user's PlayFab account bool LinkPSNId(ServerModels::FLinkPSNIdRequest& request, const FLinkPSNIdDelegate& SuccessDelegate = FLinkPSNIdDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Links the custom server identifier, generated by the title, to the user's PlayFab account. bool LinkServerCustomId(ServerModels::FLinkServerCustomIdRequest& request, const FLinkServerCustomIdDelegate& SuccessDelegate = FLinkServerCustomIdDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Links the Steam account associated with the provided Steam ID to the user's PlayFab account bool LinkSteamId(ServerModels::FLinkSteamIdRequest& request, const FLinkSteamIdDelegate& SuccessDelegate = FLinkSteamIdDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Links the Xbox Live account associated with the provided access code to the user's PlayFab account bool LinkXboxAccount(ServerModels::FLinkXboxAccountRequest& request, const FLinkXboxAccountDelegate& SuccessDelegate = FLinkXboxAccountDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Links the Xbox Live account associated with the provided Xbox ID and Sandbox to the user's PlayFab account bool LinkXboxId(ServerModels::FLinkXboxIdRequest& request, const FLinkXboxIdDelegate& SuccessDelegate = FLinkXboxIdDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Retrieves title-specific custom property values for a player. bool ListPlayerCustomProperties(ServerModels::FListPlayerCustomPropertiesRequest& request, const FListPlayerCustomPropertiesDelegate& SuccessDelegate = FListPlayerCustomPropertiesDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Signs the user in using the Android device identifier, returning a session identifier that can subsequently be used for * API calls which require an authenticated user * On Android devices, the recommendation is to use the Settings.Secure.ANDROID_ID as the AndroidDeviceId, as described in this blog post (http://android-developers.blogspot.com/2011/03/identifying-app-installations.html). More information on this identifier can be found in the Android documentation (http://developer.android.com/reference/android/provider/Settings.Secure.html). If this is the first time a user has signed in with the Android device and CreateAccount is set to true, a new PlayFab account will be created and linked to the Android device ID. In this case, no email or username will be associated with the PlayFab account. Otherwise, if no PlayFab account is linked to the Android device, an error indicating this will be returned, so that the title can guide the user through creation of a PlayFab account. Please note that while multiple devices of this type can be linked to a single user account, only the one most recently used to login (or most recently linked) will be reflected in the user's account information. We will be updating to show all linked devices in a future release. */ bool LoginWithAndroidDeviceID(ServerModels::FLoginWithAndroidDeviceIDRequest& request, const FLoginWithAndroidDeviceIDDelegate& SuccessDelegate = FLoginWithAndroidDeviceIDDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Sign in the user with a Battle.net identity token bool LoginWithBattleNet(ServerModels::FLoginWithBattleNetRequest& request, const FLoginWithBattleNetDelegate& SuccessDelegate = FLoginWithBattleNetDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Signs the user in using a custom unique identifier generated by the title, returning a session identifier that can * subsequently be used for API calls which require an authenticated user * It is highly recommended that developers ensure that it is extremely unlikely that a customer could generate an ID which is already in use by another customer. If this is the first time a user has signed in with the Custom ID and CreateAccount is set to true, a new PlayFab account will be created and linked to the Custom ID. In this case, no email or username will be associated with the PlayFab account. Otherwise, if no PlayFab account is linked to the Custom ID, an error indicating this will be returned, so that the title can guide the user through creation of a PlayFab account. */ bool LoginWithCustomID(ServerModels::FLoginWithCustomIDRequest& request, const FLoginWithCustomIDDelegate& SuccessDelegate = FLoginWithCustomIDDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Signs the user in using the iOS device identifier, returning a session identifier that can subsequently be used for API * calls which require an authenticated user * On iOS devices, the identifierForVendor (https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIDevice_Class/index.html#//apple_ref/occ/instp/UIDevice/identifierForVendor) must be used as the DeviceId, as the UIDevice uniqueIdentifier has been deprecated as of iOS 5, and use of the advertisingIdentifier for this purpose will result in failure of Apple's certification process. If this is the first time a user has signed in with the iOS device and CreateAccount is set to true, a new PlayFab account will be created and linked to the vendor-specific iOS device ID. In this case, no email or username will be associated with the PlayFab account. Otherwise, if no PlayFab account is linked to the iOS device, an error indicating this will be returned, so that the title can guide the user through creation of a PlayFab account. */ bool LoginWithIOSDeviceID(ServerModels::FLoginWithIOSDeviceIDRequest& request, const FLoginWithIOSDeviceIDDelegate& SuccessDelegate = FLoginWithIOSDeviceIDDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Signs the user in using a PlayStation :tm: Network authentication code, returning a session identifier that can * subsequently be used for API calls which require an authenticated user * If this is the first time a user has signed in with the PlayStation :tm: Network account and CreateAccount is set to true, a new PlayFab account will be created and linked to the PlayStation :tm: Network account. In this case, no email or username will be associated with the PlayFab account. Otherwise, if no PlayFab account is linked to the PlayStation :tm: Network account, an error indicating this will be returned, so that the title can guide the user through creation of a PlayFab account. */ bool LoginWithPSN(ServerModels::FLoginWithPSNRequest& request, const FLoginWithPSNDelegate& SuccessDelegate = FLoginWithPSNDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Securely login a game client from an external server backend using a custom identifier for that player. Server Custom ID * and Client Custom ID are mutually exclusive and cannot be used to retrieve the same player account. */ bool LoginWithServerCustomId(ServerModels::FLoginWithServerCustomIdRequest& request, const FLoginWithServerCustomIdDelegate& SuccessDelegate = FLoginWithServerCustomIdDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Signs the user in using an Steam ID, returning a session identifier that can subsequently be used for API calls which * require an authenticated user * If this is the first time a user has signed in with the Steam ID and CreateAccount is set to true, a new PlayFab account will be created and linked to the Steam account. In this case, no email or username will be associated with the PlayFab account. Otherwise, if no PlayFab account is linked to the Steam account, an error indicating this will be returned, so that the title can guide the user through creation of a PlayFab account. Steam users that are not logged into the Steam Client app will only have their Steam username synced, other data, such as currency and country will not be available until they login while the Client is open. */ bool LoginWithSteamId(ServerModels::FLoginWithSteamIdRequest& request, const FLoginWithSteamIdDelegate& SuccessDelegate = FLoginWithSteamIdDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Signs the user in using a Xbox Live Token from an external server backend, returning a session identifier that can * subsequently be used for API calls which require an authenticated user * If this is the first time a user has signed in with the Xbox Live account and CreateAccount is set to true, a new PlayFab account will be created and linked to the Xbox Live account. In this case, no email or username will be associated with the PlayFab account. Otherwise, if no PlayFab account is linked to the Xbox Live account, an error indicating this will be returned, so that the title can guide the user through creation of a PlayFab account. */ bool LoginWithXbox(ServerModels::FLoginWithXboxRequest& request, const FLoginWithXboxDelegate& SuccessDelegate = FLoginWithXboxDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Signs the user in using an Xbox ID and Sandbox ID, returning a session identifier that can subsequently be used for API * calls which require an authenticated user * If this is the first time a user has signed in with the Xbox ID and CreateAccount is set to true, a new PlayFab account will be created and linked to the Xbox Live account. In this case, no email or username will be associated with the PlayFab account. Otherwise, if no PlayFab account is linked to the Xbox Live account, an error indicating this will be returned, so that the title can guide the user through creation of a PlayFab account. */ bool LoginWithXboxId(ServerModels::FLoginWithXboxIdRequest& request, const FLoginWithXboxIdDelegate& SuccessDelegate = FLoginWithXboxIdDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * _NOTE: This is a Legacy Economy API, and is in bugfix-only mode. All new Economy features are being developed only for * version 2._ Modifies the number of remaining uses of a player's inventory item * This function can both add and remove uses of an inventory item. If the number of uses drops below zero, the item will be removed from active inventory. */ bool ModifyItemUses(ServerModels::FModifyItemUsesRequest& request, const FModifyItemUsesDelegate& SuccessDelegate = FModifyItemUsesDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * _NOTE: This is a Legacy Economy API, and is in bugfix-only mode. All new Economy features are being developed only for * version 2._ Moves an item from a character's inventory into another of the users's character's inventory. * Transfers an item from a character to another character that is owned by the same user. This will remove the item from the character's inventory (until and unless it is moved back), and will enable the other character to make use of the item instead. */ bool MoveItemToCharacterFromCharacter(ServerModels::FMoveItemToCharacterFromCharacterRequest& request, const FMoveItemToCharacterFromCharacterDelegate& SuccessDelegate = FMoveItemToCharacterFromCharacterDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * _NOTE: This is a Legacy Economy API, and is in bugfix-only mode. All new Economy features are being developed only for * version 2._ Moves an item from a user's inventory into their character's inventory. * Transfers an item from a user to a character she owns. This will remove the item from the user's inventory (until and unless it is moved back), and will enable the character to make use of the item instead. */ bool MoveItemToCharacterFromUser(ServerModels::FMoveItemToCharacterFromUserRequest& request, const FMoveItemToCharacterFromUserDelegate& SuccessDelegate = FMoveItemToCharacterFromUserDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * _NOTE: This is a Legacy Economy API, and is in bugfix-only mode. All new Economy features are being developed only for * version 2._ Moves an item from a character's inventory into the owning user's inventory. * Transfers an item from a character to the owning user. This will remove the item from the character's inventory (until and unless it is moved back), and will enable the user to make use of the item instead. */ bool MoveItemToUserFromCharacter(ServerModels::FMoveItemToUserFromCharacterRequest& request, const FMoveItemToUserFromCharacterDelegate& SuccessDelegate = FMoveItemToUserFromCharacterDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * _NOTE: This is a Legacy Economy API, and is in bugfix-only mode. All new Economy features are being developed only for * version 2._ Adds the virtual goods associated with the coupon to the user's inventory. Coupons can be generated via the * Economy->Catalogs tab in the PlayFab Game Manager. * Coupon codes can be created for any item, or set of items, in the catalog for the title. This operation causes the coupon to be consumed, and the specific items to be awarded to the user. Attempting to re-use an already consumed code, or a code which has not yet been created in the service, will result in an error. */ bool RedeemCoupon(ServerModels::FRedeemCouponRequest& request, const FRedeemCouponDelegate& SuccessDelegate = FRedeemCouponDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Removes the specified friend from the the user's friend list bool RemoveFriend(ServerModels::FRemoveFriendRequest& request, const FRemoveFriendDelegate& SuccessDelegate = FRemoveFriendDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Removes the specified generic service identifier from the player's PlayFab account. bool RemoveGenericID(ServerModels::FRemoveGenericIDRequest& request, const FRemoveGenericIDDelegate& SuccessDelegate = FRemoveGenericIDDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Remove a given tag from a player profile. The tag's namespace is automatically generated based on the source of the tag. * This API will trigger a player_tag_removed event and remove a tag with the given TagName and PlayFabID from the corresponding player profile. TagName can be used for segmentation and it is limited to 256 characters */ bool RemovePlayerTag(ServerModels::FRemovePlayerTagRequest& request, const FRemovePlayerTagDelegate& SuccessDelegate = FRemovePlayerTagDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Removes users from the set of those able to update the shared data and the set of users in the group. Only users in the * group can remove members. If as a result of the call, zero users remain with access, the group and its associated data * will be deleted. Shared Groups are designed for sharing data between a very small number of players, please see our * guide: https://docs.microsoft.com/gaming/playfab/features/social/groups/using-shared-group-data */ bool RemoveSharedGroupMembers(ServerModels::FRemoveSharedGroupMembersRequest& request, const FRemoveSharedGroupMembersDelegate& SuccessDelegate = FRemoveSharedGroupMembersDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Submit a report about a player (due to bad bahavior, etc.) on behalf of another player, so that customer service * representatives for the title can take action concerning potentially toxic players. */ bool ReportPlayer(ServerModels::FReportPlayerServerRequest& request, const FReportPlayerDelegate& SuccessDelegate = FReportPlayerDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Revoke all active bans for a user. * Setting the active state of all non-expired bans for a user to Inactive. Expired bans with an Active state will be ignored, however. Returns information about applied updates only. */ bool RevokeAllBansForUser(ServerModels::FRevokeAllBansForUserRequest& request, const FRevokeAllBansForUserDelegate& SuccessDelegate = FRevokeAllBansForUserDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Revoke all active bans specified with BanId. * Setting the active state of all bans requested to Inactive regardless of whether that ban has already expired. BanIds that do not exist will be skipped. Returns information about applied updates only. */ bool RevokeBans(ServerModels::FRevokeBansRequest& request, const FRevokeBansDelegate& SuccessDelegate = FRevokeBansDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * _NOTE: This is a Legacy Economy API, and is in bugfix-only mode. All new Economy features are being developed only for * version 2._ Revokes access to an item in a user's inventory * In cases where the inventory item in question is a "crate", and the items it contained have already been dispensed, this will not revoke access or otherwise remove the items which were dispensed. */ bool RevokeInventoryItem(ServerModels::FRevokeInventoryItemRequest& request, const FRevokeInventoryItemDelegate& SuccessDelegate = FRevokeInventoryItemDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * _NOTE: This is a Legacy Economy API, and is in bugfix-only mode. All new Economy features are being developed only for * version 2._ Revokes access for up to 25 items across multiple users and characters. * In cases where the inventory item in question is a "crate", and the items it contained have already been dispensed, this will not revoke access or otherwise remove the items which were dispensed. */ bool RevokeInventoryItems(ServerModels::FRevokeInventoryItemsRequest& request, const FRevokeInventoryItemsDelegate& SuccessDelegate = FRevokeInventoryItemsDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Saves push notification template for title bool SavePushNotificationTemplate(ServerModels::FSavePushNotificationTemplateRequest& request, const FSavePushNotificationTemplateDelegate& SuccessDelegate = FSavePushNotificationTemplateDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Forces an email to be sent to the registered contact email address for the user's account based on an account recovery * email template * PlayFab accounts which have valid email address or username will be able to receive a password reset email using this API.The email sent must be an account recovery email template. The username or email can be passed in to send the email */ bool SendCustomAccountRecoveryEmail(ServerModels::FSendCustomAccountRecoveryEmailRequest& request, const FSendCustomAccountRecoveryEmailDelegate& SuccessDelegate = FSendCustomAccountRecoveryEmailDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Sends an email based on an email template to a player's contact email * Sends an email for only players that have contact emails associated with them. Takes in an email template ID specifyingthe email template to send. */ bool SendEmailFromTemplate(ServerModels::FSendEmailFromTemplateRequest& request, const FSendEmailFromTemplateDelegate& SuccessDelegate = FSendEmailFromTemplateDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Sends an iOS/Android Push Notification to a specific user, if that user's device has been configured for Push * Notifications in PlayFab. If a user has linked both Android and iOS devices, both will be notified. */ bool SendPushNotification(ServerModels::FSendPushNotificationRequest& request, const FSendPushNotificationDelegate& SuccessDelegate = FSendPushNotificationDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Sends an iOS/Android Push Notification template to a specific user, if that user's device has been configured for Push * Notifications in PlayFab. If a user has linked both Android and iOS devices, both will be notified. */ bool SendPushNotificationFromTemplate(ServerModels::FSendPushNotificationFromTemplateRequest& request, const FSendPushNotificationFromTemplateDelegate& SuccessDelegate = FSendPushNotificationFromTemplateDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Updates the tag list for a specified user in the friend list of another user * This operation is not additive. It will completely replace the tag list for the specified user. Please note that only users in the PlayFab friends list can be assigned tags. Attempting to set a tag on a friend only included in the friends list from a social site integration (such as Facebook or Steam) will return the AccountNotFound error. */ bool SetFriendTags(ServerModels::FSetFriendTagsRequest& request, const FSetFriendTagsDelegate& SuccessDelegate = FSetFriendTagsDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Sets the player's secret if it is not already set. Player secrets are used to sign API requests. To reset a player's * secret use the Admin or Server API method SetPlayerSecret. * APIs that require signatures require that the player have a configured Player Secret Key that is used to sign all requests. Players that don't have a secret will be blocked from making API calls until it is configured. To create a signature header add a SHA256 hashed string containing UTF8 encoded JSON body as it will be sent to the server, the current time in UTC formatted to ISO 8601, and the players secret formatted as 'body.date.secret'. Place the resulting hash into the header X-PlayFab-Signature, along with a header X-PlayFab-Timestamp of the same UTC timestamp used in the signature. */ bool SetPlayerSecret(ServerModels::FSetPlayerSecretRequest& request, const FSetPlayerSecretDelegate& SuccessDelegate = FSetPlayerSecretDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Updates the key-value store of custom publisher settings * This API is designed to store publisher-specific values which can be read, but not written to, by the client. This data is shared across all titles assigned to a particular publisher, and can be used for cross-game coordination. Only titles assigned to a publisher can use this API. This operation is additive. If a Key does not exist in the current dataset, it will be added with the specified Value. If it already exists, the Value for that key will be overwritten with the new Value. For more information email helloplayfab@microsoft.com */ bool SetPublisherData(ServerModels::FSetPublisherDataRequest& request, const FSetPublisherDataDelegate& SuccessDelegate = FSetPublisherDataDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Updates the key-value store of custom title settings * This API is designed to store title specific values which can be read, but not written to, by the client. For example, a developer could choose to store values which modify the user experience, such as enemy spawn rates, weapon strengths, movement speeds, etc. This allows a developer to update the title without the need to create, test, and ship a new build. This operation is additive. If a Key does not exist in the current dataset, it will be added with the specified Value. If it already exists, the Value for that key will be overwritten with the new Value. */ bool SetTitleData(ServerModels::FSetTitleDataRequest& request, const FSetTitleDataDelegate& SuccessDelegate = FSetTitleDataDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Updates the key-value store of custom title settings * This API is designed to store title specific values which are accessible only to the server. This can be used to tweak settings on game servers and Cloud Scripts without needed to update and re-deploy them. This operation is additive. If a Key does not exist in the current dataset, it will be added with the specified Value. If it already exists, the Value for that key will be overwritten with the new Value. */ bool SetTitleInternalData(ServerModels::FSetTitleDataRequest& request, const FSetTitleInternalDataDelegate& SuccessDelegate = FSetTitleInternalDataDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * _NOTE: This is a Legacy Economy API, and is in bugfix-only mode. All new Economy features are being developed only for * version 2._ Decrements the character's balance of the specified virtual currency by the stated amount. It is possible to * make a VC balance negative with this API. */ bool SubtractCharacterVirtualCurrency(ServerModels::FSubtractCharacterVirtualCurrencyRequest& request, const FSubtractCharacterVirtualCurrencyDelegate& SuccessDelegate = FSubtractCharacterVirtualCurrencyDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * _NOTE: This is a Legacy Economy API, and is in bugfix-only mode. All new Economy features are being developed only for * version 2._ Decrements the user's balance of the specified virtual currency by the stated amount. It is possible to make * a VC balance negative with this API. */ bool SubtractUserVirtualCurrency(ServerModels::FSubtractUserVirtualCurrencyRequest& request, const FSubtractUserVirtualCurrencyDelegate& SuccessDelegate = FSubtractUserVirtualCurrencyDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Unlinks the related Battle.net account from the user's PlayFab account. bool UnlinkBattleNetAccount(ServerModels::FUnlinkBattleNetAccountRequest& request, const FUnlinkBattleNetAccountDelegate& SuccessDelegate = FUnlinkBattleNetAccountDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Unlinks the related Nintendo account from the user's PlayFab account bool UnlinkNintendoServiceAccount(ServerModels::FUnlinkNintendoServiceAccountRequest& request, const FUnlinkNintendoServiceAccountDelegate& SuccessDelegate = FUnlinkNintendoServiceAccountDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Unlinks the related NintendoSwitchDeviceId from the user's PlayFab account bool UnlinkNintendoSwitchDeviceId(ServerModels::FUnlinkNintendoSwitchDeviceIdRequest& request, const FUnlinkNintendoSwitchDeviceIdDelegate& SuccessDelegate = FUnlinkNintendoSwitchDeviceIdDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Unlinks the related PlayStation :tm: Network account from the user's PlayFab account bool UnlinkPSNAccount(ServerModels::FUnlinkPSNAccountRequest& request, const FUnlinkPSNAccountDelegate& SuccessDelegate = FUnlinkPSNAccountDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Unlinks the custom server identifier from the user's PlayFab account. bool UnlinkServerCustomId(ServerModels::FUnlinkServerCustomIdRequest& request, const FUnlinkServerCustomIdDelegate& SuccessDelegate = FUnlinkServerCustomIdDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Unlinks the Steam account associated with the provided Steam ID to the user's PlayFab account bool UnlinkSteamId(ServerModels::FUnlinkSteamIdRequest& request, const FUnlinkSteamIdDelegate& SuccessDelegate = FUnlinkSteamIdDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Unlinks the related Xbox Live account from the user's PlayFab account bool UnlinkXboxAccount(ServerModels::FUnlinkXboxAccountRequest& request, const FUnlinkXboxAccountDelegate& SuccessDelegate = FUnlinkXboxAccountDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * _NOTE: This is a Legacy Economy API, and is in bugfix-only mode. All new Economy features are being developed only for * version 2._ Opens a specific container (ContainerItemInstanceId), with a specific key (KeyItemInstanceId, when * required), and returns the contents of the opened container. If the container (and key when relevant) are consumable * (RemainingUses > 0), their RemainingUses will be decremented, consistent with the operation of ConsumeItem. * Specify the container and optionally the catalogVersion for the container to open */ bool UnlockContainerInstance(ServerModels::FUnlockContainerInstanceRequest& request, const FUnlockContainerInstanceDelegate& SuccessDelegate = FUnlockContainerInstanceDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * _NOTE: This is a Legacy Economy API, and is in bugfix-only mode. All new Economy features are being developed only for * version 2._ Searches Player or Character inventory for any ItemInstance matching the given CatalogItemId, if necessary * unlocks it using any appropriate key, and returns the contents of the opened container. If the container (and key when * relevant) are consumable (RemainingUses > 0), their RemainingUses will be decremented, consistent with the operation of * ConsumeItem. * Specify the type of container to open and optionally the catalogVersion for the container to open */ bool UnlockContainerItem(ServerModels::FUnlockContainerItemRequest& request, const FUnlockContainerItemDelegate& SuccessDelegate = FUnlockContainerItemDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); // Update the avatar URL of the specified player bool UpdateAvatarUrl(ServerModels::FUpdateAvatarUrlRequest& request, const FUpdateAvatarUrlDelegate& SuccessDelegate = FUpdateAvatarUrlDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Updates information of a list of existing bans specified with Ban Ids. * For each ban, only updates the values that are set. Leave any value to null for no change. If a ban could not be found, the rest are still applied. Returns information about applied updates only. */ bool UpdateBans(ServerModels::FUpdateBansRequest& request, const FUpdateBansDelegate& SuccessDelegate = FUpdateBansDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Updates the title-specific custom data for the user's character which is readable and writable by the client * This function performs an additive update of the arbitrary JSON object containing the custom data for the user. In updating the custom data object, keys which already exist in the object will have their values overwritten, while keys with null values will be removed. No other key-value pairs will be changed apart from those specified in the call. */ bool UpdateCharacterData(ServerModels::FUpdateCharacterDataRequest& request, const FUpdateCharacterDataDelegate& SuccessDelegate = FUpdateCharacterDataDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Updates the title-specific custom data for the user's character which cannot be accessed by the client * This function performs an additive update of the arbitrary JSON object containing the custom data for the user. In updating the custom data object, keys which already exist in the object will have their values overwritten, keys with null values will be removed. No other key-value pairs will be changed apart from those specified in the call. */ bool UpdateCharacterInternalData(ServerModels::FUpdateCharacterDataRequest& request, const FUpdateCharacterInternalDataDelegate& SuccessDelegate = FUpdateCharacterInternalDataDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Updates the title-specific custom data for the user's character which can only be read by the client * This function performs an additive update of the arbitrary JSON object containing the custom data for the user. In updating the custom data object, keys which already exist in the object will have their values overwritten, keys with null values will be removed. No other key-value pairs will be changed apart from those specified in the call. */ bool UpdateCharacterReadOnlyData(ServerModels::FUpdateCharacterDataRequest& request, const FUpdateCharacterReadOnlyDataDelegate& SuccessDelegate = FUpdateCharacterReadOnlyDataDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Updates the values of the specified title-specific statistics for the specific character * Character statistics are similar to user statistics in that they are numeric values which may only be updated by a server operation, in order to minimize the opportunity for unauthorized changes. In addition to being available for use by the title, the statistics are used for all leaderboard operations in PlayFab. */ bool UpdateCharacterStatistics(ServerModels::FUpdateCharacterStatisticsRequest& request, const FUpdateCharacterStatisticsDelegate& SuccessDelegate = FUpdateCharacterStatisticsDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Updates the title-specific custom property values for a player * Performs an additive update of the custom properties for the specified player. In updating the player's custom properties, properties which already exist will have their values overwritten. No other properties will be changed apart from those specified in the call. */ bool UpdatePlayerCustomProperties(ServerModels::FUpdatePlayerCustomPropertiesRequest& request, const FUpdatePlayerCustomPropertiesDelegate& SuccessDelegate = FUpdatePlayerCustomPropertiesDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Updates the values of the specified title-specific statistics for the user * This operation is additive. Statistics not currently defined will be added, while those already defined will be updated with the given values. All other user statistics will remain unchanged. */ bool UpdatePlayerStatistics(ServerModels::FUpdatePlayerStatisticsRequest& request, const FUpdatePlayerStatisticsDelegate& SuccessDelegate = FUpdatePlayerStatisticsDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Adds, updates, and removes data keys for a shared group object. If the permission is set to Public, all fields updated * or added in this call will be readable by users not in the group. By default, data permissions are set to Private. * Regardless of the permission setting, only members of the group (and the server) can update the data. Shared Groups are * designed for sharing data between a very small number of players, please see our guide: * https://docs.microsoft.com/gaming/playfab/features/social/groups/using-shared-group-data * Note that in the case of multiple calls to write to the same shared group data keys, the last write received by the PlayFab service will determine the value available to subsequent read operations. For scenarios requiring coordination of data updates, it is recommended that titles make use of user data with read permission set to public, or a combination of user data and shared group data. */ bool UpdateSharedGroupData(ServerModels::FUpdateSharedGroupDataRequest& request, const FUpdateSharedGroupDataDelegate& SuccessDelegate = FUpdateSharedGroupDataDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Updates the title-specific custom data for the user which is readable and writable by the client * This function performs an additive update of the arbitrary JSON object containing the custom data for the user. In updating the custom data object, keys which already exist in the object will have their values overwritten, while keys with null values will be removed. No other key-value pairs will be changed apart from those specified in the call. */ bool UpdateUserData(ServerModels::FUpdateUserDataRequest& request, const FUpdateUserDataDelegate& SuccessDelegate = FUpdateUserDataDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Updates the title-specific custom data for the user which cannot be accessed by the client * This function performs an additive update of the arbitrary JSON object containing the custom data for the user. In updating the custom data object, keys which already exist in the object will have their values overwritten, keys with null values will be removed. No other key-value pairs will be changed apart from those specified in the call. */ bool UpdateUserInternalData(ServerModels::FUpdateUserInternalDataRequest& request, const FUpdateUserInternalDataDelegate& SuccessDelegate = FUpdateUserInternalDataDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * _NOTE: This is a Legacy Economy API, and is in bugfix-only mode. All new Economy features are being developed only for * version 2._ Updates the key-value pair data tagged to the specified item, which is read-only from the client. * This function performs an additive update of the arbitrary JSON object containing the custom data for the item instance which belongs to the specified user. In updating the custom data object, keys which already exist in the object will have their values overwritten, while keys with null values will be removed. No other key-value pairs will be changed apart from those specified in the call. */ bool UpdateUserInventoryItemCustomData(ServerModels::FUpdateUserInventoryItemDataRequest& request, const FUpdateUserInventoryItemCustomDataDelegate& SuccessDelegate = FUpdateUserInventoryItemCustomDataDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Updates the publisher-specific custom data for the user which is readable and writable by the client * This function performs an additive update of the arbitrary JSON object containing the custom data for the user. In updating the custom data object, keys which already exist in the object will have their values overwritten, while keys with null values will be removed. No other key-value pairs will be changed apart from those specified in the call. */ bool UpdateUserPublisherData(ServerModels::FUpdateUserDataRequest& request, const FUpdateUserPublisherDataDelegate& SuccessDelegate = FUpdateUserPublisherDataDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Updates the publisher-specific custom data for the user which cannot be accessed by the client * This function performs an additive update of the arbitrary JSON object containing the custom data for the user. In updating the custom data object, keys which already exist in the object will have their values overwritten, keys with null values will be removed. No other key-value pairs will be changed apart from those specified in the call. */ bool UpdateUserPublisherInternalData(ServerModels::FUpdateUserInternalDataRequest& request, const FUpdateUserPublisherInternalDataDelegate& SuccessDelegate = FUpdateUserPublisherInternalDataDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Updates the publisher-specific custom data for the user which can only be read by the client * This function performs an additive update of the arbitrary JSON object containing the custom data for the user. In updating the custom data object, keys which already exist in the object will have their values overwritten, keys with null values will be removed. No other key-value pairs will be changed apart from those specified in the call. */ bool UpdateUserPublisherReadOnlyData(ServerModels::FUpdateUserDataRequest& request, const FUpdateUserPublisherReadOnlyDataDelegate& SuccessDelegate = FUpdateUserPublisherReadOnlyDataDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Updates the title-specific custom data for the user which can only be read by the client * This function performs an additive update of the arbitrary JSON object containing the custom data for the user. In updating the custom data object, keys which already exist in the object will have their values overwritten, keys with null values will be removed. No other key-value pairs will be changed apart from those specified in the call. */ bool UpdateUserReadOnlyData(ServerModels::FUpdateUserDataRequest& request, const FUpdateUserReadOnlyDataDelegate& SuccessDelegate = FUpdateUserReadOnlyDataDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Writes a character-based event into PlayStream. * This API is designed to write a multitude of different event types into PlayStream. It supports a flexible JSON schema, which allowsfor arbitrary key-value pairs to describe any character-based event. The created event will be locked to the authenticated title. */ bool WriteCharacterEvent(ServerModels::FWriteServerCharacterEventRequest& request, const FWriteCharacterEventDelegate& SuccessDelegate = FWriteCharacterEventDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Writes a player-based event into PlayStream. * This API is designed to write a multitude of different event types into PlayStream. It supports a flexible JSON schema, which allowsfor arbitrary key-value pairs to describe any player-based event. The created event will be locked to the authenticated title. */ bool WritePlayerEvent(ServerModels::FWriteServerPlayerEventRequest& request, const FWritePlayerEventDelegate& SuccessDelegate = FWritePlayerEventDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); /** * Writes a title-based event into PlayStream. * This API is designed to write a multitude of different event types into PlayStream. It supports a flexible JSON schema, which allowsfor arbitrary key-value pairs to describe any title-based event. The created event will be locked to the authenticated title. */ bool WriteTitleEvent(ServerModels::FWriteTitleEventRequest& request, const FWriteTitleEventDelegate& SuccessDelegate = FWriteTitleEventDelegate(), const FPlayFabErrorDelegate& ErrorDelegate = FPlayFabErrorDelegate()); private: // ------------ Generated result handlers void OnAddCharacterVirtualCurrencyResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FAddCharacterVirtualCurrencyDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnAddFriendResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FAddFriendDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnAddGenericIDResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FAddGenericIDDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnAddPlayerTagResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FAddPlayerTagDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnAddSharedGroupMembersResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FAddSharedGroupMembersDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnAddUserVirtualCurrencyResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FAddUserVirtualCurrencyDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnAuthenticateSessionTicketResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FAuthenticateSessionTicketDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnAwardSteamAchievementResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FAwardSteamAchievementDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnBanUsersResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FBanUsersDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnConsumeItemResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FConsumeItemDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnCreateSharedGroupResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FCreateSharedGroupDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnDeleteCharacterFromUserResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FDeleteCharacterFromUserDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnDeletePlayerResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FDeletePlayerDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnDeletePlayerCustomPropertiesResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FDeletePlayerCustomPropertiesDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnDeletePushNotificationTemplateResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FDeletePushNotificationTemplateDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnDeleteSharedGroupResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FDeleteSharedGroupDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnEvaluateRandomResultTableResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FEvaluateRandomResultTableDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnExecuteCloudScriptResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FExecuteCloudScriptDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetAllSegmentsResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetAllSegmentsDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetAllUsersCharactersResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetAllUsersCharactersDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetCatalogItemsResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetCatalogItemsDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetCharacterDataResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetCharacterDataDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetCharacterInternalDataResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetCharacterInternalDataDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetCharacterInventoryResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetCharacterInventoryDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetCharacterLeaderboardResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetCharacterLeaderboardDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetCharacterReadOnlyDataResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetCharacterReadOnlyDataDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetCharacterStatisticsResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetCharacterStatisticsDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetContentDownloadUrlResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetContentDownloadUrlDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetFriendLeaderboardResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetFriendLeaderboardDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetFriendsListResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetFriendsListDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetLeaderboardResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetLeaderboardDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetLeaderboardAroundCharacterResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetLeaderboardAroundCharacterDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetLeaderboardAroundUserResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetLeaderboardAroundUserDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetLeaderboardForUserCharactersResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetLeaderboardForUserCharactersDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetPlayerCombinedInfoResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetPlayerCombinedInfoDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetPlayerCustomPropertyResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetPlayerCustomPropertyDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetPlayerProfileResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetPlayerProfileDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetPlayerSegmentsResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetPlayerSegmentsDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetPlayersInSegmentResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetPlayersInSegmentDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetPlayerStatisticsResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetPlayerStatisticsDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetPlayerStatisticVersionsResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetPlayerStatisticVersionsDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetPlayerTagsResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetPlayerTagsDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetPlayFabIDsFromBattleNetAccountIdsResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetPlayFabIDsFromBattleNetAccountIdsDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetPlayFabIDsFromFacebookIDsResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetPlayFabIDsFromFacebookIDsDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetPlayFabIDsFromFacebookInstantGamesIdsResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetPlayFabIDsFromFacebookInstantGamesIdsDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetPlayFabIDsFromGenericIDsResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetPlayFabIDsFromGenericIDsDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetPlayFabIDsFromNintendoServiceAccountIdsResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetPlayFabIDsFromNintendoServiceAccountIdsDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetPlayFabIDsFromNintendoSwitchDeviceIdsResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetPlayFabIDsFromNintendoSwitchDeviceIdsDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetPlayFabIDsFromPSNAccountIDsResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetPlayFabIDsFromPSNAccountIDsDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetPlayFabIDsFromPSNOnlineIDsResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetPlayFabIDsFromPSNOnlineIDsDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetPlayFabIDsFromSteamIDsResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetPlayFabIDsFromSteamIDsDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetPlayFabIDsFromSteamNamesResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetPlayFabIDsFromSteamNamesDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetPlayFabIDsFromTwitchIDsResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetPlayFabIDsFromTwitchIDsDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetPlayFabIDsFromXboxLiveIDsResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetPlayFabIDsFromXboxLiveIDsDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetPublisherDataResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetPublisherDataDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetRandomResultTablesResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetRandomResultTablesDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetServerCustomIDsFromPlayFabIDsResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetServerCustomIDsFromPlayFabIDsDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetSharedGroupDataResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetSharedGroupDataDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetStoreItemsResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetStoreItemsDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetTimeResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetTimeDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetTitleDataResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetTitleDataDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetTitleInternalDataResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetTitleInternalDataDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetTitleNewsResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetTitleNewsDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetUserAccountInfoResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetUserAccountInfoDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetUserBansResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetUserBansDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetUserDataResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetUserDataDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetUserInternalDataResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetUserInternalDataDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetUserInventoryResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetUserInventoryDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetUserPublisherDataResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetUserPublisherDataDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetUserPublisherInternalDataResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetUserPublisherInternalDataDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetUserPublisherReadOnlyDataResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetUserPublisherReadOnlyDataDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGetUserReadOnlyDataResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGetUserReadOnlyDataDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGrantCharacterToUserResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGrantCharacterToUserDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGrantItemsToCharacterResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGrantItemsToCharacterDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGrantItemsToUserResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGrantItemsToUserDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnGrantItemsToUsersResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FGrantItemsToUsersDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnLinkBattleNetAccountResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FLinkBattleNetAccountDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnLinkNintendoServiceAccountResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FLinkNintendoServiceAccountDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnLinkNintendoServiceAccountSubjectResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FLinkNintendoServiceAccountSubjectDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnLinkNintendoSwitchDeviceIdResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FLinkNintendoSwitchDeviceIdDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnLinkPSNAccountResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FLinkPSNAccountDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnLinkPSNIdResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FLinkPSNIdDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnLinkServerCustomIdResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FLinkServerCustomIdDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnLinkSteamIdResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FLinkSteamIdDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnLinkXboxAccountResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FLinkXboxAccountDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnLinkXboxIdResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FLinkXboxIdDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnListPlayerCustomPropertiesResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FListPlayerCustomPropertiesDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnLoginWithAndroidDeviceIDResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FLoginWithAndroidDeviceIDDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnLoginWithBattleNetResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FLoginWithBattleNetDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnLoginWithCustomIDResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FLoginWithCustomIDDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnLoginWithIOSDeviceIDResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FLoginWithIOSDeviceIDDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnLoginWithPSNResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FLoginWithPSNDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnLoginWithServerCustomIdResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FLoginWithServerCustomIdDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnLoginWithSteamIdResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FLoginWithSteamIdDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnLoginWithXboxResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FLoginWithXboxDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnLoginWithXboxIdResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FLoginWithXboxIdDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnModifyItemUsesResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FModifyItemUsesDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnMoveItemToCharacterFromCharacterResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FMoveItemToCharacterFromCharacterDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnMoveItemToCharacterFromUserResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FMoveItemToCharacterFromUserDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnMoveItemToUserFromCharacterResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FMoveItemToUserFromCharacterDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnRedeemCouponResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FRedeemCouponDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnRemoveFriendResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FRemoveFriendDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnRemoveGenericIDResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FRemoveGenericIDDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnRemovePlayerTagResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FRemovePlayerTagDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnRemoveSharedGroupMembersResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FRemoveSharedGroupMembersDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnReportPlayerResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FReportPlayerDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnRevokeAllBansForUserResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FRevokeAllBansForUserDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnRevokeBansResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FRevokeBansDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnRevokeInventoryItemResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FRevokeInventoryItemDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnRevokeInventoryItemsResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FRevokeInventoryItemsDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnSavePushNotificationTemplateResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FSavePushNotificationTemplateDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnSendCustomAccountRecoveryEmailResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FSendCustomAccountRecoveryEmailDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnSendEmailFromTemplateResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FSendEmailFromTemplateDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnSendPushNotificationResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FSendPushNotificationDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnSendPushNotificationFromTemplateResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FSendPushNotificationFromTemplateDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnSetFriendTagsResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FSetFriendTagsDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnSetPlayerSecretResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FSetPlayerSecretDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnSetPublisherDataResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FSetPublisherDataDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnSetTitleDataResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FSetTitleDataDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnSetTitleInternalDataResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FSetTitleInternalDataDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnSubtractCharacterVirtualCurrencyResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FSubtractCharacterVirtualCurrencyDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnSubtractUserVirtualCurrencyResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FSubtractUserVirtualCurrencyDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnUnlinkBattleNetAccountResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUnlinkBattleNetAccountDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnUnlinkNintendoServiceAccountResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUnlinkNintendoServiceAccountDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnUnlinkNintendoSwitchDeviceIdResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUnlinkNintendoSwitchDeviceIdDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnUnlinkPSNAccountResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUnlinkPSNAccountDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnUnlinkServerCustomIdResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUnlinkServerCustomIdDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnUnlinkSteamIdResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUnlinkSteamIdDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnUnlinkXboxAccountResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUnlinkXboxAccountDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnUnlockContainerInstanceResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUnlockContainerInstanceDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnUnlockContainerItemResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUnlockContainerItemDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnUpdateAvatarUrlResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdateAvatarUrlDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnUpdateBansResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdateBansDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnUpdateCharacterDataResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdateCharacterDataDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnUpdateCharacterInternalDataResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdateCharacterInternalDataDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnUpdateCharacterReadOnlyDataResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdateCharacterReadOnlyDataDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnUpdateCharacterStatisticsResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdateCharacterStatisticsDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnUpdatePlayerCustomPropertiesResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdatePlayerCustomPropertiesDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnUpdatePlayerStatisticsResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdatePlayerStatisticsDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnUpdateSharedGroupDataResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdateSharedGroupDataDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnUpdateUserDataResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdateUserDataDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnUpdateUserInternalDataResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdateUserInternalDataDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnUpdateUserInventoryItemCustomDataResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdateUserInventoryItemCustomDataDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnUpdateUserPublisherDataResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdateUserPublisherDataDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnUpdateUserPublisherInternalDataResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdateUserPublisherInternalDataDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnUpdateUserPublisherReadOnlyDataResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdateUserPublisherReadOnlyDataDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnUpdateUserReadOnlyDataResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FUpdateUserReadOnlyDataDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnWriteCharacterEventResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FWriteCharacterEventDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnWritePlayerEventResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FWritePlayerEventDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); void OnWriteTitleEventResult(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FWriteTitleEventDelegate SuccessDelegate, FPlayFabErrorDelegate ErrorDelegate); }; };
1
0.746786
1
0.746786
game-dev
MEDIA
0.348949
game-dev
0.557611
1
0.557611
reputage/seedQuest
3,504
Unity/SeedQuest/Assets/ThirdPartyLibraries/Standard Assets/Vehicles/Aircraft/Scripts/AeroplanePropellerAnimator.cs
using System; using UnityEngine; namespace UnityStandardAssets.Vehicles.Aeroplane { public class AeroplanePropellerAnimator : MonoBehaviour { [SerializeField] private Transform m_PropellorModel; // The model of the the aeroplane's propellor. [SerializeField] private Transform m_PropellorBlur; // The plane used for the blurred propellor textures. [SerializeField] private Texture2D[] m_PropellorBlurTextures; // An array of increasingly blurred propellor textures. [SerializeField] [Range(0f, 1f)] private float m_ThrottleBlurStart = 0.25f; // The point at which the blurred textures start. [SerializeField] [Range(0f, 1f)] private float m_ThrottleBlurEnd = 0.5f; // The point at which the blurred textures stop changing. [SerializeField] private float m_MaxRpm = 2000; // The maximum speed the propellor can turn at. private AeroplaneController m_Plane; // Reference to the aeroplane controller. private int m_PropellorBlurState = -1; // To store the state of the blurred textures. private const float k_RpmToDps = 60f; // For converting from revs per minute to degrees per second. private Renderer m_PropellorModelRenderer; private Renderer m_PropellorBlurRenderer; private void Awake() { // Set up the reference to the aeroplane controller. m_Plane = GetComponent<AeroplaneController>(); m_PropellorModelRenderer = m_PropellorModel.GetComponent<Renderer>(); m_PropellorBlurRenderer = m_PropellorBlur.GetComponent<Renderer>(); // Set the propellor blur gameobject's parent to be the propellor. m_PropellorBlur.parent = m_PropellorModel; } private void Update() { // Rotate the propellor model at a rate proportional to the throttle. m_PropellorModel.Rotate(0, m_MaxRpm*m_Plane.Throttle*Time.deltaTime*k_RpmToDps, 0); // Create an integer for the new state of the blur textures. var newBlurState = 0; // choose between the blurred textures, if the throttle is high enough if (m_Plane.Throttle > m_ThrottleBlurStart) { var throttleBlurProportion = Mathf.InverseLerp(m_ThrottleBlurStart, m_ThrottleBlurEnd, m_Plane.Throttle); newBlurState = Mathf.FloorToInt(throttleBlurProportion*(m_PropellorBlurTextures.Length - 1)); } // If the blur state has changed if (newBlurState != m_PropellorBlurState) { m_PropellorBlurState = newBlurState; if (m_PropellorBlurState == 0) { // switch to using the 'real' propellor model m_PropellorModelRenderer.enabled = true; m_PropellorBlurRenderer.enabled = false; } else { // Otherwise turn off the propellor model and turn on the blur. m_PropellorModelRenderer.enabled = false; m_PropellorBlurRenderer.enabled = true; // set the appropriate texture from the blur array m_PropellorBlurRenderer.material.mainTexture = m_PropellorBlurTextures[m_PropellorBlurState]; } } } } }
1
0.754583
1
0.754583
game-dev
MEDIA
0.896895
game-dev
0.854921
1
0.854921
rhaiscript/lsp
9,145
crates/rhai-rowan/src/util.rs
use crate::parser::{ parsers::{self, def::parse_def_header, parse_expr}, Parse, Parser, }; use rowan::{TextRange, TextSize}; use thiserror::Error; pub struct Interpolated<'s> { pub segments: Vec<(InterpolatedSegment<'s>, TextRange)>, } pub enum InterpolatedSegment<'s> { Str(&'s str), Interpolation(Parse), } #[must_use] #[allow(clippy::missing_panics_doc)] pub fn parse_interpolated(s: &str) -> Interpolated { let mut segments = Vec::new(); let mut chars = s.char_indices().peekable(); let mut segment_start = 0usize; let mut segment_end = 0usize; while let Some((i, ch)) = chars.next() { match ch { '$' if matches!(chars.peek(), Some((_, '{'))) => { if segment_start < i { segments.push(( InterpolatedSegment::Str(&s[segment_start..i]), TextRange::new( TextSize::from(segment_start as u32), TextSize::from(i as u32), ), )); } let (i, _) = chars.next().unwrap(); segment_start = i; let mut parser = Parser::new(&s[i..]); parser.execute(parse_expr); let parse = parser.finish(); let end_idx = (i as u32 + u32::from(parse.green.text_len())) as usize; for (i, _) in chars.by_ref() { if i >= end_idx { break; } } segments.push(( InterpolatedSegment::Interpolation(parse), TextRange::new( TextSize::from(segment_start as u32), TextSize::from(end_idx as u32), ), )); if matches!(chars.peek(), Some((_, '}'))) { let (i, _) = chars.next().unwrap(); segment_start = i; } } _ => { segment_end = i; } } } if segment_start < segment_end { segments.push(( InterpolatedSegment::Str(&s[segment_start..segment_end]), TextRange::new( TextSize::from(segment_start as u32), TextSize::from(segment_end as u32), ), )); } Interpolated { segments } } /// Determine whether the given source is a definition file or not. /// /// Definitions should begin with the `module` keyword, only preceded by comments. pub fn is_rhai_def(source: &str) -> bool { let mut parser = Parser::new(source); parser.execute(parse_def_header); parser.finish().errors.is_empty() } /// Determine whether the given text is a valid identifier. pub fn is_valid_ident(text: &str) -> bool { let mut ident_parser = Parser::new(text); ident_parser.execute(parsers::parse_expr_ident); ident_parser.finish().errors.is_empty() } #[must_use] pub fn unescape(s: &str, termination_char: char) -> (String, Vec<EscapeError>) { let mut chars = s.chars().peekable(); let mut result = String::with_capacity(12); let mut escape = String::with_capacity(12); let mut errors = Vec::new(); let mut position = TextSize::default(); while let Some(ch) = chars.next() { match ch { // \r - ignore if followed by \n '\r' if chars.peek().map_or(false, |ch| *ch == '\n') => (), // \... '\\' if escape.is_empty() => { escape.push('\\'); } // \\ '\\' if !escape.is_empty() => { escape.clear(); result.push('\\'); } // \t 't' if !escape.is_empty() => { escape.clear(); result.push('\t'); } // \n 'n' if !escape.is_empty() => { escape.clear(); result.push('\n'); } // \r 'r' if !escape.is_empty() => { escape.clear(); result.push('\r'); } // \x??, \u????, \U???????? ch @ ('x' | 'u' | 'U') if !escape.is_empty() => { let mut seq = escape.clone(); escape.clear(); seq.push(ch); let mut out_val: u32 = 0; let len = match ch { 'x' => 2, 'u' => 4, 'U' => 8, _ => unreachable!(), }; let mut err = false; for _ in 0..len { let c = match chars.next() { Some(ch) => ch, None => { errors.push(EscapeError::MalformedEscapeSequence( seq.clone(), TextRange::new( position, position + TextSize::from(escape.len() as u32), ), )); break; } }; seq.push(c); out_val *= 16; match c.to_digit(16) { Some(c) => out_val += c, None => { err = true; errors.push(EscapeError::MalformedEscapeSequence( seq.clone(), TextRange::new( position, position + TextSize::from(escape.len() as u32), ), )); } } position += TextSize::from(c.len_utf8() as u32); } if !err { match char::from_u32(out_val) { Some(c) => result.push(c), None => errors.push(EscapeError::MalformedEscapeSequence( seq, TextRange::new( position, position + TextSize::from(escape.len() as u32), ), )), }; } } // \{termination_char} - escaped _ if termination_char == ch && !escape.is_empty() => { escape.clear(); result.push(ch); } // Line continuation '\n' if !escape.is_empty() => { escape.clear(); } // Unknown escape sequence _ if !escape.is_empty() => { escape.push(ch); errors.push(EscapeError::MalformedEscapeSequence( escape.clone(), TextRange::new(position, position + TextSize::from(escape.len() as u32)), )); } // All other characters _ => { escape.clear(); result.push(ch); } } position += TextSize::from(ch.len_utf8() as u32); } (result, errors) } #[derive(Debug, Error)] pub enum EscapeError { #[error("malformed escape sequence `{0}`")] MalformedEscapeSequence(String, TextRange), } /// Replaces the text `$$` and returns its index. /// /// Used for tests internally. #[must_use] #[allow(clippy::missing_panics_doc)] pub fn src_cursor_offset(src: &str) -> (TextSize, String) { let mut o = src_cursor_offsets(src); (o.0.next().unwrap(), o.1) } /// Replaces all occurrences of '$$' and returns their positions. /// /// Used for tests internally. pub fn src_cursor_offsets(src: &str) -> (impl Iterator<Item = TextSize>, String) { let mut offsets = Vec::new(); let mut s = String::with_capacity(src.len()); let mut replaced_count: u32 = 0; let mut prev_dollar = false; for (idx, c) in src.char_indices() { if c == '$' && prev_dollar { offsets.push(TextSize::from((idx as u32) - (replaced_count * 2) - 1)); replaced_count += 1; prev_dollar = false; } else if c == '$' { prev_dollar = true; } else if prev_dollar { s.push('$'); s.push(c); prev_dollar = false; } else { s.push(c); } } if prev_dollar { s.push('$'); } (offsets.into_iter(), s) } #[cfg(test)] #[test] fn test_cursor_offsets() { let original = "$$a$$bbb$$c$$"; let replaced = "abbbc"; let (offsets, src) = src_cursor_offsets(original); let offsets: Vec<_> = offsets.collect(); assert_eq!(src, replaced); assert_eq!( offsets, [0, 1, 4, 5] .into_iter() .map(TextSize::from) .collect::<Vec<_>>() ); }
1
0.954841
1
0.954841
game-dev
MEDIA
0.339491
game-dev
0.970718
1
0.970718
PositiveTechnologies/PT.PM
1,331
Sources/PT.PM.Patterns/MySqlPatterns.cs
using PT.PM.Common; using PT.PM.Matching; using PT.PM.Matching.Patterns; using System.Collections.Generic; namespace PT.PM.Patterns.PatternsRepository { public partial class DefaultPatternRepository { public IEnumerable<PatternRoot> CreateMySqlPatterns() { var patterns = new List<PatternRoot>(); var mysql = new HashSet<Language> { Language.MySql }; patterns.Add(new PatternRoot { Key = patternIdGenerator.NextId(), DebugInfo = "Weak Cryptographic Hash (MD2, MD4, MD5, RIPEMD-160, and SHA-1)", Languages = mysql, Node = new PatternInvocationExpression { Target = new PatternIdRegexToken("sha1"), Arguments = new PatternArgs(new PatternAny()) } }); patterns.Add(new PatternRoot { Key = patternIdGenerator.NextId(), DebugInfo = "Insecure Randomness", Languages = mysql, Node = new PatternInvocationExpression { Target = new PatternIdRegexToken("RAND"), Arguments = new PatternArgs() } }); return patterns; } } }
1
0.784836
1
0.784836
game-dev
MEDIA
0.565961
game-dev
0.59774
1
0.59774
mangosthree/server
14,221
src/game/OutdoorPvP/OutdoorPvPEP.cpp
/** * MaNGOS is a full featured server for World of Warcraft, supporting * the following clients: 1.12.x, 2.4.3, 3.3.5a, 4.3.4a and 5.4.8 * * Copyright (C) 2005-2025 MaNGOS <https://www.getmangos.eu> * * 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 * * World of Warcraft, and all World of Warcraft or Warcraft art, images, * and lore are copyrighted by Blizzard Entertainment, Inc. */ #include "OutdoorPvPEP.h" #include "WorldPacket.h" #include "World.h" #include "ObjectMgr.h" #include "Object.h" #include "Creature.h" #include "GameObject.h" #include "Player.h" OutdoorPvPEP::OutdoorPvPEP() : OutdoorPvP(), m_towersAlliance(0), m_towersHorde(0) { m_towerWorldState[0] = WORLD_STATE_EP_NORTHPASS_NEUTRAL; m_towerWorldState[1] = WORLD_STATE_EP_CROWNGUARD_NEUTRAL; m_towerWorldState[2] = WORLD_STATE_EP_EASTWALL_NEUTRAL; m_towerWorldState[3] = WORLD_STATE_EP_PLAGUEWOOD_NEUTRAL; for (uint8 i = 0; i < MAX_EP_TOWERS; ++i) { m_towerOwner[i] = TEAM_NONE; } // initially set graveyard owner to neither faction sObjectMgr.SetGraveYardLinkTeam(GRAVEYARD_ID_EASTERN_PLAGUE, GRAVEYARD_ZONE_EASTERN_PLAGUE, TEAM_INVALID); } void OutdoorPvPEP::FillInitialWorldStates(WorldPacket& data, uint32& count) { FillInitialWorldState(data, count, WORLD_STATE_EP_TOWER_COUNT_ALLIANCE, m_towersAlliance); FillInitialWorldState(data, count, WORLD_STATE_EP_TOWER_COUNT_HORDE, m_towersHorde); for (uint8 i = 0; i < MAX_EP_TOWERS; ++i) { FillInitialWorldState(data, count, m_towerWorldState[i], WORLD_STATE_ADD); } } void OutdoorPvPEP::SendRemoveWorldStates(Player* player) { for (uint8 i = 0; i < MAX_EP_TOWERS; ++i) { player->SendUpdateWorldState(m_towerWorldState[i], WORLD_STATE_REMOVE); } } void OutdoorPvPEP::HandlePlayerEnterZone(Player* player, bool isMainZone) { OutdoorPvP::HandlePlayerEnterZone(player, isMainZone); // remove the buff from the player first; Sometimes on relog players still have the aura for (uint8 i = 0; i < MAX_EP_TOWERS; ++i) { player->RemoveAurasDueToSpell(player->GetTeam() == ALLIANCE ? plaguelandsTowerBuffs[i].spellIdAlliance : plaguelandsTowerBuffs[i].spellIdHorde); } // buff the player switch (player->GetTeam()) { case ALLIANCE: if (m_towersAlliance > 0) { player->CastSpell(player, plaguelandsTowerBuffs[m_towersAlliance - 1].spellIdAlliance, true); } break; case HORDE: if (m_towersHorde > 0) { player->CastSpell(player, plaguelandsTowerBuffs[m_towersHorde - 1].spellIdHorde, true); } break; default: break; } } void OutdoorPvPEP::HandlePlayerLeaveZone(Player* player, bool isMainZone) { // remove the buff from the player for (uint8 i = 0; i < MAX_EP_TOWERS; ++i) { player->RemoveAurasDueToSpell(player->GetTeam() == ALLIANCE ? plaguelandsTowerBuffs[i].spellIdAlliance : plaguelandsTowerBuffs[i].spellIdHorde); } OutdoorPvP::HandlePlayerLeaveZone(player, isMainZone); } void OutdoorPvPEP::HandleCreatureCreate(Creature* creature) { switch (creature->GetEntry()) { case NPC_SPECTRAL_FLIGHT_MASTER: m_flightMaster = creature->GetObjectGuid(); creature->setFaction(m_towerOwner[TOWER_ID_PLAGUEWOOD] == ALLIANCE ? FACTION_FLIGHT_MASTER_ALLIANCE : FACTION_FLIGHT_MASTER_HORDE); creature->CastSpell(creature, m_towerOwner[TOWER_ID_PLAGUEWOOD] == ALLIANCE ? SPELL_SPIRIT_PARTICLES_BLUE : SPELL_SPIRIT_PARTICLES_RED, true); break; case NPC_LORDAERON_COMMANDER: case NPC_LORDAERON_SOLDIER: case NPC_LORDAERON_VETERAN: case NPC_LORDAERON_FIGHTER: m_soldiers.push_back(creature->GetObjectGuid()); break; } } void OutdoorPvPEP::HandleGameObjectCreate(GameObject* go) { OutdoorPvP::HandleGameObjectCreate(go); switch (go->GetEntry()) { case GO_TOWER_BANNER_NORTHPASS: InitBanner(go, TOWER_ID_NORTHPASS); break; case GO_TOWER_BANNER_CROWNGUARD: InitBanner(go, TOWER_ID_CROWNGUARD); break; case GO_TOWER_BANNER_EASTWALL: InitBanner(go, TOWER_ID_EASTWALL); break; case GO_TOWER_BANNER_PLAGUEWOOD: InitBanner(go, TOWER_ID_PLAGUEWOOD); break; case GO_TOWER_BANNER: // sort banners if (go->IsWithinDist2d(plaguelandsTowerLocations[TOWER_ID_NORTHPASS][0], plaguelandsTowerLocations[TOWER_ID_NORTHPASS][1], 50.0f)) { InitBanner(go, TOWER_ID_NORTHPASS); } else if (go->IsWithinDist2d(plaguelandsTowerLocations[TOWER_ID_CROWNGUARD][0], plaguelandsTowerLocations[TOWER_ID_CROWNGUARD][1], 50.0f)) { InitBanner(go, TOWER_ID_CROWNGUARD); } else if (go->IsWithinDist2d(plaguelandsTowerLocations[TOWER_ID_EASTWALL][0], plaguelandsTowerLocations[TOWER_ID_EASTWALL][1], 50.0f)) { InitBanner(go, TOWER_ID_EASTWALL); } else if (go->IsWithinDist2d(plaguelandsTowerLocations[TOWER_ID_PLAGUEWOOD][0], plaguelandsTowerLocations[TOWER_ID_PLAGUEWOOD][1], 50.0f)) { InitBanner(go, TOWER_ID_PLAGUEWOOD); } break; case GO_LORDAERON_SHRINE_ALLIANCE: m_lordaeronShrineAlliance = go->GetObjectGuid(); break; case GO_LORDAERON_SHRINE_HORDE: m_lordaeronShrineHorde = go->GetObjectGuid(); break; } } void OutdoorPvPEP::HandleObjectiveComplete(uint32 eventId, const std::list<Player*>& players, Team team) { uint32 credit = 0; switch (eventId) { case EVENT_CROWNGUARD_PROGRESS_ALLIANCE: case EVENT_CROWNGUARD_PROGRESS_HORDE: credit = NPC_CROWNGUARD_TOWER_QUEST_DOODAD; break; case EVENT_EASTWALL_PROGRESS_ALLIANCE: case EVENT_EASTWALL_PROGRESS_HORDE: credit = NPC_EASTWALL_TOWER_QUEST_DOODAD; break; case EVENT_NORTHPASS_PROGRESS_ALLIANCE: case EVENT_NORTHPASS_PROGRESS_HORDE: credit = NPC_NORTHPASS_TOWER_QUEST_DOODAD; break; case EVENT_PLAGUEWOOD_PROGRESS_ALLIANCE: case EVENT_PLAGUEWOOD_PROGRESS_HORDE: credit = NPC_PLAGUEWOOD_TOWER_QUEST_DOODAD; break; default: return; } for (std::list<Player*>::const_iterator itr = players.begin(); itr != players.end(); ++itr) { if ((*itr) && (*itr)->GetTeam() == team) { (*itr)->KilledMonsterCredit(credit); (*itr)->RewardHonor(NULL, 1, HONOR_REWARD_PLAGUELANDS); } } } // process the capture events bool OutdoorPvPEP::HandleEvent(uint32 eventId, GameObject* go) { for (uint8 i = 0; i < MAX_EP_TOWERS; ++i) { if (plaguelandsBanners[i] == go->GetEntry()) { for (uint8 j = 0; j < 4; ++j) { if (plaguelandsTowerEvents[i][j].eventEntry == eventId) { // prevent processing if the owner did not change (happens if progress event is called after contest event) if (plaguelandsTowerEvents[i][j].team != m_towerOwner[i]) { if (plaguelandsTowerEvents[i][j].defenseMessage) { sWorld.SendDefenseMessage(ZONE_ID_EASTERN_PLAGUELANDS, plaguelandsTowerEvents[i][j].defenseMessage); } return ProcessCaptureEvent(go, i, plaguelandsTowerEvents[i][j].team, plaguelandsTowerEvents[i][j].worldState); } // no need to iterate other events or towers return false; } } // no need to iterate other towers return false; } } return false; } bool OutdoorPvPEP::ProcessCaptureEvent(GameObject* go, uint32 towerId, Team team, uint32 newWorldState) { if (team == ALLIANCE) { // update banner for (GuidList::const_iterator itr = m_towerBanners[towerId].begin(); itr != m_towerBanners[towerId].end(); ++itr) { SetBannerVisual(go, (*itr), CAPTURE_ARTKIT_ALLIANCE, CAPTURE_ANIM_ALLIANCE); } // update counter ++m_towersAlliance; SendUpdateWorldState(WORLD_STATE_EP_TOWER_COUNT_ALLIANCE, m_towersAlliance); // buff players BuffTeam(ALLIANCE, plaguelandsTowerBuffs[m_towersAlliance - 1].spellIdAlliance); } else if (team == HORDE) { // update banner for (GuidList::const_iterator itr = m_towerBanners[towerId].begin(); itr != m_towerBanners[towerId].end(); ++itr) { SetBannerVisual(go, (*itr), CAPTURE_ARTKIT_HORDE, CAPTURE_ANIM_HORDE); } // update counter ++m_towersHorde; SendUpdateWorldState(WORLD_STATE_EP_TOWER_COUNT_HORDE, m_towersHorde); // buff players BuffTeam(HORDE, plaguelandsTowerBuffs[m_towersHorde - 1].spellIdHorde); } else { // update banner for (GuidList::const_iterator itr = m_towerBanners[towerId].begin(); itr != m_towerBanners[towerId].end(); ++itr) { SetBannerVisual(go, (*itr), CAPTURE_ARTKIT_NEUTRAL, CAPTURE_ANIM_NEUTRAL); } if (m_towerOwner[towerId] == ALLIANCE) { // update counter --m_towersAlliance; SendUpdateWorldState(WORLD_STATE_EP_TOWER_COUNT_ALLIANCE, m_towersAlliance); if (m_towersAlliance == 0) { BuffTeam(ALLIANCE, plaguelandsTowerBuffs[0].spellIdAlliance, true); } } else { // update counter --m_towersHorde; SendUpdateWorldState(WORLD_STATE_EP_TOWER_COUNT_HORDE, m_towersHorde); if (m_towersHorde == 0) { BuffTeam(HORDE, plaguelandsTowerBuffs[0].spellIdHorde, true); } } } bool eventHandled = true; if (team != TEAM_NONE) { // update capture point owner before rewards are applied m_towerOwner[towerId] = team; // apply rewards of changed tower switch (towerId) { case TOWER_ID_NORTHPASS: RespawnGO(go, team == ALLIANCE ? m_lordaeronShrineAlliance : m_lordaeronShrineHorde, true); break; case TOWER_ID_CROWNGUARD: sObjectMgr.SetGraveYardLinkTeam(GRAVEYARD_ID_EASTERN_PLAGUE, GRAVEYARD_ZONE_EASTERN_PLAGUE, team); break; case TOWER_ID_EASTWALL: // Return false - allow the DB to handle summons if (m_towerOwner[TOWER_ID_NORTHPASS] != team) { eventHandled = false; } break; case TOWER_ID_PLAGUEWOOD: // Return false - allow the DB to handle summons eventHandled = false; break; } } else { // remove rewards of changed tower switch (towerId) { case TOWER_ID_NORTHPASS: RespawnGO(go, m_towerOwner[TOWER_ID_NORTHPASS] == ALLIANCE ? m_lordaeronShrineAlliance : m_lordaeronShrineHorde, false); break; case TOWER_ID_CROWNGUARD: sObjectMgr.SetGraveYardLinkTeam(GRAVEYARD_ID_EASTERN_PLAGUE, GRAVEYARD_ZONE_EASTERN_PLAGUE, TEAM_INVALID); break; case TOWER_ID_EASTWALL: UnsummonSoldiers(go); break; case TOWER_ID_PLAGUEWOOD: UnsummonFlightMaster(go); break; } // update capture point owner after rewards have been removed m_towerOwner[towerId] = team; } // update tower state SendUpdateWorldState(m_towerWorldState[towerId], WORLD_STATE_REMOVE); m_towerWorldState[towerId] = newWorldState; SendUpdateWorldState(m_towerWorldState[towerId], WORLD_STATE_ADD); // there are some events which required further DB script return eventHandled; } bool OutdoorPvPEP::HandleGameObjectUse(Player* /*player*/, GameObject* go) { // prevent despawning after go use if (go->GetEntry() == GO_LORDAERON_SHRINE_ALLIANCE || go->GetEntry() == GO_LORDAERON_SHRINE_HORDE) { go->SetRespawnTime(0); } return false; } void OutdoorPvPEP::InitBanner(GameObject* go, uint32 towerId) { m_towerBanners[towerId].push_back(go->GetObjectGuid()); go->SetGoArtKit(GetBannerArtKit(m_towerOwner[towerId])); } // Handle the unsummon of the spectral flight master when the Plaguewood tower is lost void OutdoorPvPEP::UnsummonFlightMaster(const WorldObject* objRef) { if (Creature* flightMaster = objRef->GetMap()->GetCreature(m_flightMaster)) { flightMaster->ForcedDespawn(); } } // Handle the unsummon of the soldiers when the Eastwall tower is lost void OutdoorPvPEP::UnsummonSoldiers(const WorldObject* objRef) { for (GuidList::const_iterator itr = m_soldiers.begin(); itr != m_soldiers.end(); ++itr) { if (Creature* soldier = objRef->GetMap()->GetCreature(*itr)) { soldier->ForcedDespawn(); } } m_soldiers.clear(); }
1
0.960686
1
0.960686
game-dev
MEDIA
0.994968
game-dev
0.915329
1
0.915329
TrashboxBobylev/Summoning-Pixel-Dungeon
3,700
core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/items/magic/soulreaver/Defense.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2022 Evan Debenham * * Summoning Pixel Dungeon * Copyright (C) 2019-2022 TrashboxBobylev * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.shatteredpixeldungeon.items.magic.soulreaver; import com.shatteredpixel.shatteredpixeldungeon.Dungeon; import com.shatteredpixel.shatteredpixeldungeon.actors.Actor; import com.shatteredpixel.shatteredpixeldungeon.actors.Char; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.ArcaneArmor; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Barkskin; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Buff; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.powers.ArmoredShielding; import com.shatteredpixel.shatteredpixeldungeon.actors.mobs.minions.Minion; import com.shatteredpixel.shatteredpixeldungeon.items.magic.ConjurerSpell; import com.shatteredpixel.shatteredpixeldungeon.mechanics.Ballistica; import com.shatteredpixel.shatteredpixeldungeon.messages.Messages; import com.shatteredpixel.shatteredpixeldungeon.sprites.ItemSpriteSheet; public class Defense extends ConjurerSpell { { image = ItemSpriteSheet.SR_DEFENSE; } @Override public void effect(Ballistica trajectory) { Char ch = Actor.findChar(trajectory.collisionPos); if (ch instanceof Minion) { if (ch.buff(ArmoredShielding.class) == null) { Buff.affect(ch, ArmoredShielding.class, 1000000f); Buff.affect(ch, Barkskin.class).set(defenseEarthValue(), defenseEarthTime()); Buff.affect(ch, ArcaneArmor.class).set(defenseArcaneValue(), defenseArcaneTime()); } else { ch.buff(ArmoredShielding.class).detach(); Buff.affect(ch, Barkskin.class).detach(); Buff.affect(ch, ArcaneArmor.class).detach(); Dungeon.hero.mana = Math.min(Dungeon.hero.maxMana, Dungeon.hero.mana + manaCost()); } } } private int defenseEarthTime(){ switch (level()){ case 1: return 8; case 2: return 100; } return 30; } private int defenseArcaneTime(){ switch (level()){ case 1: return 12; case 2: return 120; } return 40; } private int defenseEarthValue(){ switch (level()){ case 1: return 10 + Dungeon.hero.lvl; case 2: return 5; } return 6 + Dungeon.hero.lvl*3/4; } private int defenseArcaneValue(){ switch (level()){ case 1: return 7 + Dungeon.hero.lvl/2; case 2: return 3; } return 3 + Dungeon.hero.lvl/3; } @Override public int manaCost(){ switch (level()){ case 1: return 35; case 2: return 5; } return 30; } public String desc() { return Messages.get(this, "desc", defenseEarthValue(), defenseArcaneValue(), manaCost()); } }
1
0.852015
1
0.852015
game-dev
MEDIA
0.992531
game-dev
0.930235
1
0.930235
ForestDango/Hollow-Knight-Demo
1,219
Assets/PlayMaker/Actions/Array/ArrayResize.cs
// (c) Copyright HutongGames, LLC 2010-2014. All rights reserved. using UnityEngine; namespace HutongGames.PlayMaker.Actions { [ActionCategory(ActionCategory.Array)] [Tooltip("Resize an array.")] public class ArrayResize : FsmStateAction { [RequiredField] [UIHint(UIHint.Variable)] [Tooltip("The Array Variable to resize")] public FsmArray array; [Tooltip("The new size of the array.")] public FsmInt newSize; [Tooltip("The event to trigger if the new size is out of range")] public FsmEvent sizeOutOfRangeEvent; public override void OnEnter() { if (newSize.Value >= 0) { array.Resize(newSize.Value); } else { LogError("Size out of range: " + newSize.Value); Fsm.Event(sizeOutOfRangeEvent); } Finish(); } /* Should be disallowed by the UI now public override string ErrorCheck() { if (newSize.Value<0) { return "newSize must be a positive value."; } return ""; }*/ } }
1
0.910419
1
0.910419
game-dev
MEDIA
0.922673
game-dev
0.946434
1
0.946434
Tesserex/C--MegaMan-Engine
4,421
Mega Man/Components/HealthComponent.cs
using System; using MegaMan.Common.Entities; namespace MegaMan.Engine { public class HealthComponent : Component { // alive is set to true if health ever goes above zero private bool alive; private float maxHealth; private float health; private HealthMeter meter; private int flashtime; private int flashing; private bool clearHitNextFrame; public float Health { get { return health; } set { health = value; if (health > maxHealth) health = maxHealth; if (health > 0) { alive = true; } if (meter != null) { meter.Value = health; } HealthChanged?.Invoke(health, maxHealth); } } public float StartHealth { get; private set; } public float MaxHealth { get { return maxHealth; } } public bool Hit { get; private set; } public event Action<float, float> HealthChanged; private void Instance_GameCleanup() { if (alive && Health <= 0) Parent.Die(); } public override Component Clone() { var copy = new HealthComponent { StartHealth = StartHealth, maxHealth = maxHealth, flashtime = flashtime, meter = meter }; // if it has a meter, it's intended to only have one instance on the screen // so a shallow copy should suffice if (copy.meter != null) copy.meter.Reset(); return copy; } public override void Start(IGameplayContainer container) { container.GameThink += Update; container.GameCleanup += Instance_GameCleanup; Health = StartHealth; if (meter != null) { meter.Start(container); } } public void DelayFill(int frames) { if (meter != null) meter.DelayedFill(frames); } public override void Stop(IGameplayContainer container) { container.GameThink -= Update; container.GameCleanup -= Instance_GameCleanup; if (meter != null) { meter.Stop(); } Hit = false; flashing = 0; } public override void Message(IGameMessage msg) { if (msg is DamageMessage && flashing == 0) { if (Engine.Instance.Invincible && Parent.Name == "Player") return; var damage = (DamageMessage)msg; if (!Engine.Instance.NoDamage) Health -= damage.Damage; Hit = true; clearHitNextFrame = false; flashing = flashtime; } else if (msg is HealMessage) { var heal = (HealMessage)msg; Health += heal.Health; } } protected override void Update() { if (clearHitNextFrame) Hit = false; else clearHitNextFrame = true; if (flashing > 0) { flashing--; var spr = Parent.GetComponent<SpriteComponent>(); if (spr != null) spr.Visible = (flashing % 3 != 1); } } public override void RegisterDependencies(Component component) { } public void LoadInfo(HealthComponentInfo info) { maxHealth = info.Max; StartHealth = info.StartValue ?? info.Max; flashtime = info.FlashFrames; if (info.Meter != null) { meter = HealthMeter.Create(info.Meter, true); meter.MaxValue = maxHealth; meter.IsPlayer = (Parent.Name == "Player"); } } // this exists for the sake of dynamic expressions, // which can't do assignment through operators public void Add(float val) { Health += val; } public void Reset() { Health = MaxHealth; } } }
1
0.787611
1
0.787611
game-dev
MEDIA
0.727773
game-dev
0.834456
1
0.834456
PacktPublishing/Mastering-Cpp-Game-Animation-Programming
7,936
chapter04/02_vulkan_edit_view_mode/model/AssimpAnimChannel.cpp
#include "AssimpAnimChannel.h" #include "Logger.h" void AssimpAnimChannel::loadChannelData(aiNodeAnim* nodeAnim) { mNodeName = nodeAnim->mNodeName.C_Str(); unsigned int numTranslations = nodeAnim->mNumPositionKeys; unsigned int numRotations = nodeAnim->mNumRotationKeys; unsigned int numScalings = nodeAnim->mNumScalingKeys; unsigned int preState = nodeAnim->mPreState; unsigned int postState = nodeAnim->mPostState; Logger::log(1, "%s: - loading animation channel for node '%s', with %i translation keys, %i rotation keys, %i scaling keys (preState %i, postState %i)\n", __FUNCTION__, mNodeName.c_str(), numTranslations, numRotations, numScalings, preState, postState); for (unsigned int i = 0; i < numTranslations; ++i) { mTranslationTiminngs.emplace_back(static_cast<float>(nodeAnim->mPositionKeys[i].mTime)); mTranslations.emplace_back(glm::vec3(nodeAnim->mPositionKeys[i].mValue.x, nodeAnim->mPositionKeys[i].mValue.y, nodeAnim->mPositionKeys[i].mValue.z)); } for (unsigned int i = 0; i < numRotations; ++i) { mRotationTiminigs.emplace_back(static_cast<float>(nodeAnim->mRotationKeys[i].mTime)); mRotations.emplace_back(glm::quat(nodeAnim->mRotationKeys[i].mValue.w, nodeAnim->mRotationKeys[i].mValue.x, nodeAnim->mRotationKeys[i].mValue.y, nodeAnim->mRotationKeys[i].mValue.z)); } for (unsigned int i = 0; i < numScalings; ++i) { mScaleTimings.emplace_back(static_cast<float>(nodeAnim->mScalingKeys[i].mTime)); mScalings.emplace_back(glm::vec3(nodeAnim->mScalingKeys[i].mValue.x, nodeAnim->mScalingKeys[i].mValue.y, nodeAnim->mScalingKeys[i].mValue.z)); } /* precalcuate the inverse offset to avoid divisions when scaling the section */ for (unsigned int i = 0; i < mTranslationTiminngs.size() - 1; ++i) { mInverseTranslationTimeDiffs.emplace_back(1.0f / (mTranslationTiminngs.at(i + 1) - mTranslationTiminngs.at(i))); } for (unsigned int i = 0; i < mRotationTiminigs.size() - 1; ++i) { mInverseRotationTimeDiffs.emplace_back(1.0f / (mRotationTiminigs.at(i + 1) - mRotationTiminigs.at(i))); } for (unsigned int i = 0; i < mScaleTimings.size() - 1; ++i) { mInverseScaleTimeDiffs.emplace_back(1.0f / (mScaleTimings.at(i + 1) - mScaleTimings.at(i))); } mPreState = preState; mPostState = postState; } std::string AssimpAnimChannel::getTargetNodeName() { return mNodeName; } float AssimpAnimChannel::getMaxTime() { float maxTranslationTime = mTranslationTiminngs.at(mTranslationTiminngs.size() - 1); float maxRotationTime = mRotationTiminigs.at(mRotationTiminigs.size() - 1); float maxScaleTime = mScaleTimings.at(mScaleTimings.size() - 1); return std::max(std::max(maxRotationTime, maxTranslationTime), maxScaleTime); } glm::vec4 AssimpAnimChannel::getTranslation(float time) { if (mTranslations.empty()) { return glm::vec4(0.0f); } /* handle time before and after */ switch (mPreState) { case 0: /* do not change vertex position-> aiAnimBehaviour_DEFAULT */ if (time < mTranslationTiminngs.at(0)) { return glm::vec4(0.0f); } break; case 1: /* use value at zero time "aiAnimBehaviour_CONSTANT" */ if (time < mTranslationTiminngs.at(0)) { return glm::vec4(mTranslations.at(0), 1.0f); } break; default: Logger::log(1, "%s error: preState %i not implmented\n", __FUNCTION__, mPreState); break; } switch(mPostState) { case 0: if (time > mTranslationTiminngs.at(mTranslationTiminngs.size() - 1)) { return glm::vec4(0.0f); } break; case 1: if (time >= mTranslationTiminngs.at(mTranslationTiminngs.size() - 1)) { return glm::vec4(mTranslations.at(mTranslations.size() - 1), 1.0f); } break; default: Logger::log(1, "%s error: postState %i not implmented\n", __FUNCTION__, mPostState); break; } auto timeIndexPos = std::lower_bound(mTranslationTiminngs.begin(), mTranslationTiminngs.end(), time); /* catch rare cases where time is exaclty zero */ int timeIndex = std::max(static_cast<int>(std::distance(mTranslationTiminngs.begin(), timeIndexPos)) - 1, 0); float interpolatedTime = (time - mTranslationTiminngs.at(timeIndex)) * mInverseTranslationTimeDiffs.at(timeIndex); return glm::vec4(glm::mix(mTranslations.at(timeIndex), mTranslations.at(timeIndex + 1), interpolatedTime), 1.0f); } glm::vec4 AssimpAnimChannel::getScaling(float time) { if (mScalings.empty()) { return glm::vec4(1.0f); } /* handle time before and after */ switch (mPreState) { case 0: /* do not change vertex position-> aiAnimBehaviour_DEFAULT */ if (time < mScaleTimings.at(0)) { return glm::vec4(0.0f); } break; case 1: /* use value at zero time "aiAnimBehaviour_CONSTANT" */ if (time < mScaleTimings.at(0)) { return glm::vec4(mScalings.at(0), 1.0f); } break; default: Logger::log(1, "%s error: preState %i not implmented\n", __FUNCTION__, mPreState); break; } switch(mPostState) { case 0: if (time > mScaleTimings.at(mScaleTimings.size() - 1)) { return glm::vec4(0.0f); } break; case 1: if (time >= mScaleTimings.at(mScaleTimings.size() - 1)) { return glm::vec4(mScalings.at(mScalings.size() - 1), 1.0f); } break; default: Logger::log(1, "%s error: postState %i not implmented\n", __FUNCTION__, mPostState); break; } auto timeIndexPos = std::lower_bound(mScaleTimings.begin(), mScaleTimings.end(), time); int timeIndex = std::max(static_cast<int>(std::distance(mScaleTimings.begin(), timeIndexPos)) - 1, 0); float interpolatedTime = (time - mScaleTimings.at(timeIndex)) * mInverseScaleTimeDiffs.at(timeIndex); return glm::vec4(glm::mix(mScalings.at(timeIndex), mScalings.at(timeIndex + 1), interpolatedTime), 1.0f); } glm::vec4 AssimpAnimChannel::getRotation(float time) { if (mRotations.empty()) { return glm::vec4(1.0f, 0.0f, 0.0f, 0.0f); } /* handle time before and after */ switch (mPreState) { case 0: /* do not change vertex position-> aiAnimBehaviour_DEFAULT */ if (time < mRotationTiminigs.at(0)) { return glm::vec4(1.0f, 0.0f, 0.0f, 0.0f); } break; case 1: /* use value at zero time "aiAnimBehaviour_CONSTANT" */ if (time < mRotationTiminigs.at(0)) { glm::quat rotation = mRotations.at(0); return glm::vec4(rotation.x, rotation.y, rotation.z, rotation.w); } break; default: Logger::log(1, "%s error: preState %i not implmented\n", __FUNCTION__, mPreState); break; } switch(mPostState) { case 0: if (time > mRotationTiminigs.at(mRotationTiminigs.size() - 1)) { return glm::vec4(1.0f, 0.0f, 0.0f, 0.0f); } break; case 1: if (time >= mRotationTiminigs.at(mRotationTiminigs.size() - 1)) { glm::quat rotation = mRotations.at(mRotations.size() - 1); return glm::vec4(rotation.x, rotation.y, rotation.z, rotation.w); } break; default: Logger::log(1, "%s error: postState %i not implmented\n", __FUNCTION__, mPostState); break; } auto timeIndexPos = std::lower_bound(mRotationTiminigs.begin(), mRotationTiminigs.end(), time); int timeIndex = std::max(static_cast<int>(std::distance(mRotationTiminigs.begin(), timeIndexPos)) - 1, 0); float interpolatedTime = (time - mRotationTiminigs.at(timeIndex)) * mInverseRotationTimeDiffs.at(timeIndex); /* roiations are interpolated via SLERP */ glm::quat rotation = glm::normalize(glm::slerp(mRotations.at(timeIndex), mRotations.at(timeIndex + 1), interpolatedTime)); /* return order of GLM vec4 */ return glm::vec4(rotation.x, rotation.y, rotation.z, rotation.w); } int AssimpAnimChannel::getBoneId() { return mBoneId; } void AssimpAnimChannel::setBoneId(unsigned int id) { mBoneId = id; }
1
0.950705
1
0.950705
game-dev
MEDIA
0.517789
game-dev
0.958237
1
0.958237
Ravaelles/Atlantis
1,422
src/starengine/engine_game/StarEngineGame.java
package starengine.engine_game; import atlantis.units.select.Select; import starengine.StarEngine; public class StarEngineGame { private final StarEngine starEngine; private boolean gameEnd = false; private boolean weWon = false; // ========================================================= public StarEngineGame(StarEngine starEngine) { this.starEngine = starEngine; } // ========================================================= public boolean checkForGameEnd() { // System.err.println(Select.our().havingAtLeastHp(1).count() // + " / " + Select.enemy().havingAtLeastHp(1).count()); if (Select.our().havingAtLeastHp(1).empty()) { gameEnd = true; weWon = false; } else if (Select.enemy().havingAtLeastHp(1).empty()) { gameEnd = true; weWon = true; } if (gameEnd) { System.out.println( "### StarEngine ###\n" + "GAME OVER, " + (weWon ? "VICTORY!" : "DEFEAT!") + "\n" ); starEngine.testClass().setShouldQuitGameLoopNow(true); starEngine.closeIfNeeded(); } return gameEnd; } // ========================================================= public boolean isGameEnd() { return gameEnd; } public boolean weWon() { return weWon; } }
1
0.538466
1
0.538466
game-dev
MEDIA
0.863267
game-dev
0.728713
1
0.728713
Wargus/wargus
5,575
campaigns/orc-exp/levelx07o_c.sms
-- Stratagus Map - Single player campaign Load("campaigns/orc-exp/levelx07o_c2.sms") Briefing( title, objectives, "../campaigns/orc/interface/introscreen5.png", "campaigns/orc-exp/levelx07o.txt", {"campaigns/orc-exp/levelx07o-intro1.wav", "campaigns/orc-exp/levelx07o-intro2.wav", "campaigns/orc-exp/levelx07o-intro3.wav"} ) -- FIXME: Check if units are destroyed. AddTrigger( function() return GetPlayerData(GetThisPlayer(), "UnitTypesCount", "unit-orc-shipyard") >= 5 and GetPlayerData(2, "UnitTypesCount", "unit-battleship") == 0 and GetPlayerData(1, "UnitTypesCount", "unit-battleship") == 0 and GetPlayerData(2, "UnitTypesCount", "unit-human-destroyer") == 0 and GetPlayerData(1, "UnitTypesCount", "unit-human-destroyer") == 0 and GetPlayerData(2, "UnitTypesCount", "unit-human-transport") == 0 and GetPlayerData(1, "UnitTypesCount", "unit-human-transport") == 0 end, function() return ActionVictory() end) AddTrigger( function() return GetPlayerData(GetThisPlayer(), "TotalNumUnits") == 0 end, function() return ActionDefeat() end) --Units DefineAllowNormalHumanUnits("AAAAAAAAAAAAAAAA") DefineAllowExtraHumanUnits("FFFFFFFFFFFFFFFF") DefineAllowNormalOrcUnits("AAAAAAAAAAAAAAAA") DefineAllowExtraOrcUnits("FFFFFFFFFFFFFFFF") DefineAllowSpecialUnits("FFFFFFFFFFFFFFFF") DefineAllowHumanAlways() DefineAllowOrcAlways() local orc_exp_07a_loop_funcs = { function() DebugPrint("Looping !\n") return false end, function() return AiForce(2, {AiFlyer(), 4}) end, function() return AiForce(1, {AiDestroyer(), 3, AiBattleship(), 1}) end, function() return AiSleep(5000) end, function() return AiWaitForce(2) end, function() return AiWaitForce(1) end, function() DebugMessage("Attacking..."); return AiAttackWithForce(2) end, function() return AiSleep(2000) end, function() DebugMessage("Attacking..."); return AiAttackWithForce(1) end, function() stratagus.gameData.AIState.loop_index[1 + AiPlayer()] = 0; return false end, } local orc_exp_07b_loop_funcs = { function() DebugPrint("Looping !\n") return false end, function() return AiForce(1, {AiSoldier(), 5, AiShooter(), 5, AiCavalry(), 3, AiCatapult(), 1}) end, function() return AiWaitForce(1) end, function() DebugMessage("Attacking..."); return AiAttackWithForce(1) end, function() return AiSleep(2000) end, function() stratagus.gameData.AIState.loop_index[1 + AiPlayer()] = 0; return false end, } local orc_exp_07a_funcs = { function() return AiSet(AiWorker(), 6) end, function() return AiSet(AiTanker(), 2) end, function() return AiResearch(AiUpgradeShipArmor1()) end, function() return AiResearch(AiUpgradeShipCannon1()) end, function() return AiForce(1, {AiDestroyer(), 3, AiBattleship(), 1}) end, function() return AiSleep(10000) end, function() return AiForce(2, {AiFlyer(), 3}) end, function() return AiWaitForce(2) end, function() DebugMessage("Attacking..."); return AiAttackWithForce(2) end, function() return AiSleep(8000) end, function() return AiWaitForce(1) end, function() DebugMessage("Attacking..."); return AiAttackWithForce(1) end, function() return AiResearch(AiUpgradeShipArmor2()) end, function() return AiResearch(AiUpgradeShipCannon2()) end, function() return AiSleep(3500) end, function() return AiForce(1, {AiDestroyer(), 3, AiBattleship(), 1}) end, function() return AiWaitForce(1) end, function() DebugMessage("Attacking..."); return AiAttackWithForce(1) end, function() return AiSleep(3500) end, function() return AiForce(1, {AiDestroyer(), 3, AiBattleship(), 1}) end, function() return AiWaitForce(1) end, function() DebugMessage("Attacking..."); return AiAttackWithForce(1) end, function() return AiSleep(3500) end, function() return AiLoop(orc_exp_07a_loop_funcs, stratagus.gameData.AIState.loop_index) end, } local orc_exp_07b_funcs = { function() return AiNeed(AiCityCenter()) end, function() return AiNeed(AiLumberMill()) end, function() return AiNeed(AiBarracks()) end, function() return AiSet(AiWorker(), 8) end, function() return AiWait(AiWorker()) end, function() return AiNeed(AiBlacksmith()) end, function() return AiForce(1, {AiSoldier(), 4, AiShooter(), 3}) end, function() return AiWaitForce(1) end, function() return AiNeed(AiTower()) end, function() return AiNeed(AiTower()) end, function() return AiUpgradeTo(AiGuardTower()) end, function() return AiUpgradeTo(AiGuardTower()) end, function() return AiSleep(2000) end, function() DebugMessage("Attacking..."); return AiAttackWithForce(1) end, function() return AiResearch(AiUpgradeWeapon1()) end, function() return AiSet(AiWorker(), 10) end, function() return AiWait(AiWorker()) end, function() return AiUpgradeTo(AiBetterCityCenter()) end, function() return AiForce(1, {AiSoldier(), 4, AiShooter(), 3}) end, function() return AiWaitForce(1) end, function() DebugMessage("Attacking..."); return AiAttackWithForce(1) end, function() return AiSleep(2000) end, function() return AiResearch(AiUpgradeMissile1()) end, function() return AiNeed(AiStables()) end, function() return AiResearch(AiUpgradeArmor1()) end, function() return AiNeed(AiBarracks()) end, function() return AiLoop(orc_exp_07b_loop_funcs, stratagus.gameData.AIState.loop_index) end, } function AiOrcExp07a() return AiLoop(orc_exp_07a_funcs, stratagus.gameData.AIState.index) end function AiOrcExp07b() return AiLoop(orc_exp_07b_funcs, stratagus.gameData.AIState.index) end DefineAi("orc-exp-7a", "*", "orc-exp-7a", AiOrcExp07a) DefineAi("orc-exp-7b", "*", "orc-exp-7b", AiOrcExp07b) Load("campaigns/orc-exp/levelx07o.sms")
1
0.668328
1
0.668328
game-dev
MEDIA
0.773092
game-dev
0.62345
1
0.62345
gscept/nebula-trifid
2,820
code/tests/testrender/animsequencertest.cc
//------------------------------------------------------------------------------ // animsequencertest.cc // (C) 2008 Radon Labs GmbH //------------------------------------------------------------------------------ #include "stdneb.h" #include "animsequencertest.h" #include "resources/managedresource.h" #include "coreanimation/animresource.h" #include "animation/animsequencer.h" #include "animation/playclipjob.h" namespace Test { __ImplementClass(Test::AnimSequencerTest, 'asrt', Test::CoreGraphicsTest); using namespace Util; using namespace Resources; using namespace CoreAnimation; using namespace Animation; //------------------------------------------------------------------------------ /** *** OBSOLETE *** */ void AnimSequencerTest::Run() { if (this->SetupRuntime()) { // first load an animation resource through the resource manager Ptr<ManagedResource> res = this->resManager->CreateManagedResource(AnimResource::RTTI, ResourceId("anim:characters/mensch_m_animations.nax2")); this->resManager->WaitForPendingResources(5.0); this->Verify(!res->IsPlaceholder()); if (!res->IsPlaceholder()) { Ptr<AnimResource> animRes = res->GetLoadedResource().downcast<AnimResource>(); // setup an AnimSequencer object AnimSequencer animSequencer; animSequencer.Setup(animRes); // setup a few same-priority PlayClip jobs and attach them to the sequencer Ptr<PlayClipJob> playClip0 = PlayClipJob::Create(); playClip0->SetClipName("idle_01"); playClip0->SetStartTime(0); playClip0->SetDuration(5000); playClip0->SetFadeInTime(100); animSequencer.EnqueueAnimJob(playClip0.cast<AnimJob>()); Ptr<PlayClipJob> playClip1 = PlayClipJob::Create(); playClip1->SetClipName("gehen_01"); playClip1->SetStartTime(2000); playClip1->SetDuration(5000); playClip1->SetFadeInTime(100); animSequencer.EnqueueAnimJob(playClip1.cast<AnimJob>()); Ptr<PlayClipJob> playClip2 = PlayClipJob::Create(); playClip2->SetClipName("laufen_01"); playClip2->SetStartTime(1000); playClip2->SetDuration(5000); playClip2->SetFadeInTime(100); animSequencer.EnqueueAnimJob(playClip2.cast<AnimJob>()); // evaluate the anim sequencer at different points in time animSequencer.UpdateTime(0); // animSequencer->UpdateAnimation(); animSequencer.UpdateTime(50); // animSequencer->UpdateAnimation(); animSequencer.UpdateTime(1000); // animSequencer->UpdateAnimation(); } this->ShutdownRuntime(); } } } // namespace Test
1
0.564558
1
0.564558
game-dev
MEDIA
0.715826
game-dev,graphics-rendering
0.778253
1
0.778253
Planimeter/hl2sb-src
26,760
src/game/server/player_lagcompensation.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "usercmd.h" #include "igamesystem.h" #include "ilagcompensationmanager.h" #include "inetchannelinfo.h" #include "utllinkedlist.h" #include "BaseAnimatingOverlay.h" #include "tier0/vprof.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #define LC_NONE 0 #define LC_ALIVE (1<<0) #define LC_ORIGIN_CHANGED (1<<8) #define LC_ANGLES_CHANGED (1<<9) #define LC_SIZE_CHANGED (1<<10) #define LC_ANIMATION_CHANGED (1<<11) static ConVar sv_lagcompensation_teleport_dist( "sv_lagcompensation_teleport_dist", "64", FCVAR_DEVELOPMENTONLY | FCVAR_CHEAT, "How far a player got moved by game code before we can't lag compensate their position back" ); #define LAG_COMPENSATION_EPS_SQR ( 0.1f * 0.1f ) // Allow 4 units of error ( about 1 / 8 bbox width ) #define LAG_COMPENSATION_ERROR_EPS_SQR ( 4.0f * 4.0f ) ConVar sv_unlag( "sv_unlag", "1", FCVAR_DEVELOPMENTONLY, "Enables player lag compensation" ); ConVar sv_maxunlag( "sv_maxunlag", "1.0", FCVAR_DEVELOPMENTONLY, "Maximum lag compensation in seconds", true, 0.0f, true, 1.0f ); ConVar sv_lagflushbonecache( "sv_lagflushbonecache", "1", FCVAR_DEVELOPMENTONLY, "Flushes entity bone cache on lag compensation" ); ConVar sv_showlagcompensation( "sv_showlagcompensation", "0", FCVAR_CHEAT, "Show lag compensated hitboxes whenever a player is lag compensated." ); ConVar sv_unlag_fixstuck( "sv_unlag_fixstuck", "0", FCVAR_DEVELOPMENTONLY, "Disallow backtracking a player for lag compensation if it will cause them to become stuck" ); //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- #define MAX_LAYER_RECORDS (CBaseAnimatingOverlay::MAX_OVERLAYS) struct LayerRecord { int m_sequence; float m_cycle; float m_weight; int m_order; LayerRecord() { m_sequence = 0; m_cycle = 0; m_weight = 0; m_order = 0; } LayerRecord( const LayerRecord& src ) { m_sequence = src.m_sequence; m_cycle = src.m_cycle; m_weight = src.m_weight; m_order = src.m_order; } }; struct LagRecord { public: LagRecord() { m_fFlags = 0; m_vecOrigin.Init(); m_vecAngles.Init(); m_vecMinsPreScaled.Init(); m_vecMaxsPreScaled.Init(); m_flSimulationTime = -1; m_masterSequence = 0; m_masterCycle = 0; } LagRecord( const LagRecord& src ) { m_fFlags = src.m_fFlags; m_vecOrigin = src.m_vecOrigin; m_vecAngles = src.m_vecAngles; m_vecMinsPreScaled = src.m_vecMinsPreScaled; m_vecMaxsPreScaled = src.m_vecMaxsPreScaled; m_flSimulationTime = src.m_flSimulationTime; for( int layerIndex = 0; layerIndex < MAX_LAYER_RECORDS; ++layerIndex ) { m_layerRecords[layerIndex] = src.m_layerRecords[layerIndex]; } m_masterSequence = src.m_masterSequence; m_masterCycle = src.m_masterCycle; } // Did player die this frame int m_fFlags; // Player position, orientation and bbox Vector m_vecOrigin; QAngle m_vecAngles; Vector m_vecMinsPreScaled; Vector m_vecMaxsPreScaled; float m_flSimulationTime; // Player animation details, so we can get the legs in the right spot. LayerRecord m_layerRecords[MAX_LAYER_RECORDS]; int m_masterSequence; float m_masterCycle; }; // // Try to take the player from his current origin to vWantedPos. // If it can't get there, leave the player where he is. // ConVar sv_unlag_debug( "sv_unlag_debug", "0", FCVAR_GAMEDLL | FCVAR_DEVELOPMENTONLY ); float g_flFractionScale = 0.95; static void RestorePlayerTo( CBasePlayer *pPlayer, const Vector &vWantedPos ) { // Try to move to the wanted position from our current position. trace_t tr; VPROF_BUDGET( "RestorePlayerTo", "CLagCompensationManager" ); UTIL_TraceEntity( pPlayer, vWantedPos, vWantedPos, MASK_PLAYERSOLID, pPlayer, COLLISION_GROUP_PLAYER_MOVEMENT, &tr ); if ( tr.startsolid || tr.allsolid ) { if ( sv_unlag_debug.GetBool() ) { DevMsg( "RestorePlayerTo() could not restore player position for client \"%s\" ( %.1f %.1f %.1f )\n", pPlayer->GetPlayerName(), vWantedPos.x, vWantedPos.y, vWantedPos.z ); } UTIL_TraceEntity( pPlayer, pPlayer->GetLocalOrigin(), vWantedPos, MASK_PLAYERSOLID, pPlayer, COLLISION_GROUP_PLAYER_MOVEMENT, &tr ); if ( tr.startsolid || tr.allsolid ) { // In this case, the guy got stuck back wherever we lag compensated him to. Nasty. if ( sv_unlag_debug.GetBool() ) DevMsg( " restore failed entirely\n" ); } else { // We can get to a valid place, but not all the way back to where we were. Vector vPos; VectorLerp( pPlayer->GetLocalOrigin(), vWantedPos, tr.fraction * g_flFractionScale, vPos ); UTIL_SetOrigin( pPlayer, vPos, true ); if ( sv_unlag_debug.GetBool() ) DevMsg( " restore got most of the way\n" ); } } else { // Cool, the player can go back to whence he came. UTIL_SetOrigin( pPlayer, tr.endpos, true ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- class CLagCompensationManager : public CAutoGameSystemPerFrame, public ILagCompensationManager { public: CLagCompensationManager( char const *name ) : CAutoGameSystemPerFrame( name ), m_flTeleportDistanceSqr( 64 *64 ) { m_isCurrentlyDoingCompensation = false; } // IServerSystem stuff virtual void Shutdown() { ClearHistory(); } virtual void LevelShutdownPostEntity() { ClearHistory(); } // called after entities think virtual void FrameUpdatePostEntityThink(); // ILagCompensationManager stuff // Called during player movement to set up/restore after lag compensation void StartLagCompensation( CBasePlayer *player, CUserCmd *cmd ); void FinishLagCompensation( CBasePlayer *player ); bool IsCurrentlyDoingLagCompensation() const OVERRIDE { return m_isCurrentlyDoingCompensation; } private: void BacktrackPlayer( CBasePlayer *player, float flTargetTime ); void ClearHistory() { for ( int i=0; i<MAX_PLAYERS; i++ ) m_PlayerTrack[i].Purge(); } // keep a list of lag records for each player CUtlFixedLinkedList< LagRecord > m_PlayerTrack[ MAX_PLAYERS ]; // Scratchpad for determining what needs to be restored CBitVec<MAX_PLAYERS> m_RestorePlayer; bool m_bNeedToRestore; LagRecord m_RestoreData[ MAX_PLAYERS ]; // player data before we moved him back LagRecord m_ChangeData[ MAX_PLAYERS ]; // player data where we moved him back CBasePlayer *m_pCurrentPlayer; // The player we are doing lag compensation for float m_flTeleportDistanceSqr; bool m_isCurrentlyDoingCompensation; // Sentinel to prevent calling StartLagCompensation a second time before a Finish. }; static CLagCompensationManager g_LagCompensationManager( "CLagCompensationManager" ); ILagCompensationManager *lagcompensation = &g_LagCompensationManager; //----------------------------------------------------------------------------- // Purpose: Called once per frame after all entities have had a chance to think //----------------------------------------------------------------------------- void CLagCompensationManager::FrameUpdatePostEntityThink() { if ( (gpGlobals->maxClients <= 1) || !sv_unlag.GetBool() ) { ClearHistory(); return; } m_flTeleportDistanceSqr = sv_lagcompensation_teleport_dist.GetFloat() * sv_lagcompensation_teleport_dist.GetFloat(); VPROF_BUDGET( "FrameUpdatePostEntityThink", "CLagCompensationManager" ); // remove all records before that time: int flDeadtime = gpGlobals->curtime - sv_maxunlag.GetFloat(); // Iterate all active players for ( int i = 1; i <= gpGlobals->maxClients; i++ ) { CBasePlayer *pPlayer = UTIL_PlayerByIndex( i ); CUtlFixedLinkedList< LagRecord > *track = &m_PlayerTrack[i-1]; if ( !pPlayer ) { if ( track->Count() > 0 ) { track->RemoveAll(); } continue; } Assert( track->Count() < 1000 ); // insanity check // remove tail records that are too old int tailIndex = track->Tail(); while ( track->IsValidIndex( tailIndex ) ) { LagRecord &tail = track->Element( tailIndex ); // if tail is within limits, stop if ( tail.m_flSimulationTime >= flDeadtime ) break; // remove tail, get new tail track->Remove( tailIndex ); tailIndex = track->Tail(); } // check if head has same simulation time if ( track->Count() > 0 ) { LagRecord &head = track->Element( track->Head() ); // check if player changed simulation time since last time updated if ( head.m_flSimulationTime >= pPlayer->GetSimulationTime() ) continue; // don't add new entry for same or older time } // add new record to player track LagRecord &record = track->Element( track->AddToHead() ); record.m_fFlags = 0; if ( pPlayer->IsAlive() ) { record.m_fFlags |= LC_ALIVE; } record.m_flSimulationTime = pPlayer->GetSimulationTime(); record.m_vecAngles = pPlayer->GetLocalAngles(); record.m_vecOrigin = pPlayer->GetLocalOrigin(); record.m_vecMinsPreScaled = pPlayer->CollisionProp()->OBBMinsPreScaled(); record.m_vecMaxsPreScaled = pPlayer->CollisionProp()->OBBMaxsPreScaled(); int layerCount = pPlayer->GetNumAnimOverlays(); for( int layerIndex = 0; layerIndex < layerCount; ++layerIndex ) { CAnimationLayer *currentLayer = pPlayer->GetAnimOverlay(layerIndex); if( currentLayer ) { record.m_layerRecords[layerIndex].m_cycle = currentLayer->m_flCycle; record.m_layerRecords[layerIndex].m_order = currentLayer->m_nOrder; record.m_layerRecords[layerIndex].m_sequence = currentLayer->m_nSequence; record.m_layerRecords[layerIndex].m_weight = currentLayer->m_flWeight; } } record.m_masterSequence = pPlayer->GetSequence(); record.m_masterCycle = pPlayer->GetCycle(); } //Clear the current player. m_pCurrentPlayer = NULL; } // Called during player movement to set up/restore after lag compensation void CLagCompensationManager::StartLagCompensation( CBasePlayer *player, CUserCmd *cmd ) { Assert( !m_isCurrentlyDoingCompensation ); //DONT LAG COMP AGAIN THIS FRAME IF THERES ALREADY ONE IN PROGRESS //IF YOU'RE HITTING THIS THEN IT MEANS THERES A CODE BUG if ( m_pCurrentPlayer ) { Assert( m_pCurrentPlayer == NULL ); Warning( "Trying to start a new lag compensation session while one is already active!\n" ); return; } // Assume no players need to be restored m_RestorePlayer.ClearAll(); m_bNeedToRestore = false; m_pCurrentPlayer = player; if ( !player->m_bLagCompensation // Player not wanting lag compensation || (gpGlobals->maxClients <= 1) // no lag compensation in single player || !sv_unlag.GetBool() // disabled by server admin || player->IsBot() // not for bots || player->IsObserver() // not for spectators ) return; // NOTE: Put this here so that it won't show up in single player mode. VPROF_BUDGET( "StartLagCompensation", VPROF_BUDGETGROUP_OTHER_NETWORKING ); Q_memset( m_RestoreData, 0, sizeof( m_RestoreData ) ); Q_memset( m_ChangeData, 0, sizeof( m_ChangeData ) ); m_isCurrentlyDoingCompensation = true; // Get true latency // correct is the amout of time we have to correct game time float correct = 0.0f; INetChannelInfo *nci = engine->GetPlayerNetInfo( player->entindex() ); if ( nci ) { // add network latency correct+= nci->GetLatency( FLOW_OUTGOING ); } // calc number of view interpolation ticks - 1 int lerpTicks = TIME_TO_TICKS( player->m_fLerpTime ); // add view interpolation latency see C_BaseEntity::GetInterpolationAmount() correct += TICKS_TO_TIME( lerpTicks ); // check bouns [0,sv_maxunlag] correct = clamp( correct, 0.0f, sv_maxunlag.GetFloat() ); // correct tick send by player int targettick = cmd->tick_count - lerpTicks; // calc difference between tick send by player and our latency based tick float deltaTime = correct - TICKS_TO_TIME(gpGlobals->tickcount - targettick); if ( fabs( deltaTime ) > 0.2f ) { // difference between cmd time and latency is too big > 200ms, use time correction based on latency // DevMsg("StartLagCompensation: delta too big (%.3f)\n", deltaTime ); targettick = gpGlobals->tickcount - TIME_TO_TICKS( correct ); } // Iterate all active players const CBitVec<MAX_EDICTS> *pEntityTransmitBits = engine->GetEntityTransmitBitsForClient( player->entindex() - 1 ); for ( int i = 1; i <= gpGlobals->maxClients; i++ ) { CBasePlayer *pPlayer = UTIL_PlayerByIndex( i ); if ( !pPlayer ) { continue; } // Don't lag compensate yourself you loser... if ( player == pPlayer ) { continue; } // Custom checks for if things should lag compensate (based on things like what team the player is on). if ( !player->WantsLagCompensationOnEntity( pPlayer, cmd, pEntityTransmitBits ) ) continue; // Move other player back in time BacktrackPlayer( pPlayer, TICKS_TO_TIME( targettick ) ); } } void CLagCompensationManager::BacktrackPlayer( CBasePlayer *pPlayer, float flTargetTime ) { Vector org; Vector minsPreScaled; Vector maxsPreScaled; QAngle ang; VPROF_BUDGET( "BacktrackPlayer", "CLagCompensationManager" ); int pl_index = pPlayer->entindex() - 1; // get track history of this player CUtlFixedLinkedList< LagRecord > *track = &m_PlayerTrack[ pl_index ]; // check if we have at leat one entry if ( track->Count() <= 0 ) return; int curr = track->Head(); LagRecord *prevRecord = NULL; LagRecord *record = NULL; Vector prevOrg = pPlayer->GetLocalOrigin(); // Walk context looking for any invalidating event while( track->IsValidIndex(curr) ) { // remember last record prevRecord = record; // get next record record = &track->Element( curr ); if ( !(record->m_fFlags & LC_ALIVE) ) { // player most be alive, lost track return; } Vector delta = record->m_vecOrigin - prevOrg; if ( delta.Length2DSqr() > m_flTeleportDistanceSqr ) { // lost track, too much difference return; } // did we find a context smaller than target time ? if ( record->m_flSimulationTime <= flTargetTime ) break; // hurra, stop prevOrg = record->m_vecOrigin; // go one step back curr = track->Next( curr ); } Assert( record ); if ( !record ) { if ( sv_unlag_debug.GetBool() ) { DevMsg( "No valid positions in history for BacktrackPlayer client ( %s )\n", pPlayer->GetPlayerName() ); } return; // that should never happen } float frac = 0.0f; if ( prevRecord && (record->m_flSimulationTime < flTargetTime) && (record->m_flSimulationTime < prevRecord->m_flSimulationTime) ) { // we didn't find the exact time but have a valid previous record // so interpolate between these two records; Assert( prevRecord->m_flSimulationTime > record->m_flSimulationTime ); Assert( flTargetTime < prevRecord->m_flSimulationTime ); // calc fraction between both records frac = ( flTargetTime - record->m_flSimulationTime ) / ( prevRecord->m_flSimulationTime - record->m_flSimulationTime ); Assert( frac > 0 && frac < 1 ); // should never extrapolate ang = Lerp( frac, record->m_vecAngles, prevRecord->m_vecAngles ); org = Lerp( frac, record->m_vecOrigin, prevRecord->m_vecOrigin ); minsPreScaled = Lerp( frac, record->m_vecMinsPreScaled, prevRecord->m_vecMinsPreScaled ); maxsPreScaled = Lerp( frac, record->m_vecMaxsPreScaled, prevRecord->m_vecMaxsPreScaled ); } else { // we found the exact record or no other record to interpolate with // just copy these values since they are the best we have org = record->m_vecOrigin; ang = record->m_vecAngles; minsPreScaled = record->m_vecMinsPreScaled; maxsPreScaled = record->m_vecMaxsPreScaled; } // See if this is still a valid position for us to teleport to if ( sv_unlag_fixstuck.GetBool() ) { // Try to move to the wanted position from our current position. trace_t tr; UTIL_TraceEntity( pPlayer, org, org, MASK_PLAYERSOLID, &tr ); if ( tr.startsolid || tr.allsolid ) { if ( sv_unlag_debug.GetBool() ) DevMsg( "WARNING: BackupPlayer trying to back player into a bad position - client %s\n", pPlayer->GetPlayerName() ); CBasePlayer *pHitPlayer = dynamic_cast<CBasePlayer *>( tr.m_pEnt ); // don't lag compensate the current player if ( pHitPlayer && ( pHitPlayer != m_pCurrentPlayer ) ) { // If we haven't backtracked this player, do it now // this deliberately ignores WantsLagCompensationOnEntity. if ( !m_RestorePlayer.Get( pHitPlayer->entindex() - 1 ) ) { // prevent recursion - save a copy of m_RestorePlayer, // pretend that this player is off-limits int pl_index = pPlayer->entindex() - 1; // Temp turn this flag on m_RestorePlayer.Set( pl_index ); BacktrackPlayer( pHitPlayer, flTargetTime ); // Remove the temp flag m_RestorePlayer.Clear( pl_index ); } } // now trace us back as far as we can go UTIL_TraceEntity( pPlayer, pPlayer->GetLocalOrigin(), org, MASK_PLAYERSOLID, &tr ); if ( tr.startsolid || tr.allsolid ) { // Our starting position is bogus if ( sv_unlag_debug.GetBool() ) DevMsg( "Backtrack failed completely, bad starting position\n" ); } else { // We can get to a valid place, but not all the way to the target Vector vPos; VectorLerp( pPlayer->GetLocalOrigin(), org, tr.fraction * g_flFractionScale, vPos ); // This is as close as we're going to get org = vPos; if ( sv_unlag_debug.GetBool() ) DevMsg( "Backtrack got most of the way\n" ); } } } // See if this represents a change for the player int flags = 0; LagRecord *restore = &m_RestoreData[ pl_index ]; LagRecord *change = &m_ChangeData[ pl_index ]; QAngle angdiff = pPlayer->GetLocalAngles() - ang; Vector orgdiff = pPlayer->GetLocalOrigin() - org; // Always remember the pristine simulation time in case we need to restore it. restore->m_flSimulationTime = pPlayer->GetSimulationTime(); if ( angdiff.LengthSqr() > LAG_COMPENSATION_EPS_SQR ) { flags |= LC_ANGLES_CHANGED; restore->m_vecAngles = pPlayer->GetLocalAngles(); pPlayer->SetLocalAngles( ang ); change->m_vecAngles = ang; } // Use absolute equality here if ( minsPreScaled != pPlayer->CollisionProp()->OBBMinsPreScaled() || maxsPreScaled != pPlayer->CollisionProp()->OBBMaxsPreScaled() ) { flags |= LC_SIZE_CHANGED; restore->m_vecMinsPreScaled = pPlayer->CollisionProp()->OBBMinsPreScaled(); restore->m_vecMaxsPreScaled = pPlayer->CollisionProp()->OBBMaxsPreScaled(); pPlayer->SetSize( minsPreScaled, maxsPreScaled ); change->m_vecMinsPreScaled = minsPreScaled; change->m_vecMaxsPreScaled = maxsPreScaled; } // Note, do origin at end since it causes a relink into the k/d tree if ( orgdiff.LengthSqr() > LAG_COMPENSATION_EPS_SQR ) { flags |= LC_ORIGIN_CHANGED; restore->m_vecOrigin = pPlayer->GetLocalOrigin(); pPlayer->SetLocalOrigin( org ); change->m_vecOrigin = org; } // Sorry for the loss of the optimization for the case of people // standing still, but you breathe even on the server. // This is quicker than actually comparing all bazillion floats. flags |= LC_ANIMATION_CHANGED; restore->m_masterSequence = pPlayer->GetSequence(); restore->m_masterCycle = pPlayer->GetCycle(); bool interpolationAllowed = false; if( prevRecord && (record->m_masterSequence == prevRecord->m_masterSequence) ) { // If the master state changes, all layers will be invalid too, so don't interp (ya know, interp barely ever happens anyway) interpolationAllowed = true; } //////////////////////// // First do the master settings bool interpolatedMasters = false; if( frac > 0.0f && interpolationAllowed ) { interpolatedMasters = true; pPlayer->SetSequence( Lerp( frac, record->m_masterSequence, prevRecord->m_masterSequence ) ); pPlayer->SetCycle( Lerp( frac, record->m_masterCycle, prevRecord->m_masterCycle ) ); if( record->m_masterCycle > prevRecord->m_masterCycle ) { // the older record is higher in frame than the newer, it must have wrapped around from 1 back to 0 // add one to the newer so it is lerping from .9 to 1.1 instead of .9 to .1, for example. float newCycle = Lerp( frac, record->m_masterCycle, prevRecord->m_masterCycle + 1 ); pPlayer->SetCycle(newCycle < 1 ? newCycle : newCycle - 1 );// and make sure .9 to 1.2 does not end up 1.05 } else { pPlayer->SetCycle( Lerp( frac, record->m_masterCycle, prevRecord->m_masterCycle ) ); } } if( !interpolatedMasters ) { pPlayer->SetSequence(record->m_masterSequence); pPlayer->SetCycle(record->m_masterCycle); } //////////////////////// // Now do all the layers int layerCount = pPlayer->GetNumAnimOverlays(); for( int layerIndex = 0; layerIndex < layerCount; ++layerIndex ) { CAnimationLayer *currentLayer = pPlayer->GetAnimOverlay(layerIndex); if( currentLayer ) { restore->m_layerRecords[layerIndex].m_cycle = currentLayer->m_flCycle; restore->m_layerRecords[layerIndex].m_order = currentLayer->m_nOrder; restore->m_layerRecords[layerIndex].m_sequence = currentLayer->m_nSequence; restore->m_layerRecords[layerIndex].m_weight = currentLayer->m_flWeight; bool interpolated = false; if( (frac > 0.0f) && interpolationAllowed ) { LayerRecord &recordsLayerRecord = record->m_layerRecords[layerIndex]; LayerRecord &prevRecordsLayerRecord = prevRecord->m_layerRecords[layerIndex]; if( (recordsLayerRecord.m_order == prevRecordsLayerRecord.m_order) && (recordsLayerRecord.m_sequence == prevRecordsLayerRecord.m_sequence) ) { // We can't interpolate across a sequence or order change interpolated = true; if( recordsLayerRecord.m_cycle > prevRecordsLayerRecord.m_cycle ) { // the older record is higher in frame than the newer, it must have wrapped around from 1 back to 0 // add one to the newer so it is lerping from .9 to 1.1 instead of .9 to .1, for example. float newCycle = Lerp( frac, recordsLayerRecord.m_cycle, prevRecordsLayerRecord.m_cycle + 1 ); currentLayer->m_flCycle = newCycle < 1 ? newCycle : newCycle - 1;// and make sure .9 to 1.2 does not end up 1.05 } else { currentLayer->m_flCycle = Lerp( frac, recordsLayerRecord.m_cycle, prevRecordsLayerRecord.m_cycle ); } currentLayer->m_nOrder = recordsLayerRecord.m_order; currentLayer->m_nSequence = recordsLayerRecord.m_sequence; currentLayer->m_flWeight = Lerp( frac, recordsLayerRecord.m_weight, prevRecordsLayerRecord.m_weight ); } } if( !interpolated ) { //Either no interp, or interp failed. Just use record. currentLayer->m_flCycle = record->m_layerRecords[layerIndex].m_cycle; currentLayer->m_nOrder = record->m_layerRecords[layerIndex].m_order; currentLayer->m_nSequence = record->m_layerRecords[layerIndex].m_sequence; currentLayer->m_flWeight = record->m_layerRecords[layerIndex].m_weight; } } } if ( !flags ) return; // we didn't change anything if ( sv_lagflushbonecache.GetBool() ) pPlayer->InvalidateBoneCache(); /*char text[256]; Q_snprintf( text, sizeof(text), "time %.2f", flTargetTime ); pPlayer->DrawServerHitboxes( 10 ); NDebugOverlay::Text( org, text, false, 10 ); NDebugOverlay::EntityBounds( pPlayer, 255, 0, 0, 32, 10 ); */ m_RestorePlayer.Set( pl_index ); //remember that we changed this player m_bNeedToRestore = true; // we changed at least one player restore->m_fFlags = flags; // we need to restore these flags change->m_fFlags = flags; // we have changed these flags if( sv_showlagcompensation.GetInt() == 1 ) { pPlayer->DrawServerHitboxes(4, true); } } void CLagCompensationManager::FinishLagCompensation( CBasePlayer *player ) { VPROF_BUDGET_FLAGS( "FinishLagCompensation", VPROF_BUDGETGROUP_OTHER_NETWORKING, BUDGETFLAG_CLIENT|BUDGETFLAG_SERVER ); m_pCurrentPlayer = NULL; if ( !m_bNeedToRestore ) { m_isCurrentlyDoingCompensation = false; return; // no player was changed at all } // Iterate all active players for ( int i = 1; i <= gpGlobals->maxClients; i++ ) { int pl_index = i - 1; if ( !m_RestorePlayer.Get( pl_index ) ) { // player wasn't changed by lag compensation continue; } CBasePlayer *pPlayer = UTIL_PlayerByIndex( i ); if ( !pPlayer ) { continue; } LagRecord *restore = &m_RestoreData[ pl_index ]; LagRecord *change = &m_ChangeData[ pl_index ]; bool restoreSimulationTime = false; if ( restore->m_fFlags & LC_SIZE_CHANGED ) { restoreSimulationTime = true; // see if simulation made any changes, if no, then do the restore, otherwise, // leave new values in if ( pPlayer->CollisionProp()->OBBMinsPreScaled() == change->m_vecMinsPreScaled && pPlayer->CollisionProp()->OBBMaxsPreScaled() == change->m_vecMaxsPreScaled ) { // Restore it pPlayer->SetSize( restore->m_vecMinsPreScaled, restore->m_vecMaxsPreScaled ); } #ifdef STAGING_ONLY else { Warning( "Should we really not restore the size?\n" ); } #endif } if ( restore->m_fFlags & LC_ANGLES_CHANGED ) { restoreSimulationTime = true; if ( pPlayer->GetLocalAngles() == change->m_vecAngles ) { pPlayer->SetLocalAngles( restore->m_vecAngles ); } } if ( restore->m_fFlags & LC_ORIGIN_CHANGED ) { restoreSimulationTime = true; // Okay, let's see if we can do something reasonable with the change Vector delta = pPlayer->GetLocalOrigin() - change->m_vecOrigin; // If it moved really far, just leave the player in the new spot!!! if ( delta.Length2DSqr() < m_flTeleportDistanceSqr ) { RestorePlayerTo( pPlayer, restore->m_vecOrigin + delta ); } } if( restore->m_fFlags & LC_ANIMATION_CHANGED ) { restoreSimulationTime = true; pPlayer->SetSequence(restore->m_masterSequence); pPlayer->SetCycle(restore->m_masterCycle); int layerCount = pPlayer->GetNumAnimOverlays(); for( int layerIndex = 0; layerIndex < layerCount; ++layerIndex ) { CAnimationLayer *currentLayer = pPlayer->GetAnimOverlay(layerIndex); if( currentLayer ) { currentLayer->m_flCycle = restore->m_layerRecords[layerIndex].m_cycle; currentLayer->m_nOrder = restore->m_layerRecords[layerIndex].m_order; currentLayer->m_nSequence = restore->m_layerRecords[layerIndex].m_sequence; currentLayer->m_flWeight = restore->m_layerRecords[layerIndex].m_weight; } } } if ( restoreSimulationTime ) { pPlayer->SetSimulationTime( restore->m_flSimulationTime ); } } m_isCurrentlyDoingCompensation = false; }
1
0.998267
1
0.998267
game-dev
MEDIA
0.889454
game-dev
0.998148
1
0.998148
Hoto-Mocha/Re-ARranged-Pixel-Dungeon
15,596
core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/items/Sheath.java
package com.shatteredpixel.shatteredpixeldungeon.items; import static com.shatteredpixel.shatteredpixeldungeon.Dungeon.hero; import com.shatteredpixel.shatteredpixeldungeon.Assets; import com.shatteredpixel.shatteredpixeldungeon.Dungeon; import com.shatteredpixel.shatteredpixeldungeon.actors.Actor; import com.shatteredpixel.shatteredpixeldungeon.actors.Char; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Buff; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.FlavourBuff; import com.shatteredpixel.shatteredpixeldungeon.actors.hero.Hero; import com.shatteredpixel.shatteredpixeldungeon.actors.hero.HeroAction; import com.shatteredpixel.shatteredpixeldungeon.actors.hero.HeroSubClass; import com.shatteredpixel.shatteredpixeldungeon.actors.hero.Talent; import com.shatteredpixel.shatteredpixeldungeon.actors.mobs.npcs.NPC; import com.shatteredpixel.shatteredpixeldungeon.effects.CellEmitter; import com.shatteredpixel.shatteredpixeldungeon.effects.Speck; import com.shatteredpixel.shatteredpixeldungeon.items.weapon.bow.SpiritBow; import com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee.MeleeWeapon; import com.shatteredpixel.shatteredpixeldungeon.messages.Messages; import com.shatteredpixel.shatteredpixeldungeon.scenes.CellSelector; import com.shatteredpixel.shatteredpixeldungeon.scenes.GameScene; import com.shatteredpixel.shatteredpixeldungeon.scenes.PixelScene; import com.shatteredpixel.shatteredpixeldungeon.sprites.ItemSpriteSheet; import com.shatteredpixel.shatteredpixeldungeon.ui.ActionIndicator; import com.shatteredpixel.shatteredpixeldungeon.ui.BuffIndicator; import com.shatteredpixel.shatteredpixeldungeon.ui.HeroIcon; import com.shatteredpixel.shatteredpixeldungeon.utils.GLog; import com.watabou.noosa.Image; import com.watabou.noosa.audio.Sample; import com.watabou.utils.BArray; import com.watabou.utils.Bundle; import com.watabou.utils.PathFinder; import java.util.ArrayList; public class Sheath extends Item { public static final String AC_USE = "USE"; { image = ItemSpriteSheet.SHEATH; defaultAction = AC_USE; unique = true; bones = false; } @Override public ArrayList<String> actions(Hero hero ) { ArrayList<String> actions = super.actions(hero); actions.add(AC_USE); return actions; } @Override public void execute(Hero hero, String action) { super.execute(hero, action); if (action.equals( AC_USE )) { if (hero.belongings.weapon instanceof MeleeWeapon) { if (hero.buff(Sheathing.class) != null) { hero.buff(Sheathing.class).detach(); } else { Buff.affect(hero, Sheathing.class); } hero.spendAndNext(Actor.TICK); } else { GLog.w(Messages.get(this, "no_weapon")); } } } @Override public boolean isUpgradable() { return false; } @Override public boolean isIdentified() { return true; } @Override public int value() { return -1; } public static boolean isFlashSlash() { Hero hero = Dungeon.hero; return hero.subClass == HeroSubClass.MASTER && hero.buff(Sheathing.class) != null && hero.buff(FlashSlashCooldown.class) == null && hero.buff(DashAttackTracker.class) == null; } public static class Sheathing extends Buff implements ActionIndicator.Action { { type = buffType.POSITIVE; announced = true; } public int pos = -1; @Override public boolean attachTo(Char target) { if (super.attachTo(target)){ if (hero != null) { Dungeon.observe(); if (hero.subClass == HeroSubClass.MASTER && hero.buff(DashAttackCooldown.class) == null) { ActionIndicator.setAction(this); } } return true; } else { return false; } } @Override public void detach() { super.detach(); if (hero != null) { Dungeon.observe(); GameScene.updateFog(); ActionIndicator.clearAction(this); } } @Override public boolean act() { if (hero.subClass == HeroSubClass.MASTER) { if (hero.buff(DashAttackCooldown.class) == null) { ActionIndicator.setAction(this); } else { ActionIndicator.clearAction(this); } } if (pos == -1) pos = target.pos; if (pos != target.pos || !(hero.belongings.weapon instanceof MeleeWeapon)) { detach(); } else { spend(TICK); } return true; } @Override public String actionName() { return Messages.get(this, "action"); } @Override public int actionIcon() { return HeroIcon.PREPARATION; } @Override public int indicatorColor() { return 0x171717; } @Override public void doAction() { GameScene.selectCell(attack); } private static final String POS = "pos"; private static final String CAN_DASH = "canDash"; @Override public void storeInBundle(Bundle bundle) { super.storeInBundle(bundle); bundle.put( POS, pos ); bundle.put( CAN_DASH, (hero.subClass == HeroSubClass.MASTER && hero.buff(DashAttackCooldown.class) == null) ); } @Override public void restoreFromBundle(Bundle bundle) { super.restoreFromBundle(bundle); pos = bundle.getInt( POS ); if (bundle.getBoolean(CAN_DASH)) { ActionIndicator.setAction(this); } } @Override public int icon() { return BuffIndicator.SHEATHING; } @Override public String toString() { return Messages.get(this, "name"); } @Override public String desc() { return Messages.get(this, "desc"); } public int blinkDistance(){ return 500; } private CellSelector.Listener attack = new CellSelector.Listener() { @Override public void onSelect(Integer cell) { if (cell == null) return; final Char enemy = Actor.findChar( cell ); if (enemy != null) { if (Dungeon.hero.isCharmedBy(enemy) || enemy instanceof NPC || enemy == Dungeon.hero) { GLog.w(Messages.get(Sheathing.class, "no_target")); } else { //just attack them then! if (Dungeon.hero.canAttack(enemy)){ Dungeon.hero.curAction = new HeroAction.Attack( enemy ); Dungeon.hero.next(); return; } PathFinder.buildDistanceMap(Dungeon.hero.pos,BArray.or(Dungeon.level.passable, Dungeon.level.avoid, null), blinkDistance()); int dest = -1; for (int i : PathFinder.NEIGHBOURS8){ //cannot blink into a cell that's occupied or impassable, only over them if (Actor.findChar(cell+i) != null) continue; if (!Dungeon.level.passable[cell+i] && !(target.flying && Dungeon.level.avoid[cell+i])) { continue; } if (dest == -1 || PathFinder.distance[dest] > PathFinder.distance[cell+i]){ dest = cell+i; //if two cells have the same pathfinder distance, prioritize the one with the closest true distance to the hero } else if (PathFinder.distance[dest] == PathFinder.distance[cell+i]){ if (Dungeon.level.trueDistance(Dungeon.hero.pos, dest) > Dungeon.level.trueDistance(Dungeon.hero.pos, cell+i)){ dest = cell+i; } } } if (dest == -1 || PathFinder.distance[dest] == Integer.MAX_VALUE || Dungeon.hero.rooted) { GLog.w(Messages.get(Sheathing.class, "cannot_dash")); if (Dungeon.hero.rooted) PixelScene.shake( 1, 1f ); return; } Buff.affect(hero, DashAttackTracker.class); if (hero.hasTalent(Talent.INNER_EYE)) { Buff.affect(hero, DashAttackVision.class, 2f); } Dungeon.hero.pos = dest; Dungeon.level.occupyCell(Dungeon.hero); //prevents the hero from being interrupted by seeing new enemies Dungeon.observe(); GameScene.updateFog(); Dungeon.hero.checkVisibleMobs(); Dungeon.hero.sprite.place( Dungeon.hero.pos ); Dungeon.hero.sprite.turnTo( Dungeon.hero.pos, cell); CellEmitter.get( Dungeon.hero.pos ).burst( Speck.factory( Speck.WOOL ), 6 ); Sample.INSTANCE.play( Assets.Sounds.PUFF ); Dungeon.hero.curAction = new HeroAction.Attack( enemy ); Dungeon.hero.next(); } } else { int dest; PathFinder.buildDistanceMap(Dungeon.hero.pos,BArray.or(Dungeon.level.passable, Dungeon.level.avoid, null), blinkDistance()); if (!Dungeon.level.passable[cell] && !(target.flying && Dungeon.level.avoid[cell])) { GLog.w(Messages.get(Sheathing.class, "cannot_dash")); return; } else { dest = cell; } if (PathFinder.distance[dest] == Integer.MAX_VALUE || Dungeon.hero.rooted) { GLog.w(Messages.get(Sheathing.class, "cannot_dash")); if (Dungeon.hero.rooted) PixelScene.shake( 1, 1f ); return; } Dungeon.hero.pos = dest; Dungeon.level.occupyCell(Dungeon.hero); //prevents the hero from being interrupted by seeing new enemies Dungeon.observe(); GameScene.updateFog(); Dungeon.hero.checkVisibleMobs(); Dungeon.hero.sprite.place( Dungeon.hero.pos ); Dungeon.hero.sprite.turnTo( Dungeon.hero.pos, cell); CellEmitter.get( Dungeon.hero.pos ).burst( Speck.factory( Speck.WOOL ), 6 ); Sample.INSTANCE.play( Assets.Sounds.PUFF ); Dungeon.hero.spendAndNext(Actor.TICK); GLog.w(Messages.get(Sheathing.class, "no_target")); Buff.prolong(hero, DashAttackCooldown.class, (100-10*hero.pointsInTalent(Talent.DYNAMIC_PREPARATION))); if (hero.buff(DashAttackAcceleration.class) != null) { hero.buff(DashAttackAcceleration.class).detach(); } ActionIndicator.clearAction(Sheathing.this); } } @Override public String prompt() { return Messages.get(SpiritBow.class, "prompt"); } }; } public static class CriticalAttack extends Buff {} public static class CertainCrit extends Buff { { type = buffType.POSITIVE; announced = true; } private int hitAmount = 0; public void set(int amount) { this.hitAmount = amount; } public void hit() { this.hitAmount--; if (this.hitAmount <= 0) { detach(); } } private static final String HIT_AMOUNT = "hitAmount"; @Override public void storeInBundle(Bundle bundle) { super.storeInBundle(bundle); bundle.put( HIT_AMOUNT, hitAmount ); } @Override public void restoreFromBundle(Bundle bundle) { super.restoreFromBundle(bundle); hitAmount = bundle.getInt( HIT_AMOUNT ); } public String iconTextDisplay(){ return String.valueOf(hitAmount); } @Override public int icon() { return BuffIndicator.CRITICAL; } @Override public String toString() { return Messages.get(this, "name"); } @Override public String desc() { return Messages.get(this, "desc", hitAmount); } } public static class FlashSlashCooldown extends FlavourBuff{ public int icon() { return BuffIndicator.TIME; } public void tintIcon(Image icon) { icon.hardlight(0x586EDB); } public float iconFadePercent() { return Math.max(0, visualcooldown() / 30); } }; public static class DashAttackCooldown extends FlavourBuff{ public int icon() { return BuffIndicator.TIME; } public void tintIcon(Image icon) { icon.hardlight(0xFF7F00); } public float iconFadePercent() { return Math.max(0, visualcooldown() / 100); } @Override public void detach() { super.detach(); } }; public static class DashAttackTracker extends Buff {} public static class DashAttackVision extends FlavourBuff {} public static class DashAttackAcceleration extends FlavourBuff { { type = buffType.POSITIVE; announced = false; } public static final float DURATION = 10f; float dmgMulti = 1; public void hit() { dmgMulti += 0.05f; dmgMulti = Math.min(dmgMulti, 1+0.25f*hero.pointsInTalent(Talent.ACCELERATION)); } public float getDmgMulti() { return dmgMulti; } @Override public float iconFadePercent() { return Math.max(0, (DURATION - visualcooldown()) / DURATION); } private static final String MULTI = "dmgMulti"; @Override public void storeInBundle(Bundle bundle) { super.storeInBundle(bundle); bundle.put( MULTI, dmgMulti ); } @Override public void restoreFromBundle(Bundle bundle) { super.restoreFromBundle(bundle); dmgMulti = bundle.getFloat( MULTI ); } @Override public int icon() { return BuffIndicator.CRITICAL; } @Override public String toString() { return Messages.get(this, "name"); } @Override public String desc() { return Messages.get(this, "desc", Messages.decimalFormat("#", dmgMulti*100)); } } }
1
0.917736
1
0.917736
game-dev
MEDIA
0.980919
game-dev
0.985999
1
0.985999