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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
godotengine/godot | 16,343 | modules/navigation_3d/3d/godot_navigation_server_3d.h | /**************************************************************************/
/* godot_navigation_server_3d.h */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#pragma once
#include "../nav_agent_3d.h"
#include "../nav_link_3d.h"
#include "../nav_map_3d.h"
#include "../nav_obstacle_3d.h"
#include "../nav_region_3d.h"
#include "core/templates/local_vector.h"
#include "core/templates/rid.h"
#include "core/templates/rid_owner.h"
#include "servers/navigation_3d/navigation_path_query_parameters_3d.h"
#include "servers/navigation_3d/navigation_path_query_result_3d.h"
#include "servers/navigation_3d/navigation_server_3d.h"
/// The commands are functions executed during the `sync` phase.
#define MERGE_INTERNAL(A, B) A##B
#define MERGE(A, B) MERGE_INTERNAL(A, B)
#define COMMAND_1(F_NAME, T_0, D_0) \
virtual void F_NAME(T_0 D_0) override; \
void MERGE(_cmd_, F_NAME)(T_0 D_0)
#define COMMAND_2(F_NAME, T_0, D_0, T_1, D_1) \
virtual void F_NAME(T_0 D_0, T_1 D_1) override; \
void MERGE(_cmd_, F_NAME)(T_0 D_0, T_1 D_1)
class GodotNavigationServer3D;
class NavMeshGenerator3D;
struct SetCommand3D {
virtual ~SetCommand3D() {}
virtual void exec(GodotNavigationServer3D *server) = 0;
};
class GodotNavigationServer3D : public NavigationServer3D {
Mutex commands_mutex;
/// Mutex used to make any operation threadsafe.
Mutex operations_mutex;
LocalVector<SetCommand3D *> commands;
mutable RID_Owner<NavLink3D> link_owner;
mutable RID_Owner<NavMap3D> map_owner;
mutable RID_Owner<NavRegion3D> region_owner;
mutable RID_Owner<NavAgent3D> agent_owner;
mutable RID_Owner<NavObstacle3D> obstacle_owner;
bool active = true;
LocalVector<NavMap3D *> active_maps;
NavMeshGenerator3D *navmesh_generator_3d = nullptr;
// Performance Monitor
int pm_region_count = 0;
int pm_agent_count = 0;
int pm_link_count = 0;
int pm_polygon_count = 0;
int pm_edge_count = 0;
int pm_edge_merge_count = 0;
int pm_edge_connection_count = 0;
int pm_edge_free_count = 0;
int pm_obstacle_count = 0;
public:
GodotNavigationServer3D();
virtual ~GodotNavigationServer3D();
void add_command(SetCommand3D *command);
virtual TypedArray<RID> get_maps() const override;
virtual RID map_create() override;
COMMAND_2(map_set_active, RID, p_map, bool, p_active);
virtual bool map_is_active(RID p_map) const override;
COMMAND_2(map_set_up, RID, p_map, Vector3, p_up);
virtual Vector3 map_get_up(RID p_map) const override;
COMMAND_2(map_set_cell_size, RID, p_map, real_t, p_cell_size);
virtual real_t map_get_cell_size(RID p_map) const override;
COMMAND_2(map_set_cell_height, RID, p_map, real_t, p_cell_height);
virtual real_t map_get_cell_height(RID p_map) const override;
COMMAND_2(map_set_merge_rasterizer_cell_scale, RID, p_map, float, p_value);
virtual float map_get_merge_rasterizer_cell_scale(RID p_map) const override;
COMMAND_2(map_set_use_edge_connections, RID, p_map, bool, p_enabled);
virtual bool map_get_use_edge_connections(RID p_map) const override;
COMMAND_2(map_set_edge_connection_margin, RID, p_map, real_t, p_connection_margin);
virtual real_t map_get_edge_connection_margin(RID p_map) const override;
COMMAND_2(map_set_link_connection_radius, RID, p_map, real_t, p_connection_radius);
virtual real_t map_get_link_connection_radius(RID p_map) const override;
virtual Vector<Vector3> map_get_path(RID p_map, Vector3 p_origin, Vector3 p_destination, bool p_optimize, uint32_t p_navigation_layers = 1) override;
virtual Vector3 map_get_closest_point_to_segment(RID p_map, const Vector3 &p_from, const Vector3 &p_to, const bool p_use_collision = false) const override;
virtual Vector3 map_get_closest_point(RID p_map, const Vector3 &p_point) const override;
virtual Vector3 map_get_closest_point_normal(RID p_map, const Vector3 &p_point) const override;
virtual RID map_get_closest_point_owner(RID p_map, const Vector3 &p_point) const override;
virtual TypedArray<RID> map_get_links(RID p_map) const override;
virtual TypedArray<RID> map_get_regions(RID p_map) const override;
virtual TypedArray<RID> map_get_agents(RID p_map) const override;
virtual TypedArray<RID> map_get_obstacles(RID p_map) const override;
virtual void map_force_update(RID p_map) override;
virtual uint32_t map_get_iteration_id(RID p_map) const override;
COMMAND_2(map_set_use_async_iterations, RID, p_map, bool, p_enabled);
virtual bool map_get_use_async_iterations(RID p_map) const override;
virtual Vector3 map_get_random_point(RID p_map, uint32_t p_navigation_layers, bool p_uniformly) const override;
virtual RID region_create() override;
virtual uint32_t region_get_iteration_id(RID p_region) const override;
COMMAND_2(region_set_use_async_iterations, RID, p_region, bool, p_enabled);
virtual bool region_get_use_async_iterations(RID p_region) const override;
COMMAND_2(region_set_enabled, RID, p_region, bool, p_enabled);
virtual bool region_get_enabled(RID p_region) const override;
COMMAND_2(region_set_use_edge_connections, RID, p_region, bool, p_enabled);
virtual bool region_get_use_edge_connections(RID p_region) const override;
COMMAND_2(region_set_enter_cost, RID, p_region, real_t, p_enter_cost);
virtual real_t region_get_enter_cost(RID p_region) const override;
COMMAND_2(region_set_travel_cost, RID, p_region, real_t, p_travel_cost);
virtual real_t region_get_travel_cost(RID p_region) const override;
COMMAND_2(region_set_owner_id, RID, p_region, ObjectID, p_owner_id);
virtual ObjectID region_get_owner_id(RID p_region) const override;
virtual bool region_owns_point(RID p_region, const Vector3 &p_point) const override;
COMMAND_2(region_set_map, RID, p_region, RID, p_map);
virtual RID region_get_map(RID p_region) const override;
COMMAND_2(region_set_navigation_layers, RID, p_region, uint32_t, p_navigation_layers);
virtual uint32_t region_get_navigation_layers(RID p_region) const override;
COMMAND_2(region_set_transform, RID, p_region, Transform3D, p_transform);
virtual Transform3D region_get_transform(RID p_region) const override;
COMMAND_2(region_set_navigation_mesh, RID, p_region, Ref<NavigationMesh>, p_navigation_mesh);
#ifndef DISABLE_DEPRECATED
virtual void region_bake_navigation_mesh(Ref<NavigationMesh> p_navigation_mesh, Node *p_root_node) override;
#endif // DISABLE_DEPRECATED
virtual int region_get_connections_count(RID p_region) const override;
virtual Vector3 region_get_connection_pathway_start(RID p_region, int p_connection_id) const override;
virtual Vector3 region_get_connection_pathway_end(RID p_region, int p_connection_id) const override;
virtual Vector3 region_get_closest_point_to_segment(RID p_region, const Vector3 &p_from, const Vector3 &p_to, bool p_use_collision = false) const override;
virtual Vector3 region_get_closest_point(RID p_region, const Vector3 &p_point) const override;
virtual Vector3 region_get_closest_point_normal(RID p_region, const Vector3 &p_point) const override;
virtual Vector3 region_get_random_point(RID p_region, uint32_t p_navigation_layers, bool p_uniformly) const override;
virtual AABB region_get_bounds(RID p_region) const override;
virtual RID link_create() override;
virtual uint32_t link_get_iteration_id(RID p_link) const override;
COMMAND_2(link_set_map, RID, p_link, RID, p_map);
virtual RID link_get_map(RID p_link) const override;
COMMAND_2(link_set_enabled, RID, p_link, bool, p_enabled);
virtual bool link_get_enabled(RID p_link) const override;
COMMAND_2(link_set_bidirectional, RID, p_link, bool, p_bidirectional);
virtual bool link_is_bidirectional(RID p_link) const override;
COMMAND_2(link_set_navigation_layers, RID, p_link, uint32_t, p_navigation_layers);
virtual uint32_t link_get_navigation_layers(RID p_link) const override;
COMMAND_2(link_set_start_position, RID, p_link, Vector3, p_position);
virtual Vector3 link_get_start_position(RID p_link) const override;
COMMAND_2(link_set_end_position, RID, p_link, Vector3, p_position);
virtual Vector3 link_get_end_position(RID p_link) const override;
COMMAND_2(link_set_enter_cost, RID, p_link, real_t, p_enter_cost);
virtual real_t link_get_enter_cost(RID p_link) const override;
COMMAND_2(link_set_travel_cost, RID, p_link, real_t, p_travel_cost);
virtual real_t link_get_travel_cost(RID p_link) const override;
COMMAND_2(link_set_owner_id, RID, p_link, ObjectID, p_owner_id);
virtual ObjectID link_get_owner_id(RID p_link) const override;
virtual RID agent_create() override;
COMMAND_2(agent_set_avoidance_enabled, RID, p_agent, bool, p_enabled);
virtual bool agent_get_avoidance_enabled(RID p_agent) const override;
COMMAND_2(agent_set_use_3d_avoidance, RID, p_agent, bool, p_enabled);
virtual bool agent_get_use_3d_avoidance(RID p_agent) const override;
COMMAND_2(agent_set_map, RID, p_agent, RID, p_map);
virtual RID agent_get_map(RID p_agent) const override;
COMMAND_2(agent_set_paused, RID, p_agent, bool, p_paused);
virtual bool agent_get_paused(RID p_agent) const override;
COMMAND_2(agent_set_neighbor_distance, RID, p_agent, real_t, p_distance);
virtual real_t agent_get_neighbor_distance(RID p_agent) const override;
COMMAND_2(agent_set_max_neighbors, RID, p_agent, int, p_count);
virtual int agent_get_max_neighbors(RID p_agent) const override;
COMMAND_2(agent_set_time_horizon_agents, RID, p_agent, real_t, p_time_horizon);
virtual real_t agent_get_time_horizon_agents(RID p_agent) const override;
COMMAND_2(agent_set_time_horizon_obstacles, RID, p_agent, real_t, p_time_horizon);
virtual real_t agent_get_time_horizon_obstacles(RID p_agent) const override;
COMMAND_2(agent_set_radius, RID, p_agent, real_t, p_radius);
virtual real_t agent_get_radius(RID p_agent) const override;
COMMAND_2(agent_set_height, RID, p_agent, real_t, p_height);
virtual real_t agent_get_height(RID p_agent) const override;
COMMAND_2(agent_set_max_speed, RID, p_agent, real_t, p_max_speed);
virtual real_t agent_get_max_speed(RID p_agent) const override;
COMMAND_2(agent_set_velocity, RID, p_agent, Vector3, p_velocity);
virtual Vector3 agent_get_velocity(RID p_agent) const override;
COMMAND_2(agent_set_velocity_forced, RID, p_agent, Vector3, p_velocity);
COMMAND_2(agent_set_position, RID, p_agent, Vector3, p_position);
virtual Vector3 agent_get_position(RID p_agent) const override;
virtual bool agent_is_map_changed(RID p_agent) const override;
COMMAND_2(agent_set_avoidance_callback, RID, p_agent, Callable, p_callback);
virtual bool agent_has_avoidance_callback(RID p_agent) const override;
COMMAND_2(agent_set_avoidance_layers, RID, p_agent, uint32_t, p_layers);
virtual uint32_t agent_get_avoidance_layers(RID p_agent) const override;
COMMAND_2(agent_set_avoidance_mask, RID, p_agent, uint32_t, p_mask);
virtual uint32_t agent_get_avoidance_mask(RID p_agent) const override;
COMMAND_2(agent_set_avoidance_priority, RID, p_agent, real_t, p_priority);
virtual real_t agent_get_avoidance_priority(RID p_agent) const override;
virtual RID obstacle_create() override;
COMMAND_2(obstacle_set_avoidance_enabled, RID, p_obstacle, bool, p_enabled);
virtual bool obstacle_get_avoidance_enabled(RID p_obstacle) const override;
COMMAND_2(obstacle_set_use_3d_avoidance, RID, p_obstacle, bool, p_enabled);
virtual bool obstacle_get_use_3d_avoidance(RID p_obstacle) const override;
COMMAND_2(obstacle_set_map, RID, p_obstacle, RID, p_map);
virtual RID obstacle_get_map(RID p_obstacle) const override;
COMMAND_2(obstacle_set_paused, RID, p_obstacle, bool, p_paused);
virtual bool obstacle_get_paused(RID p_obstacle) const override;
COMMAND_2(obstacle_set_radius, RID, p_obstacle, real_t, p_radius);
virtual real_t obstacle_get_radius(RID p_obstacle) const override;
COMMAND_2(obstacle_set_velocity, RID, p_obstacle, Vector3, p_velocity);
virtual Vector3 obstacle_get_velocity(RID p_obstacle) const override;
COMMAND_2(obstacle_set_position, RID, p_obstacle, Vector3, p_position);
virtual Vector3 obstacle_get_position(RID p_obstacle) const override;
COMMAND_2(obstacle_set_height, RID, p_obstacle, real_t, p_height);
virtual real_t obstacle_get_height(RID p_obstacle) const override;
virtual void obstacle_set_vertices(RID p_obstacle, const Vector<Vector3> &p_vertices) override;
virtual Vector<Vector3> obstacle_get_vertices(RID p_obstacle) const override;
COMMAND_2(obstacle_set_avoidance_layers, RID, p_obstacle, uint32_t, p_layers);
virtual uint32_t obstacle_get_avoidance_layers(RID p_obstacle) const override;
virtual void parse_source_geometry_data(const Ref<NavigationMesh> &p_navigation_mesh, const Ref<NavigationMeshSourceGeometryData3D> &p_source_geometry_data, Node *p_root_node, const Callable &p_callback = Callable()) override;
virtual void bake_from_source_geometry_data(const Ref<NavigationMesh> &p_navigation_mesh, const Ref<NavigationMeshSourceGeometryData3D> &p_source_geometry_data, const Callable &p_callback = Callable()) override;
virtual void bake_from_source_geometry_data_async(const Ref<NavigationMesh> &p_navigation_mesh, const Ref<NavigationMeshSourceGeometryData3D> &p_source_geometry_data, const Callable &p_callback = Callable()) override;
virtual bool is_baking_navigation_mesh(Ref<NavigationMesh> p_navigation_mesh) const override;
virtual String get_baking_navigation_mesh_state_msg(Ref<NavigationMesh> p_navigation_mesh) const override;
virtual RID source_geometry_parser_create() override;
virtual void source_geometry_parser_set_callback(RID p_parser, const Callable &p_callback) override;
virtual Vector<Vector3> simplify_path(const Vector<Vector3> &p_path, real_t p_epsilon) override;
public:
COMMAND_1(free_rid, RID, p_object);
virtual void set_active(bool p_active) override;
void flush_queries();
virtual void process(double p_delta_time) override;
virtual void physics_process(double p_delta_time) override;
virtual void init() override;
virtual void sync() override;
virtual void finish() override;
virtual void query_path(const Ref<NavigationPathQueryParameters3D> &p_query_parameters, Ref<NavigationPathQueryResult3D> p_query_result, const Callable &p_callback = Callable()) override;
int get_process_info(ProcessInfo p_info) const override;
private:
void internal_free_agent(RID p_object);
void internal_free_obstacle(RID p_object);
};
#undef COMMAND_1
#undef COMMAND_2
| 412 | 0.949878 | 1 | 0.949878 | game-dev | MEDIA | 0.3994 | game-dev | 0.77062 | 1 | 0.77062 |
google/agi | 64,804 | gapic/src/main/com/google/gapid/util/Paths.java | /*
* Copyright (C) 2017 Google 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.
*/
package com.google.gapid.util;
import com.google.common.collect.Lists;
import com.google.common.primitives.UnsignedLongs;
import com.google.gapid.image.Images;
import com.google.gapid.models.CommandStream.CommandIndex;
import com.google.gapid.models.Settings;
import com.google.gapid.proto.SettingsProto;
import com.google.gapid.proto.device.Device;
import com.google.gapid.proto.image.Image;
import com.google.gapid.proto.service.Service;
import com.google.gapid.proto.service.path.Path;
import com.google.gapid.proto.service.vertex.Vertex;
import com.google.gapid.views.Formatter;
import com.google.protobuf.Message;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Predicate;
/**
* Path utilities.
*/
public class Paths {
private Paths() {
}
public static Path.Command command(Path.Capture capture, long index) {
if (capture == null) {
return null;
}
return Path.Command.newBuilder()
.setCapture(capture)
.addIndices(index)
.build();
}
public static Path.Command firstCommand(Path.Commands commands) {
return Path.Command.newBuilder()
.setCapture(commands.getCapture())
.addAllIndices(commands.getFromList())
.build();
}
public static Path.Command lastCommand(Path.Commands commands) {
return Path.Command.newBuilder()
.setCapture(commands.getCapture())
.addAllIndices(commands.getToList())
.build();
}
public static Path.Device device(Device.ID device) {
return Path.Device.newBuilder()
.setID(Path.ID.newBuilder()
.setData(device.getData()))
.build();
}
public static Path.Any capture(Path.ID id, boolean excludeObservations) {
return Path.Any.newBuilder()
.setCapture(Path.Capture.newBuilder()
.setID(id)
.setExcludeMemoryRanges(excludeObservations))
.build();
}
public static Path.Any command(Path.Command command) {
return Path.Any.newBuilder()
.setCommand(command)
.build();
}
public static Path.Any commandTree(Path.Capture capture, CommandFilter filter) {
return Path.Any.newBuilder()
.setCommandTree(filter.toProto(
Path.CommandTree.newBuilder()
.setCapture(capture)
.setGroupByFrame(true)
.setGroupByDrawCall(true)
.setGroupByTransformFeedback(true)
.setGroupByUserMarkers(true)
.setGroupBySubmission(true)
.setAllowIncompleteFrame(true)
.setMaxChildren(2000)
.setMaxNeighbours(20)))
.build();
}
public static Path.Any commandTree(Path.CommandTreeNode node) {
return Path.Any.newBuilder()
.setCommandTreeNode(node)
.build();
}
public static Path.Any commandTree(Path.CommandTreeNode.Builder node) {
return Path.Any.newBuilder()
.setCommandTreeNode(node)
.build();
}
public static Path.Any commandTreeNodeForCommand(Path.ID tree, Path.Command command, boolean preferGroup) {
return Path.Any.newBuilder()
.setCommandTreeNodeForCommand(Path.CommandTreeNodeForCommand.newBuilder()
.setTree(tree)
.setCommand(command)
.setPreferGroup(preferGroup))
.build();
}
public static Path.State stateAfter(Path.Command command) {
if (command == null) {
return null;
}
return Path.State.newBuilder()
.setAfter(command)
.build();
}
public static Path.Any stateTree(CommandIndex command) {
if (command == null) {
return null;
}
return Path.Any.newBuilder()
.setStateTree(Path.StateTree.newBuilder()
.setState(stateAfter(command.getCommand()))
.setArrayGroupSize(2000))
.build();
}
public static Path.Any stateTree(Path.ID tree, Path.Any statePath) {
return Path.Any.newBuilder()
.setStateTreeNodeForPath(Path.StateTreeNodeForPath.newBuilder()
.setTree(tree)
.setMember(statePath))
.build();
}
public static Path.Any stateTree(Path.StateTreeNode node) {
return Path.Any.newBuilder()
.setStateTreeNode(node)
.build();
}
public static Path.Any stateTree(Path.StateTreeNode.Builder node) {
return Path.Any.newBuilder()
.setStateTreeNode(node)
.build();
}
public static Path.Any memoryAfter(CommandIndex index, int pool, long address, long size) {
if (index == null) {
return null;
}
return Path.Any.newBuilder()
.setMemory(Path.Memory.newBuilder()
.setAfter(index.getCommand())
.setPool(pool)
.setAddress(address)
.setSize(size)
.setIncludeTypes(true))
.build();
}
public static Path.Any memoryAfter(CommandIndex index, int pool, Service.MemoryRange range) {
if (index == null || range == null) {
return null;
}
return Path.Any.newBuilder()
.setMemory(Path.Memory.newBuilder()
.setAfter(index.getCommand())
.setPool(pool)
.setAddress(range.getBase())
.setSize(range.getSize())
.setIncludeTypes(true))
.build();
}
public static Path.Any observationsAfter(CommandIndex index, int pool) {
if (index == null) {
return null;
}
return Path.Any.newBuilder()
.setMemory(Path.Memory.newBuilder()
.setAfter(index.getCommand())
.setPool(pool)
.setAddress(0)
.setSize(UnsignedLongs.MAX_VALUE)
.setExcludeData(true)
.setExcludeObserved(true)
.setIncludeTypes(true))
.build();
}
public static Path.Any memoryAsType(CommandIndex index, int pool, Service.TypedMemoryRange typed) {
return Path.Any.newBuilder()
.setMemoryAsType(Path.MemoryAsType.newBuilder()
.setAddress(typed.getRange().getBase())
.setSize(typed.getRange().getSize())
.setPool(pool)
.setAfter(index.getCommand())
.setType(typed.getType()))
.build();
}
public static Path.Any resourceAfter(CommandIndex command, Path.ID id) {
if (command == null || id == null) {
return null;
}
return Path.Any.newBuilder()
.setResourceData(Path.ResourceData.newBuilder()
.setAfter(command.getCommand())
.setID(id))
.build();
}
public static Path.Any resourcesAfter(CommandIndex command, Path.ResourceType type) {
if (command == null || type == null) {
return null;
}
return Path.Any.newBuilder()
.setMultiResourceData(Path.MultiResourceData.newBuilder()
.setAfter(command.getCommand())
.setAll(true)
.setType(type))
.build();
}
public static Path.Any resourceExtrasAfter(CommandIndex command, Path.ID id) {
if (command == null || id == null) {
return null;
}
return Path.Any.newBuilder()
.setResourceExtras(Path.ResourceExtras.newBuilder()
.setAfter(command.getCommand())
.setID(id))
.build();
}
public static Path.Any pipelinesAfter(CommandIndex command) {
if (command == null) {
return null;
}
return Path.Any.newBuilder()
.setPipelines(Path.Pipelines.newBuilder()
.setCommandTreeNode(command.getNode()))
.build();
}
public static Path.Any framebufferAttachmentsAfter(CommandIndex command) {
if (command == null) {
return null;
}
return Path.Any.newBuilder()
.setFramebufferAttachments(Path.FramebufferAttachments.newBuilder()
.setAfter(command.getCommand()))
.build();
}
public static Path.Any framebufferAttachmentAfter(CommandIndex command, int index, Path.RenderSettings settings, Path.UsageHints hints) {
if (command == null) {
return null;
}
return Path.Any.newBuilder()
.setFramebufferAttachment(Path.FramebufferAttachment.newBuilder()
.setAfter(command.getCommand())
.setIndex(index)
.setRenderSettings(settings)
.setHints(hints))
.build();
}
public static final Path.MeshOptions NODATA_MESH_OPTIONS = Path.MeshOptions.newBuilder()
.setExcludeData(true)
.build();
public static Path.Any meshAfter(CommandIndex command, Path.MeshOptions options) {
return Path.Any.newBuilder()
.setMesh(Path.Mesh.newBuilder()
.setCommandTreeNode(command.getNode())
.setOptions(options))
.build();
}
public static Path.Any meshAfter(
CommandIndex command, Path.MeshOptions options, Vertex.BufferFormat format) {
return Path.Any.newBuilder()
.setAs(Path.As.newBuilder()
.setMesh(Path.Mesh.newBuilder()
.setCommandTreeNode(command.getNode())
.setOptions(options))
.setVertexBufferFormat(format))
.build();
}
public static Path.Any commandField(Path.Command command, String field) {
if (command == null || field == null) {
return null;
}
return Path.Any.newBuilder()
.setParameter(Path.Parameter.newBuilder()
.setCommand(command)
.setName(field))
.build();
}
public static Path.Any commandResult(Path.Command command) {
if (command == null) {
return null;
}
return Path.Any.newBuilder()
.setResult(Path.Result.newBuilder()
.setCommand(command))
.build();
}
public static Path.Any constantSet(Path.ConstantSet set) {
return Path.Any.newBuilder()
.setConstantSet(set)
.build();
}
public static Path.Any imageInfo(Path.ImageInfo image) {
return Path.Any.newBuilder()
.setImageInfo(image)
.build();
}
public static Path.Any resourceInfo(Path.ResourceData resource) {
return Path.Any.newBuilder()
.setResourceData(resource)
.build();
}
public static Path.Any imageData(Path.ImageInfo image, Image.Format format) {
return Path.Any.newBuilder()
.setAs(Path.As.newBuilder()
.setImageInfo(image)
.setImageFormat(format))
.build();
}
public static Path.Any imageData(Path.ResourceData resource, Image.Format format) {
return Path.Any.newBuilder()
.setAs(Path.As.newBuilder()
.setResourceData(resource)
.setImageFormat(format))
.build();
}
public static Path.RenderSettings renderSettings(int maxWidth, int maxHeight, Path.DrawMode drawMode, boolean disableReplayOptiimization) {
return Path.RenderSettings.newBuilder()
.setMaxWidth(maxWidth)
.setMaxHeight(maxHeight)
.setDrawMode(drawMode)
.setDisableReplayOptimization(disableReplayOptiimization)
.build();
}
public static Path.Thumbnail thumbnail(Path.Command command, int size, boolean disableOpt) {
return Path.Thumbnail.newBuilder()
.setCommand(command)
.setDesiredFormat(Images.FMT_RGBA_U8_NORM)
.setDesiredMaxHeight(size)
.setDesiredMaxWidth(size)
.setDisableOptimization(disableOpt)
.build();
}
public static Path.Thumbnail thumbnail(Path.CommandTreeNode node, int size, boolean disableOpt) {
return Path.Thumbnail.newBuilder()
.setCommandTreeNode(node)
.setDesiredFormat(Images.FMT_RGBA_U8_NORM)
.setDesiredMaxHeight(size)
.setDesiredMaxWidth(size)
.setDisableOptimization(disableOpt)
.build();
}
public static Path.Thumbnail thumbnail(Path.ResourceData resource, int size, boolean disableOpt) {
return Path.Thumbnail.newBuilder()
.setResource(resource)
.setDesiredFormat(Images.FMT_RGBA_U8_NORM)
.setDesiredMaxHeight(size)
.setDesiredMaxWidth(size)
.setDisableOptimization(disableOpt)
.build();
}
public static Path.Thumbnail thumbnail(CommandIndex command, int attachment, int size, boolean disableOpt) {
return Path.Thumbnail.newBuilder()
.setFramebufferAttachment(framebufferAttachmentAfter(command, attachment,
renderSettings(size, size, Path.DrawMode.NORMAL, disableOpt),
Path.UsageHints.newBuilder()
.setPreview(true)
.build()).getFramebufferAttachment())
.setDesiredFormat(Images.FMT_RGBA_U8_NORM)
.setDesiredMaxHeight(size)
.setDesiredMaxWidth(size)
.setDisableOptimization(disableOpt)
.build();
}
public static Path.Any thumbnails(
CommandIndex command, Path.ResourceType type, int size, boolean disableOpt) {
return thumbnail(Path.Thumbnail.newBuilder()
.setResources(Path.MultiResourceData.newBuilder()
.setAfter(command.getCommand())
.setAll(true)
.setType(type))
.setDesiredFormat(Images.FMT_RGBA_U8_NORM)
.setDesiredMaxHeight(size)
.setDesiredMaxWidth(size)
.setDisableOptimization(disableOpt)
.build());
}
public static Path.Any thumbnail(Path.Thumbnail thumb) {
return Path.Any.newBuilder()
.setThumbnail(thumb)
.build();
}
public static Path.Any blob(Image.ID id) {
return Path.Any.newBuilder()
.setBlob(Path.Blob.newBuilder()
.setID(Path.ID.newBuilder()
.setData(id.getData())))
.build();
}
public static Path.Any device(Path.Device device) {
return Path.Any.newBuilder()
.setDevice(device)
.build();
}
public static Path.Any traceInfo(Path.Device device) {
return Path.Any.newBuilder()
.setTraceConfig(Path.DeviceTraceConfiguration.newBuilder()
.setDevice(device))
.build();
}
public static Path.Type type(long typeIndex, Path.API api) {
return Path.Type.newBuilder()
.setTypeIndex(typeIndex)
.setAPI(api)
.build();
}
public static Path.Any type(Path.Type type) {
return Path.Any.newBuilder()
.setType(type)
.build();
}
public static boolean isNull(Path.Command c) {
return (c == null) || (c.getIndicesCount() == 0);
}
public static boolean isNull(Path.Commands c) {
return (c == null) || (c.getFromCount() == 0);
}
/**
* Compares a and b, returning -1 if a comes before b, 1 if b comes before a and 0 if they
* are equal.
*/
public static int compare(Path.Command a, Path.Command b) {
if (isNull(a)) {
return isNull(b) ? 0 : -1;
} else if (isNull(b)) {
return 1;
}
return compareCommands(a.getIndicesList(), b.getIndicesList(), false);
}
public static int compareCommands(List<Long> a, List<Long> b, boolean open) {
for (int i = 0; i < a.size(); i++) {
if (i >= b.size()) {
return 1;
}
int r = Long.compare(a.get(i), b.get(i));
if (r != 0) {
return r;
}
}
return open || (a.size() == b.size()) ? 0 : -1;
}
public static boolean contains(Path.Any path, Predicate<Object> predicate) {
return find(path, predicate) != null;
}
public static Path.Any find(Path.Any path, Predicate<Object> predicate) {
for (Object p = toNode(path); p != null; p = parentOf(p)) {
if (predicate.test(p)) {
return toAny(p);
}
}
return null;
}
public static Path.GlobalState findGlobalState(Path.Any path) {
return find(path, n -> n instanceof Path.GlobalState).getGlobalState();
}
/**
* @return the unboxed path node from the {@link com.google.gapid.proto.service.path.Path.Any}.
*/
public static Object toNode(Path.Any node) {
return dispatch(node, TO_NODE_VISITOR, null);
}
/**
* @return the path node boxed into a {@link com.google.gapid.proto.service.path.Path.Any}.
*/
public static Path.Any toAny(Object node) {
return dispatch(node, TO_ANY_VISITOR, null);
}
/**
* @return the parent path node of the given path node.
*/
public static Object parentOf(Object path) {
return dispatch(path, GET_PARENT_VISITOR, null);
}
/**
* @return a copy of the given the path node with its parent set to the given parent.
*/
public static Object setParent(Object path, Object parent) {
return dispatch(path, SET_PARENT_VISITOR, parent);
}
/**
* @return the path as a string.
*/
public static String toString(Object path) {
return dispatch(path, PRINT_VISITOR, new StringBuilder()).toString();
}
/**
* @return the path with the {@link com.google.gapid.proto.service.path.Path.GlobalState} ancestor
* replaced with state. If there is no
* {@link com.google.gapid.proto.service.path.Path.GlobalState} ancestor, then null is returned.
*/
public static Path.Any reparent(Path.Any path, Path.GlobalState state) {
LinkedList<Object> nodes = Lists.newLinkedList();
boolean found = false;
for (Object p = toNode(path); p != null; p = parentOf(p)) {
if (p instanceof Path.GlobalState) {
found = true;
break;
}
nodes.addFirst(p);
}
if (!found) {
return null;
}
Object head = state;
for (Object node : nodes) {
head = setParent(node, head);
}
return toAny(head);
}
public static class CommandFilter {
public boolean showHostCommands;
public boolean showSubmitInfoNodes;
public boolean showSyncCommands;
public boolean showBeginEndCommands;
public CommandFilter(boolean showHostCommands, boolean showSubmitInfoNodes,
boolean showSyncCommands, boolean showBeginEndCommands) {
this.showHostCommands = showHostCommands;
this.showSubmitInfoNodes = showSubmitInfoNodes;
this.showSyncCommands = showSyncCommands;
this.showBeginEndCommands = showBeginEndCommands;
}
public static CommandFilter fromSettings(Settings settings) {
SettingsProto.UI.CommandFilter filter = settings.ui().getCommandFilter();
return new CommandFilter(filter.getShowHostCommands(), filter.getShowSubmitInfoNodes(),
filter.getShowSyncCommands(), filter.getShowBeginEndCommands());
}
public CommandFilter copy() {
return new CommandFilter(
showHostCommands, showSubmitInfoNodes, showSyncCommands, showBeginEndCommands);
}
public boolean update(CommandFilter from) {
boolean changed =
showHostCommands != from.showHostCommands ||
showSubmitInfoNodes != from.showSubmitInfoNodes ||
showSyncCommands != from.showSyncCommands ||
showBeginEndCommands != from.showBeginEndCommands;
if (changed) {
showHostCommands = from.showHostCommands;
showSubmitInfoNodes = from.showSubmitInfoNodes;
showSyncCommands = from.showSyncCommands;
showBeginEndCommands = from.showBeginEndCommands;
}
return changed;
}
public Path.CommandTree.Builder toProto(Path.CommandTree.Builder path) {
return path
.setFilter(Path.CommandFilter.newBuilder()
.setSuppressHostCommands(!showHostCommands)
.setSuppressDeviceSideSyncCommands(!showSyncCommands)
.setSuppressBeginEndMarkers(!showBeginEndCommands))
.setSuppressSubmitInfoNodes(!showSubmitInfoNodes);
}
public void save(Settings settings) {
SettingsProto.UI.CommandFilter.Builder filter = settings.writeUi().getCommandFilterBuilder();
filter.setShowHostCommands(showHostCommands);
filter.setShowSubmitInfoNodes(showSubmitInfoNodes);
filter.setShowSyncCommands(showSyncCommands);
filter.setShowBeginEndCommands(showBeginEndCommands);
}
}
/**
* Visitor is the interface implemented by types that operate each of the path types.
* @param <R> the type of the result value.
* @param <A> the type of the argument value.
*/
private interface Visitor<R, A> {
R visit(Image.ID path, A arg);
R visit(Path.API path, A arg);
R visit(Path.ArrayIndex path, A arg);
R visit(Path.As path, A arg);
R visit(Path.Blob path, A arg);
R visit(Path.Capture path, A arg);
R visit(Path.ConstantSet path, A arg);
R visit(Path.Command path, A arg);
R visit(Path.Commands path, A arg);
R visit(Path.CommandTree path, A arg);
R visit(Path.CommandTreeNode path, A arg);
R visit(Path.CommandTreeNodeForCommand path, A arg);
R visit(Path.Device path, A arg);
R visit(Path.DeviceTraceConfiguration path, A arg);
R visit(Path.FramebufferObservation path, A arg);
R visit(Path.Field path, A arg);
R visit(Path.GlobalState path, A arg);
R visit(Path.ID path, A arg);
R visit(Path.ImageInfo path, A arg);
R visit(Path.MapIndex path, A arg);
R visit(Path.Memory path, A arg);
R visit(Path.Mesh path, A arg);
R visit(Path.Parameter path, A arg);
R visit(Path.Report path, A arg);
R visit(Path.ResourceData path, A arg);
R visit(Path.Resources path, A arg);
R visit(Path.Result path, A arg);
R visit(Path.Slice path, A arg);
R visit(Path.State path, A arg);
R visit(Path.StateTree path, A arg);
R visit(Path.StateTreeNode path, A arg);
R visit(Path.StateTreeNodeForPath path, A arg);
R visit(Path.Thumbnail path, A arg);
}
/**
* Unboxes the path node from the {@link com.google.gapid.proto.service.path.Path.Any} and
* dispatches the node to the visitor. Throws an exception if the path is not an expected type.
*/
private static <T, A> T dispatchAny(Path.Any path, Visitor<T, A> visitor, A arg) {
switch (path.getPathCase()) {
case API:
return visitor.visit(path.getAPI(), arg);
case ARRAY_INDEX:
return visitor.visit(path.getArrayIndex(), arg);
case AS:
return visitor.visit(path.getAs(), arg);
case BLOB:
return visitor.visit(path.getBlob(), arg);
case CAPTURE:
return visitor.visit(path.getCapture(), arg);
case CONSTANT_SET:
return visitor.visit(path.getConstantSet(), arg);
case COMMAND:
return visitor.visit(path.getCommand(), arg);
case COMMANDS:
return visitor.visit(path.getCommands(), arg);
case COMMAND_TREE:
return visitor.visit(path.getCommandTree(), arg);
case COMMAND_TREE_NODE:
return visitor.visit(path.getCommandTreeNode(), arg);
case COMMAND_TREE_NODE_FOR_COMMAND:
return visitor.visit(path.getCommandTreeNodeForCommand(), arg);
case DEVICE:
return visitor.visit(path.getDevice(), arg);
case TRACECONFIG:
return visitor.visit(path.getTraceConfig(), arg);
case FBO:
return visitor.visit(path.getFBO(), arg);
case FIELD:
return visitor.visit(path.getField(), arg);
case GLOBAL_STATE:
return visitor.visit(path.getGlobalState(), arg);
case IMAGE_INFO:
return visitor.visit(path.getImageInfo(), arg);
case MAP_INDEX:
return visitor.visit(path.getMapIndex(), arg);
case MEMORY:
return visitor.visit(path.getMemory(), arg);
case MESH:
return visitor.visit(path.getMesh(), arg);
case PARAMETER:
return visitor.visit(path.getParameter(), arg);
case REPORT:
return visitor.visit(path.getReport(), arg);
case RESOURCE_DATA:
return visitor.visit(path.getResourceData(), arg);
case RESOURCES:
return visitor.visit(path.getResources(), arg);
case RESULT:
return visitor.visit(path.getResult(), arg);
case SLICE:
return visitor.visit(path.getSlice(), arg);
case STATE:
return visitor.visit(path.getState(), arg);
case STATE_TREE:
return visitor.visit(path.getStateTree(), arg);
case STATE_TREE_NODE:
return visitor.visit(path.getStateTreeNode(), arg);
case STATE_TREE_NODE_FOR_PATH:
return visitor.visit(path.getStateTreeNodeForPath(), arg);
case THUMBNAIL:
return visitor.visit(path.getThumbnail(), arg);
default:
throw new RuntimeException("Unexpected path case: " + path.getPathCase());
}
}
/**
* Dispatches the path node to the visitor.
* Throws an exception if the path is not an expected type.
*/
protected static <T, A> T dispatch(Object path, Visitor<T, A> visitor, A arg) {
if (path instanceof Path.Any) {
return dispatchAny((Path.Any)path, visitor, arg);
} else if (path instanceof Image.ID) {
return visitor.visit((Image.ID)path, arg);
} else if (path instanceof Path.API) {
return visitor.visit((Path.API)path, arg);
} else if (path instanceof Path.ArrayIndex) {
return visitor.visit((Path.ArrayIndex)path, arg);
} else if (path instanceof Path.As) {
return visitor.visit((Path.As)path, arg);
} else if (path instanceof Path.Blob) {
return visitor.visit((Path.Blob)path, arg);
} else if (path instanceof Path.Capture) {
return visitor.visit((Path.Capture)path, arg);
} else if (path instanceof Path.ConstantSet) {
return visitor.visit((Path.ConstantSet)path, arg);
} else if (path instanceof Path.Command) {
return visitor.visit((Path.Command)path, arg);
} else if (path instanceof Path.Commands) {
return visitor.visit((Path.Commands)path, arg);
} else if (path instanceof Path.CommandTree) {
return visitor.visit((Path.CommandTree)path, arg);
} else if (path instanceof Path.CommandTreeNode) {
return visitor.visit((Path.CommandTreeNode)path, arg);
} else if (path instanceof Path.CommandTreeNodeForCommand) {
return visitor.visit((Path.CommandTreeNodeForCommand)path, arg);
} else if (path instanceof Path.Device) {
return visitor.visit((Path.Device)path, arg);
} else if (path instanceof Path.DeviceTraceConfiguration) {
return visitor.visit((Path.DeviceTraceConfiguration)path, arg);
} else if (path instanceof Path.FramebufferObservation) {
return visitor.visit((Path.FramebufferObservation)path, arg);
} else if (path instanceof Path.Field) {
return visitor.visit((Path.Field)path, arg);
} else if (path instanceof Path.GlobalState) {
return visitor.visit((Path.GlobalState)path, arg);
} else if (path instanceof Path.ID) {
return visitor.visit((Path.ID)path, arg);
} else if (path instanceof Path.ImageInfo) {
return visitor.visit((Path.ImageInfo)path, arg);
} else if (path instanceof Path.MapIndex) {
return visitor.visit((Path.MapIndex)path, arg);
} else if (path instanceof Path.Memory) {
return visitor.visit((Path.Memory)path, arg);
} else if (path instanceof Path.Mesh) {
return visitor.visit((Path.Mesh)path, arg);
} else if (path instanceof Path.Parameter) {
return visitor.visit((Path.Parameter)path, arg);
} else if (path instanceof Path.Report) {
return visitor.visit((Path.Report)path, arg);
} else if (path instanceof Path.ResourceData) {
return visitor.visit((Path.ResourceData)path, arg);
} else if (path instanceof Path.Resources) {
return visitor.visit((Path.Resources)path, arg);
} else if (path instanceof Path.Result) {
return visitor.visit((Path.Result)path, arg);
} else if (path instanceof Path.Slice) {
return visitor.visit((Path.Slice)path, arg);
} else if (path instanceof Path.State) {
return visitor.visit((Path.State)path, arg);
} else if (path instanceof Path.StateTree) {
return visitor.visit((Path.StateTree)path, arg);
} else if (path instanceof Path.StateTreeNode) {
return visitor.visit((Path.StateTreeNode)path, arg);
} else if (path instanceof Path.StateTreeNodeForPath) {
return visitor.visit((Path.StateTreeNodeForPath)path, arg);
} else if (path instanceof Path.Thumbnail) {
return visitor.visit((Path.Thumbnail)path, arg);
} else if (path instanceof Message.Builder) {
return dispatch(((Message.Builder)path).build(), visitor, arg);
} else {
throw new RuntimeException("Unexpected path type: " + path.getClass().getName());
}
}
/**
* {@link Visitor} that simply returns the node type. Used by {@link #toNode(Path.Any)}.
*/
private static final Visitor<Object, Void> TO_NODE_VISITOR = new Visitor<Object, Void>() {
@Override public Object visit(Image.ID path, Void ignored) { return path; }
@Override public Object visit(Path.API path, Void ignored) { return path; }
@Override public Object visit(Path.ArrayIndex path, Void ignored) { return path; }
@Override public Object visit(Path.As path, Void ignored) { return path; }
@Override public Object visit(Path.Blob path, Void ignored) { return path; }
@Override public Object visit(Path.Capture path, Void ignored) { return path; }
@Override public Object visit(Path.ConstantSet path, Void ignored) { return path; }
@Override public Object visit(Path.Command path, Void ignored) { return path; }
@Override public Object visit(Path.Commands path, Void ignored) { return path; }
@Override public Object visit(Path.CommandTree path, Void ignored) { return path; }
@Override public Object visit(Path.CommandTreeNode path, Void ignored) { return path; }
@Override public Object visit(Path.CommandTreeNodeForCommand path, Void ignored) { return path; }
@Override public Object visit(Path.Device path, Void ignored) { return path; }
@Override public Object visit(Path.DeviceTraceConfiguration path, Void ignored) { return path; }
@Override public Object visit(Path.FramebufferObservation path, Void ignored) { return path; }
@Override public Object visit(Path.Field path, Void ignored) { return path; }
@Override public Object visit(Path.GlobalState path, Void ignored) { return path; }
@Override public Object visit(Path.ID path, Void ignored) { return path; }
@Override public Object visit(Path.ImageInfo path, Void ignored) { return path; }
@Override public Object visit(Path.MapIndex path, Void ignored) { return path; }
@Override public Object visit(Path.Memory path, Void ignored) { return path; }
@Override public Object visit(Path.Mesh path, Void ignored) { return path; }
@Override public Object visit(Path.Parameter path, Void ignored) { return path; }
@Override public Object visit(Path.Report path, Void ignored) { return path; }
@Override public Object visit(Path.ResourceData path, Void ignored) { return path; }
@Override public Object visit(Path.Resources path, Void ignored) { return path; }
@Override public Object visit(Path.Result path, Void ignored) { return path; }
@Override public Object visit(Path.Slice path, Void ignored) { return path; }
@Override public Object visit(Path.State path, Void ignored) { return path; }
@Override public Object visit(Path.StateTree path, Void ignored) { return path; }
@Override public Object visit(Path.StateTreeNode path, Void ignored) { return path; }
@Override public Object visit(Path.StateTreeNodeForPath path, Void ignored) { return path; }
@Override public Object visit(Path.Thumbnail path, Void ignored) { return path; }
};
/**
* {@link Visitor} that returns the passed node type boxed in a
* {@link com.google.gapid.proto.service.path.Path.Any}. Used by {@link #toAny(Object)}.
*/
private static final Visitor<Path.Any, Void> TO_ANY_VISITOR = new Visitor<Path.Any, Void>() {
@Override
public Path.Any visit(Image.ID path, Void ignored) {
throw new RuntimeException("Image.ID cannot be stored in a Path.Any");
}
@Override
public Path.Any visit(Path.API path, Void ignored) {
return Path.Any.newBuilder().setAPI(path).build();
}
@Override
public Path.Any visit(Path.ArrayIndex path, Void ignored) {
return Path.Any.newBuilder().setArrayIndex(path).build();
}
@Override
public Path.Any visit(Path.As path, Void ignored) {
return Path.Any.newBuilder().setAs(path).build();
}
@Override
public Path.Any visit(Path.Blob path, Void ignored) {
return Path.Any.newBuilder().setBlob(path).build();
}
@Override
public Path.Any visit(Path.Capture path, Void ignored) {
return Path.Any.newBuilder().setCapture(path).build();
}
@Override
public Path.Any visit(Path.ConstantSet path, Void ignored) {
return Path.Any.newBuilder().setConstantSet(path).build();
}
@Override
public Path.Any visit(Path.Command path, Void ignored) {
return Path.Any.newBuilder().setCommand(path).build();
}
@Override
public Path.Any visit(Path.Commands path, Void ignored) {
return Path.Any.newBuilder().setCommands(path).build();
}
@Override
public Path.Any visit(Path.CommandTree path, Void ignored) {
return Path.Any.newBuilder().setCommandTree(path).build();
}
@Override
public Path.Any visit(Path.CommandTreeNode path, Void ignored) {
return Path.Any.newBuilder().setCommandTreeNode(path).build();
}
@Override
public Path.Any visit(Path.CommandTreeNodeForCommand path, Void ignored) {
return Path.Any.newBuilder().setCommandTreeNodeForCommand(path).build();
}
@Override
public Path.Any visit(Path.Device path, Void ignored) {
return Path.Any.newBuilder().setDevice(path).build();
}
@Override
public Path.Any visit(Path.DeviceTraceConfiguration path, Void ignored) {
return Path.Any.newBuilder().setTraceConfig(path).build();
}
@Override
public Path.Any visit(Path.FramebufferObservation path, Void ignored) {
return Path.Any.newBuilder().setFBO(path).build();
}
@Override
public Path.Any visit(Path.Field path, Void ignored) {
return Path.Any.newBuilder().setField(path).build();
}
@Override
public Path.Any visit(Path.GlobalState path, Void ignored) {
return Path.Any.newBuilder().setGlobalState(path).build();
}
@Override
public Path.Any visit(Path.ID path, Void ignored) {
throw new RuntimeException("Path.ID cannot be stored in a Path.Any");
}
@Override
public Path.Any visit(Path.ImageInfo path, Void ignored) {
return Path.Any.newBuilder().setImageInfo(path).build();
}
@Override
public Path.Any visit(Path.MapIndex path, Void ignored) {
return Path.Any.newBuilder().setMapIndex(path).build();
}
@Override
public Path.Any visit(Path.Memory path, Void ignored) {
return Path.Any.newBuilder().setMemory(path).build();
}
@Override
public Path.Any visit(Path.Mesh path, Void ignored) {
return Path.Any.newBuilder().setMesh(path).build();
}
@Override
public Path.Any visit(Path.Parameter path, Void ignored) {
return Path.Any.newBuilder().setParameter(path).build();
}
@Override
public Path.Any visit(Path.Report path, Void ignored) {
return Path.Any.newBuilder().setReport(path).build();
}
@Override
public Path.Any visit(Path.ResourceData path, Void ignored) {
return Path.Any.newBuilder().setResourceData(path).build();
}
@Override
public Path.Any visit(Path.Resources path, Void ignored) {
return Path.Any.newBuilder().setResources(path).build();
}
@Override
public Path.Any visit(Path.Result path, Void ignored) {
return Path.Any.newBuilder().setResult(path).build();
}
@Override
public Path.Any visit(Path.Slice path, Void ignored) {
return Path.Any.newBuilder().setSlice(path).build();
}
@Override
public Path.Any visit(Path.State path, Void ignored) {
return Path.Any.newBuilder().setState(path).build();
}
@Override
public Path.Any visit(Path.StateTree path, Void ignored) {
return Path.Any.newBuilder().setStateTree(path).build();
}
@Override
public Path.Any visit(Path.StateTreeNode path, Void ignored) {
return Path.Any.newBuilder().setStateTreeNode(path).build();
}
@Override
public Path.Any visit(Path.StateTreeNodeForPath path, Void ignored) {
return Path.Any.newBuilder().setStateTreeNodeForPath(path).build();
}
@Override
public Path.Any visit(Path.Thumbnail path, Void ignored) {
return Path.Any.newBuilder().setThumbnail(path).build();
}
};
/**
* {@link Visitor} that returns the parent node of the given path node.
* Used by {@link #parentOf(Object)}.
*/
private static final Visitor<Object, Void> GET_PARENT_VISITOR = new Visitor<Object, Void>() {
@Override
public Object visit(Image.ID path, Void ignored) {
return null;
}
@Override
public Object visit(Path.API path, Void ignored) {
return null;
}
@Override
public Object visit(Path.ArrayIndex path, Void ignored) {
switch (path.getArrayCase()) {
case FIELD:
return path.getField();
case ARRAY_INDEX:
return path.getArrayIndex();
case SLICE:
return path.getSlice();
case MAP_INDEX:
return path.getMapIndex();
default:
return null;
}
}
@Override
public Object visit(Path.As path, Void ignored) {
switch (path.getFromCase()) {
case FIELD:
return path.getField();
case SLICE:
return path.getSlice();
case ARRAY_INDEX:
return path.getArrayIndex();
case MAP_INDEX:
return path.getMapIndex();
case IMAGE_INFO:
return path.getImageInfo();
case RESOURCE_DATA:
return path.getResourceData();
case MESH:
return path.getMesh();
default:
return null;
}
}
@Override
public Object visit(Path.Blob path, Void ignored) {
return null;
}
@Override
public Object visit(Path.Capture path, Void ignored) {
return null;
}
@Override
public Object visit(Path.ConstantSet path, Void ignored) {
return path.getAPI();
}
@Override
public Object visit(Path.Command path, Void ignored) {
return path.getCapture();
}
@Override
public Object visit(Path.Commands path, Void ignored) {
return path.getCapture();
}
@Override
public Object visit(Path.CommandTree path, Void ignored) {
return path.getCapture();
}
@Override
public Object visit(Path.CommandTreeNode path, Void ignored) {
return null;
}
@Override
public Object visit(Path.CommandTreeNodeForCommand path, Void ignored) {
return path.getCommand();
}
@Override
public Object visit(Path.Device path, Void ignored) {
return null;
}
@Override
public Object visit(Path.DeviceTraceConfiguration path, Void ignored) {
return path.getDevice();
}
@Override
public Object visit(Path.FramebufferObservation path, Void ignored) {
return path.getCommand();
}
@Override
public Object visit(Path.Field path, Void ignored) {
switch (path.getStructCase()) {
case STATE:
return path.getState();
case GLOBAL_STATE:
return path.getGlobalState();
case FIELD:
return path.getField();
case ARRAY_INDEX:
return path.getArrayIndex();
case SLICE:
return path.getSlice();
case MAP_INDEX:
return path.getMapIndex();
default:
return null;
}
}
@Override
public Object visit(Path.GlobalState path, Void ignored) {
return path.getAfter();
}
@Override
public Object visit(Path.ID path, Void ignored) {
return null;
}
@Override
public Object visit(Path.ImageInfo path, Void ignored) {
return null;
}
@Override
public Object visit(Path.MapIndex path, Void ignored) {
switch (path.getMapCase()) {
case STATE:
return path.getState();
case FIELD:
return path.getField();
case ARRAY_INDEX:
return path.getArrayIndex();
case SLICE:
return path.getSlice();
case MAP_INDEX:
return path.getMapIndex();
default:
return null;
}
}
@Override
public Object visit(Path.Memory path, Void ignored) {
return path.getAfter();
}
@Override
public Object visit(Path.Mesh path, Void ignored) {
switch (path.getObjectCase()) {
case COMMAND:
return path.getCommand();
case COMMAND_TREE_NODE:
return path.getCommandTreeNode();
default:
return null;
}
}
@Override
public Object visit(Path.Parameter path, Void ignored) {
return path.getCommand();
}
@Override
public Object visit(Path.Report path, Void ignored) {
return path.getCapture();
}
@Override
public Object visit(Path.ResourceData path, Void ignored) {
return path.getAfter();
}
@Override
public Object visit(Path.Resources path, Void ignored) {
return path.getCapture();
}
@Override
public Object visit(Path.Result path, Void ignored) {
return path.getCommand();
}
@Override
public Object visit(Path.Slice path, Void ignored) {
switch (path.getArrayCase()) {
case FIELD:
return path.getField();
case ARRAY_INDEX:
return path.getArrayIndex();
case SLICE:
return path.getSlice();
case MAP_INDEX:
return path.getMapIndex();
default:
return null;
}
}
@Override
public Object visit(Path.State path, Void ignored) {
return path.getAfter();
}
@Override
public Object visit(Path.StateTree path, Void ignored) {
return path.getState();
}
@Override
public Object visit(Path.StateTreeNode path, Void ignored) {
return null;
}
@Override
public Object visit(Path.StateTreeNodeForPath path, Void ignored) {
return null;
}
@Override
public Object visit(Path.Thumbnail path, Void ignored) {
switch (path.getObjectCase()) {
case RESOURCE:
return path.getResource();
case COMMAND:
return path.getCommand();
case COMMAND_TREE_NODE:
return path.getCommandTreeNode();
default:
return null;
}
}
};
/**
* {@link Visitor} that returns the a copy of the provided path node, but with the parent changed
* to the specified parent node.
* Used by {@link #setParent(Object, Object)}.
*/
private static final Visitor<Object, Object> SET_PARENT_VISITOR = new Visitor<Object, Object>() {
@Override
public Object visit(Image.ID path, Object parent) {
throw new RuntimeException("Image.ID has no parent to set");
}
@Override
public Object visit(Path.API path, Object parent) {
throw new RuntimeException("Path.API has no parent to set");
}
@Override
public Object visit(Path.ArrayIndex path, Object parent) {
if (parent instanceof Path.Field) {
return path.toBuilder().setField((Path.Field) parent).build();
} else if (parent instanceof Path.ArrayIndex) {
return path.toBuilder().setArrayIndex((Path.ArrayIndex) parent).build();
} else if (parent instanceof Path.Slice) {
return path.toBuilder().setSlice((Path.Slice) parent).build();
} else if (parent instanceof Path.MapIndex) {
return path.toBuilder().setMapIndex((Path.MapIndex) parent).build();
} else {
throw new RuntimeException("Path.ArrayIndex cannot set parent to " + parent.getClass().getName());
}
}
@Override
public Object visit(Path.As path, Object parent) {
if (parent instanceof Path.Field) {
return path.toBuilder().setField((Path.Field) parent).build();
} else if (parent instanceof Path.ArrayIndex) {
return path.toBuilder().setArrayIndex((Path.ArrayIndex) parent).build();
} else if (parent instanceof Path.Slice) {
return path.toBuilder().setSlice((Path.Slice) parent).build();
} else if (parent instanceof Path.MapIndex) {
return path.toBuilder().setMapIndex((Path.MapIndex) parent).build();
} else if (parent instanceof Path.ImageInfo) {
return path.toBuilder().setImageInfo((Path.ImageInfo) parent).build();
} else if (parent instanceof Path.ResourceData) {
return path.toBuilder().setResourceData((Path.ResourceData) parent).build();
} else if (parent instanceof Path.Mesh) {
return path.toBuilder().setMesh((Path.Mesh) parent).build();
} else {
throw new RuntimeException("Path.As cannot set parent to " + parent.getClass().getName());
}
}
@Override
public Object visit(Path.DeviceTraceConfiguration path, Object parent) {
if (!(parent instanceof Path.Device)) {
throw new RuntimeException("Path.DeviceTraceConfiguration cannot set parent to " + parent.getClass().getName());
}
return path.toBuilder().setDevice((Path.Device) parent).build();
}
@Override
public Object visit(Path.Blob path, Object parent) {
throw new RuntimeException("Path.Blob has no parent to set");
}
@Override
public Object visit(Path.Capture path, Object parent) {
throw new RuntimeException("Path.Capture has no parent to set");
}
@Override
public Object visit(Path.ConstantSet path, Object parent) {
if (parent instanceof Path.API) {
return path.toBuilder().setAPI((Path.API) parent).build();
} else {
throw new RuntimeException("Path.ConstantSet cannot set parent to " + parent.getClass().getName());
}
}
@Override
public Object visit(Path.Command path, Object parent) {
if (parent instanceof Path.Capture) {
return path.toBuilder().setCapture((Path.Capture) parent).build();
} else {
throw new RuntimeException("Path.Command cannot set parent to " + parent.getClass().getName());
}
}
@Override
public Object visit(Path.Commands path, Object parent) {
if (parent instanceof Path.Capture) {
return path.toBuilder().setCapture((Path.Capture) parent).build();
} else {
throw new RuntimeException("Path.Commands cannot set parent to " + parent.getClass().getName());
}
}
@Override
public Object visit(Path.CommandTree path, Object parent) {
if (parent instanceof Path.Capture) {
return path.toBuilder().setCapture((Path.Capture) parent).build();
} else {
throw new RuntimeException("Path.CommandTree cannot set parent to " + parent.getClass().getName());
}
}
@Override
public Object visit(Path.CommandTreeNode path, Object parent) {
throw new RuntimeException("Path.CommandTreeNode has no parent to set");
}
@Override
public Object visit(Path.CommandTreeNodeForCommand path, Object parent) {
if (parent instanceof Path.Command) {
return path.toBuilder().setCommand((Path.Command) parent).build();
} else {
throw new RuntimeException("Path.CommandTreeNodeForCommand cannot set parent to " + parent.getClass().getName());
}
}
@Override
public Object visit(Path.Device path, Object parent) {
throw new RuntimeException("Path.Device has no parent to set");
}
@Override
public Object visit(Path.FramebufferObservation path, Object parent) {
if (parent instanceof Path.Command) {
return path.toBuilder().setCommand((Path.Command) parent).build();
} else {
throw new RuntimeException("Path.FramebufferObservation cannot set parent to " + parent.getClass().getName());
}
}
@Override
public Object visit(Path.Field path, Object parent) {
if (parent instanceof Path.State) {
return path.toBuilder().setState((Path.State) parent).build();
} else if (parent instanceof Path.GlobalState) {
return path.toBuilder().setGlobalState((Path.GlobalState) parent).build();
} else if (parent instanceof Path.Field) {
return path.toBuilder().setField((Path.Field) parent).build();
} else if (parent instanceof Path.ArrayIndex) {
return path.toBuilder().setArrayIndex((Path.ArrayIndex) parent).build();
} else if (parent instanceof Path.Slice) {
return path.toBuilder().setSlice((Path.Slice) parent).build();
} else if (parent instanceof Path.MapIndex) {
return path.toBuilder().setMapIndex((Path.MapIndex) parent).build();
} else {
throw new RuntimeException("Path.Field cannot set parent to " + parent.getClass().getName());
}
}
@Override
public Object visit(Path.GlobalState path, Object parent) {
if (parent instanceof Path.Command) {
return path.toBuilder().setAfter((Path.Command) parent).build();
} else {
throw new RuntimeException("Path.GlobalState cannot set parent to " + parent.getClass().getName());
}
}
@Override
public Object visit(Path.ID path, Object parent) {
throw new RuntimeException("Path.ID has no parent to set");
}
@Override
public Object visit(Path.ImageInfo path, Object parent) {
throw new RuntimeException("Path.ImageInfo has no parent to set");
}
@Override
public Object visit(Path.MapIndex path, Object parent) {
if (parent instanceof Path.State) {
return path.toBuilder().setState((Path.State) parent).build();
} else if (parent instanceof Path.Field) {
return path.toBuilder().setField((Path.Field) parent).build();
} else if (parent instanceof Path.ArrayIndex) {
return path.toBuilder().setArrayIndex((Path.ArrayIndex) parent).build();
} else if (parent instanceof Path.Slice) {
return path.toBuilder().setSlice((Path.Slice) parent).build();
} else if (parent instanceof Path.MapIndex) {
return path.toBuilder().setMapIndex((Path.MapIndex) parent).build();
} else {
throw new RuntimeException("Path.MapIndex cannot set parent to " + parent.getClass().getName());
}
}
@Override
public Object visit(Path.Memory path, Object parent) {
if (parent instanceof Path.Command) {
return path.toBuilder().setAfter((Path.Command) parent).build();
} else {
throw new RuntimeException("Path.Memory cannot set parent to " + parent.getClass().getName());
}
}
@Override
public Object visit(Path.Mesh path, Object parent) {
if (parent instanceof Path.Command) {
return path.toBuilder().setCommand((Path.Command) parent).build();
} else if (parent instanceof Path.CommandTreeNode) {
return path.toBuilder().setCommandTreeNode((Path.CommandTreeNode) parent).build();
} else {
throw new RuntimeException("Path.Mesh cannot set parent to " + parent.getClass().getName());
}
}
@Override
public Object visit(Path.Parameter path, Object parent) {
if (parent instanceof Path.Command) {
return path.toBuilder().setCommand((Path.Command) parent).build();
} else {
throw new RuntimeException("Path.Parameter cannot set parent to " + parent.getClass().getName());
}
}
@Override
public Object visit(Path.Report path, Object parent) {
if (parent instanceof Path.Capture) {
return path.toBuilder().setCapture((Path.Capture) parent).build();
} else {
throw new RuntimeException("Path.Report cannot set parent to " + parent.getClass().getName());
}
}
@Override
public Object visit(Path.ResourceData path, Object parent) {
if (parent instanceof Path.Command) {
return path.toBuilder().setAfter((Path.Command) parent).build();
} else {
throw new RuntimeException("Path.ResourceData cannot set parent to " + parent.getClass().getName());
}
}
@Override
public Object visit(Path.Resources path, Object parent) {
if (parent instanceof Path.Capture) {
return path.toBuilder().setCapture((Path.Capture) parent).build();
} else {
throw new RuntimeException("Path.Resources cannot set parent to " + parent.getClass().getName());
}
}
@Override
public Object visit(Path.Result path, Object parent) {
if (parent instanceof Path.Command) {
return path.toBuilder().setCommand((Path.Command) parent).build();
} else {
throw new RuntimeException("Path.Result cannot set parent to " + parent.getClass().getName());
}
}
@Override
public Object visit(Path.Slice path, Object parent) {
if (parent instanceof Path.Field) {
return path.toBuilder().setField((Path.Field) parent).build();
} else if (parent instanceof Path.ArrayIndex) {
return path.toBuilder().setArrayIndex((Path.ArrayIndex) parent).build();
} else if (parent instanceof Path.Slice) {
return path.toBuilder().setSlice((Path.Slice) parent).build();
} else if (parent instanceof Path.MapIndex) {
return path.toBuilder().setMapIndex((Path.MapIndex) parent).build();
} else {
throw new RuntimeException("Path.Slice cannot set parent to " + parent.getClass().getName());
}
}
@Override
public Object visit(Path.State path, Object parent) {
if (parent instanceof Path.Command) {
return path.toBuilder().setAfter((Path.Command) parent).build();
} else {
throw new RuntimeException("Path.State cannot set parent to " + parent.getClass().getName());
}
}
@Override
public Object visit(Path.StateTree path, Object parent) {
if (parent instanceof Path.State) {
return path.toBuilder().setState((Path.State) parent).build();
} else {
throw new RuntimeException("Path.StateTree cannot set parent to " + parent.getClass().getName());
}
}
@Override
public Object visit(Path.StateTreeNode path, Object parent) {
throw new RuntimeException("Path.StateTreeNode has no parent to set");
}
@Override
public Object visit(Path.StateTreeNodeForPath path, Object parent) {
throw new RuntimeException("Path.StateTreeNodeForPath has no parent to set");
}
@Override
public Object visit(Path.Thumbnail path, Object parent) {
if (parent instanceof Path.ResourceData) {
return path.toBuilder().setResource((Path.ResourceData) parent).build();
} else if (parent instanceof Path.Command) {
return path.toBuilder().setCommand((Path.Command) parent).build();
} else if (parent instanceof Path.CommandTreeNode) {
return path.toBuilder().setCommandTreeNode((Path.CommandTreeNode) parent).build();
} else {
throw new RuntimeException("Path.Thumbnail cannot set parent to " + parent.getClass().getName());
}
}
};
/**
* {@link Visitor} that prints the path to the provided {@link StringBuilder}, then returns that
* {@link StringBuilder}.
* Used by {@link #toString(Object)}.
*/
private static final Visitor<StringBuilder, StringBuilder> PRINT_VISITOR = new Visitor<StringBuilder, StringBuilder>() {
@Override
public StringBuilder visit(Image.ID path, StringBuilder sb) {
return sb.append(ProtoDebugTextFormat.shortDebugString(path));
}
@Override
public StringBuilder visit(Path.API path, StringBuilder sb) {
sb.append("API{");
visit(path.getID(), sb);
sb.append("}");
return sb;
}
@Override
public StringBuilder visit(Path.ArrayIndex path, StringBuilder sb) {
return dispatch(parentOf(path), this, sb)
.append("[")
.append(UnsignedLongs.toString(path.getIndex()))
.append("]");
}
@Override
public StringBuilder visit(Path.As path, StringBuilder sb) {
dispatch(parentOf(path), this, sb);
switch (path.getToCase()) {
case IMAGE_FORMAT:
sb.append(".as(");
sb.append(path.getImageFormat().getName()); // TODO
sb.append(")");
break;
case VERTEX_BUFFER_FORMAT:
sb.append(".as(VBF)"); // TODO
break;
default:
sb.append(".as(??)");
}
return sb;
}
@Override
public StringBuilder visit(Path.Blob path, StringBuilder sb) {
sb.append("blob{");
visit(path.getID(), sb);
sb.append("}");
return sb;
}
@Override
public StringBuilder visit(Path.Capture path, StringBuilder sb) {
sb.append("capture{");
visit(path.getID(), sb);
sb.append("}");
return sb;
}
@Override
public StringBuilder visit(Path.ConstantSet path, StringBuilder sb) {
return visit(path.getAPI(), sb)
.append(".constants[")
.append(path.getIndex())
.append("]");
}
@Override
public StringBuilder visit(Path.Command path, StringBuilder sb) {
return visit(path.getCapture(), sb)
.append(".command[")
.append(Formatter.commandIndex(path))
.append("]");
}
@Override
public StringBuilder visit(Path.Commands path, StringBuilder sb) {
return visit(path.getCapture(), sb)
.append(".command[")
.append(Formatter.firstIndex(path))
.append(":")
.append(Formatter.lastIndex(path))
.append("]");
}
@Override
public StringBuilder visit(Path.CommandTree path, StringBuilder sb) {
visit(path.getCapture(), sb)
.append(".tree");
append(sb, path.getFilter()).append('[');
if (path.getGroupByFrame()) sb.append('F');
if (path.getAllowIncompleteFrame()) sb.append('i');
if (path.getGroupByDrawCall()) sb.append('D');
if (path.getGroupByUserMarkers()) sb.append('M');
if (path.getGroupBySubmission()) sb.append('S');
if (path.getMaxChildren() != 0) {
sb.append(",max=").append(path.getMaxChildren());
}
sb.append(']');
return sb;
}
@Override
public StringBuilder visit(Path.CommandTreeNode path, StringBuilder sb) {
sb.append("tree{");
visit(path.getTree(), sb);
sb.append("}.node(");
sb.append(Formatter.index(path.getIndicesList()));
sb.append(")");
return sb;
}
@Override
public StringBuilder visit(Path.CommandTreeNodeForCommand path, StringBuilder sb) {
sb.append("tree{");
visit(path.getTree(), sb);
sb.append("}.command(");
visit(path.getCommand(), sb);
sb.append(")");
return sb;
}
@Override
public StringBuilder visit(Path.Device path, StringBuilder sb) {
sb.append("device{");
visit(path.getID(), sb);
sb.append("}");
return sb;
}
@Override
public StringBuilder visit(Path.DeviceTraceConfiguration path, StringBuilder sb) {
sb.append("device_configuration{");
visit(path.getDevice(), sb);
sb.append("}");
return sb;
}
@Override
public StringBuilder visit(Path.FramebufferObservation path, StringBuilder sb) {
return visit(path.getCommand(), sb).append(".fbo");
}
@Override
public StringBuilder visit(Path.Field path, StringBuilder sb) {
return dispatch(parentOf(path), this, sb)
.append(".")
.append(path.getName());
}
@Override
public StringBuilder visit(Path.GlobalState path, StringBuilder sb) {
return visit(path.getAfter(), sb).append(".global-state");
}
@Override
public StringBuilder visit(Path.ID path, StringBuilder sb) {
return sb.append(ProtoDebugTextFormat.shortDebugString(path));
}
@Override
public StringBuilder visit(Path.ImageInfo path, StringBuilder sb) {
sb.append("image{");
visit(path.getID(), sb);
sb.append("}");
return sb;
}
@Override
public StringBuilder visit(Path.MapIndex path, StringBuilder sb) {
dispatch(parentOf(path), this, sb);
switch (path.getKeyCase()) {
case BOX:
return sb.append("[").append(Formatter.toString(path.getBox(), null, true)).append("]");
default:
return sb.append("[??]");
}
}
@Override
public StringBuilder visit(Path.Memory path, StringBuilder sb) {
visit(path.getAfter(), sb)
.append(".memory(")
.append("pool:").append(path.getPool()).append(',')
.append(Long.toHexString(path.getAddress())).append('[').append(path.getSize()).append(']');
if (path.getExcludeData()) sb.append(",nodata");
if (path.getExcludeObserved()) sb.append(",noobs");
return sb.append(')');
}
@Override
public StringBuilder visit(Path.Mesh path, StringBuilder sb) {
visit(path.getCommand(), sb).append(".mesh(");
if (path.getOptions().getFaceted()) sb.append("faceted");
return sb.append(')');
}
@Override
public StringBuilder visit(Path.Parameter path, StringBuilder sb) {
return visit(path.getCommand(), sb).append(".").append(path.getName());
}
@Override
public StringBuilder visit(Path.Report path, StringBuilder sb) {
visit(path.getCapture(), sb).append(".report");
if (path.hasDevice()) {
sb.append('[');
visit(path.getDevice(), sb);
sb.append(']');
}
return sb;
}
@Override
public StringBuilder visit(Path.ResourceData path, StringBuilder sb) {
visit(path.getAfter(), sb).append(".resource{");
visit(path.getID(), sb).append("}");
return sb;
}
@Override
public StringBuilder visit(Path.Resources path, StringBuilder sb) {
return visit(path.getCapture(), sb).append(".resources");
}
@Override
public StringBuilder visit(Path.Result path, StringBuilder sb) {
return visit(path.getCommand(), sb).append(".<result>");
}
@Override
public StringBuilder visit(Path.Slice path, StringBuilder sb) {
return dispatch(parentOf(path), this, sb)
.append("[")
.append(path.getStart())
.append(":")
.append(path.getEnd())
.append("]");
}
@Override
public StringBuilder visit(Path.State path, StringBuilder sb) {
return visit(path.getAfter(), sb).append(".state");
}
@Override
public StringBuilder visit(Path.StateTree path, StringBuilder sb) {
visit(path.getState(), sb).append(".tree");
if (path.getArrayGroupSize() > 0) {
sb.append("(groupSize=").append(path.getArrayGroupSize()).append(')');
}
return sb;
}
@Override
public StringBuilder visit(Path.StateTreeNode path, StringBuilder sb) {
sb.append("stateTree{");
visit(path.getTree(), sb);
return sb.append("}.node(")
.append(Formatter.index(path.getIndicesList()))
.append(")");
}
@Override
public StringBuilder visit(Path.StateTreeNodeForPath path, StringBuilder sb) {
sb.append("stateTree{");
visit(path.getTree(), sb);
return sb.append("}.path(")
.append(Paths.toString(path.getMember()))
.append(")");
}
@Override
public StringBuilder visit(Path.Thumbnail path, StringBuilder sb) {
dispatch(parentOf(path), this, sb)
.append(".thumbnail");
String sep = "(", end = "";
if (path.getDesiredMaxWidth() > 0) {
sb.append(sep).append("w=").append(path.getDesiredMaxWidth());
sep = ",";
end = ")";
}
if (path.getDesiredMaxHeight() > 0) {
sb.append(sep).append("h=").append(path.getDesiredMaxHeight());
sep = ",";
end = ")";
}
if (path.hasDesiredFormat()) {
sb.append(sep).append("f=").append(path.getDesiredFormat().getName()); // TODO
sep = ",";
end = ")";
}
return sb.append(end);
}
private StringBuilder append(StringBuilder sb, Path.CommandFilter filter) {
String sep = "(", end = "";
if (filter.getThreadsCount() > 0) {
sb.append(sep).append("threads=").append(filter.getThreadsList());
sep = ",";
end = ")";
}
return sb.append(end);
}
};
}
| 412 | 0.952668 | 1 | 0.952668 | game-dev | MEDIA | 0.650011 | game-dev | 0.967714 | 1 | 0.967714 |
Open-KO/KnightOnline | 4,664 | Client/WarFare/PlayerNPC.cpp | // PlayerNPC.cpp: implementation of the CPlayerNPC class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "PlayerNPC.h"
#include "GameProcMain.h"
#include "N3WorldManager.h"
#include "PlayerMySelf.h"
#include <N3Base/N3Shape.h>
#include <N3Base/N3ShapeMgr.h>
#include <N3Base/N3SndObj.h>
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CPlayerNPC::CPlayerNPC()
{
m_ePlayerType = PLAYER_NPC; // Player Type ... Base, NPC, OTher, MySelf
m_vPosFromServer = m_Chr.Pos(); // 서버에게 받은 위치.
}
CPlayerNPC::~CPlayerNPC()
{
}
void CPlayerNPC::Tick()
{
if(m_pShapeExtraRef) // 오브젝트이면..
{
CPlayerBase::Tick();
return;
}
if(m_fTimeAfterDeath > 0) // 죽어야하거나 죽은 넘이면...
{
if(m_fTimeAfterDeath > 3.0f)
this->Action(PSA_DYING, false); // 5 초가 지나야 죽는다.
CPlayerBase::Tick(); // 회전, 지정된 에니메이션 Tick 및 색깔 지정 처리.. 등등..
return;
}
__Vector3 vPos = m_Chr.Pos();
if( m_vPosFromServer.x != vPos.x || m_vPosFromServer.z != vPos.z ) // 조금 더 가야한다.
{
if(m_fMoveSpeedPerSec == 0)
{
__Vector3 vT1(m_vPosFromServer.x, 0, m_vPosFromServer.z), vT2(vPos.x, 0, vPos.z);
m_fMoveSpeedPerSec = (vT2 - vT1).Magnitude();
}
__Vector3 vOffset = m_vPosFromServer - vPos; vOffset.y = 0;
__Vector3 vDir = vOffset; vDir.Normalize(); // 방향..
float fSpeedAbsolute = (m_fMoveSpeedPerSec > 0) ? m_fMoveSpeedPerSec : -m_fMoveSpeedPerSec; // 속도 절대값
float fDist = vOffset.Magnitude(); // 거리
if(fDist < fSpeedAbsolute * CN3Base::s_fSecPerFrm) // 움직이는 거리가 거의 다온거면..
{
vPos.x = m_vPosFromServer.x; // 위치를 고정해주고..
vPos.z = m_vPosFromServer.z; // 위치를 고정해주고..
// m_fMoveSpeedPerSec = 0; // 움직이는 속도를 0으로!
this->ActionMove(PSM_STOP); // 움직이는 모션 처리..
}
else
{
float fYaw = (m_fMoveSpeedPerSec < 0) ? ::_Yaw2D(-vDir.x, -vDir.z) : ::_Yaw2D(vDir.x, vDir.z); // 방향을 계산해서..
this->RotateTo(fYaw, false); // 진행 방향으로 돌리고..
e_StateMove eMove = PSM_STOP; // 움직임...
// 플레이어면 걷는 속도가 기준 나머지는 덩치에 반비례..
float fStandWalk = ((PLAYER_OTHER == m_ePlayerType) ? (MOVE_SPEED_WHEN_WALK * 2.0f) : (MOVE_SPEED_WHEN_WALK * m_Chr.Radius() * 2.0f));
if(m_fMoveSpeedPerSec < 0) eMove = PSM_WALK_BACKWARD; // 뒤로 걷기..
else if(m_fMoveSpeedPerSec < fStandWalk) eMove = PSM_WALK; // 앞으로 걷기..
else eMove = PSM_RUN; // if(fDN > 5.0f) // 다음 위치의 거리가 일정 이상이면 뛰어간다.
this->ActionMove(eMove); // 움직이는 모션 처리..
vPos += vDir * (fSpeedAbsolute * s_fSecPerFrm); // 이동..
}
float fYTerrain = ACT_WORLD->GetHeightWithTerrain(vPos.x, vPos.z); // 지면의 높이값..
float fYMesh = ACT_WORLD->GetHeightNearstPosWithShape(vPos, 1.0f); // 충돌 체크 오브젝트의 높이값..
if(fYMesh != -FLT_MAX && fYMesh > fYTerrain && fYMesh < m_fYNext + 1.0f) m_fYNext = fYMesh; // 올라갈수 있는 오브젝트이고 높이값이 지면보다 높으면.
else m_fYNext = fYTerrain;
this->PositionSet(vPos, false); // 위치 최종 적용..
}
// 공격 중이거나 스킬 사용중이면..
if (PSA_ATTACK == m_eState
|| PSA_SPELLMAGIC == m_eState)
{
CPlayerBase* pTarget = this->TargetPointerCheck(false);
CPlayerBase::ProcessAttack(pTarget); // 공격에 관한 루틴 처리.. 에니메이션 세팅과 충돌만 처리할뿐 패킷은 처리 안한다..
}
CPlayerBase::Tick(); // 회전. 이동, 에니메이션 틱.. 상태 바뀜 등을 처리한다.
}
void CPlayerNPC::MoveTo(float fPosX, float fPosY, float fPosZ, float fSpeed, int iMoveMode)
{
m_vPosFromServer.Set(fPosX, fPosY, fPosZ);
if(m_pShapeExtraRef) return; // 오브젝트 형식이면 움직일수가 없다..
// iMoveMode : 현재 움직이는 상태.. 0 -정지 1 움직임시작 2 - 1초마다 한번 연속움직임..
if(0 == iMoveMode)
{
}
else if(iMoveMode) // 움직임 시작.. // 계속 움직임
{
m_fMoveSpeedPerSec = fSpeed;
__Vector3 vPos = m_Chr.Pos(); vPos.y = 0;
__Vector3 vPosS(fPosX, 0, fPosZ);
if(fSpeed) m_fMoveSpeedPerSec *= ((vPosS - vPos).Magnitude() / (fSpeed * PACKET_INTERVAL_MOVE)) * 0.85f; // 속도보간.. 동기화때문에 그런다.. 약간 줄여주는 이유는 멈칫하는걸 방지하기 위해서이다..
else m_fMoveSpeedPerSec = ((vPosS - vPos).Magnitude() / (fSpeed * PACKET_INTERVAL_MOVE)) * 0.85f; // 속도보간.. 동기화때문에 그런다.. 약간 줄여주는 이유는 멈칫하는걸 방지하기 위해서이다..
if(fSpeed < 0) m_fMoveSpeedPerSec *= -1.0f; // 뒤로 간다..
}
else
{
// __ASSERT(0, "Invalid Move Mode");
}
}
void CPlayerNPC::SetSoundAndInitFont(uint32_t dwFontFlag)
{
CPlayerBase::SetSoundAndInitFont(dwFontFlag);
if (s_pPlayer->m_InfoBase.iAuthority == AUTHORITY_MANAGER)
{
// NOTE: Type is the AI state (not the NPC's type as you'd expect), but it's not sent at all here,
// and is rarely ever even sent officially, so we'll just placeholder it to 0 for now.
std::string szInfo = fmt::format("ID({}) : TYPE({})", m_InfoBase.iID, 0);
InfoStringSet(szInfo, D3DCOLOR_XRGB(0, 255, 0));
}
}
| 412 | 0.786977 | 1 | 0.786977 | game-dev | MEDIA | 0.946213 | game-dev | 0.971438 | 1 | 0.971438 |
amazon-gamelift/amazon-gamelift-plugin-unreal | 20,846 | GameLiftPlugin/Source/GameLiftCore/Private/AWSScenariosDeployer.cpp | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
#include "AWSScenariosDeployer.h"
#include "Misc/FileHelper.h"
#include "Misc/EngineVersionComparison.h"
#include "aws/gamelift/core/exports.h"
#include "aws/gamelift/core/errors.h"
#include "GameLiftCoreLog.h"
#include "GameLiftCoreConstants.h"
#include "AwsAccount/AwsAccountCredentials.h"
#include "AwsAccount/AwsAccountInstanceManager.h"
#include "AwsAccount/AwsAccountInfo.h"
#include "Utils/StringPaths.h"
#include "Utils/StringConvertors.h"
#include "Utils/LogMessageStorage.h"
#include "Utils/NativeLogPrinter.h"
#include "Utils/UnrealVersion.h"
#include "AwsErrors/Converter.h"
#include "AwsScenarios/ContainerFlexMatch.h"
#include "AwsScenarios/ContainerSingleRegionFleet.h"
#include "AwsScenarios/FlexMatch.h"
#include "AwsScenarios/SingleRegionFleet.h"
#include "AwsScenarios/CustomScenario.h"
#define LOCTEXT_NAMESPACE "AWSScenariosDeployer"
namespace AwsDeployerInternal
{
static Logs::MessageStorage sLatestDeploymentLogErrorMessage = {};
void LogCallback(unsigned int InLevel, const char* InMessage, int InSize)
{
auto Level = Logs::PrintAwsLog(InLevel, InMessage, InSize, Deploy::Logs::kLogReceived);
if (Level == ELogVerbosity::Error)
{
sLatestDeploymentLogErrorMessage.Set(InMessage);
}
}
void ReceiveReplacementId(DISPATCH_RECEIVER_HANDLE DispatchReceiver, const char* ReplacementId)
{
UE_LOG(GameLiftCoreLog, Verbose, TEXT("%s %s"), Deploy::Logs::kReceiveReplacementIdCallback, *Convertors::ASToFS(ReplacementId));
((AWSScenariosDeployer*)DispatchReceiver)->SetMainFunctionsReplacementId(ReplacementId);
}
void ReceiveClientConfigPath(DISPATCH_RECEIVER_HANDLE DispatchReceiver, const char* ConfigPath)
{
UE_LOG(GameLiftCoreLog, Verbose, TEXT("%s %s"), Deploy::Logs::kReceiveClientConfigPathCallback, *Convertors::ASToFS(ConfigPath));
((AWSScenariosDeployer*)DispatchReceiver)->SetClientConfigPath(ConfigPath);
}
auto BuildAwsScenarios(const IAWSScenariosCategory Category)
{
TMap<FString, TUniquePtr<AwsScenarios::IAWSScenario>> ScenarioMap;
switch (Category)
{
case IAWSScenariosCategory::ManagedEC2:
{
ScenarioMap.Add(AwsScenarios::SingleRegionFleet::Name().ToString(),
AwsScenarios::SingleRegionFleet::Create());
ScenarioMap.Add(AwsScenarios::FlexMatch::Name().ToString(),
AwsScenarios::FlexMatch::Create());
break;
}
case IAWSScenariosCategory::Containers:
{
ScenarioMap.Add(AwsScenarios::ContainersSingleRegionFleet::Name().ToString(),
AwsScenarios::ContainersSingleRegionFleet::Create());
ScenarioMap.Add(AwsScenarios::ContainersFlexMatch::Name().ToString(),
AwsScenarios::ContainersFlexMatch::Create());
break;
}
}
return ScenarioMap;
}
const auto& GetAwsScenarios(const IAWSScenariosCategory Category)
{
static TMap<FString, TUniquePtr<AwsScenarios::IAWSScenario>>
ManagedEC2ScenarioMap(BuildAwsScenarios(IAWSScenariosCategory::ManagedEC2));
static TMap<FString, TUniquePtr<AwsScenarios::IAWSScenario>>
ContainersScenarioMap(BuildAwsScenarios(IAWSScenariosCategory::Containers));
switch (Category)
{
case IAWSScenariosCategory::ManagedEC2:
{
return ManagedEC2ScenarioMap;
}
case IAWSScenariosCategory::Containers:
{
return ContainersScenarioMap;
}
default:
{
static TMap<FString, TUniquePtr<AwsScenarios::IAWSScenario>> DefaultMap = {};
return DefaultMap;
}
}
}
AwsScenarios::IAWSScenario* GetAwsScenarioByName(const FText& ScenarioName, const IAWSScenariosCategory Category)
{
auto Invariant = FText::AsCultureInvariant(ScenarioName);
return GetAwsScenarios(Category).FindChecked(Invariant.ToString()).Get();
}
FString ExtractYamlValue(const TArray<FString>& YamlStrings, const char* Name)
{
for (const FString& Line : YamlStrings)
{
auto FoundPosition = Line.Find(Name);
if (FoundPosition >= 0)
{
FoundPosition += strlen(Name);
return Line.RightChop(FoundPosition + 1);
}
}
return FString();
}
class ResourcesInstanceGuard
{
public:
ResourcesInstanceGuard(IAWSAccountInstance* AwsAccountInstance) :
Instance(GameLiftAccountCreateGameLiftResourcesInstance(AwsAccountInstance->GetInstance()))
{
}
~ResourcesInstanceGuard()
{
GameLiftResourcesInstanceRelease(Instance);
}
GAMELIFT_FEATURERESOURCES_INSTANCE_HANDLE Get()
{
return Instance;
}
private:
GAMELIFT_FEATURERESOURCES_INSTANCE_HANDLE Instance;
};
bool IsDeployedSuccessfully(const std::string& StackStatus)
{
static std::unordered_set<std::string> SuccessfulStatuses
{
Aws::Status::kStackUpdateComplete, Aws::Status::kStackCreateComplete
};
return SuccessfulStatuses.find(StackStatus) != SuccessfulStatuses.end();
}
} // namespace AwsDeployerInternal
void AWSScenariosDeployer::SetMainFunctionsReplacementId(const char* ReplacementId)
{
MainFunctionsReplacementId = ReplacementId;
}
void AWSScenariosDeployer::SetClientConfigPath(const char* ConfigPath)
{
ClientConfigPath = Convertors::ASToFS(ConfigPath);
}
void AWSScenariosDeployer::SetLastCognitoClientId(const FString& ClientId)
{
LastCognitoClientId = ClientId;
}
void AWSScenariosDeployer::SetLastApiGatewayEndpoint(const FString& ApiGateway)
{
LastApiGatewayEndpoint = ApiGateway;
}
/**
* Returns the Unreal Engine version used to package the game server build
*
* @param AwsAccountInstance Pointer to AwsAccountInstance to call APIs
* @param BuildFilePath Path to the packaged game server executable
* @return PackagedVersion Unreal Engine version used to package the game server build
*/
UnrealVersion::Version GetUnrealPackagedBuildVersion(IAWSAccountInstance* AwsAccountInstance, const FString& BuildFilePath)
{
AwsDeployerInternal::ResourcesInstanceGuard ResourcesInstance(AwsAccountInstance);
std::string ExecutablePath = Convertors::FSToStdS(BuildFilePath);
FString PackagedVersionString = Convertors::ASToFS(GameLiftResourcesGetUnrealPackagedBuildVersion(ResourcesInstance.Get(), ExecutablePath));
UnrealVersion::Version PackagedVersion = UnrealVersionUtils::ParseVersionString(PackagedVersionString);
if (PackagedVersion == UnrealVersion::INVALID_VERSION) {
// We failed to determine version, proceed with deployment without copying dependencies
UE_LOG(GameLiftCoreLog, Log, TEXT("Failed to determine version from %s"), *BuildFilePath);
}
else {
UE_LOG(GameLiftCoreLog, Log, TEXT("Detected game server build packaged with Unreal Version %s from game server executable path %s"),
*UnrealVersionUtils::GetVersionString(PackagedVersion), *BuildFilePath);
}
return PackagedVersion;
}
/**
* Sets extra server resources path for older Unreal Engine versions if needed
* For UE versions older than 5.6.0, we need to copy additional dependencies
*
* @param ExtraServerResources Path Path to the extra resources that may need to be copied
* @param Params Deployment parameters to be updated with extra resources path if needed
* @return True if extra server resources path was set
*/
bool SetExtraServerResourcesPath(UnrealVersion::Version PackagedVersion, const FString& ExtraServerResourcesPath, AwsScenarios::ManagedEC2InstanceTemplateParams& Params)
{
// UE5.6.0 does not require extra dependencies
if (PackagedVersion < UnrealVersion::UE5_6_0) {
UE_LOG(GameLiftCoreLog, Log, TEXT("Required dependencies will automatically be copied from %s since game server packaged version is < 5.6.0"),
*ExtraServerResourcesPath);
Params.ExtraServerResourcesPath = Convertors::FSToStdS(ExtraServerResourcesPath);
return true;
}
return false;
}
bool AWSScenariosDeployer::DeployManagedEC2Scenario(
const FText& Scenario,
IAWSAccountInstance* AwsAccountInstance,
const FString& GameName,
const FString& BuildOperatingSystem,
const FString& BuildFolderPath,
const FString& BuildFilePath,
const FString& OutConfigFilePath,
const FString& ExtraServerResourcesPath
)
{
UE_LOG(GameLiftCoreLog, Log, TEXT("%s %s"), Deploy::Logs::kRunAwsScenario, *Scenario.ToString());
AwsScenarios::IAWSScenario* BaseAwsScenario = AwsDeployerInternal::GetAwsScenarioByName(Scenario, IAWSScenariosCategory::ManagedEC2);
AwsScenarios::ScenarioWithGameServer* AwsScenario = static_cast<AwsScenarios::ScenarioWithGameServer*>(BaseAwsScenario);
std::string stdLaunchPathParameter;
AwsScenario->CreateLaunchPathParameter(BuildOperatingSystem, BuildFolderPath, BuildFilePath, stdLaunchPathParameter);
AwsScenarios::ManagedEC2InstanceTemplateParams Params;
Params.GameNameParameter = Convertors::FSToStdS(GameName);
Params.BuildFolderPath = Convertors::FSToStdS(BuildFolderPath);
UnrealVersion::Version PackagedVersion = GetUnrealPackagedBuildVersion(AwsAccountInstance, BuildFilePath);
SetExtraServerResourcesPath(PackagedVersion, ExtraServerResourcesPath, Params);
Params.BuildOperatingSystemParameter = Convertors::FSToStdS(BuildOperatingSystem);
Params.LaunchPathParameter = stdLaunchPathParameter;
return DeployScenarioImpl(AwsAccountInstance, AwsScenario, Params, OutConfigFilePath);
}
bool AWSScenariosDeployer::DeployCustomScenario(
const FString& CustomScenarioPath,
IAWSAccountInstance* AwsAccountInstance,
const FString& GameName,
const FString& BuildOperatingSystem,
const FString& BuildFolderPath,
const FString& BuildFilePath,
const FString& OutConfigFilePath,
const FString& ExtraServerResourcesPath
)
{
UE_LOG(GameLiftCoreLog, Log, TEXT("%s %s"), Deploy::Logs::kRunCustomScenario, *CustomScenarioPath);
TUniquePtr<AwsScenarios::CustomScenario> AwsScenario = AwsScenarios::CustomScenario::Create(CustomScenarioPath);
std::string stdLaunchPathParameter;
AwsScenario->CreateLaunchPathParameter(BuildOperatingSystem, BuildFolderPath, BuildFilePath, stdLaunchPathParameter);
AwsScenarios::ManagedEC2InstanceTemplateParams Params;
Params.GameNameParameter = Convertors::FSToStdS(GameName);
Params.BuildFolderPath = Convertors::FSToStdS(BuildFolderPath);
Params.ExtraServerResourcesPath = Convertors::FSToStdS(ExtraServerResourcesPath);
Params.BuildOperatingSystemParameter = Convertors::FSToStdS(BuildOperatingSystem);
Params.LaunchPathParameter = stdLaunchPathParameter;
return DeployScenarioImpl(AwsAccountInstance, AwsScenario.Get(), Params, OutConfigFilePath);
}
bool AWSScenariosDeployer::DeployContainerScenario(
const FText& Scenario, IAWSAccountInstance* AwsAccountInstance, const FString& ContainerGroupDefinitionName,
const FString& ContainerImageName, const FString& ContainerImageUri, const FString& IntraContainerLaunchPath,
const FString& GameName, const FString& OutConfigFilePath, const FText& ConnectionPortRange, const FString& TotalVcpuLimit,
const FString& TotalMemoryLimit)
{
AwsScenarios::IAWSScenario* AwsScenario = AwsDeployerInternal::GetAwsScenarioByName(
Scenario,
IAWSScenariosCategory::Containers);
auto StdBootstrapBucketName = Convertors::FSToStdS(AwsAccountInstance->GetBucketName());
AwsScenarios::ContainerInstanceTemplateParams Params;
Params.GameNameParameter = Convertors::FSToStdS(GameName);
Params.ContainerGroupDefinitionNameParameter = Convertors::FSToStdS(ContainerGroupDefinitionName);
Params.ContainerImageNameParameter = Convertors::FSToStdS(ContainerImageName);
Params.ContainerImageUriParameter = Convertors::FSToStdS(ContainerImageUri);
Params.LaunchPathParameter = Convertors::FSToStdS(IntraContainerLaunchPath);
FString FleetUdpFromPort;
FString FleetUdpToPort;
ConnectionPortRange.ToString().Split("-", &FleetUdpFromPort, &FleetUdpToPort);
Params.FleetUdpFromPortParameter = Convertors::FSToStdS(FleetUdpFromPort);
Params.FleetUdpToPortParameter = Convertors::FSToStdS(FleetUdpToPort);
Params.TotalVcpuLimitParameter = Convertors::FSToStdS(TotalVcpuLimit);
Params.TotalMemoryLimitParameter = Convertors::FSToStdS(TotalMemoryLimit);
return DeployScenarioImpl(AwsAccountInstance, AwsScenario, Params, OutConfigFilePath);
}
bool AWSScenariosDeployer::StopDeployment(IAWSAccountInstance* AwsAccountInstance)
{
UE_LOG(GameLiftCoreLog, Log, TEXT("%s"), Deploy::Logs::kDeploymentStop);
AwsDeployerInternal::sLatestDeploymentLogErrorMessage.Clear();
if (!AwsAccountInstance->IsValid())
{
AwsDeployerInternal::sLatestDeploymentLogErrorMessage.Set(Deploy::Errors::kAccountIsInvalidText);
return false;
}
AwsDeployerInternal::ResourcesInstanceGuard ResourcesInstance(AwsAccountInstance);
std::string StackStatus = GameLiftResourcesGetCurrentStackStatus(ResourcesInstance.Get());
if (StackStatus.compare(Aws::Status::kStackUndeployed) == 0)
{
AwsDeployerInternal::sLatestDeploymentLogErrorMessage.Set(Deploy::Errors::kNoStacksToStopDeployment);
return false;
}
ShouldBeStopped = true;
bool IsStopped = GameLiftResourcesInstanceCancelUpdateStack(ResourcesInstance.Get()) == GameLift::GAMELIFT_SUCCESS;
if (!IsStopped)
{
AwsDeployerInternal::sLatestDeploymentLogErrorMessage.Set(Deploy::Errors::kUnableToStopDeployment);
}
return IsStopped;
}
bool AWSScenariosDeployer::DeployScenarioImpl(
IAWSAccountInstance* AwsAccountInstance,
AwsScenarios::IAWSScenario* AwsScenario,
AwsScenarios::BaseInstanceTemplateParams& Params,
const FString& OutConfigFilePath
)
{
constexpr auto DeployAbortResult = false;
constexpr auto DeployCompletedResult = true;
AwsDeployerInternal::sLatestDeploymentLogErrorMessage.Clear();
ShouldBeStopped = false;
auto AccountHandle = AwsAccountInstance->GetInstance();
if (AccountHandle == nullptr)
{
AwsDeployerInternal::sLatestDeploymentLogErrorMessage.Set(Deploy::Errors::kAccountIsInvalidText);
LastAwsError = GameLift::GAMELIFT_ERROR_GENERAL;
UE_LOG(GameLiftCoreLog, Error, TEXT("%s"), Deploy::Logs::kAccountInstanceIsNull);
return DeployAbortResult;
}
if (Params.GameNameParameter.size() > Deploy::kMaxGameNameWithPrefixLength)
{
AwsDeployerInternal::sLatestDeploymentLogErrorMessage.Set(Deploy::Errors::kGameNameIsTooLongText);
LastAwsError = GameLift::GAMELIFT_ERROR_GENERAL;
return DeployAbortResult;
}
GameLiftAccountSetGameName(AccountHandle, Params.GameNameParameter.c_str());
auto ScenarioPath = AwsScenario->GetScenarioPath();
auto StdScenarioPath = Convertors::FSToStdS(ScenarioPath);
GameLiftAccountSetPluginRootPath(AccountHandle, StdScenarioPath.c_str());
auto ScenarioInstancePath = AwsScenario->GetScenarioInstancePath();
auto StdScenarioInstancePath = Convertors::FSToStdS(ScenarioInstancePath);
GameLiftAccountSetRootPath(AccountHandle, StdScenarioInstancePath.c_str());
std::string StdAwsAccountId = GameLiftGetAwsAccountIdByAccountInstance(AccountHandle);
if (ShouldBeStopped)
{
LastAwsError = GameLift::GAMELIFT_ERROR_GENERAL;
UE_LOG(GameLiftCoreLog, Error, TEXT("%s"), Deploy::Logs::kDeploymentHasBeenStopped);
return DeployAbortResult;
}
auto ShouldDeployBeAborted = [this](int ErrorCode, auto&& ErrorDebugString)
{
LastAwsError = ErrorCode;
if (LastAwsError != GameLift::GAMELIFT_SUCCESS)
{
UE_LOG(GameLiftCoreLog, Error, TEXT("%s %s"), ErrorDebugString, *GameLiftErrorAsString::Convert(LastAwsError));
return true;
}
if (ShouldBeStopped)
{
LastAwsError = GameLift::GAMELIFT_ERROR_GENERAL;
UE_LOG(GameLiftCoreLog, Error, TEXT("%s"), Deploy::Logs::kDeploymentHasBeenStopped);
return true;
}
return false;
};
if (ShouldDeployBeAborted(GameLiftAccountCreateAndSetFunctionsReplacementId(AccountHandle), Deploy::Logs::kCreateAndSetFunctionsReplacementIdFailed))
{
return DeployAbortResult;
}
if (ShouldDeployBeAborted(GameLiftAccountGetMainFunctionsReplacementId(AccountHandle, this, AwsDeployerInternal::ReceiveReplacementId),
Deploy::Logs::kGetMainFunctionsReplacementIdFailed))
{
return DeployAbortResult;
}
auto StdBootstrapBucketName = Convertors::FSToStdS(AwsAccountInstance->GetBucketName());
if (ShouldDeployBeAborted(AwsScenario->UploadGameServer(AwsAccountInstance, Params.BuildFolderPath.c_str(), Params.ExtraServerResourcesPath.c_str()),
Deploy::Logs::kUploadGameServerFailed))
{
return DeployAbortResult;
}
Params.AccountId = StdAwsAccountId;
Params.ApiGatewayStageNameParameter = AwsAccountInstance->GetBuildConfiguration();
Params.BuildS3BucketParameter = StdBootstrapBucketName;
Params.LambdaZipS3BucketParameter = StdBootstrapBucketName;
Params.LambdaZipS3KeyParameter = AwsScenarios::GetLambdaS3Key(Params.GameNameParameter, MainFunctionsReplacementId);
Params.UnrealEngineVersionParameter = Convertors::FSToStdS(UnrealVersionUtils::GetCurrentEngineVersion());
if (ShouldDeployBeAborted(AwsScenario->SaveFeatureInstanceTemplate(AwsAccountInstance, Params.ToMap()),
Deploy::Logs::kSaveFeatureInstanceTemplatesFailed))
{
return DeployAbortResult;
}
if (ShouldDeployBeAborted(GameLiftAccountUploadFunctions(AccountHandle), Deploy::Logs::kAccountUploadFunctionsFailed))
{
return DeployAbortResult;
}
if (ShouldDeployBeAborted(GameLiftAccountCreateOrUpdateMainStack(AccountHandle), Deploy::Logs::kCreateOrUpdateMainStackFailed))
{
return DeployAbortResult;
}
if (ShouldDeployBeAborted(GameLiftAccountDeployApiGatewayStage(AccountHandle), Deploy::Logs::kDeployApiGatewayStageFailed))
{
return DeployAbortResult;
}
if (ShouldDeployBeAborted(UpdateDeploymentResults(AwsAccountInstance, ScenarioInstancePath, FString(Params.GameNameParameter.c_str()), AwsAccountInstance->GetBucketName(), OutConfigFilePath),
Deploy::Logs::kDeploymentStackStatusFailed))
{
return DeployAbortResult;
}
return DeployCompletedResult;
}
int AWSScenariosDeployer::UpdateDeploymentResults(IAWSAccountInstance* AwsAccountInstance, const FString& ScenarioInstancePath, const FString& GameName, const FString& BucketName, const FString& OutConfigFilePath)
{
AwsDeployerInternal::ResourcesInstanceGuard ResourcesInstance(AwsAccountInstance);
// Result will be stored to ClientConfigPath with sync call.
GameLiftResourcesGetInstanceClientConfigPath(ResourcesInstance.Get(), this, AwsDeployerInternal::ReceiveClientConfigPath);
std::string StackStatus = GameLiftResourcesGetCurrentStackStatus(ResourcesInstance.Get());
UE_LOG(GameLiftCoreLog, Log, TEXT("%s %s"), Deploy::Logs::kDeploymentStackStatus, *Convertors::ASToFS(StackStatus.c_str()));
auto CurrentScenarioInstancePath = Paths::ScenarioInstancePath(Menu::DeploymentServer::kCurrentScenarioFolder);
FString ConfigPathPart, ConfigFilenamePart, ConfigExtensionPart;
FPaths::Split(ClientConfigPath, ConfigPathPart, ConfigFilenamePart, ConfigExtensionPart);
IPlatformFile& PlatformFile = FPlatformFileManager::Get().GetPlatformFile();
PlatformFile.DeleteDirectoryRecursively(*CurrentScenarioInstancePath);
PlatformFile.CopyDirectoryTree(*CurrentScenarioInstancePath, *ConfigPathPart, true);
FString DestinationFileName = ConfigFilenamePart + "." + ConfigExtensionPart;
PlatformFile.CreateDirectoryTree(*OutConfigFilePath);
PlatformFile.CopyFile(*FPaths::Combine(OutConfigFilePath, DestinationFileName), *ClientConfigPath);
FString UUID;
FString Temp;
BucketName.Split("-", &Temp, &UUID, ESearchCase::IgnoreCase, ESearchDir::FromEnd);
FString Region;
Temp.Split("-", &Temp, &Region, ESearchCase::IgnoreCase, ESearchDir::FromEnd);
FString DestinationFileNameExtra = GameName + "_" + UUID + "_" + Region + "_" + ConfigFilenamePart + "." + ConfigExtensionPart;
PlatformFile.CopyFile(*FPaths::Combine(OutConfigFilePath, DestinationFileNameExtra), *ClientConfigPath);
TArray<FString> YamlStrings;
FFileHelper::LoadANSITextFileToStrings(*ClientConfigPath, NULL, YamlStrings);
LastCognitoClientId = AwsDeployerInternal::ExtractYamlValue(YamlStrings, Aws::Config::kUserPoolClientIdYamlName).TrimStartAndEnd();
LastApiGatewayEndpoint = AwsDeployerInternal::ExtractYamlValue(YamlStrings, Aws::Config::kApiGatewayEndpointYamlName).TrimStartAndEnd();
return AwsDeployerInternal::IsDeployedSuccessfully(StackStatus) ?
GameLift::GAMELIFT_SUCCESS : GameLift::GAMELIFT_ERROR_GENERAL;
}
FString AWSScenariosDeployer::GetLastCognitoClientId() const
{
return LastCognitoClientId;
}
FString AWSScenariosDeployer::GetLastApiGatewayEndpoint() const
{
return LastApiGatewayEndpoint;
}
FString AWSScenariosDeployer::GetLastError() const
{
return GameLiftErrorAsString::Convert(LastAwsError);
}
FString AWSScenariosDeployer::GetLastErrorMessage() const
{
return AwsDeployerInternal::sLatestDeploymentLogErrorMessage.Get();
}
TArray<FText> AWSScenariosDeployer::GetScenarios(const IAWSScenariosCategory Category) const
{
TArray<FText> Result;
const auto& Scenarios = AwsDeployerInternal::GetAwsScenarios(Category);
Result.Reserve(Scenarios.Num());
for (const auto& Item : Scenarios)
{
Result.Add(Item.Value->GetUserName());
}
return Result;
}
FText AWSScenariosDeployer::GetToolTip(const FText& ScenarioName, const IAWSScenariosCategory Category) const
{
return AwsDeployerInternal::GetAwsScenarioByName(ScenarioName, Category)->GetTooltip();
}
#undef LOCTEXT_NAMESPACE | 412 | 0.914021 | 1 | 0.914021 | game-dev | MEDIA | 0.412207 | game-dev | 0.804009 | 1 | 0.804009 |
spiffcode/hostile-takeover | 1,332 | AniMax/UndoManager.cs | using System;
using System.Collections;
using System.Diagnostics;
namespace SpiffCode {
public delegate void UndoDelegate(object[] aobArgs);
public class UndoManager {
private static Stack s_stk = new Stack();
private static int s_cElements;
private static bool s_fGrouping = false;
public static void AddUndo(UndoDelegate dgtUndo, object[] aobArgs) {
if (s_fGrouping)
s_cElements++;
s_stk.Push(aobArgs);
s_stk.Push(dgtUndo);
}
public static void Flush() {
s_stk.Clear();
}
public static void Undo() {
if (s_stk.Count == 0)
return;
UndoDelegate dgtUndo;
object[] aobArgs;
object ob = s_stk.Pop();
if (ob is int) {
int cElements = (int)ob;
for (int i = 0; i < cElements; i++) {
dgtUndo = (UndoDelegate)s_stk.Pop();
aobArgs = (object[])s_stk.Pop();
dgtUndo(aobArgs);
}
return;
}
dgtUndo = (UndoDelegate)ob;
aobArgs = (object[])s_stk.Pop();
dgtUndo(aobArgs);
}
public static void Redo() {
// UNDONE:
}
public static bool AnyUndos() {
return s_stk.Count != 0;
}
// WARNING: can't do nested groups
public static void BeginGroup() {
Debug.Assert(!s_fGrouping);
s_fGrouping = true;
s_cElements = 0;
}
public static void EndGroup() {
s_fGrouping = false;
s_stk.Push(s_cElements);
}
}
}
| 412 | 0.527243 | 1 | 0.527243 | game-dev | MEDIA | 0.294241 | game-dev | 0.648068 | 1 | 0.648068 |
cocoatoucher/Glide | 4,387 | Sources/Components/Ability/DasherComponent.swift | //
// DasherComponent.swift
// glide
//
// Copyright (c) 2019 cocoatoucher user on github.com (https://github.com/cocoatoucher/)
//
// 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.
//
import GameplayKit
/// Component that makes an entity gain extra horizontal speed which will
/// last until taking a given distance.
public final class DasherComponent: GKComponent, GlideComponent {
public static let componentPriority: Int = 760
/// Horizontal velocity to apply for dashing.
public let velocity: CGFloat
/// Target distance to take during dashing. After reaching this distance
/// from start position, dashing stops.
public let distance: CGFloat
/// `true` if there was dashing in the last frame.
public private(set) var didDash: Bool = false
/// Set to `true` to perform a dash given that the other conditions are met.
/// If an entity has `PlayableCharacterComponent`, this property
/// is automatically set for this component where needed.
public var dashes: Bool = false
// MARK: - Initialize
/// Create a dasher component.
///
/// - Parameters:
/// - velocity: Horizontal velocity to apply for dashing.
/// - distance: Target distance to take during dashing.
public init(velocity: CGFloat, distance: CGFloat) {
self.velocity = velocity
self.distance = distance
super.init()
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func update(deltaTime seconds: TimeInterval) {
dashIfNeeded()
}
// MARK: - Private
/// Position that the dashing has started from.
private var startPosition: CGFloat = 0
/// Diretion for the dashing that will stay fixed until dashing stops.
private var direction: TransformNodeComponent.HeadingDirection = .right
private func dashIfNeeded() {
guard let transform = transform else {
return
}
if didDash == false && dashes {
startPosition = transform.node.position.x
direction = transform.headingDirection
}
if dashes {
let kinematicsBody = entity?.component(ofType: KinematicsBodyComponent.self)
kinematicsBody?.velocity.dx = (direction == .left) ? -velocity : velocity
if let collider = entity?.component(ofType: ColliderComponent.self) {
if collider.pushesLeftWall || collider.pushesRightWall {
endDashing()
}
}
switch direction {
case .right:
if transform.proposedPosition.x >= startPosition + distance {
endDashing()
}
case .left:
if transform.proposedPosition.x <= startPosition - distance {
endDashing()
}
}
}
}
private func endDashing() {
dashes = false
startPosition = 0
entity?.component(ofType: KinematicsBodyComponent.self)?.velocity.dx = 0
}
}
extension DasherComponent: StateResettingComponent {
public func resetStates() {
didDash = dashes
}
}
| 412 | 0.78345 | 1 | 0.78345 | game-dev | MEDIA | 0.817319 | game-dev | 0.853777 | 1 | 0.853777 |
aarcangeli/Serious-Sam-Android | 2,587 | Serious-Engine/Sources/Engine/Network/EntityHashing.h | /* Copyright (c) 2002-2012 Croteam Ltd.
This program is free software; you can redistribute it and/or modify
it under the terms of version 2 of the GNU General Public License as published by
the Free Software Foundation
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */
#ifndef SE_INCL_ENTITYHASHING_H
#define SE_INCL_ENTITYHASHING_H
#ifdef PRAGMA_ONCE
#pragma once
#endif
#include <Engine\Math\Types.h>
#include <Engine\Math\Placement.h>
#include <Engine\Templates\CommunicationInterface.h>
#include <Engine\Classes\MovableEntity.h>
struct CClientEntry {
//implementation
TIME ce_tmLastUpdated;
CPlacement3D ce_plLastSentPlacement;
CPlacement3D ce_plLastSentSpeed;
CClientEntry() {
ce_tmLastUpdated = -1.0f;
ce_plLastSentPlacement.pl_PositionVector = FLOAT3D(0,0,0);
ce_plLastSentPlacement.pl_OrientationAngle = ANGLE3D(0,0,0);
ce_plLastSentSpeed.pl_PositionVector = FLOAT3D(0,0,0);
ce_plLastSentSpeed.pl_OrientationAngle = ANGLE3D(0,0,0);
}
}
class CEntityHashItem {
// implementation
public:
ULONG ehi_ulEntityID;
CEntityPointer ehi_epEntityPointer;
CClientEntry ehi_ceClientEntries[SERVER_CLIENTS];
CEntityHashItem() {ehi_ulEntityID = -1;} // entity pointer will initialize itself to NULL
~CEntityItem() {}; // entity poiner will destroy itself and remove the reference
void WritePackedPlacement(CClientEntry &ceEntry,CNetworkMessage &nmMessage);
// interface
public:
BOOL ClientNeedsUpdate(INDEX iClient,CNetworkMessage &nmMessage);
};
#define VALUE_TYPE ULONG
#define TYPE CEntityHashItem
#define CHashTableSlot_TYPE CEntityHashTableSlot
#define CHashTable_TYPE CEntityHashTable
#include <Engine\Templates\HashTable.h>
class ENGINE_API CEntityHash {
// implementation
public:
CEntityHashTable eh_ehtHashTable;
CEntityHash();
~CEntityHash();
ULONG GetItemKey(ULONG ulEntityID) {return ulEntityID;}
ULONG GetItemValue(CEntityHashItem* ehiItem) {return ehiItem->ehi_ulUntityID;}
// interface
public:
BOOL ClientNeedsUpdate(INDEX iClient,ULONG ulEntityID,CNetworkMessage &nmMessage);
void AddEntity(CEntityPointer* penEntity);
void RemoveEntity(CEntityPointer* penEntity);
}
#endif // include
| 412 | 0.817881 | 1 | 0.817881 | game-dev | MEDIA | 0.392957 | game-dev | 0.502534 | 1 | 0.502534 |
magefree/mage | 1,731 | Mage.Sets/src/mage/cards/e/ErtaiTheCorrupted.java |
package mage.cards.e;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.common.SimpleActivatedAbility;
import mage.abilities.costs.common.SacrificeTargetCost;
import mage.abilities.costs.common.TapSourceCost;
import mage.abilities.costs.mana.ManaCostsImpl;
import mage.abilities.effects.common.CounterTargetEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.constants.SuperType;
import mage.constants.Zone;
import mage.filter.StaticFilters;
import mage.target.TargetSpell;
import java.util.UUID;
/**
* @author fireshoes
*/
public final class ErtaiTheCorrupted extends CardImpl {
public ErtaiTheCorrupted(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{2}{W}{U}{B}");
this.supertype.add(SuperType.LEGENDARY);
this.subtype.add(SubType.PHYREXIAN);
this.subtype.add(SubType.HUMAN);
this.subtype.add(SubType.WIZARD);
this.power = new MageInt(3);
this.toughness = new MageInt(4);
// {U}, {tap}, Sacrifice a creature or enchantment: Counter target spell.
Ability ability = new SimpleActivatedAbility(new CounterTargetEffect(), new ManaCostsImpl<>("{U}"));
ability.addCost(new TapSourceCost());
ability.addCost(new SacrificeTargetCost(StaticFilters.FILTER_PERMANENT_CREATURE_OR_ENCHANTMENT));
ability.addTarget(new TargetSpell());
this.addAbility(ability);
}
private ErtaiTheCorrupted(final ErtaiTheCorrupted card) {
super(card);
}
@Override
public ErtaiTheCorrupted copy() {
return new ErtaiTheCorrupted(this);
}
}
| 412 | 0.942582 | 1 | 0.942582 | game-dev | MEDIA | 0.984459 | game-dev | 0.990043 | 1 | 0.990043 |
DruidMech/UE4-CPP-Shooter-Series | 12,196 | Source Code Per Lesson/Section 14 - The Enemy Class/252 Explosive/Item.h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "Engine/DataTable.h"
#include "Item.generated.h"
UENUM(BlueprintType)
enum class EItemRarity : uint8
{
EIR_Damaged UMETA(DisplayName = "Damaged"),
EIR_Common UMETA(DisplayName = "Common"),
EIR_Uncommon UMETA(DisplayName = "Uncommon"),
EIR_Rare UMETA(DisplayName = "Rare"),
EIR_Legendary UMETA(DisplayName = "Legendary"),
EIR_MAX UMETA(DisplayName = "DefaultMAX")
};
UENUM(BlueprintType)
enum class EItemState : uint8
{
EIS_Pickup UMETA(DisplayName = "Pickup"),
EIS_EquipInterping UMETA(DisplayName = "EquipInterping"),
EIS_PickedUp UMETA(DisplayName = "PickedUp"),
EIS_Equipped UMETA(DisplayName = "Equipped"),
EIS_Falling UMETA(DisplayName = "Falling"),
EIS_MAX UMETA(DisplayName = "DefaultMAX")
};
UENUM(BlueprintType)
enum class EItemType : uint8
{
EIT_Ammo UMETA(DisplayName = "Ammo"),
EIT_Weapon UMETA(DisplayName = "Weapon"),
EIT_MAX UMETA(DisplayName = "DefaultMAX")
};
USTRUCT(BlueprintType)
struct FItemRarityTable : public FTableRowBase
{
GENERATED_BODY()
UPROPERTY(EditAnywhere, BlueprintReadWrite)
FLinearColor GlowColor;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
FLinearColor LightColor;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
FLinearColor DarkColor;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
int32 NumberOfStars;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
UTexture2D* IconBackground;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
int32 CustomDepthStencil;
};
UCLASS()
class SHOOTER_API AItem : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
AItem();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
/** Called when overlapping AreaSphere */
UFUNCTION()
void OnSphereOverlap(
UPrimitiveComponent* OverlappedComponent,
AActor* OtherActor,
UPrimitiveComponent* OtherComp,
int32 OtherBodyIndex,
bool bFromSweep,
const FHitResult& SweepResult);
/** Called when End Overlapping AreaSphere */
UFUNCTION()
void OnSphereEndOverlap(
UPrimitiveComponent* OverlappedComponent,
AActor* OtherActor,
UPrimitiveComponent* OtherComp,
int32 OtherBodyIndex);
/** Sets the ActiveStars array of bools based on rarity */
void SetActiveStars();
/** Sets properties of the Item's components based on State */
virtual void SetItemProperties(EItemState State);
/** Called when ItemInterpTimer is finished */
void FinishInterping();
/** Handles item interpolation when in the EquipInterping state */
void ItemInterp(float DeltaTime);
/** Get interp location based on the item type */
FVector GetInterpLocation();
void PlayPickupSound(bool bForcePlaySound = false);
virtual void InitializeCustomDepth();
virtual void OnConstruction(const FTransform& Transform) override;
void EnableGlowMaterial();
void UpdatePulse();
void ResetPulseTimer();
void StartPulseTimer();
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
// Called in AShooterCharacter::GetPickupItem
void PlayEquipSound(bool bForcePlaySound = false);
private:
/** Skeletal Mesh for the item */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Item Properties", meta = (AllowPrivateAccess = "true"))
USkeletalMeshComponent* ItemMesh;
/** Line trace collides with box to show HUD widgets */
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Item Properties", meta = (AllowPrivateAccess = "true"))
class UBoxComponent* CollisionBox;
/** Popup widget for when the player looks at the item */
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Item Properties", meta = (AllowPrivateAccess = "true"))
class UWidgetComponent* PickupWidget;
/** Enables item tracing when overlapped */
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Item Properties", meta = (AllowPrivateAccess = "true"))
class USphereComponent* AreaSphere;
/** The name which appears on the Pickup Widget */
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Item Properties", meta = (AllowPrivateAccess = "true"))
FString ItemName;
/** Item count (ammo, etc.) */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Item Properties", meta = (AllowPrivateAccess = "true"))
int32 ItemCount;
/** Item rarity - determines number of stars in Pickup Widget */
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = Rarity, meta = (AllowPrivateAccess = "true"))
EItemRarity ItemRarity;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Item Properties", meta = (AllowPrivateAccess = "true"))
TArray<bool> ActiveStars;
/** State of the Item */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Item Properties", meta = (AllowPrivateAccess = "true"))
EItemState ItemState;
/** The curve asset to use for the item's Z location when interping */
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Item Properties", meta = (AllowPrivateAccess = "true"))
class UCurveFloat* ItemZCurve;
/** Starting location when interping begins */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Item Properties", meta = (AllowPrivateAccess = "true"))
FVector ItemInterpStartLocation;
/** Target interp location in front of the camera */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Item Properties", meta = (AllowPrivateAccess = "true"))
FVector CameraTargetLocation;
/** true when interping */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Item Properties", meta = (AllowPrivateAccess = "true"))
bool bInterping;
/** Plays when we start interping */
FTimerHandle ItemInterpTimer;
/** Duration of the curve and timer */
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Item Properties", meta = (AllowPrivateAccess = "true"))
float ZCurveTime;
/** Pointer to the character */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Item Properties", meta = (AllowPrivateAccess = "true"))
class AShooterCharacter* Character;
/** X and Y for the Item while interping in the EquipInterping state */
float ItemInterpX;
float ItemInterpY;
/** Initial Yaw offset between the camera and the interping item */
float InterpInitialYawOffset;
/** Curve used to scale the item when interping */
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Item Properties", meta = (AllowPrivateAccess = "true"))
UCurveFloat* ItemScaleCurve;
/** Sound played when Item is picked up */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Item Properties", meta = (AllowPrivateAccess = "true"))
class USoundCue* PickupSound;
/** Sound played when the Item is equipped */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Item Properties", meta = (AllowPrivateAccess = "true"))
USoundCue* EquipSound;
/** Enum for the type of item this Item is */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Item Properties", meta = (AllowPrivateAccess = "true"))
EItemType ItemType;
/** Index of the interp location this item is interping to */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Item Properties", meta = (AllowPrivateAccess = "true"))
int32 InterpLocIndex;
/** Index for the material we'd like to change at runtime */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Item Properties", meta = (AllowPrivateAccess = "true"))
int32 MaterialIndex;
/** Dynamic instance that we can change at runtime */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Item Properties", meta = (AllowPrivateAccess = "true"))
UMaterialInstanceDynamic* DynamicMaterialInstance;
/** Material Instance used with the Dynamic Material Instance */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Item Properties", meta = (AllowPrivateAccess = "true"))
UMaterialInstance* MaterialInstance;
bool bCanChangeCustomDepth;
/** Curve to drive the dynamic material parameters */
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Item Properties", meta = (AllowPrivateAccess = "true"))
class UCurveVector* PulseCurve;
/** Curve to drive the dynamic material parameters */
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Item Properties", meta = (AllowPrivateAccess = "true"))
UCurveVector* InterpPulseCurve;
FTimerHandle PulseTimer;
/** Time for the PulseTimer */
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Item Properties", meta = (AllowPrivateAccess = "true"))
float PulseCurveTime;
UPROPERTY(VisibleAnywhere, Category = "Item Properties", meta = (AllowPrivateAccess = "true"))
float GlowAmount;
UPROPERTY(VisibleAnywhere, Category = "Item Properties", meta = (AllowPrivateAccess = "true"))
float FresnelExponent;
UPROPERTY(VisibleAnywhere, Category = "Item Properties", meta = (AllowPrivateAccess = "true"))
float FresnelReflectFraction;
/** Icon for this item in the inventory */
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = Inventory, meta = (AllowPrivateAccess = "true"))
UTexture2D* IconItem;
/** Ammo Icon for this item in the inventory */
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = Inventory, meta = (AllowPrivateAccess = "true"))
UTexture2D* AmmoItem;
/** Slot in the Inventory array */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Inventory, meta = (AllowPrivateAccess = "true"))
int32 SlotIndex;
/** True when the Character's inventory is full */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Inventory, meta = (AllowPrivateAccess = "true"))
bool bCharacterInventoryFull;
/** Item Rarity data table */
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = DataTable, meta = (AllowPrivateAccess = "true"))
class UDataTable* ItemRarityDataTable;
/** Color in the glow material */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Rarity, meta = (AllowPrivateAccess = "true"))
FLinearColor GlowColor;
/** Light color in the pickup widget */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Rarity, meta = (AllowPrivateAccess = "true"))
FLinearColor LightColor;
/** Dark color in the pickup widget */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Rarity, meta = (AllowPrivateAccess = "true"))
FLinearColor DarkColor;
/** Number of stars in the pickup widget */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Rarity, meta = (AllowPrivateAccess = "true"))
int32 NumberOfStars;
/** Backgroud icon for the inventory */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Rarity, meta = (AllowPrivateAccess = "true"))
UTexture2D* IconBackground;
public:
FORCEINLINE UWidgetComponent* GetPickupWidget() const { return PickupWidget; }
FORCEINLINE USphereComponent* GetAreaSphere() const { return AreaSphere; }
FORCEINLINE UBoxComponent* GetCollisionBox() const { return CollisionBox; }
FORCEINLINE EItemState GetItemState() const { return ItemState; }
void SetItemState(EItemState State);
FORCEINLINE USkeletalMeshComponent* GetItemMesh() const { return ItemMesh; }
FORCEINLINE USoundCue* GetPickupSound() const { return PickupSound; }
FORCEINLINE void SetPickupSound(USoundCue* Sound) { PickupSound = Sound; }
FORCEINLINE USoundCue* GetEquipSound() const { return EquipSound; }
FORCEINLINE void SetEquipSound(USoundCue* Sound) { EquipSound = Sound; }
FORCEINLINE int32 GetItemCount() const { return ItemCount; }
FORCEINLINE int32 GetSlotIndex() const { return SlotIndex; }
FORCEINLINE void SetSlotIndex(int32 Index) { SlotIndex = Index; }
FORCEINLINE void SetCharacter(AShooterCharacter* Char) { Character = Char; }
FORCEINLINE void SetCharacterInventoryFull(bool bFull) { bCharacterInventoryFull = bFull; }
FORCEINLINE void SetItemName(FString Name) { ItemName = Name; }
// Set item icon for the inventory
FORCEINLINE void SetIconItem(UTexture2D* Icon) { IconItem = Icon; }
// Set ammo icon for the pickup widget
FORCEINLINE void SetAmmoIcon(UTexture2D* Icon) { AmmoItem = Icon; }
/** Called from the AShooterCharacter class */
void StartItemCurve(AShooterCharacter* Char, bool bForcePlaySound = false);
virtual void EnableCustomDepth();
virtual void DisableCustomDepth();
void DisableGlowMaterial();
};
| 412 | 0.941932 | 1 | 0.941932 | game-dev | MEDIA | 0.887359 | game-dev | 0.77224 | 1 | 0.77224 |
Caeden117/ChroMapper | 1,407 | Assets/__Scripts/UI/Dark Theme/DarkThemeSO.cs | using TMPro;
using UnityEngine;
using UnityEngine.Serialization;
using UnityEngine.UI;
[CreateAssetMenu(fileName = "DarkThemeSO", menuName = "Map/Dark Theme SO")]
public class DarkThemeSO : ScriptableObject
{
[FormerlySerializedAs("BeonReplacement")] [SerializeField] private TMP_FontAsset beonReplacement;
public TMP_FontAsset TekoReplacement;
[FormerlySerializedAs("BeonUnityReplacement")] [SerializeField] private Font beonUnityReplacement;
[FormerlySerializedAs("TekoUnityReplacement")] [SerializeField] private Font tekoUnityReplacement;
public void DarkThemeifyUI()
{
if (!Settings.Instance.DarkTheme) return;
foreach (var jankCodeMate in Resources.FindObjectsOfTypeAll<TextMeshProUGUI>())
{
if (jankCodeMate == null || jankCodeMate.font == null) continue;
if (jankCodeMate.font.name.Contains("Beon")) jankCodeMate.font = beonReplacement;
if (jankCodeMate.font.name.Contains("Teko")) jankCodeMate.font = TekoReplacement;
}
foreach (var jankCodeMate in Resources.FindObjectsOfTypeAll<Text>())
{
if (jankCodeMate == null || jankCodeMate.font == null) continue;
if (jankCodeMate.font.name.Contains("Beon")) jankCodeMate.font = beonUnityReplacement;
if (jankCodeMate.font.name.Contains("Teko")) jankCodeMate.font = tekoUnityReplacement;
}
}
}
| 412 | 0.522126 | 1 | 0.522126 | game-dev | MEDIA | 0.622506 | game-dev,desktop-app | 0.965866 | 1 | 0.965866 |
MovingBlocks/Terasology | 1,830 | engine/src/main/java/org/terasology/engine/logic/behavior/core/Action.java | // Copyright 2021 The Terasology Foundation
// SPDX-License-Identifier: Apache-2.0
package org.terasology.engine.logic.behavior.core;
import org.terasology.context.annotation.API;
import org.terasology.context.annotation.IndexInherited;
/**
* The action that is used by an action or decorator node. Every action node of a behavior tree has its own action
* instance. There is only one action instance for all actors, that run a behavior tree - so all state information
* needs to be stored at the actor.
* <p>
* Action instances are shown in the property panel of the behavior editor.
*/
@API
@IndexInherited
public interface Action {
/**
* @return the name of this action used by serialization.
*/
String getName();
/**
* @return the id of the action node, which is unique in a behavior tree
*/
int getId();
void setId(int id);
/**
* Is called right after all fields are injected.
*/
void setup();
/**
* Is called when the action node is constructed on first update tick
*/
void construct(Actor actor);
/**
* Is called before the update. If the action node is a decorator, the result will decide if the child node should
* be run.
*
* @return true, child node is not run; false, child is run
*/
boolean prune(Actor actor);
/**
* Is called after the update with the result of the child node, if it is not pruned.
*
* @param result BehaviorState.UNDEFINED if this node is a action node or pruned
* @return the final state of the node
*/
BehaviorState modify(Actor actor, BehaviorState result);
/**
* Is called when the action node is deconstructed on last update tick (when state switches from RUNNING to anything else)
*/
void destruct(Actor actor);
}
| 412 | 0.859732 | 1 | 0.859732 | game-dev | MEDIA | 0.850765 | game-dev | 0.666832 | 1 | 0.666832 |
devMEremenko/XcodeBenchmark | 4,842 | Pods/gRPC-Core/third_party/re2/util/strutil.cc | // Copyright 1999-2005 The RE2 Authors. All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#include <stdarg.h>
#include <stdio.h>
#include "util/strutil.h"
#ifdef _WIN32
#define snprintf _snprintf
#define vsnprintf _vsnprintf
#endif
namespace re2 {
// ----------------------------------------------------------------------
// CEscapeString()
// Copies 'src' to 'dest', escaping dangerous characters using
// C-style escape sequences. 'src' and 'dest' should not overlap.
// Returns the number of bytes written to 'dest' (not including the \0)
// or (size_t)-1 if there was insufficient space.
// ----------------------------------------------------------------------
static size_t CEscapeString(const char* src, size_t src_len,
char* dest, size_t dest_len) {
const char* src_end = src + src_len;
size_t used = 0;
for (; src < src_end; src++) {
if (dest_len - used < 2) // space for two-character escape
return (size_t)-1;
unsigned char c = *src;
switch (c) {
case '\n': dest[used++] = '\\'; dest[used++] = 'n'; break;
case '\r': dest[used++] = '\\'; dest[used++] = 'r'; break;
case '\t': dest[used++] = '\\'; dest[used++] = 't'; break;
case '\"': dest[used++] = '\\'; dest[used++] = '\"'; break;
case '\'': dest[used++] = '\\'; dest[used++] = '\''; break;
case '\\': dest[used++] = '\\'; dest[used++] = '\\'; break;
default:
// Note that if we emit \xNN and the src character after that is a hex
// digit then that digit must be escaped too to prevent it being
// interpreted as part of the character code by C.
if (c < ' ' || c > '~') {
if (dest_len - used < 5) // space for four-character escape + \0
return (size_t)-1;
snprintf(dest + used, 5, "\\%03o", c);
used += 4;
} else {
dest[used++] = c; break;
}
}
}
if (dest_len - used < 1) // make sure that there is room for \0
return (size_t)-1;
dest[used] = '\0'; // doesn't count towards return value though
return used;
}
// ----------------------------------------------------------------------
// CEscape()
// Copies 'src' to result, escaping dangerous characters using
// C-style escape sequences. 'src' and 'dest' should not overlap.
// ----------------------------------------------------------------------
std::string CEscape(const StringPiece& src) {
const size_t dest_len = src.size() * 4 + 1; // Maximum possible expansion
char* dest = new char[dest_len];
const size_t used = CEscapeString(src.data(), src.size(),
dest, dest_len);
std::string s = std::string(dest, used);
delete[] dest;
return s;
}
void PrefixSuccessor(std::string* prefix) {
// We can increment the last character in the string and be done
// unless that character is 255, in which case we have to erase the
// last character and increment the previous character, unless that
// is 255, etc. If the string is empty or consists entirely of
// 255's, we just return the empty string.
while (!prefix->empty()) {
char& c = prefix->back();
if (c == '\xff') { // char literal avoids signed/unsigned.
prefix->pop_back();
} else {
++c;
break;
}
}
}
static void StringAppendV(std::string* dst, const char* format, va_list ap) {
// First try with a small fixed size buffer
char space[1024];
// It's possible for methods that use a va_list to invalidate
// the data in it upon use. The fix is to make a copy
// of the structure before using it and use that copy instead.
va_list backup_ap;
va_copy(backup_ap, ap);
int result = vsnprintf(space, sizeof(space), format, backup_ap);
va_end(backup_ap);
if ((result >= 0) && (static_cast<size_t>(result) < sizeof(space))) {
// It fit
dst->append(space, result);
return;
}
// Repeatedly increase buffer size until it fits
int length = sizeof(space);
while (true) {
if (result < 0) {
// Older behavior: just try doubling the buffer size
length *= 2;
} else {
// We need exactly "result+1" characters
length = result+1;
}
char* buf = new char[length];
// Restore the va_list before we use it again
va_copy(backup_ap, ap);
result = vsnprintf(buf, length, format, backup_ap);
va_end(backup_ap);
if ((result >= 0) && (result < length)) {
// It fit
dst->append(buf, result);
delete[] buf;
return;
}
delete[] buf;
}
}
std::string StringPrintf(const char* format, ...) {
va_list ap;
va_start(ap, format);
std::string result;
StringAppendV(&result, format, ap);
va_end(ap);
return result;
}
} // namespace re2
| 412 | 0.955083 | 1 | 0.955083 | game-dev | MEDIA | 0.162526 | game-dev | 0.990476 | 1 | 0.990476 |
IoLanguage/io | 12,502 | libs/garbagecollector/source/Collector.c | #define COLLECTOR_C
#include "Collector.h"
#undef COLLECTOR_C
#include <assert.h>
#include <time.h>
#ifdef COLLECTOR_TIMER_ON
#define BEGIN_TIMER self->clocksUsed -= clock();
#define END_TIMER self->clocksUsed += clock();
#else
#define BEGIN_TIMER
#define END_TIMER
#endif
Collector *Collector_new(void) {
Collector *self = (Collector *)io_calloc(1, sizeof(Collector));
self->retainedValues = List_new();
self->whites = CollectorMarker_new();
self->grays = CollectorMarker_new();
self->blacks = CollectorMarker_new();
self->freed = CollectorMarker_new();
CollectorMarker_loop(self->whites);
CollectorMarker_removeIfNeededAndInsertAfter_(self->grays, self->whites);
CollectorMarker_removeIfNeededAndInsertAfter_(self->blacks, self->grays);
CollectorMarker_removeIfNeededAndInsertAfter_(self->freed, self->blacks);
// important to set colors *after* inserts, since inserts set colors
CollectorMarker_setColor_(self->whites, COLLECTOR_INITIAL_WHITE);
CollectorMarker_setColor_(self->blacks, COLLECTOR_INITIAL_BLACK);
CollectorMarker_setColor_(self->grays, COLLECTOR_GRAY);
CollectorMarker_setColor_(self->freed, COLLECTOR_FREE);
Collector_setSafeModeOn_(self, 1);
self->allocated = 0;
self->allocatedSweepLevel = 3000;
self->allocatedStep = 1.1f;
self->marksPerAlloc = 2;
#ifdef COLLECTOR_USE_NONINCREMENTAL_MARK_SWEEP
self->allocsPerSweep = 10000;
#endif
self->clocksUsed = 0;
Collector_check(self);
return self;
}
void Collector_check(Collector *self) {
CollectorMarker *w = self->whites;
CollectorMarker *g = self->grays;
CollectorMarker *b = self->blacks;
// colors are different
assert(w->color != g->color);
assert(w->color != b->color);
assert(g->color != b->color);
// prev color is different
assert(w->prev->color != w->color);
assert(g->prev->color != g->color);
assert(b->prev->color != b->color);
CollectorMarker_check(w);
}
size_t CollectorMarker_checkObjectPointer(CollectorMarker *marker) {
if (marker->object == NULL) {
printf("WARNING: Collector found a null object pointer on marker %p! "
"Memory is likely hosed.\n",
(void *)marker);
exit(-1);
return 1;
} else {
// read a word of memory to check for bad pointers
uintptr_t p = *(uintptr_t *)(marker->object);
return p - p; // so compiler doesn't complain about unused variable
}
return 0;
}
void Collector_checkObjectPointers(Collector *self) {
COLLECTMARKER_FOREACH(self->blacks, v,
CollectorMarker_checkObjectPointer(v););
COLLECTMARKER_FOREACH(self->grays, v,
CollectorMarker_checkObjectPointer(v););
COLLECTMARKER_FOREACH(self->whites, v,
CollectorMarker_checkObjectPointer(v););
}
void Collector_checkObjectsWith_(Collector *self, CollectorCheckFunc *func) {
COLLECTMARKER_FOREACH(self->blacks, v, func(v););
COLLECTMARKER_FOREACH(self->grays, v, func(v););
COLLECTMARKER_FOREACH(self->whites, v, func(v););
}
void Collector_free(Collector *self) {
List_free(self->retainedValues);
CollectorMarker_free(self->whites);
CollectorMarker_free(self->grays);
CollectorMarker_free(self->blacks);
CollectorMarker_free(self->freed);
io_free(self);
}
void Collector_setMarkBeforeSweepValue_(Collector *self, void *v) {
self->markBeforeSweepValue = v;
}
// callbacks
void Collector_setFreeFunc_(Collector *self, CollectorFreeFunc *func) {
self->freeFunc = func;
}
void Collector_setWillFreeFunc_(Collector *self, CollectorWillFreeFunc *func) {
self->willFreeFunc = func;
}
void Collector_setMarkFunc_(Collector *self, CollectorMarkFunc *func) {
self->markFunc = func;
}
// marks per alloc
void Collector_setMarksPerAlloc_(Collector *self, float n) {
self->marksPerAlloc = n;
}
float Collector_marksPerAlloc(Collector *self) { return self->marksPerAlloc; }
// allocated step
void Collector_setAllocatedStep_(Collector *self, float n) {
self->allocatedStep = n;
}
float Collector_allocatedStep(Collector *self) { return self->allocatedStep; }
void Collector_setDebug_(Collector *self, int b) { self->debugOn = b ? 1 : 0; }
void Collector_setSafeModeOn_(Collector *self, int b) {
self->safeMode = b ? 1 : 0;
}
// retain/release --------------------------------------------
void *Collector_retain_(Collector *self, void *v) {
List_append_(self->retainedValues, v);
CollectorMarker_removeIfNeededAndInsertAfter_(v, self->grays);
return v;
}
void Collector_stopRetaining_(Collector *self, void *v) {
List_removeLast_(self->retainedValues, v);
}
void Collector_removeAllRetainedValues(Collector *self) {
List_removeAll(self->retainedValues);
}
// pausing -------------------------------------------------------------------
int Collector_isPaused(Collector *self) { return (self->pauseCount != 0); }
void Collector_pushPause(Collector *self) { self->pauseCount++; }
void Collector_popPause(Collector *self) {
assert(self->pauseCount > 0);
self->pauseCount--;
// printf("collect newMarkerCount %i\n", self->newMarkerCount);
#ifdef COLLECTOR_USE_NONINCREMENTAL_MARK_SWEEP
if (self->pauseCount == 0 && self->newMarkerCount > self->allocsPerSweep) {
// printf("collect newMarkerCount %i\n", self->newMarkerCount);
if (self->debugOn) {
printf("\n newMarkerCount %i\n", (int)self->newMarkerCount);
}
self->newMarkerCount = 0;
Collector_collect(self);
}
#else
if (self->pauseCount == 0 && self->queuedMarks > 1.0) {
Collector_markPhase(self);
}
#endif
}
#ifdef COLLECTOR_USE_NONINCREMENTAL_MARK_SWEEP
void Collector_setAllocsPerSweep_(Collector *self, int n) {
self->allocsPerSweep = n;
}
float Collector_allocsPerSweep(Collector *self) { return self->allocsPerSweep; }
#endif
// adding ------------------------------------------------
CollectorMarker *Collector_newMarker(Collector *self) {
CollectorMarker *m;
BEGIN_TIMER
m = self->freed->next;
if (m->color != self->freed->color) {
m = CollectorMarker_new();
// printf("new marker\n");
} else {
// printf("using recycled marker\n");
}
self->allocated++;
Collector_addValue_(self, m);
END_TIMER
return m;
}
void Collector_addValue_(Collector *self, void *v) {
CollectorMarker_removeIfNeededAndInsertAfter_(v, self->whites);
self->queuedMarks += self->marksPerAlloc;
#ifdef COLLECTOR_USE_NONINCREMENTAL_MARK_SWEEP
self->newMarkerCount++;
#endif
// pauseCount is never zero here...
/*
if (self->pauseCount == 0)
{
if(self->allocated > self->allocatedSweepLevel)
{
Collector_sweep(self);
}
else if (self->queuedMarks > 1.0)
{
Collector_markPhase(self);
}
}
*/
}
// collection ------------------------------------------------
void Collector_markGrays(Collector *self) {
CollectorMarkFunc *markFunc = self->markFunc;
COLLECTMARKER_FOREACH(self->grays, v,
//(*markFunc)(v); Collector_makeBlack_(self, v);
if ((*markFunc)(v)) Collector_makeBlack_(self, v);
// count ++;
);
self->queuedMarks = 0;
}
void Collector_markGraysMax_(Collector *self, size_t max) {
CollectorMarkFunc *markFunc = self->markFunc;
if (!max)
return;
COLLECTMARKER_FOREACH(self->grays, v,
//(*markFunc)(v); Collector_makeBlack_(self, v);
if ((*markFunc)(v)) Collector_makeBlack_(self, v);
max--; if (0 == max) break;);
self->queuedMarks = 0;
}
void Collector_sendWillFreeCallbacks(Collector *self) {
CollectorWillFreeFunc *willFreeFunc = self->willFreeFunc;
if (willFreeFunc) {
Collector_pushPause(self); // since the callback may create new objects
COLLECTMARKER_FOREACH(self->whites, v, (*willFreeFunc)(v));
Collector_popPause(self);
}
}
size_t Collector_freeWhites(Collector *self) {
size_t count = 0;
CollectorFreeFunc *freeFunc = self->freeFunc;
COLLECTMARKER_FOREACH(self->whites, v, (*freeFunc)(v);
// v->object = 0x0;
Collector_makeFree_(self, v); count++;);
self->allocated -= count;
return count;
}
// ---------------------
void Collector_initPhase(Collector *self) {
LIST_FOREACH(self->retainedValues, i, v, Collector_makeGray_(self, v));
}
void Collector_markForTimePeriod_(Collector *self, double seconds) {
clock_t until = clock() + seconds * CLOCKS_PER_SEC;
for (;;) {
if (until < clock())
return;
if (CollectorMarker_colorSetIsEmpty(self->grays)) {
Collector_sweep(self);
return;
}
Collector_markGrays(self);
}
}
void Collector_markPhase(Collector *self) {
if (self->allocated > self->allocatedSweepLevel) {
Collector_sweep(self);
} else {
Collector_markGraysMax_(self, self->queuedMarks);
}
if (CollectorMarker_isEmpty(self->grays)) {
Collector_freeWhites(self);
// Collector_sweepPhase(self);
}
}
size_t Collector_sweep(Collector *self) {
size_t freedCount = Collector_sweepPhase(self);
/*
if (self->debugOn)
{
size_t freedCount2 = Collector_sweepPhase(self);
return freedCount + freedCount2;
}
*/
return freedCount;
}
size_t Collector_sweepPhase(Collector *self) {
size_t freedCount = 0;
self->newMarkerCount = 0;
if (self->debugOn) {
printf("Collector_sweepPhase()\n");
// printf(" newMarkerCount %i\n", (int)self->newMarkerCount);
printf(" allocsPerSweep %i\n", (int)self->allocsPerSweep);
printf(" allocated %i\n", (int)self->allocated);
printf(" allocatedSweepLevel %i\n", (int)self->allocatedSweepLevel);
}
if (self->markBeforeSweepValue) {
Collector_makeGray_(self, self->markBeforeSweepValue);
}
while (!CollectorMarker_isEmpty(self->grays)) {
do {
Collector_markGrays(self);
} while (!CollectorMarker_isEmpty(self->grays));
Collector_sendWillFreeCallbacks(self);
}
freedCount = Collector_freeWhites(self);
self->sweepCount++;
// printf("whites freed %i\n", (int)freedCount);
{
CollectorMarker *b = self->blacks;
self->blacks = self->whites;
self->whites = b;
}
Collector_initPhase(self);
self->allocatedSweepLevel = self->allocated * self->allocatedStep;
// printf("allocatedSweepLevel = %i\n", self->allocatedSweepLevel);
return freedCount;
}
size_t Collector_collect(Collector *self) {
size_t result;
BEGIN_TIMER
if (self->pauseCount) {
printf("Collector warning: attempt to force collection while pause "
"count = %i\n",
self->pauseCount);
result = 0;
} else {
// collect twice to ensure that any now unreachable blacks get collected
result = Collector_sweepPhase(self) + Collector_sweepPhase(self);
}
END_TIMER
return result;
}
size_t Collector_freeAllValues(Collector *self) {
size_t count = 0;
CollectorFreeFunc *freeFunc = self->freeFunc;
COLLECTOR_FOREACH(self, v, (*freeFunc)(v); CollectorMarker_free(v);
count++;);
self->allocated -= count;
COLLECTMARKER_FOREACH(self->freed, v, CollectorMarker_free(v); count++;);
return count;
}
// helpers
// ----------------------------------------------------------------------------
void Collector_show(Collector *self) {
printf("black: %i\n", (int)CollectorMarker_count(self->blacks));
printf("gray: %i\n", (int)CollectorMarker_count(self->grays));
printf("white: %i\n", (int)CollectorMarker_count(self->whites));
}
char *Collector_colorNameFor_(Collector *self, void *v) {
if (self->whites->color == MARKER(v)->color)
return "white";
if (self->grays->color == MARKER(v)->color)
return "gray";
if (self->blacks->color == MARKER(v)->color)
return "black";
return "off-white";
}
double Collector_timeUsed(Collector *self) {
return (double)self->clocksUsed / (double)CLOCKS_PER_SEC;
}
| 412 | 0.915697 | 1 | 0.915697 | game-dev | MEDIA | 0.358768 | game-dev | 0.968391 | 1 | 0.968391 |
endless-sky/endless-sky | 2,712 | source/NPCAction.cpp | /* NPCAction.cpp
Copyright (c) 2023 by Amazinite
Endless Sky 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.
Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "NPCAction.h"
#include "DataNode.h"
#include "DataWriter.h"
#include "PlayerInfo.h"
#include "System.h"
#include "UI.h"
using namespace std;
// Construct and Load() at the same time.
NPCAction::NPCAction(const DataNode &node, const ConditionsStore *playerConditions,
const set<const System *> *visitedSystems, const set<const Planet *> *visitedPlanets)
{
Load(node, playerConditions, visitedSystems, visitedPlanets);
}
void NPCAction::Load(const DataNode &node, const ConditionsStore *playerConditions,
const set<const System *> *visitedSystems, const set<const Planet *> *visitedPlanets)
{
if(node.Size() >= 2)
trigger = node.Token(1);
for(const DataNode &child : node)
{
const string &key = child.Token(0);
if(key == "triggered")
triggered = true;
else
action.LoadSingle(child, playerConditions, visitedSystems, visitedPlanets);
}
}
// Note: the Save() function can assume this is an instantiated action, not
// a template, so it only has to save a subset of the data.
void NPCAction::Save(DataWriter &out) const
{
out.Write("on", trigger);
out.BeginChild();
{
if(triggered)
out.Write("triggered");
action.SaveBody(out);
}
out.EndChild();
}
// Check this template or instantiated NPCAction to see if any used content
// is not fully defined (e.g. plugin removal, typos in names, etc.).
string NPCAction::Validate() const
{
return action.Validate();
}
void NPCAction::Do(PlayerInfo &player, UI *ui, const Mission *caller, const shared_ptr<Ship> &target)
{
// All actions are currently one-time-use. Actions that are used
// are marked as triggered, and cannot be used again.
if(triggered)
return;
triggered = true;
action.Do(player, ui, caller, nullptr, target);
}
// Convert this validated template into a populated action.
NPCAction NPCAction::Instantiate(map<string, string> &subs, const System *origin,
int jumps, int64_t payload) const
{
NPCAction result;
result.trigger = trigger;
result.action = action.Instantiate(subs, origin, jumps, payload);
return result;
}
| 412 | 0.919517 | 1 | 0.919517 | game-dev | MEDIA | 0.856456 | game-dev | 0.849826 | 1 | 0.849826 |
MrKinau/FishingBot | 3,237 | src/main/java/systems/kinau/fishingbot/modules/command/commands/CommandDropRod.java | package systems.kinau.fishingbot.modules.command.commands;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import systems.kinau.fishingbot.FishingBot;
import systems.kinau.fishingbot.bot.Inventory;
import systems.kinau.fishingbot.bot.Slot;
import systems.kinau.fishingbot.modules.command.BrigardierCommand;
import systems.kinau.fishingbot.modules.command.executor.CommandExecutor;
import systems.kinau.fishingbot.utils.ItemUtils;
public class CommandDropRod extends BrigardierCommand {
public CommandDropRod() {
super("droprod", FishingBot.getI18n().t("command-droprod-desc"), "roddrop", "droprods", "rodsdrop", "emptyrod", "rodempty");
}
@Override
public void register(LiteralArgumentBuilder<CommandExecutor> builder) {
builder.then(argument("filter", StringArgumentType.greedyString())
.executes(getExecutor()))
.executes(getExecutor());
}
private Command<CommandExecutor> getExecutor() {
return context -> {
CommandExecutor source = context.getSource();
Filter filter = Filter.ALL_BUT_SELECTED;
String filterStr = null;
try {
filterStr = context.getArgument("filter", String.class);
} catch (IllegalArgumentException ignore) {}
if (filterStr != null) {
try {
filter = Filter.valueOf(filterStr.replace(" ", "_").toUpperCase());
} catch (Exception e) {
source.sendTranslatedMessages("command-droprod-unknown-type", filterStr.replace(" ", "_").toUpperCase());
return 0;
}
}
Inventory inventory = FishingBot.getInstance().getCurrentBot().getPlayer().getInventory();
int dropCount = 0;
for (int slotId : inventory.getContent().keySet()) {
Slot slot = inventory.getContent().get(slotId);
if (!ItemUtils.isFishingRod(slot)) continue;
if (filter == Filter.ALL || (filter == Filter.ALL_BUT_SELECTED && slotId != FishingBot.getInstance().getCurrentBot().getPlayer().getHeldSlot())) {
FishingBot.getInstance().getCurrentBot().getPlayer().dropStack((short) slotId, (short) (slotId - 8));
dropCount++;
} else if (filter == Filter.SELECTED && slotId == FishingBot.getInstance().getCurrentBot().getPlayer().getHeldSlot()) {
FishingBot.getInstance().getCurrentBot().getPlayer().dropStack((short) slotId, (short) (slotId - 8));
FishingBot.getInstance().getCurrentBot().getFishingModule().swapWithBestFishingRod();
dropCount++;
break;
}
}
source.sendTranslatedMessages("command-droprod-item-count", dropCount);
return 0;
};
}
@Override
public String getSyntax(String label) {
return FishingBot.getI18n().t("command-droprod-syntax", label);
}
public enum Filter {
ALL,
SELECTED,
ALL_BUT_SELECTED
}
}
| 412 | 0.809139 | 1 | 0.809139 | game-dev | MEDIA | 0.903912 | game-dev | 0.936367 | 1 | 0.936367 |
TauCetiStation/TauCetiClassic | 4,293 | code/game/objects/items/weapons/table_rack_parts.dm | /* Table parts and rack parts
* Contains:
* Table Parts
* Reinforced Table Parts
* Glass Table Parts
* Wooden Table Parts
* Fancy Table Parts
* Black Fancy Table Parts
* Rack Parts
*/
/*
* Table Parts
*/
// Return TRUE if reacted to a tool.
/obj/item/weapon/table_parts
var/build_time = 0
/obj/item/weapon/table_parts/proc/attack_tools(obj/item/W, mob/user)
if(iswrenching(W))
deconstruct(TRUE, user)
return TRUE
else if(istype(W, /obj/item/stack/rods))
var/obj/item/stack/rods/R = W
if (R.use(4))
new /obj/item/weapon/table_parts/reinforced( user.loc )
to_chat(user, "<span class='notice'>You reinforce the [name].</span>")
qdel(src)
else
to_chat(user, "<span class='warning'>You need at least four rods to do this.</span>")
return TRUE
return FALSE
/obj/item/weapon/table_parts/attackby(obj/item/I, mob/user, params)
if(attack_tools(I, user))
return
return ..()
/obj/item/weapon/table_parts/deconstruct(disassembled, user = FALSE)
if(flags & NODECONSTRUCT)
return ..()
var/turf/T = get_turf(user || src)
for(var/debrit_type in debris)
new debrit_type(T)
..()
/obj/item/weapon/table_parts/attack_self(mob/user)
var/turf/simulated/T = get_turf(user)
if(!can_place(T))
to_chat(user, "<span class='warning'>You can't put it here!</span>")
return
if(build_time > 0 && !handle_fumbling(user, src, build_time, list(/datum/skill/engineering = SKILL_LEVEL_NOVICE)))
return
if(!can_place(T))
to_chat(user, "<span class='warning'>You can't put it here!</span>")
return
var/obj/structure/table/R = new table_type(T)
to_chat(user, "<span class='notice'>You assemble [src].</span>")
R.add_fingerprint(user)
qdel(src)
/obj/item/weapon/table_parts/proc/can_place(turf/T)
return T && T.CanPass(null, T)
/*
* Reinforced Table Parts
*/
/obj/item/weapon/table_parts/reinforced
build_time = SKILL_TASK_AVERAGE
/obj/item/weapon/table_parts/reinforced/attack_tools(obj/item/W, mob/user)
if(iswrenching(W))
deconstruct(TRUE, user)
return TRUE
return FALSE
/*
* Reinforced Glass Table Parts
*/
/obj/item/weapon/table_parts/rglass
build_time = SKILL_TASK_AVERAGE
/obj/item/weapon/table_parts/rglass/attack_tools(obj/item/W, mob/user)
if(iswrenching(W))
deconstruct(TRUE, user)
return TRUE
return FALSE
/*
* Glass Table Parts
*/
/obj/item/weapon/table_parts/glass/attack_tools(obj/item/W, mob/user)
if(iswrenching(W))
deconstruct(TRUE, user)
return TRUE
else if(istype(W, /obj/item/stack/rods))
var/obj/item/stack/rods/R = W
if (R.use(2))
new /obj/item/weapon/table_parts/rglass( user.loc )
to_chat(user, "<span class='notice'>You reinforce the [name].</span>")
qdel(src)
else
to_chat(user, "<span class='warning'>You need at least two rods to do this.</span>")
return TRUE
return FALSE
/*
* Wooden Table Parts
*/
/obj/item/weapon/table_parts/wood/attack_tools(obj/item/W, mob/user)
if(iswrenching(W))
deconstruct(TRUE, user)
return TRUE
else if(istype(W, /obj/item/stack/tile/grass))
var/obj/item/stack/tile/grass/Grass = W
Grass.use(1)
new /obj/item/weapon/table_parts/wood/poker(loc)
visible_message("<span class='notice'>[user] adds grass to the wooden table parts</span>")
qdel(src)
return TRUE
return FALSE
/*
* Fancy Wooden Table Parts
*/
/obj/item/weapon/table_parts/wood/fancy/attack_tools(obj/item/W, mob/user)
if(iswrenching(W))
deconstruct(TRUE, user)
return TRUE
return FALSE
/*
* Poker Table Parts
*/
/obj/item/weapon/table_parts/wood/poker/attack_tools(obj/item/W, mob/user)
if(iswrenching(W))
deconstruct(TRUE, user)
return TRUE
return FALSE
/*
* Rack Parts
*/
/obj/item/weapon/rack_parts/attackby(obj/item/I, mob/user, params)
if(iswrenching(I))
deconstruct(TRUE, user)
return
return ..()
/obj/item/weapon/rack_parts/deconstruct(disassembled, user = FALSE)
if(!(flags & NODECONSTRUCT))
new /obj/item/stack/sheet/metal(get_turf(user || src))
..()
/obj/item/weapon/rack_parts/attack_self(mob/user)
var/turf/simulated/T = get_turf(user)
if(T.CanPass(null, T))
var/obj/structure/rack/R = new /obj/structure/rack( T )
to_chat(user, "<span class='notice'>You assemble [src].</span>")
R.add_fingerprint(user)
qdel(src)
else
to_chat(user, "<span class='warning'>You can't put it here!</span>")
| 412 | 0.917939 | 1 | 0.917939 | game-dev | MEDIA | 0.982948 | game-dev | 0.878709 | 1 | 0.878709 |
DarkStorm652/DarkBot | 1,064 | src/main/java/org/darkstorm/darkbot/minecraftbot/world/item/BasicItemStack.java | package org.darkstorm.darkbot.minecraftbot.world.item;
import org.darkstorm.darkbot.minecraftbot.nbt.NBTTagCompound;
public class BasicItemStack implements ItemStack {
private int id, stackSize, damage;
private NBTTagCompound stackTagCompound;
public BasicItemStack(int id, int stackSize, int damage) {
this.id = id;
this.stackSize = stackSize;
this.damage = damage;
}
public int getId() {
return id;
}
public int getStackSize() {
return stackSize;
}
public void setStackSize(int stackSize) {
this.stackSize = stackSize;
}
public int getDamage() {
return damage;
}
public void setDamage(int damage) {
this.damage = damage;
}
public NBTTagCompound getStackTagCompound() {
return stackTagCompound;
}
public void setStackTagCompound(NBTTagCompound stackTagCompound) {
this.stackTagCompound = stackTagCompound;
}
@Override
public ItemStack clone() {
return new BasicItemStack(id, stackSize, damage);
}
@Override
public String toString() {
return "ItemStack[" + id + ":" + damage + "x" + stackSize + "]";
}
}
| 412 | 0.869054 | 1 | 0.869054 | game-dev | MEDIA | 0.998352 | game-dev | 0.656689 | 1 | 0.656689 |
Source-SDK-Archives/source-sdk-2004 | 95,450 | src_mod/dlls/hl2_dll/npc_combine.cpp | //========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "cbase.h"
#include "ai_hull.h"
#include "ai_navigator.h"
#include "ai_motor.h"
#include "ai_squadslot.h"
#include "ai_squad.h"
#include "ai_route.h"
#include "ai_interactions.h"
#include "soundent.h"
#include "game.h"
#include "npcevent.h"
#include "npc_combine.h"
#include "activitylist.h"
#include "player.h"
#include "basecombatweapon.h"
#include "basegrenade_shared.h"
#include "vstdlib/random.h"
#include "engine/IEngineSound.h"
#include "globals.h"
#include "grenade_frag.h"
#include "ndebugoverlay.h"
#include "weapon_physcannon.h"
#include "SoundEmitterSystem/isoundemittersystembase.h"
#include "npc_headcrab.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
int g_fCombineQuestion; // true if an idle grunt asked a question. Cleared when someone answers. YUCK old global from grunt code
#define COMBINE_GRENADE_THROW_SPEED 650
#define COMBINE_GRENADE_TIMER 3.5
#define COMBINE_GRENADE_FLUSH_TIME 3.0 // Don't try to flush an enemy who has been out of sight for longer than this.
#define COMBINE_GRENADE_FLUSH_DIST 256.0 // Don't try to flush an enemy who has moved farther than this distance from the last place I saw him.
// Used when only what combine to react to what the spotlight sees
#define SF_COMBINE_NO_LOOK (1 << 16)
#define COMBINE_LIMP_HEALTH 20
#define COMBINE_MIN_GRENADE_CLEAR_DIST 250
#define COMBINE_EYE_STANDING_POSITION Vector( 0, 0, 66 )
#define COMBINE_GUN_STANDING_POSITION Vector( 0, 0, 57 )
#define COMBINE_EYE_CROUCHING_POSITION Vector( 0, 0, 40 )
#define COMBINE_GUN_CROUCHING_POSITION Vector( 0, 0, 36 )
#define COMBINE_SHOTGUN_STANDING_POSITION Vector( 0, 0, 36 )
#define COMBINE_SHOTGUN_CROUCHING_POSITION Vector( 0, 0, 36 )
#define COMBINE_MIN_CROUCH_DISTANCE 256.0
//-----------------------------------------------------------------------------
// Static stuff local to this file.
//-----------------------------------------------------------------------------
// This is the index to the name of the shotgun's classname in the string pool
// so that we can get away with an integer compare rather than a string compare.
string_t s_iszShotgunClassname;
//-----------------------------------------------------------------------------
// Interactions
//-----------------------------------------------------------------------------
int g_interactionCombineBash = 0; // melee bash attack
//=========================================================
// Combines's Anim Events Go Here
//=========================================================
#define COMBINE_AE_RELOAD ( 2 )
#define COMBINE_AE_KICK ( 3 )
#define COMBINE_AE_AIM ( 4 )
#define COMBINE_AE_GREN_TOSS ( 7 )
#define COMBINE_AE_GREN_LAUNCH ( 8 )
#define COMBINE_AE_GREN_DROP ( 9 )
#define COMBINE_AE_CAUGHT_ENEMY ( 10) // grunt established sight with an enemy (player only) that had previously eluded the squad.
int COMBINE_AE_BEGIN_ALTFIRE;
int COMBINE_AE_ALTFIRE;
//=========================================================
// Combine activities
//=========================================================
//Activity ACT_COMBINE_STANDING_SMG1;
//Activity ACT_COMBINE_CROUCHING_SMG1;
//Activity ACT_COMBINE_STANDING_AR2;
//Activity ACT_COMBINE_CROUCHING_AR2;
//Activity ACT_COMBINE_WALKING_AR2;
//Activity ACT_COMBINE_STANDING_SHOTGUN;
//Activity ACT_COMBINE_CROUCHING_SHOTGUN;
Activity ACT_COMBINE_THROW_GRENADE;
Activity ACT_COMBINE_LAUNCH_GRENADE;
Activity ACT_COMBINE_BUGBAIT;
Activity ACT_COMBINE_AR2_ALTFIRE;
// -----------------------------------------------
// > Squad slots
// -----------------------------------------------
enum SquadSlot_T
{
SQUAD_SLOT_GRENADE1 = LAST_SHARED_SQUADSLOT,
SQUAD_SLOT_GRENADE2,
SQUAD_SLOT_ATTACK_OCCLUDER,
};
#define bits_MEMORY_PAIN_LIGHT_SOUND bits_MEMORY_CUSTOM1
#define bits_MEMORY_PAIN_HEAVY_SOUND bits_MEMORY_CUSTOM2
#define bits_MEMORY_PLAYER_HURT bits_MEMORY_CUSTOM3
LINK_ENTITY_TO_CLASS( npc_combine, CNPC_Combine );
//---------------------------------------------------------
// Save/Restore
//---------------------------------------------------------
BEGIN_DATADESC( CNPC_Combine )
DEFINE_FIELD( m_nKickDamage, FIELD_INTEGER ),
DEFINE_FIELD( m_vecTossVelocity, FIELD_VECTOR ),
DEFINE_FIELD( m_bStanding, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bShouldPatrol, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bCanCrouch, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bFirstEncounter, FIELD_BOOLEAN ),
DEFINE_FIELD( m_flNextPainSoundTime, FIELD_TIME ),
DEFINE_FIELD( m_flNextAlertSoundTime, FIELD_TIME ),
DEFINE_FIELD( m_flNextGrenadeCheck, FIELD_TIME ),
DEFINE_FIELD( m_flNextLostSoundTime, FIELD_TIME ),
DEFINE_FIELD( m_flAlertPatrolTime, FIELD_TIME ),
DEFINE_FIELD( m_flNextAltFireTime, FIELD_TIME ),
DEFINE_FIELD( m_nShots, FIELD_INTEGER ),
DEFINE_FIELD( m_flShotDelay, FIELD_FLOAT ),
DEFINE_KEYFIELD( m_iNumGrenades, FIELD_INTEGER, "NumGrenades" ),
DEFINE_EMBEDDED( m_Sentences ),
// m_AssaultBehavior (auto saved by AI)
// m_StandoffBehavior (auto saved by AI)
// m_FollowBehavior (auto saved by AI)
// m_FuncTankBehavior (auto saved by AI)
// m_RappelBehavior (auto saved by AI)
// m_ActBusyBehavior (auto saved by AI)
DEFINE_INPUTFUNC( FIELD_VOID, "LookOff", InputLookOff ),
DEFINE_INPUTFUNC( FIELD_VOID, "LookOn", InputLookOn ),
DEFINE_INPUTFUNC( FIELD_VOID, "StartPatrolling", InputStartPatrolling ),
DEFINE_INPUTFUNC( FIELD_VOID, "StopPatrolling", InputStopPatrolling ),
DEFINE_INPUTFUNC( FIELD_STRING, "Assault", InputAssault ),
DEFINE_INPUTFUNC( FIELD_VOID, "HitByBugbait", InputHitByBugbait ),
DEFINE_FIELD( m_iLastAnimEventHandled, FIELD_INTEGER ),
DEFINE_FIELD( m_fIsElite, FIELD_BOOLEAN ),
DEFINE_FIELD( m_vecAltFireTarget, FIELD_VECTOR ),
END_DATADESC()
//------------------------------------------------------------------------------
// Constructor.
//------------------------------------------------------------------------------
CNPC_Combine::CNPC_Combine()
{
m_vecTossVelocity = vec3_origin;
}
//-----------------------------------------------------------------------------
// Create components
//-----------------------------------------------------------------------------
bool CNPC_Combine::CreateComponents()
{
if ( !BaseClass::CreateComponents() )
return false;
m_Sentences.Init( this, "NPC_Combine.SentenceParameters" );
return true;
}
//------------------------------------------------------------------------------
// Purpose: Don't look, only get info from squad.
//------------------------------------------------------------------------------
void CNPC_Combine::InputLookOff( inputdata_t &inputdata )
{
m_spawnflags |= SF_COMBINE_NO_LOOK;
}
//------------------------------------------------------------------------------
// Purpose: Enable looking.
//------------------------------------------------------------------------------
void CNPC_Combine::InputLookOn( inputdata_t &inputdata )
{
m_spawnflags &= ~SF_COMBINE_NO_LOOK;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_Combine::InputStartPatrolling( inputdata_t &inputdata )
{
m_bShouldPatrol = true;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_Combine::InputStopPatrolling( inputdata_t &inputdata )
{
m_bShouldPatrol = false;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_Combine::InputAssault( inputdata_t &inputdata )
{
m_AssaultBehavior.SetParameters( AllocPooledString(inputdata.value.String()), CUE_DONT_WAIT );
}
//-----------------------------------------------------------------------------
// We were hit by bugbait
//-----------------------------------------------------------------------------
void CNPC_Combine::InputHitByBugbait( inputdata_t &inputdata )
{
SetCondition( COND_COMBINE_HIT_BY_BUGBAIT );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_Combine::Precache()
{
PrecacheModel("models/Weapons/w_grenade.mdl");
UTIL_PrecacheOther( "npc_handgrenade" );
PrecacheScriptSound( "NPC_Combine.GrenadeLaunch" );
PrecacheScriptSound( "NPC_Combine.WeaponBash" );
PrecacheScriptSound( "Weapon_CombineGuard.Special1" );
BaseClass::Precache();
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CNPC_Combine::Activate()
{
s_iszShotgunClassname = FindPooledString( "weapon_shotgun" );
BaseClass::Activate();
}
//-----------------------------------------------------------------------------
// Purpose:
//
//
//-----------------------------------------------------------------------------
void CNPC_Combine::Spawn( void )
{
SetHullType(HULL_HUMAN);
SetHullSizeNormal();
SetSolid( SOLID_BBOX );
AddSolidFlags( FSOLID_NOT_STANDABLE );
SetMoveType( MOVETYPE_STEP );
SetBloodColor( BLOOD_COLOR_RED );
m_flFieldOfView = -0.2;// indicates the width of this NPC's forward view cone ( as a dotproduct result )
m_NPCState = NPC_STATE_NONE;
m_flNextGrenadeCheck = gpGlobals->curtime + 1;
m_flNextPainSoundTime = 0;
m_flNextAlertSoundTime = 0;
m_bStanding = true;
m_bShouldPatrol = false;
// CapabilitiesAdd( bits_CAP_TURN_HEAD | bits_CAP_MOVE_GROUND | bits_CAP_MOVE_JUMP | bits_CAP_MOVE_CLIMB);
// JAY: Disabled jump for now - hard to compare to HL1
CapabilitiesAdd( bits_CAP_TURN_HEAD | bits_CAP_MOVE_GROUND );
CapabilitiesAdd( bits_CAP_AIM_GUN );
// Innate range attack for grenade
// CapabilitiesAdd(bits_CAP_INNATE_RANGE_ATTACK2 );
// Innate range attack for kicking
CapabilitiesAdd(bits_CAP_INNATE_MELEE_ATTACK1 );
// Can be in a squad
CapabilitiesAdd( bits_CAP_SQUAD);
CapabilitiesAdd( bits_CAP_USE_WEAPONS );
CapabilitiesAdd( bits_CAP_DUCK ); // In reloading and cover
CapabilitiesAdd( bits_CAP_NO_HIT_SQUADMATES );
m_bFirstEncounter = true;// this is true when the grunt spawns, because he hasn't encountered an enemy yet.
m_HackedGunPos = Vector ( 0, 0, 55 );
m_MoveAndShootOverlay.SetInitialDelay( 0.75 );
m_flNextLostSoundTime = 0;
m_flAlertPatrolTime = 0;
m_flNextAltFireTime = gpGlobals->curtime;
NPCInit();
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CNPC_Combine::CreateBehaviors()
{
AddBehavior( &m_RappelBehavior );
AddBehavior( &m_ActBusyBehavior );
AddBehavior( &m_AssaultBehavior );
AddBehavior( &m_StandoffBehavior );
AddBehavior( &m_FollowBehavior );
AddBehavior( &m_FuncTankBehavior );
return BaseClass::CreateBehaviors();
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CNPC_Combine::PostNPCInit()
{
if( IsElite() )
{
// Give a warning if a Combine Soldier is equipped with anything other than
// an AR2.
if( !GetActiveWeapon() || !FClassnameIs( GetActiveWeapon(), "weapon_ar2" ) )
{
DevWarning("**Combine Elite Soldier MUST be equipped with AR2\n");
}
}
BaseClass::PostNPCInit();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CNPC_Combine::PrescheduleThink()
{
BaseClass::PrescheduleThink();
// Speak any queued sentences
m_Sentences.UpdateSentenceQueue();
if ( IsOnFire() )
{
SetCondition( COND_COMBINE_ON_FIRE );
}
else
{
ClearCondition( COND_COMBINE_ON_FIRE );
}
extern ConVar ai_debug_shoot_positions;
if ( ai_debug_shoot_positions.GetBool() )
NDebugOverlay::Cross3D( EyePosition(), 16, 0, 255, 0, false, 0.1 );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CNPC_Combine::DelayAltFireAttack( float flDelay )
{
float flNextAltFire = gpGlobals->curtime + flDelay;
if( flNextAltFire > m_flNextAltFireTime )
{
// Don't let this delay order preempt a previous request to wait longer.
m_flNextAltFireTime = flNextAltFire;
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CNPC_Combine::DelaySquadAltFireAttack( float flDelay )
{
// Make sure to delay my own alt-fire attack.
DelayAltFireAttack( flDelay );
AISquadIter_t iter;
CAI_BaseNPC *pSquadmate = m_pSquad ? m_pSquad->GetFirstMember( &iter ) : NULL;
while ( pSquadmate )
{
CNPC_Combine *pCombine = dynamic_cast<CNPC_Combine*>(pSquadmate);
if( pCombine && pCombine->IsElite() )
{
pCombine->DelayAltFireAttack( flDelay );
}
pSquadmate = m_pSquad->GetNextMember( &iter );
}
}
//-----------------------------------------------------------------------------
// Purpose: degrees to turn in 0.1 seconds
//-----------------------------------------------------------------------------
float CNPC_Combine::MaxYawSpeed( void )
{
switch( GetActivity() )
{
case ACT_TURN_LEFT:
case ACT_TURN_RIGHT:
return 45;
break;
case ACT_RUN:
case ACT_RUN_HURT:
return 15;
break;
case ACT_WALK:
case ACT_WALK_CROUCH:
return 25;
break;
case ACT_RANGE_ATTACK1:
case ACT_RANGE_ATTACK2:
case ACT_MELEE_ATTACK1:
case ACT_MELEE_ATTACK2:
return 35;
default:
return 35;
break;
}
}
//-----------------------------------------------------------------------------
// Purpose: turn in the direction of movement
// Output :
//-----------------------------------------------------------------------------
bool CNPC_Combine::OverrideMoveFacing( const AILocalMoveGoal_t &move, float flInterval )
{
// FIXME: this will break scripted sequences that walk when they have an enemy
if (GetEnemy() && (GetNavigator()->GetMovementActivity() == ACT_WALK_AIM || GetNavigator()->GetMovementActivity() == ACT_WALK || GetNavigator()->GetMovementActivity() == ACT_RUN_AIM))
{
Vector vecEnemyLKP = GetEnemyLKP();
AddFacingTarget( GetEnemy(), vecEnemyLKP, 1.0, 0.2 );
}
return BaseClass::OverrideMoveFacing( move, flInterval );
}
//-----------------------------------------------------------------------------
// Purpose:
//
//
//-----------------------------------------------------------------------------
Class_T CNPC_Combine::Classify ( void )
{
return CLASS_COMBINE;
}
//-----------------------------------------------------------------------------
// Continuous movement tasks
//-----------------------------------------------------------------------------
bool CNPC_Combine::IsCurTaskContinuousMove()
{
const Task_t* pTask = GetTask();
if ( pTask && (pTask->iTask == TASK_COMBINE_CHASE_ENEMY_CONTINUOUSLY) )
return true;
return BaseClass::IsCurTaskContinuousMove();
}
//-----------------------------------------------------------------------------
// Chase the enemy, updating the target position as the player moves
//-----------------------------------------------------------------------------
void CNPC_Combine::StartTaskChaseEnemyContinuously( const Task_t *pTask )
{
CBaseEntity *pEnemy = GetEnemy();
if ( !pEnemy )
{
TaskFail( FAIL_NO_ENEMY );
return;
}
// We're done once we get close enough
if ( WorldSpaceCenter().DistToSqr( pEnemy->WorldSpaceCenter() ) <= pTask->flTaskData * pTask->flTaskData )
{
TaskComplete();
return;
}
// TASK_GET_PATH_TO_ENEMY
if ( IsUnreachable( pEnemy ) )
{
TaskFail(FAIL_NO_ROUTE);
return;
}
if ( !GetNavigator()->SetGoal( GOALTYPE_ENEMY, AIN_NO_PATH_TASK_FAIL ) )
{
// no way to get there =(
DevWarning( 2, "GetPathToEnemy failed!!\n" );
RememberUnreachable( pEnemy );
TaskFail(FAIL_NO_ROUTE);
return;
}
// NOTE: This is TaskRunPath here.
if ( TranslateActivity( ACT_RUN ) != ACT_INVALID )
{
GetNavigator()->SetMovementActivity( ACT_RUN );
}
else
{
GetNavigator()->SetMovementActivity(ACT_WALK);
}
// Cover is void once I move
Forget( bits_MEMORY_INCOVER );
if (GetNavigator()->GetGoalType() == GOALTYPE_NONE)
{
TaskComplete();
GetNavigator()->ClearGoal(); // Clear residual state
return;
}
// No shooting delay when in this mode
m_MoveAndShootOverlay.SetInitialDelay( 0.0 );
if (!GetNavigator()->IsGoalActive())
{
SetIdealActivity( GetStoppedActivity() );
}
else
{
// Check validity of goal type
ValidateNavGoal();
}
// set that we're probably going to stop before the goal
GetNavigator()->SetArrivalDistance( pTask->flTaskData );
m_vSavePosition = GetEnemy()->WorldSpaceCenter();
}
void CNPC_Combine::RunTaskChaseEnemyContinuously( const Task_t *pTask )
{
if (!GetNavigator()->IsGoalActive())
{
SetIdealActivity( GetStoppedActivity() );
}
else
{
// Check validity of goal type
ValidateNavGoal();
}
CBaseEntity *pEnemy = GetEnemy();
if ( !pEnemy )
{
TaskFail( FAIL_NO_ENEMY );
return;
}
// We're done once we get close enough
if ( WorldSpaceCenter().DistToSqr( pEnemy->WorldSpaceCenter() ) <= pTask->flTaskData * pTask->flTaskData )
{
GetNavigator()->StopMoving();
TaskComplete();
return;
}
// Recompute path if the enemy has moved too much
if ( m_vSavePosition.DistToSqr( pEnemy->WorldSpaceCenter() ) < (pTask->flTaskData * pTask->flTaskData) )
return;
if ( IsUnreachable( pEnemy ) )
{
TaskFail(FAIL_NO_ROUTE);
return;
}
if ( !GetNavigator()->RefindPathToGoal() )
{
TaskFail(FAIL_NO_ROUTE);
return;
}
m_vSavePosition = pEnemy->WorldSpaceCenter();
}
//=========================================================
// start task
//=========================================================
void CNPC_Combine::StartTask( const Task_t *pTask )
{
// NOTE: This reset is required because we change it in TASK_COMBINE_CHASE_ENEMY_CONTINUOUSLY
m_MoveAndShootOverlay.SetInitialDelay( 0.75 );
switch ( pTask->iTask )
{
case TASK_COMBINE_CHASE_ENEMY_CONTINUOUSLY:
StartTaskChaseEnemyContinuously( pTask );
break;
case TASK_COMBINE_PLAY_SEQUENCE_FACE_ALTFIRE_TARGET:
SetIdealActivity( (Activity)(int)pTask->flTaskData );
GetMotor()->SetIdealYawToTargetAndUpdate( m_vecAltFireTarget, AI_KEEP_YAW_SPEED );
break;
case TASK_COMBINE_SIGNAL_BEST_SOUND:
if( IsInSquad() && GetSquad()->NumMembers() > 1 )
{
CBasePlayer *pPlayer = AI_GetSinglePlayer();
if( pPlayer && OccupyStrategySlot( SQUAD_SLOT_EXCLUSIVE_HANDSIGN ) && pPlayer->FInViewCone( this ) )
{
CSound *pSound;
pSound = GetBestSound();
Assert( pSound != NULL );
Vector right, tosound;
GetVectors( NULL, &right, NULL );
tosound = pSound->GetSoundReactOrigin() - GetAbsOrigin();
VectorNormalize( tosound);
tosound.z = 0;
right.z = 0;
if( DotProduct( right, tosound ) > 0 )
{
// Right
SetIdealActivity( ACT_SIGNAL_RIGHT );
}
else
{
// Left
SetIdealActivity( ACT_SIGNAL_LEFT );
}
break;
}
}
// Otherwise, just skip it.
TaskComplete();
break;
case TASK_ANNOUNCE_ATTACK:
{
// If Primary Attack
if ((int)pTask->flTaskData == 1)
{
// -----------------------------------------------------------
// If enemy isn't facing me and I haven't attacked in a while
// annouce my attack before I start wailing away
// -----------------------------------------------------------
CBaseCombatCharacter *pBCC = GetEnemyCombatCharacterPointer();
if (pBCC && pBCC->IsPlayer() && (!pBCC->FInViewCone ( this )) &&
(gpGlobals->curtime - m_flLastAttackTime > 3.0) )
{
m_flLastAttackTime = gpGlobals->curtime;
m_Sentences.Speak( "COMBINE_ANNOUNCE", SENTENCE_PRIORITY_HIGH );
// Wait two seconds
SetWait( 2.0 );
if ( m_bStanding )
{
SetActivity(ACT_IDLE);
}
else
{
SetActivity(ACT_COWER); // This is really crouch idle
}
}
// -------------------------------------------------------------
// Otherwise move on
// -------------------------------------------------------------
else
{
TaskComplete();
}
}
else
{
m_Sentences.Speak( "COMBINE_THROW_GRENADE", SENTENCE_PRIORITY_MEDIUM );
SetActivity(ACT_IDLE);
// Wait two seconds
SetWait( 2.0 );
}
break;
}
case TASK_WALK_PATH:
case TASK_RUN_PATH:
// grunt no longer assumes he is covered if he moves
Forget( bits_MEMORY_INCOVER );
BaseClass::StartTask( pTask );
break;
case TASK_COMBINE_FACE_TOSS_DIR:
break;
case TASK_COMBINE_IGNORE_ATTACKS:
// must be in a squad
if (m_pSquad && m_pSquad->NumMembers() > 2)
{
// the enemy must be far enough away
if (GetEnemy() && (GetEnemy()->WorldSpaceCenter() - WorldSpaceCenter()).Length() > 512.0 )
{
m_flNextAttack = gpGlobals->curtime + pTask->flTaskData;
}
}
TaskComplete( );
break;
case TASK_COMBINE_DEFER_SQUAD_GRENADES:
{
if ( m_pSquad )
{
// iterate my squad and stop everyone from throwing grenades for a little while.
AISquadIter_t iter;
CAI_BaseNPC *pSquadmate = m_pSquad ? m_pSquad->GetFirstMember( &iter ) : NULL;
while ( pSquadmate )
{
CNPC_Combine *pCombine = dynamic_cast<CNPC_Combine*>(pSquadmate);
if( pCombine )
{
pCombine->m_flNextGrenadeCheck = gpGlobals->curtime + 5;
}
pSquadmate = m_pSquad->GetNextMember( &iter );
}
}
TaskComplete();
break;
}
case TASK_FACE_IDEAL:
case TASK_FACE_ENEMY:
{
if( pTask->iTask == TASK_FACE_ENEMY && HasCondition( COND_CAN_RANGE_ATTACK1 ) )
{
TaskComplete();
return;
}
BaseClass::StartTask( pTask );
bool bIsFlying = (GetMoveType() == MOVETYPE_FLY) || (GetMoveType() == MOVETYPE_FLYGRAVITY);
if (bIsFlying)
{
SetIdealActivity( ACT_GLIDE );
}
}
break;
case TASK_FIND_COVER_FROM_ENEMY:
{
if (GetHintGroup() == NULL_STRING)
{
CBaseEntity *pEntity = GetEnemy();
// FIXME: this should be generalized by the schedules that are selected, or in the definition of
// what "cover" means (i.e., trace attack vulnerability vs. physical attack vulnerability
if ( pEntity )
{
// NOTE: This is a good time to check to see if the player is hurt.
// Have the combine notice this and call out
if ( !HasMemory(bits_MEMORY_PLAYER_HURT) && pEntity->IsPlayer() && pEntity->GetHealth() <= 20 )
{
if ( m_pSquad )
{
m_pSquad->SquadRemember(bits_MEMORY_PLAYER_HURT);
}
m_Sentences.Speak( "COMBINE_PLAYERHIT", SENTENCE_PRIORITY_INVALID );
JustMadeSound( SENTENCE_PRIORITY_HIGH );
}
if ( pEntity->MyNPCPointer() )
{
if ( !(pEntity->MyNPCPointer()->CapabilitiesGet( ) & bits_CAP_WEAPON_RANGE_ATTACK1))
{
TaskComplete();
return;
}
}
}
}
BaseClass::StartTask( pTask );
}
break;
case TASK_RANGE_ATTACK1:
{
m_nShots = GetActiveWeapon()->GetRandomBurst();
m_flShotDelay = GetActiveWeapon()->GetFireRate();
m_flNextAttack = gpGlobals->curtime + m_flShotDelay - 0.1;
ResetIdealActivity( ACT_RANGE_ATTACK1 );
m_flLastAttackTime = gpGlobals->curtime;
}
break;
case TASK_COMBINE_DIE_INSTANTLY:
{
CTakeDamageInfo info;
info.SetAttacker( this );
info.SetInflictor( this );
info.SetDamage( m_iHealth );
info.SetDamageType( pTask->flTaskData );
info.SetDamageForce( Vector( 0.1, 0.1, 0.1 ) );
TakeDamage( info );
TaskComplete();
}
break;
default:
BaseClass:: StartTask( pTask );
break;
}
}
//=========================================================
// RunTask
//=========================================================
void CNPC_Combine::RunTask( const Task_t *pTask )
{
/*
{
CBaseEntity *pEnemy = GetEnemy();
if (pEnemy)
{
NDebugOverlay::Line(Center(), pEnemy->Center(), 0,255,255, false, 0.1);
}
}
*/
/*
if (m_iMySquadSlot != SQUAD_SLOT_NONE)
{
char text[64];
Q_snprintf( text, strlen( text ), "%d", m_iMySquadSlot );
NDebugOverlay::Text( Center() + Vector( 0, 0, 72 ), text, false, 0.1 );
}
*/
switch ( pTask->iTask )
{
case TASK_COMBINE_CHASE_ENEMY_CONTINUOUSLY:
RunTaskChaseEnemyContinuously( pTask );
break;
case TASK_COMBINE_SIGNAL_BEST_SOUND:
AutoMovement( );
if ( IsActivityFinished() )
{
TaskComplete();
}
break;
case TASK_ANNOUNCE_ATTACK:
{
// Stop waiting if enemy facing me or lost enemy
CBaseCombatCharacter* pBCC = GetEnemyCombatCharacterPointer();
if (!pBCC || pBCC->FInViewCone( this ))
{
TaskComplete();
}
if ( IsWaitFinished() )
{
TaskComplete();
}
}
break;
case TASK_COMBINE_PLAY_SEQUENCE_FACE_ALTFIRE_TARGET:
GetMotor()->SetIdealYawToTargetAndUpdate( m_vecAltFireTarget, AI_KEEP_YAW_SPEED );
if ( IsActivityFinished() )
{
TaskComplete();
}
break;
case TASK_COMBINE_FACE_TOSS_DIR:
{
// project a point along the toss vector and turn to face that point.
GetMotor()->SetIdealYawToTargetAndUpdate( GetLocalOrigin() + m_vecTossVelocity * 64, AI_KEEP_YAW_SPEED );
if ( FacingIdeal() )
{
TaskComplete( true );
}
break;
}
case TASK_RANGE_ATTACK1:
{
AutoMovement( );
Vector vecEnemyLKP = GetEnemyLKP();
if (!FInAimCone( vecEnemyLKP ))
{
GetMotor()->SetIdealYawToTargetAndUpdate( vecEnemyLKP, AI_KEEP_YAW_SPEED );
}
else
{
GetMotor()->SetIdealYawAndUpdate( GetMotor()->GetIdealYaw(), AI_KEEP_YAW_SPEED );
}
if ( gpGlobals->curtime >= m_flNextAttack )
{
if ( IsActivityFinished() )
{
if (--m_nShots > 0)
{
// DevMsg("ACT_RANGE_ATTACK1\n");
ResetIdealActivity( ACT_RANGE_ATTACK1 );
m_flLastAttackTime = gpGlobals->curtime;
m_flNextAttack = gpGlobals->curtime + m_flShotDelay - 0.1;
}
else
{
// DevMsg("TASK_RANGE_ATTACK1 complete\n");
TaskComplete();
}
}
}
else
{
// DevMsg("Wait\n");
}
}
break;
default:
{
BaseClass::RunTask( pTask );
break;
}
}
}
//------------------------------------------------------------------------------
// Purpose : Override to always shoot at eyes (for ducking behind things)
// Input :
// Output :
//------------------------------------------------------------------------------
Vector CNPC_Combine::BodyTarget( const Vector &posSrc, bool bNoisy )
{
Vector result = BaseClass::BodyTarget( posSrc, bNoisy );
// @TODO (toml 02-02-04): this seems wrong. Isn't this already be accounted for
// with the eye position used in the base BodyTarget()
if ( GetFlags() & FL_DUCKING )
result -= Vector(0,0,16);
return result;
}
//------------------------------------------------------------------------------
// Purpose:
//------------------------------------------------------------------------------
bool CNPC_Combine::FVisible( CBaseEntity *pEntity, int traceMask, CBaseEntity **ppBlocker )
{
if( m_spawnflags & SF_COMBINE_NO_LOOK )
{
// When no look is set, if enemy has eluded the squad,
// he's always invisble to me
if (GetEnemies()->HasEludedMe(pEntity))
{
return false;
}
}
return BaseClass::FVisible(pEntity, traceMask, ppBlocker);
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CNPC_Combine::Event_Killed( const CTakeDamageInfo &info )
{
// if I was killed before I could finish throwing my grenade, drop
// a grenade item that the player can retrieve.
if( GetActivity() == ACT_RANGE_ATTACK2 )
{
if( m_iLastAnimEventHandled != COMBINE_AE_GREN_TOSS )
{
// Drop the grenade as an item.
Vector vecStart;
GetAttachment( "lefthand", vecStart );
CBaseEntity *pItem = DropItem( "weapon_frag", vecStart, RandomAngle(0,360) );
if ( pItem )
{
IPhysicsObject *pObj = pItem->VPhysicsGetObject();
if ( pObj )
{
Vector vel;
vel.x = random->RandomFloat( -100.0f, 100.0f );
vel.y = random->RandomFloat( -100.0f, 100.0f );
vel.z = random->RandomFloat( 800.0f, 1200.0f );
AngularImpulse angImp = RandomAngularImpulse( -300.0f, 300.0f );
vel[2] = 0.0f;
pObj->AddVelocity( &vel, &angImp );
}
// In the Citadel we need to dissolve this
if ( PlayerHasMegaPhysCannon() )
{
CBaseCombatWeapon *pWeapon = static_cast<CBaseCombatWeapon *>(pItem);
pWeapon->Dissolve( NULL, gpGlobals->curtime, false, ENTITY_DISSOLVE_NORMAL );
}
}
}
}
BaseClass::Event_Killed( info );
}
//-----------------------------------------------------------------------------
// Purpose: Override. Don't update if I'm not looking
// Input :
// Output : Returns true is new enemy, false is known enemy
//-----------------------------------------------------------------------------
bool CNPC_Combine::UpdateEnemyMemory( CBaseEntity *pEnemy, const Vector &position, CBaseEntity *pInformer )
{
if( m_spawnflags & SF_COMBINE_NO_LOOK )
{
return false;
}
return BaseClass::UpdateEnemyMemory( pEnemy, position, pInformer );
}
//-----------------------------------------------------------------------------
// Purpose: Allows for modification of the interrupt mask for the current schedule.
// In the most cases the base implementation should be called first.
//-----------------------------------------------------------------------------
void CNPC_Combine::BuildScheduleTestBits( void )
{
BaseClass::BuildScheduleTestBits();
if (gpGlobals->curtime < m_flNextAttack)
{
ClearCustomInterruptCondition( COND_CAN_RANGE_ATTACK1 );
ClearCustomInterruptCondition( COND_CAN_RANGE_ATTACK2 );
}
SetCustomInterruptCondition( COND_COMBINE_HIT_BY_BUGBAIT );
if ( !IsCurSchedule( SCHED_COMBINE_BURNING_STAND ) )
{
SetCustomInterruptCondition( COND_COMBINE_ON_FIRE );
}
}
//-----------------------------------------------------------------------------
// Purpose: Translate base class activities into combot activites
//-----------------------------------------------------------------------------
Activity CNPC_Combine::NPC_TranslateActivity( Activity eNewActivity )
{
if (eNewActivity == ACT_RANGE_ATTACK1)
{
if ( !m_bStanding )
{
eNewActivity = ACT_RANGE_ATTACK1_LOW;
}
}
else if (eNewActivity == ACT_RELOAD)
{
if (!m_bStanding)
{
eNewActivity = ACT_RELOAD_LOW;
}
}
else if (eNewActivity == ACT_RANGE_ATTACK2)
{
// grunt is going to a secondary long range attack. This may be a thrown
// grenade or fired grenade, we must determine which and pick proper sequence
if (Weapon_OwnsThisType( "weapon_grenadelauncher" ) )
{
return ( Activity )ACT_COMBINE_LAUNCH_GRENADE;
}
else
{
return ( Activity )ACT_COMBINE_THROW_GRENADE;
}
}
else if (eNewActivity == ACT_RUN)
{
m_bStanding = true;
if ( m_iHealth <= COMBINE_LIMP_HEALTH )
{
// limp!
//return ACT_RUN_HURT;
}
}
else if (eNewActivity == ACT_WALK)
{
m_bStanding = true;
if ( m_iHealth <= COMBINE_LIMP_HEALTH )
{
// limp!
//return ACT_WALK_HURT;
}
}
else if (eNewActivity == ACT_IDLE)
{
if ( !m_bStanding )
{
eNewActivity = ACT_CROUCHIDLE;
}
else if ( m_NPCState == NPC_STATE_COMBAT || m_NPCState == NPC_STATE_ALERT )
{
eNewActivity = ACT_IDLE_ANGRY;
}
}
if ( m_AssaultBehavior.IsRunning() )
{
switch ( eNewActivity )
{
case ACT_IDLE:
eNewActivity = ACT_IDLE_ANGRY;
break;
case ACT_WALK:
eNewActivity = ACT_WALK_AIM;
break;
case ACT_RUN:
eNewActivity = ACT_RUN_AIM;
break;
}
}
return BaseClass::NPC_TranslateActivity( eNewActivity );
}
//-----------------------------------------------------------------------------
// Purpose: Overidden for human grunts because they hear the DANGER sound
// Input :
// Output :
//-----------------------------------------------------------------------------
int CNPC_Combine::GetSoundInterests( void )
{
return SOUND_WORLD | SOUND_COMBAT | SOUND_PLAYER | SOUND_DANGER | SOUND_PHYSICS_DANGER | SOUND_BULLET_IMPACT | SOUND_MOVE_AWAY;
}
//-----------------------------------------------------------------------------
// Purpose: Return true if this NPC can hear the specified sound
//-----------------------------------------------------------------------------
bool CNPC_Combine::QueryHearSound( CSound *pSound )
{
if ( pSound->SoundContext() & SOUND_CONTEXT_COMBINE_ONLY )
return true;
if ( pSound->SoundContext() & SOUND_CONTEXT_EXCLUDE_COMBINE )
return false;
return BaseClass::QueryHearSound( pSound );
}
//-----------------------------------------------------------------------------
// Purpose: Announce an assault if the enemy can see me and we are pretty
// close to him/her
// Input :
// Output :
//-----------------------------------------------------------------------------
void CNPC_Combine::AnnounceAssault(void)
{
if (random->RandomInt(0,5) > 1)
return;
// If enemy can see me make assualt sound
CBaseCombatCharacter* pBCC = GetEnemyCombatCharacterPointer();
if (!pBCC)
return;
if (!FOkToMakeSound())
return;
// Make sure we are pretty close
if ( WorldSpaceCenter().DistToSqr( pBCC->WorldSpaceCenter() ) > (2000 * 2000))
return;
// Make sure we are in view cone of player
if (!pBCC->FInViewCone ( this ))
return;
// Make sure player can see me
if ( FVisible( pBCC ) )
{
m_Sentences.Speak( "COMBINE_ASSAULT" );
}
}
void CNPC_Combine::AnnounceEnemyType( CBaseEntity *pEnemy )
{
const char *pSentenceName = "COMBINE_MONST";
switch ( pEnemy->Classify() )
{
case CLASS_PLAYER:
pSentenceName = "COMBINE_ALERT";
break;
case CLASS_PLAYER_ALLY:
case CLASS_CITIZEN_REBEL:
case CLASS_CITIZEN_PASSIVE:
case CLASS_VORTIGAUNT:
pSentenceName = "COMBINE_MONST_CITIZENS";
break;
case CLASS_PLAYER_ALLY_VITAL:
pSentenceName = "COMBINE_MONST_CHARACTER";
break;
case CLASS_ANTLION:
pSentenceName = "COMBINE_MONST_BUGS";
break;
case CLASS_ZOMBIE:
pSentenceName = "COMBINE_MONST_ZOMBIES";
break;
case CLASS_HEADCRAB:
case CLASS_BARNACLE:
pSentenceName = "COMBINE_MONST_PARASITES";
break;
}
m_Sentences.Speak( pSentenceName, SENTENCE_PRIORITY_HIGH );
}
void CNPC_Combine::AnnounceEnemyKill( CBaseEntity *pEnemy )
{
if (!pEnemy )
return;
const char *pSentenceName = "COMBINE_KILL_MONST";
switch ( pEnemy->Classify() )
{
case CLASS_PLAYER:
pSentenceName = "COMBINE_PLAYER_DEAD";
break;
// no sentences for these guys yet
case CLASS_PLAYER_ALLY:
case CLASS_CITIZEN_REBEL:
case CLASS_CITIZEN_PASSIVE:
case CLASS_VORTIGAUNT:
break;
case CLASS_PLAYER_ALLY_VITAL:
break;
case CLASS_ANTLION:
break;
case CLASS_ZOMBIE:
break;
case CLASS_HEADCRAB:
case CLASS_BARNACLE:
break;
}
m_Sentences.Speak( pSentenceName, SENTENCE_PRIORITY_HIGH );
}
//-----------------------------------------------------------------------------
// Select the combat schedule
//-----------------------------------------------------------------------------
int CNPC_Combine::SelectCombatSchedule()
{
// -----------
// dead enemy
// -----------
if ( HasCondition( COND_ENEMY_DEAD ) )
{
// call base class, all code to handle dead enemies is centralized there.
return SCHED_NONE;
}
// -----------
// new enemy
// -----------
if ( HasCondition( COND_NEW_ENEMY ) )
{
CBaseEntity *pEnemy = GetEnemy();
if ( m_pSquad && pEnemy )
{
if ( m_pSquad->IsLeader( this ) || ( m_pSquad->GetLeader() && m_pSquad->GetLeader()->GetEnemy() != pEnemy ) )
{
// First contact, and I'm the squad leader.
AnnounceEnemyType( pEnemy );
if ( HasCondition( COND_CAN_RANGE_ATTACK1 ) && OccupyStrategySlotRange( SQUAD_SLOT_ATTACK1, SQUAD_SLOT_ATTACK2 ) )
{
return SCHED_COMBINE_SUPPRESS;
}
else
{
return SCHED_COMBINE_ASSAULT;
}
}
else
{
if ( m_pSquad->GetLeader() && FOkToMakeSound( SENTENCE_PRIORITY_MEDIUM ) )
{
JustMadeSound( SENTENCE_PRIORITY_MEDIUM ); // squelch anything that isn't high priority so the leader can speak
}
// First contact, and I'm solo, or not the squad leader.
if( HasCondition( COND_SEE_ENEMY ) && CanGrenadeEnemy() )
{
if( OccupyStrategySlot( SQUAD_SLOT_GRENADE1 ) )
{
return SCHED_RANGE_ATTACK2;
}
}
return SCHED_TAKE_COVER_FROM_ENEMY;
}
}
}
// ---------------------
// no ammo
// ---------------------
if ( ( HasCondition ( COND_NO_PRIMARY_AMMO ) || HasCondition ( COND_LOW_PRIMARY_AMMO ) ) && !HasCondition( COND_CAN_MELEE_ATTACK1) )
{
return SCHED_HIDE_AND_RELOAD;
}
#if 0 //WEDGE
if (!HasCondition(COND_CAN_RANGE_ATTACK1) && HasCondition( COND_NO_SECONDARY_AMMO ))
{
return SCHED_HIDE_AND_RELOAD;
}
#endif
// ----------------------
// LIGHT DAMAGE
// ----------------------
if ( HasCondition( COND_LIGHT_DAMAGE ) )
{
// if hurt:
// 90% chance of taking cover
// 10% chance of flinch.
int iPercent = random->RandomInt(0,99);
if ( iPercent <= 90 && GetEnemy() != NULL )
{
// only try to take cover if we actually have an enemy!
// FIXME: need to take cover for enemy dealing the damage
//!!!KELLY - this grunt was hit and is going to run to cover.
// m_Sentences.Speak( "COMBINE_COVER" );
return SCHED_TAKE_COVER_FROM_ENEMY;
}
else
{
// taking damage should have entered a "null" enemy position into memory
return SCHED_FEAR_FACE;
}
}
int attackSchedule = SelectScheduleAttack();
if ( attackSchedule != SCHED_NONE )
return attackSchedule;
if (HasCondition(COND_ENEMY_OCCLUDED))
{
// stand up, just in case
m_bStanding = true;
m_bCanCrouch = false;
if( GetEnemy() && !(GetEnemy()->GetFlags() & FL_NOTARGET) && OccupyStrategySlotRange( SQUAD_SLOT_ATTACK1, SQUAD_SLOT_ATTACK2 ) )
{
// Charge in and break the enemy's cover!
return SCHED_COMBINE_ESTABLISH_LINE_OF_FIRE;
}
// If I'm a long, long way away, establish a LOF anyway. Once I get there I'll
// start respecting the squad slots again.
float flDistSq = GetEnemy()->WorldSpaceCenter().DistToSqr( WorldSpaceCenter() );
if ( flDistSq > (3000*3000) )
return SCHED_COMBINE_ESTABLISH_LINE_OF_FIRE;
return SCHED_STANDOFF;
}
// --------------------------------------------------------------
// Enemy not occluded but isn't open to attack
// --------------------------------------------------------------
if ( HasCondition( COND_SEE_ENEMY ) && !HasCondition( COND_CAN_RANGE_ATTACK1 ) )
{
if (HasCondition( COND_TOO_FAR_TO_ATTACK ) && OccupyStrategySlotRange( SQUAD_SLOT_ATTACK1, SQUAD_SLOT_ATTACK2 ))
{
return SCHED_COMBINE_PRESS_ATTACK;
}
AnnounceAssault();
return SCHED_COMBINE_ASSAULT;
}
return SCHED_NONE;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input :
// Output :
//-----------------------------------------------------------------------------
int CNPC_Combine::SelectSchedule( void )
{
if ( HasCondition(COND_COMBINE_ON_FIRE) )
return SCHED_COMBINE_BURNING_STAND;
int nSched = SelectFlinchSchedule();
if ( nSched != SCHED_NONE )
return nSched;
if ( m_NPCState != NPC_STATE_SCRIPT)
{
// If we're hit by bugbait, thrash around
if ( HasCondition( COND_COMBINE_HIT_BY_BUGBAIT ) )
{
// Don't do this if we're mounting a func_tank
if ( m_FuncTankBehavior.IsMounted() == true )
{
m_FuncTankBehavior.Dismount();
}
ClearCondition( COND_COMBINE_HIT_BY_BUGBAIT );
return SCHED_COMBINE_BUGBAIT_DISTRACTION;
}
// We've been told to move away from a target to make room for a grenade to be thrown at it
if ( HasCondition( COND_HEAR_MOVE_AWAY ) )
{
return SCHED_MOVE_AWAY;
}
// These things are done in any state but dead and prone
if (m_NPCState != NPC_STATE_DEAD && m_NPCState != NPC_STATE_PRONE )
{
// Cower when physics objects are thrown at me
if ( HasCondition( COND_HEAR_PHYSICS_DANGER ) )
return SCHED_FLINCH_PHYSICS;
// grunts place HIGH priority on running away from danger sounds.
if ( HasCondition(COND_HEAR_DANGER) )
{
CSound *pSound;
pSound = GetBestSound();
Assert( pSound != NULL );
if ( pSound)
{
if (pSound->m_iType & SOUND_DANGER)
{
// I hear something dangerous, probably need to take cover.
// dangerous sound nearby!, call it out
const char *pSentenceName = "COMBINE_DANGER";
CBaseEntity *pSoundOwner = pSound->m_hOwner;
if ( pSoundOwner )
{
CBaseGrenade *pGrenade = dynamic_cast<CBaseGrenade *>(pSoundOwner);
if ( pGrenade && pGrenade->GetThrower() )
{
if ( IRelationType( pGrenade->GetThrower() ) != D_LI )
{
// special case call out for enemy grenades
pSentenceName = "COMBINE_GREN";
}
}
}
m_Sentences.Speak( pSentenceName, SENTENCE_PRIORITY_NORMAL, SENTENCE_CRITERIA_NORMAL );
return SCHED_TAKE_COVER_FROM_BEST_SOUND;
}
// JAY: This was disabled in HL1. Test?
if (!HasCondition( COND_SEE_ENEMY ) && ( pSound->m_iType & (SOUND_PLAYER | SOUND_COMBAT) ))
{
GetMotor()->SetIdealYawToTarget( pSound->GetSoundReactOrigin() );
}
}
}
}
if( BehaviorSelectSchedule() )
{
return BaseClass::SelectSchedule();
}
}
switch ( m_NPCState )
{
case NPC_STATE_IDLE:
{
if ( m_bShouldPatrol )
return SCHED_COMBINE_PATROL;
}
// NOTE: Fall through!
case NPC_STATE_ALERT:
{
if( HasCondition(COND_LIGHT_DAMAGE) || HasCondition(COND_HEAVY_DAMAGE) )
{
AI_EnemyInfo_t *pDanger = GetEnemies()->GetDangerMemory();
if( pDanger && FInViewCone(pDanger->vLastKnownLocation) && !BaseClass::FVisible(pDanger->vLastKnownLocation) )
{
// I've been hurt, I'm facing the danger, but I don't see it, so move from this position.
return SCHED_TAKE_COVER_FROM_ORIGIN;
}
}
if( HasCondition( COND_HEAR_COMBAT ) )
{
if( m_pSquad && OccupyStrategySlot( SQUAD_SLOT_INVESTIGATE_SOUND ) )
return SCHED_INVESTIGATE_SOUND;
}
// Don't patrol if I'm in the middle of an assault, because I'll never return to the assault.
if ( !m_AssaultBehavior.HasAssaultCue() )
{
if( m_bShouldPatrol || HasCondition( COND_COMBINE_SHOULD_PATROL ) )
return SCHED_COMBINE_PATROL;
}
}
break;
case NPC_STATE_COMBAT:
{
int nSched = SelectCombatSchedule();
if ( nSched != SCHED_NONE )
return nSched;
}
break;
}
// no special cases here, call the base class
return BaseClass::SelectSchedule();
}
//-----------------------------------------------------------------------------
// Should we charge the player?
//-----------------------------------------------------------------------------
bool CNPC_Combine::ShouldChargePlayer()
{
return GetEnemy() && GetEnemy()->IsPlayer() && PlayerHasMegaPhysCannon() && !IsLimitingHintGroups();
}
//-----------------------------------------------------------------------------
// Select attack schedules
//-----------------------------------------------------------------------------
#define COMBINE_MEGA_PHYSCANNON_ATTACK_DISTANCE 192
#define COMBINE_MEGA_PHYSCANNON_ATTACK_DISTANCE_SQ (COMBINE_MEGA_PHYSCANNON_ATTACK_DISTANCE*COMBINE_MEGA_PHYSCANNON_ATTACK_DISTANCE)
int CNPC_Combine::SelectScheduleAttack()
{
// Drop a grenade?
if ( HasCondition( COND_COMBINE_DROP_GRENADE ) )
return SCHED_COMBINE_DROP_GRENADE;
// Kick attack?
if ( HasCondition( COND_CAN_MELEE_ATTACK1 ) )
{
return SCHED_MELEE_ATTACK1;
}
// If I'm fighting a combine turret (it's been hacked to attack me), I can't really
// hurt it with bullets, so become grenade happy.
if ( GetEnemy() && GetEnemy()->Classify() == CLASS_COMBINE && FClassnameIs(GetEnemy(), "npc_turret_floor") )
{
// Don't do this until I've been fighting the turret for a few seconds
float flTimeAtFirstHand = GetEnemies()->TimeAtFirstHand(GetEnemy());
if ( flTimeAtFirstHand != AI_INVALID_TIME )
{
float flTimeEnemySeen = gpGlobals->curtime - flTimeAtFirstHand;
if ( flTimeEnemySeen > 4.0 )
{
if ( CanGrenadeEnemy() && OccupyStrategySlot( SQUAD_SLOT_GRENADE1 ) )
return SCHED_RANGE_ATTACK2;
}
}
// If we're not in the viewcone of the turret, run up and hit it. Do this a bit later to
// give other squadmembers a chance to throw a grenade before I run in.
if ( !GetEnemy()->MyNPCPointer()->FInViewCone( this ) && OccupyStrategySlot( SQUAD_SLOT_GRENADE1 ) )
return SCHED_COMBINE_CHARGE_TURRET;
}
// When fighting against the player who's wielding a mega-physcannon,
// always close the distance if possible
// But don't do it if you're in a nav-limited hint group
if ( ShouldChargePlayer() )
{
float flDistSq = GetEnemy()->WorldSpaceCenter().DistToSqr( WorldSpaceCenter() );
if ( flDistSq <= COMBINE_MEGA_PHYSCANNON_ATTACK_DISTANCE_SQ )
{
if ( OccupyStrategySlotRange( SQUAD_SLOT_ATTACK1, SQUAD_SLOT_ATTACK2 ) )
return SCHED_RANGE_ATTACK1;
}
if ( HasCondition(COND_SEE_ENEMY) && !IsUnreachable( GetEnemy() ) )
{
return SCHED_COMBINE_CHARGE_PLAYER;
}
}
// Can I shoot?
if ( HasCondition(COND_CAN_RANGE_ATTACK1) )
{
// JAY: HL1 behavior missing?
#if 0
if ( m_pSquad )
{
// if the enemy has eluded the squad and a squad member has just located the enemy
// and the enemy does not see the squad member, issue a call to the squad to waste a
// little time and give the player a chance to turn.
if ( MySquadLeader()->m_fEnemyEluded && !HasConditions ( bits_COND_ENEMY_FACING_ME ) )
{
MySquadLeader()->m_fEnemyEluded = FALSE;
return SCHED_GRUNT_FOUND_ENEMY;
}
}
#endif
// Engage if allowed
if ( OccupyStrategySlotRange( SQUAD_SLOT_ATTACK1, SQUAD_SLOT_ATTACK2 ) )
{
return SCHED_RANGE_ATTACK1;
}
// Throw a grenade if not allowed to engage with weapon.
if ( CanGrenadeEnemy() )
{
if ( OccupyStrategySlot( SQUAD_SLOT_GRENADE1 ) )
{
return SCHED_RANGE_ATTACK2;
}
}
m_bCanCrouch = true;
return SCHED_TAKE_COVER_FROM_ENEMY;
}
if ( GetEnemy() && !HasCondition(COND_SEE_ENEMY) )
{
// We don't see our enemy. If it hasn't been long since I last saw him,
// and he's pretty close to the last place I saw him, throw a grenade in
// to flush him out. A wee bit of cheating here...
float flTime;
float flDist;
flTime = gpGlobals->curtime - GetEnemies()->LastTimeSeen( GetEnemy() );
flDist = ( GetEnemy()->GetAbsOrigin() - GetEnemies()->LastSeenPosition( GetEnemy() ) ).Length();
//Msg("Time: %f Dist: %f\n", flTime, flDist );
if ( flTime <= COMBINE_GRENADE_FLUSH_TIME && flDist <= COMBINE_GRENADE_FLUSH_DIST && CanGrenadeEnemy( false ) && OccupyStrategySlot( SQUAD_SLOT_GRENADE1 ) )
{
return SCHED_RANGE_ATTACK2;
}
}
if (HasCondition(COND_WEAPON_SIGHT_OCCLUDED))
{
// If they are hiding behind something that we can destroy, start shooting at it.
CBaseEntity *pBlocker = GetEnemyOccluder();
if ( pBlocker && pBlocker->GetHealth() > 0 && OccupyStrategySlot( SQUAD_SLOT_ATTACK_OCCLUDER ) )
{
return SCHED_SHOOT_ENEMY_COVER;
}
}
return SCHED_NONE;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input :
// Output :
//-----------------------------------------------------------------------------
int CNPC_Combine::TranslateSchedule( int scheduleType )
{
switch( scheduleType )
{
case SCHED_TAKE_COVER_FROM_ENEMY:
{
if ( m_pSquad )
{
// Have to explicitly check innate range attack condition as may have weapon with range attack 2
if ( g_pGameRules->IsSkillLevel( SKILL_HARD ) &&
HasCondition(COND_CAN_RANGE_ATTACK2) &&
OccupyStrategySlot( SQUAD_SLOT_GRENADE1 ) )
{
m_Sentences.Speak( "COMBINE_THROW_GRENADE" );
return SCHED_COMBINE_TOSS_GRENADE_COVER1;
}
else
{
if ( ShouldChargePlayer() && !IsUnreachable( GetEnemy() ) )
return SCHED_COMBINE_CHARGE_PLAYER;
return SCHED_COMBINE_TAKE_COVER1;
}
}
else
{
// Have to explicitly check innate range attack condition as may have weapon with range attack 2
if ( random->RandomInt(0,1) && HasCondition(COND_CAN_RANGE_ATTACK2) )
{
return SCHED_COMBINE_GRENADE_COVER1;
}
else
{
if ( ShouldChargePlayer() && !IsUnreachable( GetEnemy() ) )
return SCHED_COMBINE_CHARGE_PLAYER;
return SCHED_COMBINE_TAKE_COVER1;
}
}
}
case SCHED_TAKE_COVER_FROM_BEST_SOUND:
{
return SCHED_COMBINE_TAKE_COVER_FROM_BEST_SOUND;
}
break;
case SCHED_COMBINE_TAKECOVER_FAILED:
{
if ( HasCondition( COND_CAN_RANGE_ATTACK1 ) && OccupyStrategySlotRange( SQUAD_SLOT_ATTACK1, SQUAD_SLOT_ATTACK2 ) )
{
return TranslateSchedule( SCHED_RANGE_ATTACK1 );
}
// Run somewhere randomly
return TranslateSchedule( SCHED_FAIL );
break;
}
break;
case SCHED_FAIL_ESTABLISH_LINE_OF_FIRE:
{
if( HasCondition( COND_SEE_ENEMY ) )
{
return TranslateSchedule( SCHED_TAKE_COVER_FROM_ENEMY );
}
else
{
if ( GetEnemy() )
RememberUnreachable( GetEnemy() );
return TranslateSchedule( SCHED_COMBINE_PATROL );
}
}
break;
case SCHED_COMBINE_ASSAULT:
{
CBaseEntity *pEntity = GetEnemy();
// FIXME: this should be generalized by the schedules that are selected, or in the definition of
// what "cover" means (i.e., trace attack vulnerability vs. physical attack vulnerability
if (pEntity && pEntity->MyNPCPointer())
{
if ( !(pEntity->MyNPCPointer()->CapabilitiesGet( ) & bits_CAP_WEAPON_RANGE_ATTACK1))
{
return TranslateSchedule( SCHED_ESTABLISH_LINE_OF_FIRE );
}
}
// don't charge forward if there's a hint group
if (GetHintGroup() != NULL_STRING)
{
return TranslateSchedule( SCHED_ESTABLISH_LINE_OF_FIRE );
}
return SCHED_COMBINE_ASSAULT;
}
case SCHED_ESTABLISH_LINE_OF_FIRE:
{
// always assume standing
m_bStanding = true;
if( CanAltFireEnemy(true) && OccupyStrategySlot(SQUAD_SLOT_SPECIAL_ATTACK) )
{
// If an elite in the squad could fire a combine ball at the player's last known position,
// do so!
return SCHED_COMBINE_AR2_ALTFIRE;
}
return SCHED_COMBINE_ESTABLISH_LINE_OF_FIRE;
}
break;
case SCHED_HIDE_AND_RELOAD:
{
// stand up, just in case
// m_bStanding = true;
// m_bCanCrouch = true;
if( CanGrenadeEnemy() && OccupyStrategySlot( SQUAD_SLOT_GRENADE1 ) && random->RandomInt( 0, 100 ) < 20 )
{
// If I COULD throw a grenade and I need to reload, 20% chance I'll throw a grenade before I hide to reload.
return SCHED_COMBINE_GRENADE_AND_RELOAD;
}
// No running away in the citadel!
if ( ShouldChargePlayer() )
return SCHED_RELOAD;
return SCHED_COMBINE_HIDE_AND_RELOAD;
}
break;
case SCHED_RANGE_ATTACK1:
{
if ( HasCondition( COND_NO_PRIMARY_AMMO ) || HasCondition( COND_LOW_PRIMARY_AMMO ) )
{
return TranslateSchedule( SCHED_HIDE_AND_RELOAD );
}
if( CanAltFireEnemy(true) && OccupyStrategySlot(SQUAD_SLOT_SPECIAL_ATTACK) )
{
// Since I'm holding this squadslot, no one else can try right now. If I die before the shot
// goes off, I won't have affected anyone else's ability to use this attack at their nearest
// convenience.
return SCHED_COMBINE_AR2_ALTFIRE;
}
if (m_bCanCrouch && !HasCondition( COND_HEAVY_DAMAGE ))
{
// See if we can crouch and shoot
if (GetEnemy() != NULL)
{
float dist = (GetLocalOrigin() - GetEnemy()->GetLocalOrigin()).Length();
// only crouch if they are relativly far away
if (dist > COMBINE_MIN_CROUCH_DISTANCE)
{
// try crouching
m_bStanding = false;
Vector targetPos = GetEnemy()->BodyTarget(GetActiveWeapon()->GetLocalOrigin());
// if we can't see it crouched, stand up
if (!WeaponLOSCondition(GetLocalOrigin(),targetPos,false))
{
m_bStanding = true;
}
}
}
}
else
{
// always assume standing
m_bStanding = true;
}
return SCHED_COMBINE_RANGE_ATTACK1;
}
case SCHED_RANGE_ATTACK2:
{
// If my weapon can range attack 2 use the weapon
if (GetActiveWeapon() && GetActiveWeapon()->CapabilitiesGet() & bits_CAP_WEAPON_RANGE_ATTACK2)
{
return SCHED_RANGE_ATTACK2;
}
// Otherwise use innate attack
else
{
return SCHED_COMBINE_RANGE_ATTACK2;
}
}
// SCHED_COMBAT_FACE:
// SCHED_COMBINE_WAIT_FACE_ENEMY:
// SCHED_COMBINE_SWEEP:
// SCHED_COMBINE_COVER_AND_RELOAD:
// SCHED_COMBINE_FOUND_ENEMY:
case SCHED_VICTORY_DANCE:
{
return SCHED_COMBINE_VICTORY_DANCE;
}
case SCHED_COMBINE_SUPPRESS:
{
#define MIN_SIGNAL_DIST 256
if ( GetEnemy() != NULL && GetEnemy()->IsPlayer() && m_bFirstEncounter )
{
float flDistToEnemy = ( GetEnemy()->GetAbsOrigin() - GetAbsOrigin() ).Length();
if( flDistToEnemy >= MIN_SIGNAL_DIST )
{
m_bFirstEncounter = false;// after first encounter, leader won't issue handsigns anymore when he has a new enemy
return SCHED_COMBINE_SIGNAL_SUPPRESS;
}
}
return SCHED_COMBINE_SUPPRESS;
}
case SCHED_FAIL:
{
if ( GetEnemy() != NULL )
{
return SCHED_COMBINE_COMBAT_FAIL;
}
return SCHED_FAIL;
}
case SCHED_COMBINE_PATROL:
{
// If I have an enemy, don't go off into random patrol mode.
if ( GetEnemy() && GetEnemy()->IsAlive() )
return SCHED_COMBINE_PATROL_ENEMY;
return SCHED_COMBINE_PATROL;
}
}
return BaseClass::TranslateSchedule( scheduleType );
}
//=========================================================
//=========================================================
void CNPC_Combine::OnStartSchedule( int scheduleType )
{
}
//=========================================================
// HandleAnimEvent - catches the monster-specific messages
// that occur when tagged animation frames are played.
//=========================================================
void CNPC_Combine::HandleAnimEvent( animevent_t *pEvent )
{
Vector vecShootDir;
Vector vecShootOrigin;
bool handledEvent = false;
if (pEvent->type & AE_TYPE_NEWEVENTSYSTEM)
{
if( pEvent->event == COMBINE_AE_BEGIN_ALTFIRE )
{
EmitSound( "Weapon_CombineGuard.Special1" );
return;
}
if( pEvent->event == COMBINE_AE_ALTFIRE )
{
if( IsElite() )
{
animevent_t fakeEvent;
fakeEvent.pSource = this;
fakeEvent.event = EVENT_WEAPON_AR2_ALTFIRE;
GetActiveWeapon()->Operator_HandleAnimEvent( &fakeEvent, this );
// Stop other squad members from combine balling for a while.
DelaySquadAltFireAttack( 10.0f );
m_iNumGrenades--;
}
return;
}
}
switch( pEvent->event )
{
case COMBINE_AE_AIM:
{
handledEvent = true;
break;
}
case COMBINE_AE_RELOAD:
// We never actually run out of ammo, just need to refill the clip
if (GetActiveWeapon())
{
GetActiveWeapon()->WeaponSound( RELOAD_NPC );
GetActiveWeapon()->m_iClip1 = GetActiveWeapon()->GetMaxClip1();
GetActiveWeapon()->m_iClip2 = GetActiveWeapon()->GetMaxClip2();
}
ClearCondition(COND_LOW_PRIMARY_AMMO);
ClearCondition(COND_NO_PRIMARY_AMMO);
ClearCondition(COND_NO_SECONDARY_AMMO);
handledEvent = true;
break;
case COMBINE_AE_GREN_TOSS:
{
Vector vecSpin;
vecSpin.x = random->RandomFloat( -1000.0, 1000.0 );
vecSpin.y = random->RandomFloat( -1000.0, 1000.0 );
vecSpin.z = random->RandomFloat( -1000.0, 1000.0 );
Vector vecStart;
GetAttachment( "lefthand", vecStart );
if( m_NPCState == NPC_STATE_SCRIPT )
{
// Use a fixed velocity for grenades thrown in scripted state.
// Grenades thrown from a script do not count against grenades remaining for the AI to use.
Vector forward, up, vecThrow;
GetVectors( &forward, NULL, &up );
vecThrow = forward * 750 + up * 175;
Fraggrenade_Create( vecStart, vec3_angle, vecThrow, vecSpin, this, COMBINE_GRENADE_TIMER );
}
else
{
// Use the Velocity that AI gave us.
Fraggrenade_Create( vecStart, vec3_angle, m_vecTossVelocity, vecSpin, this, COMBINE_GRENADE_TIMER );
m_iNumGrenades--;
}
// wait six seconds before even looking again to see if a grenade can be thrown.
m_flNextGrenadeCheck = gpGlobals->curtime + 6;
}
handledEvent = true;
break;
case COMBINE_AE_GREN_LAUNCH:
{
EmitSound( "NPC_Combine.GrenadeLaunch" );
CBaseEntity *pGrenade = CreateNoSpawn( "npc_contactgrenade", Weapon_ShootPosition(), vec3_angle, this );
pGrenade->KeyValue( "velocity", m_vecTossVelocity );
pGrenade->Spawn( );
if ( g_pGameRules->IsSkillLevel(SKILL_HARD) )
m_flNextGrenadeCheck = gpGlobals->curtime + random->RandomFloat( 2, 5 );// wait a random amount of time before shooting again
else
m_flNextGrenadeCheck = gpGlobals->curtime + 6;// wait six seconds before even looking again to see if a grenade can be thrown.
}
handledEvent = true;
break;
case COMBINE_AE_GREN_DROP:
{
Vector vecStart;
GetAttachment( "lefthand", vecStart );
Fraggrenade_Create( vecStart, vec3_angle, m_vecTossVelocity, vec3_origin, this, COMBINE_GRENADE_TIMER );
m_iNumGrenades--;
}
handledEvent = true;
break;
case COMBINE_AE_KICK:
{
// Does no damage, because damage is applied based upon whether the target can handle the interaction
CBaseEntity *pHurt = CheckTraceHullAttack( 70, -Vector(16,16,18), Vector(16,16,18), 0, DMG_CLUB );
CBaseCombatCharacter* pBCC = ToBaseCombatCharacter( pHurt );
if (pBCC)
{
Vector forward, up;
AngleVectors( GetLocalAngles(), &forward, NULL, &up );
if ( !pBCC->DispatchInteraction( g_interactionCombineBash, NULL, this ) )
{
pBCC->ViewPunch( QAngle(-12,-7,0) );
pHurt->ApplyAbsVelocityImpulse( forward * 100 + up * 50 );
CTakeDamageInfo info( this, this, m_nKickDamage, DMG_CLUB );
CalculateMeleeDamageForce( &info, forward, pBCC->GetAbsOrigin() );
pBCC->TakeDamage( info );
EmitSound( "NPC_Combine.WeaponBash" );
}
}
m_Sentences.Speak( "COMBINE_KICK" );
handledEvent = true;
break;
}
case COMBINE_AE_CAUGHT_ENEMY:
m_Sentences.Speak( "COMBINE_ALERT" );
handledEvent = true;
break;
default:
BaseClass::HandleAnimEvent( pEvent );
break;
}
if( handledEvent )
{
m_iLastAnimEventHandled = pEvent->event;
}
}
//-----------------------------------------------------------------------------
// Purpose: Get shoot position of BCC at an arbitrary position
// Input :
// Output :
//-----------------------------------------------------------------------------
Vector CNPC_Combine::Weapon_ShootPosition( )
{
bool bStanding = m_bStanding;
Vector right;
GetVectors( NULL, &right, NULL );
if ((CapabilitiesGet() & bits_CAP_DUCK) )
{
if ( IsCrouchedActivity( GetActivity() ) )
bStanding = false;
}
// FIXME: rename this "estimated" since it's not based on animation
// FIXME: the orientation won't be correct when testing from arbitary positions for arbitary angles
if ( bStanding )
{
if( HasShotgun() )
{
return GetAbsOrigin() + COMBINE_SHOTGUN_STANDING_POSITION + right * 8;
}
else
{
return GetAbsOrigin() + COMBINE_GUN_STANDING_POSITION + right * 8;
}
}
else
{
if( HasShotgun() )
{
return GetAbsOrigin() + COMBINE_SHOTGUN_CROUCHING_POSITION + right * 8;
}
else
{
return GetAbsOrigin() + COMBINE_GUN_CROUCHING_POSITION + right * 8;
}
}
}
//=========================================================
// Speak Sentence - say your cued up sentence.
//
// Some grunt sentences (take cover and charge) rely on actually
// being able to execute the intended action. It's really lame
// when a grunt says 'COVER ME' and then doesn't move. The problem
// is that the sentences were played when the decision to TRY
// to move to cover was made. Now the sentence is played after
// we know for sure that there is a valid path. The schedule
// may still fail but in most cases, well after the grunt has
// started moving.
//=========================================================
void CNPC_Combine::SpeakSentence( int sentenceType )
{
switch( sentenceType )
{
case 0: // assault
AnnounceAssault();
break;
case 1: // Flanking the player
// If I'm moving more than 20ft, I need to talk about it
if ( GetNavigator()->GetPath()->GetPathLength() > 20 * 12.0f )
{
m_Sentences.Speak( "COMBINE_FLANK" );
}
break;
}
}
//=========================================================
// PainSound
//=========================================================
void CNPC_Combine::PainSound ( void )
{
// NOTE: The response system deals with this at the moment
if ( GetFlags() & FL_DISSOLVING )
return;
if ( gpGlobals->curtime > m_flNextPainSoundTime )
{
const char *pSentenceName = "COMBINE_PAIN";
float healthRatio = (float)GetHealth() / (float)GetMaxHealth();
if ( !HasMemory(bits_MEMORY_PAIN_LIGHT_SOUND) && healthRatio > 0.9 )
{
Remember( bits_MEMORY_PAIN_LIGHT_SOUND );
pSentenceName = "COMBINE_TAUNT";
}
else if ( !HasMemory(bits_MEMORY_PAIN_HEAVY_SOUND) && healthRatio < 0.25 )
{
Remember( bits_MEMORY_PAIN_HEAVY_SOUND );
pSentenceName = "COMBINE_COVER";
}
m_Sentences.Speak( pSentenceName, SENTENCE_PRIORITY_INVALID, SENTENCE_CRITERIA_ALWAYS );
m_flNextPainSoundTime = gpGlobals->curtime + 1;
}
}
//-----------------------------------------------------------------------------
// Purpose: implemented by subclasses to give them an opportunity to make
// a sound when they lose their enemy
// Input :
// Output :
//-----------------------------------------------------------------------------
void CNPC_Combine::LostEnemySound( void)
{
if ( gpGlobals->curtime <= m_flNextLostSoundTime )
return;
const char *pSentence;
if (!(CBaseEntity*)GetEnemy() || gpGlobals->curtime - GetEnemyLastTimeSeen() > 10)
{
pSentence = "COMBINE_LOST_LONG";
}
else
{
pSentence = "COMBINE_LOST_SHORT";
}
if ( m_Sentences.Speak( pSentence ) >= 0 )
{
m_flNextLostSoundTime = gpGlobals->curtime + random->RandomFloat(5.0,15.0);
}
}
//-----------------------------------------------------------------------------
// Purpose: implemented by subclasses to give them an opportunity to make
// a sound when they lose their enemy
// Input :
// Output :
//-----------------------------------------------------------------------------
void CNPC_Combine::FoundEnemySound( void)
{
m_Sentences.Speak( "COMBINE_REFIND_ENEMY", SENTENCE_PRIORITY_HIGH );
}
//-----------------------------------------------------------------------------
// Purpose: Implemented by subclasses to give them an opportunity to make
// a sound before they attack
// Input :
// Output :
//-----------------------------------------------------------------------------
// BUGBUG: It looks like this is never played because combine don't do SCHED_WAKE_ANGRY or anything else that does a TASK_SOUND_WAKE
void CNPC_Combine::AlertSound( void)
{
if ( gpGlobals->curtime > m_flNextAlertSoundTime )
{
m_Sentences.Speak( "COMBINE_GO_ALERT", SENTENCE_PRIORITY_HIGH );
m_flNextAlertSoundTime = gpGlobals->curtime + 10.0f;
}
}
//=========================================================
// NotifyDeadFriend
//=========================================================
void CNPC_Combine::NotifyDeadFriend ( CBaseEntity* pFriend )
{
if ( GetSquad()->NumMembers() < 2 )
{
m_Sentences.Speak( "COMBINE_LAST_OF_SQUAD", SENTENCE_PRIORITY_INVALID, SENTENCE_CRITERIA_NORMAL );
JustMadeSound();
return;
}
// relaxed visibility test so that guys say this more often
//if( FInViewCone( pFriend ) && FVisible( pFriend ) )
{
m_Sentences.Speak( "COMBINE_MAN_DOWN" );
}
BaseClass::NotifyDeadFriend(pFriend);
}
//=========================================================
// DeathSound
//=========================================================
void CNPC_Combine::DeathSound ( void )
{
// NOTE: The response system deals with this at the moment
if ( GetFlags() & FL_DISSOLVING )
return;
m_Sentences.Speak( "COMBINE_DIE", SENTENCE_PRIORITY_INVALID, SENTENCE_CRITERIA_ALWAYS );
}
//=========================================================
// IdleSound
//=========================================================
void CNPC_Combine::IdleSound( void )
{
if (g_fCombineQuestion || random->RandomInt(0,1))
{
if (!g_fCombineQuestion)
{
// ask question or make statement
switch (random->RandomInt(0,2))
{
case 0: // check in
if ( m_Sentences.Speak( "COMBINE_CHECK" ) >= 0 )
{
g_fCombineQuestion = 1;
}
break;
case 1: // question
if ( m_Sentences.Speak( "COMBINE_QUEST" ) >= 0 )
{
g_fCombineQuestion = 2;
}
break;
case 2: // statement
m_Sentences.Speak( "COMBINE_IDLE" );
break;
}
}
else
{
switch (g_fCombineQuestion)
{
case 1: // check in
if ( m_Sentences.Speak( "COMBINE_CLEAR" ) >= 0 )
{
g_fCombineQuestion = 0;
}
break;
case 2: // question
if ( m_Sentences.Speak( "COMBINE_ANSWER" ) >= 0 )
{
g_fCombineQuestion = 0;
}
break;
}
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//
// This is for Grenade attacks. As the test for grenade attacks
// is expensive we don't want to do it every frame. Return true
// if we meet minimum set of requirements and then test for actual
// throw later if we actually decide to do a grenade attack.
// Input :
// Output :
//-----------------------------------------------------------------------------
int CNPC_Combine::RangeAttack2Conditions( float flDot, float flDist )
{
return COND_NONE;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CNPC_Combine::CanThrowGrenade( const Vector &vecTarget )
{
if( m_iNumGrenades < 1 )
{
// Out of grenades!
return false;
}
if (gpGlobals->curtime < m_flNextGrenadeCheck )
{
// Not allowed to throw another grenade right now.
return false;
}
float flDist;
flDist = ( vecTarget - GetAbsOrigin() ).Length();
if( flDist > 1024 || flDist < 128 )
{
// Too close or too far!
m_flNextGrenadeCheck = gpGlobals->curtime + 1; // one full second.
return false;
}
// -----------------------
// If moving, don't check.
// -----------------------
if ( m_flGroundSpeed != 0 )
return false;
#if 0
Vector vecEnemyLKP = GetEnemyLKP();
if ( !( GetEnemy()->GetFlags() & FL_ONGROUND ) && GetEnemy()->GetWaterLevel() == 0 && vecEnemyLKP.z > (GetAbsOrigin().z + WorldAlignMaxs().z) )
{
//!!!BUGBUG - we should make this check movetype and make sure it isn't FLY? Players who jump a lot are unlikely to
// be grenaded.
// don't throw grenades at anything that isn't on the ground!
return COND_NONE;
}
#endif
// ---------------------------------------------------------------------
// Are any of my squad members near the intended grenade impact area?
// ---------------------------------------------------------------------
if ( m_pSquad )
{
if (m_pSquad->SquadMemberInRange( vecTarget, COMBINE_MIN_GRENADE_CLEAR_DIST ))
{
// crap, I might blow my own guy up. Don't throw a grenade and don't check again for a while.
m_flNextGrenadeCheck = gpGlobals->curtime + 1; // one full second.
// Tell my squad members to clear out so I can get a grenade in
CSoundEnt::InsertSound( SOUND_MOVE_AWAY | SOUND_CONTEXT_COMBINE_ONLY, vecTarget, COMBINE_MIN_GRENADE_CLEAR_DIST, 0.1 );
return false;
}
}
//NDebugOverlay::Line( EyePosition(), vecTarget, 0, 255, 0, false, 5 );
// ---------------------------------------------------------------------
// Check that throw is legal and clear
// ---------------------------------------------------------------------
// FIXME: this is only valid for hand grenades, not RPG's
Vector vecToss;
Vector vecMins = -Vector(4,4,4);
Vector vecMaxs = Vector(4,4,4);
if( FInViewCone( vecTarget ) && CBaseEntity::FVisible( vecTarget ) )
{
vecToss = VecCheckThrow( this, EyePosition(), vecTarget, COMBINE_GRENADE_THROW_SPEED, 1.0, &vecMins, &vecMaxs );
}
else
{
// Have to try a high toss. Do I have enough room?
trace_t tr;
AI_TraceLine( EyePosition(), EyePosition() + Vector( 0, 0, 64 ), MASK_SHOT, this, COLLISION_GROUP_NONE, &tr );
if( tr.fraction != 1.0 )
{
return false;
}
vecToss = VecCheckToss( this, EyePosition(), vecTarget, -1, 1.0, true, &vecMins, &vecMaxs );
}
if ( vecToss != vec3_origin )
{
m_vecTossVelocity = vecToss;
// don't check again for a while.
m_flNextGrenadeCheck = gpGlobals->curtime + 1; // 1/3 second.
return true;
}
else
{
// don't check again for a while.
m_flNextGrenadeCheck = gpGlobals->curtime + 1; // one full second.
return false;
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CNPC_Combine::CanAltFireEnemy( bool bUseFreeKnowledge )
{
if (!IsElite() )
return false;
if (!m_bStanding)
return false;
if( gpGlobals->curtime < m_flNextAltFireTime )
return false;
if( !GetEnemy() )
return false;
if (gpGlobals->curtime < m_flNextGrenadeCheck )
return false;
if (m_iNumGrenades < 1)
return false;
CBaseEntity *pEnemy = GetEnemy();
if( !pEnemy->IsPlayer() && (!pEnemy->IsNPC() || !pEnemy->MyNPCPointer()->IsPlayerAlly()) )
return false;
Vector vecTarget;
if( bUseFreeKnowledge )
{
vecTarget = GetEnemies()->LastKnownPosition( pEnemy ) + (pEnemy->GetViewOffset()*0.75);// approximates the chest
}
else
{
vecTarget = GetEnemies()->LastSeenPosition( pEnemy ) + (pEnemy->GetViewOffset()*0.75);// approximates the chest
trace_t tr;
Vector mins( -12, -12, -12 );
Vector maxs( 12, 12, 12 );
// Trace a hull about the size of the combine ball.
UTIL_TraceHull( EyePosition(), GetEnemies()->LastSeenPosition( pEnemy ), mins, maxs, MASK_SHOT, this, COLLISION_GROUP_NONE, &tr );
if( tr.fraction != 1.0 )
{
vecTarget += tr.plane.normal * 16;
}
}
if( BaseClass::FVisible( vecTarget ) )
{
m_vecAltFireTarget = vecTarget;
return true;
}
// Not now. Check again later.
m_vecAltFireTarget = vec3_origin;
m_flNextGrenadeCheck = gpGlobals->curtime + 1.0f;
return false;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CNPC_Combine::CanGrenadeEnemy( bool bUseFreeKnowledge )
{
if( IsElite() )
return false;
CBaseEntity *pEnemy = GetEnemy();
Assert( pEnemy != NULL );
if( pEnemy )
{
// I'm not allowed to throw grenades during dustoff
if ( IsCurSchedule(SCHED_DROPSHIP_DUSTOFF) )
return false;
if( bUseFreeKnowledge )
{
// throw to where we think they are.
return CanThrowGrenade( GetEnemies()->LastKnownPosition( pEnemy ) );
}
else
{
// hafta throw to where we last saw them.
return CanThrowGrenade( GetEnemies()->LastSeenPosition( pEnemy ) );
}
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose: For combine melee attack (kick/hit)
// Input :
// Output :
//-----------------------------------------------------------------------------
int CNPC_Combine::MeleeAttack1Conditions ( float flDot, float flDist )
{
if (flDist > 64)
{
return COND_NONE; // COND_TOO_FAR_TO_ATTACK;
}
else if (flDot < 0.7)
{
return COND_NONE; // COND_NOT_FACING_ATTACK;
}
// Check Z
if ( GetEnemy() && fabs(GetEnemy()->GetAbsOrigin().z - GetAbsOrigin().z) > 64 )
return COND_NONE;
if ( dynamic_cast<CBaseHeadcrab *>(GetEnemy()) != NULL )
{
return COND_NONE;
}
// Make sure not trying to kick through a window or something.
trace_t tr;
Vector vecSrc, vecEnd;
vecSrc = WorldSpaceCenter();
vecEnd = GetEnemy()->WorldSpaceCenter();
AI_TraceLine(vecSrc, vecEnd, MASK_SHOT, this, COLLISION_GROUP_NONE, &tr);
if( tr.m_pEnt != GetEnemy() )
{
return COND_NONE;
}
return COND_CAN_MELEE_ATTACK1;
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Vector
//-----------------------------------------------------------------------------
Vector CNPC_Combine::EyePosition( void )
{
if ( m_bStanding )
{
return GetAbsOrigin() + COMBINE_EYE_STANDING_POSITION;
}
else
{
return GetAbsOrigin() + COMBINE_EYE_CROUCHING_POSITION;
}
/*
Vector m_EyePos;
GetAttachment( "eyes", m_EyePos );
return m_EyePos;
*/
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
Vector CNPC_Combine::GetAltFireTarget()
{
Assert( IsElite() );
return m_vecAltFireTarget;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CNPC_Combine::IsCrouchedActivity( Activity activity )
{
Activity realActivity = TranslateActivity(activity);
switch ( realActivity )
{
case ACT_RELOAD_LOW:
case ACT_COVER_LOW:
case ACT_COVER_PISTOL_LOW:
case ACT_COVER_SMG1_LOW:
case ACT_RELOAD_SMG1_LOW:
// Aren't these supposed to be a little higher than the above?
case ACT_RANGE_ATTACK1_LOW:
case ACT_RANGE_ATTACK2_LOW:
case ACT_RANGE_ATTACK_AR2_LOW:
case ACT_RANGE_ATTACK_SMG1_LOW:
case ACT_RANGE_ATTACK_SHOTGUN_LOW:
case ACT_RANGE_ATTACK_PISTOL_LOW:
case ACT_RANGE_AIM_LOW:
case ACT_RANGE_AIM_SMG1_LOW:
case ACT_RANGE_AIM_PISTOL_LOW:
case ACT_RANGE_AIM_AR2_LOW:
return true;
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : nActivity -
// Output : Vector
//-----------------------------------------------------------------------------
Vector CNPC_Combine::EyeOffset( Activity nActivity )
{
if (CapabilitiesGet() & bits_CAP_DUCK)
{
if ( IsCrouchedActivity( nActivity ) )
return COMBINE_EYE_CROUCHING_POSITION;
}
// if the hint doesn't tell anything, assume current state
if ( m_bStanding )
{
return COMBINE_EYE_STANDING_POSITION;
}
else
{
return COMBINE_EYE_CROUCHING_POSITION;
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CNPC_Combine::SetActivity( Activity NewActivity )
{
BaseClass::SetActivity( NewActivity );
m_iLastAnimEventHandled = -1;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
NPC_STATE CNPC_Combine::SelectIdealState( void )
{
switch ( m_NPCState )
{
case NPC_STATE_COMBAT:
{
if ( GetEnemy() == NULL )
{
if ( !HasCondition( COND_ENEMY_DEAD ) )
{
// Lost track of my enemy. Patrol.
SetCondition( COND_COMBINE_SHOULD_PATROL );
}
return NPC_STATE_ALERT;
}
else if ( HasCondition( COND_ENEMY_DEAD ) )
{
AnnounceEnemyKill(GetEnemy());
}
}
default:
{
return BaseClass::SelectIdealState();
}
}
return GetIdealState();
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CNPC_Combine::OnBeginMoveAndShoot()
{
if ( BaseClass::OnBeginMoveAndShoot() )
{
if( HasStrategySlotRange( SQUAD_SLOT_ATTACK1, SQUAD_SLOT_ATTACK2 ) )
return true; // already have the slot I need
if( !HasStrategySlotRange( SQUAD_SLOT_GRENADE1, SQUAD_SLOT_ATTACK_OCCLUDER ) && OccupyStrategySlotRange( SQUAD_SLOT_ATTACK1, SQUAD_SLOT_ATTACK2 ) )
return true;
}
return false;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CNPC_Combine::OnEndMoveAndShoot()
{
VacateStrategySlot();
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
WeaponProficiency_t CNPC_Combine::CalcWeaponProficiency( CBaseCombatWeapon *pWeapon )
{
if( FClassnameIs( pWeapon, "weapon_ar2" ) )
{
return WEAPON_PROFICIENCY_GOOD;
}
else if( FClassnameIs( pWeapon, "weapon_shotgun" ) )
{
return WEAPON_PROFICIENCY_PERFECT;
}
else if( FClassnameIs( pWeapon, "weapon_smg1" ) )
{
return WEAPON_PROFICIENCY_GOOD;
}
return BaseClass::CalcWeaponProficiency( pWeapon );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CNPC_Combine::HasShotgun()
{
if( GetActiveWeapon() && GetActiveWeapon()->m_iClassname == s_iszShotgunClassname )
{
return true;
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose: This is a generic function (to be implemented by sub-classes) to
// handle specific interactions between different types of characters
// (For example the barnacle grabbing an NPC)
// Input : The type of interaction, extra info pointer, and who started it
// Output : true - if sub-class has a response for the interaction
// false - if sub-class has no response
//-----------------------------------------------------------------------------
bool CNPC_Combine::HandleInteraction(int interactionType, void *data, CBaseCombatCharacter *sourceEnt)
{
if ( interactionType == g_interactionTurretStillStanding )
{
// A turret that I've kicked recently is still standing 5 seconds later.
if ( sourceEnt == GetEnemy() )
{
// It's still my enemy. Time to grenade it.
Vector forward, up;
AngleVectors( GetLocalAngles(), &forward, NULL, &up );
m_vecTossVelocity = forward * 10;
SetCondition( COND_COMBINE_DROP_GRENADE );
ClearSchedule();
}
return true;
}
return BaseClass::HandleInteraction( interactionType, data, sourceEnt );
}
//-----------------------------------------------------------------------------
//
// Schedules
//
//-----------------------------------------------------------------------------
AI_BEGIN_CUSTOM_NPC( npc_combine, CNPC_Combine )
//Tasks
DECLARE_TASK( TASK_COMBINE_FACE_TOSS_DIR )
DECLARE_TASK( TASK_COMBINE_IGNORE_ATTACKS )
DECLARE_TASK( TASK_COMBINE_SIGNAL_BEST_SOUND )
DECLARE_TASK( TASK_COMBINE_DEFER_SQUAD_GRENADES )
DECLARE_TASK( TASK_COMBINE_CHASE_ENEMY_CONTINUOUSLY )
DECLARE_TASK( TASK_COMBINE_DIE_INSTANTLY )
DECLARE_TASK( TASK_COMBINE_PLAY_SEQUENCE_FACE_ALTFIRE_TARGET )
//Activities
DECLARE_ACTIVITY( ACT_COMBINE_THROW_GRENADE )
DECLARE_ACTIVITY( ACT_COMBINE_LAUNCH_GRENADE )
DECLARE_ACTIVITY( ACT_COMBINE_BUGBAIT )
DECLARE_ACTIVITY( ACT_COMBINE_AR2_ALTFIRE )
DECLARE_ANIMEVENT( COMBINE_AE_BEGIN_ALTFIRE )
DECLARE_ANIMEVENT( COMBINE_AE_ALTFIRE )
DECLARE_SQUADSLOT( SQUAD_SLOT_GRENADE1 )
DECLARE_SQUADSLOT( SQUAD_SLOT_GRENADE2 )
DECLARE_CONDITION( COND_COMBINE_NO_FIRE )
DECLARE_CONDITION( COND_COMBINE_DEAD_FRIEND )
DECLARE_CONDITION( COND_COMBINE_SHOULD_PATROL )
DECLARE_CONDITION( COND_COMBINE_HIT_BY_BUGBAIT )
DECLARE_CONDITION( COND_COMBINE_DROP_GRENADE )
DECLARE_CONDITION( COND_COMBINE_ON_FIRE )
DECLARE_INTERACTION( g_interactionCombineBash );
//=========================================================
// SCHED_COMBINE_TAKE_COVER_FROM_BEST_SOUND
//
// hide from the loudest sound source (to run from grenade)
//=========================================================
DEFINE_SCHEDULE
(
SCHED_COMBINE_TAKE_COVER_FROM_BEST_SOUND,
" Tasks"
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_COMBINE_RUN_AWAY_FROM_BEST_SOUND"
" TASK_STOP_MOVING 0"
" TASK_COMBINE_SIGNAL_BEST_SOUND 0"
" TASK_FIND_COVER_FROM_BEST_SOUND 0"
" TASK_RUN_PATH 0"
" TASK_WAIT_FOR_MOVEMENT 0"
" TASK_REMEMBER MEMORY:INCOVER"
" TASK_FACE_REASONABLE 0"
""
" Interrupts"
)
DEFINE_SCHEDULE
(
SCHED_COMBINE_RUN_AWAY_FROM_BEST_SOUND,
" Tasks"
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_COWER"
" TASK_GET_PATH_AWAY_FROM_BEST_SOUND 600"
" TASK_RUN_PATH_TIMED 2"
" TASK_STOP_MOVING 0"
""
" Interrupts"
)
//=========================================================
// SCHED_COMBINE_COMBAT_FAIL
//=========================================================
DEFINE_SCHEDULE
(
SCHED_COMBINE_COMBAT_FAIL,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE "
" TASK_WAIT_FACE_ENEMY 2"
" TASK_WAIT_PVS 0"
""
" Interrupts"
" COND_CAN_RANGE_ATTACK1"
" COND_CAN_RANGE_ATTACK2"
" COND_CAN_MELEE_ATTACK1"
" COND_CAN_MELEE_ATTACK2"
)
//=========================================================
// SCHED_COMBINE_VICTORY_DANCE
//=========================================================
DEFINE_SCHEDULE
(
SCHED_COMBINE_VICTORY_DANCE,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_FACE_ENEMY 0"
" TASK_WAIT 1.5"
" TASK_GET_PATH_TO_ENEMY_CORPSE 0"
" TASK_WALK_PATH 0"
" TASK_WAIT_FOR_MOVEMENT 0"
" TASK_FACE_ENEMY 0"
" TASK_PLAY_SEQUENCE ACTIVITY:ACT_VICTORY_DANCE"
""
" Interrupts"
" COND_NEW_ENEMY"
" COND_LIGHT_DAMAGE"
" COND_HEAVY_DAMAGE"
)
//=========================================================
// SCHED_COMBINE_ASSAULT
//=========================================================
DEFINE_SCHEDULE
(
SCHED_COMBINE_ASSAULT,
" Tasks "
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_COMBINE_ESTABLISH_LINE_OF_FIRE"
" TASK_SET_TOLERANCE_DISTANCE 48"
" TASK_GET_PATH_TO_ENEMY_LKP 0"
" TASK_COMBINE_IGNORE_ATTACKS 0.2"
" TASK_SPEAK_SENTENCE 0"
" TASK_RUN_PATH 0"
// " TASK_COMBINE_MOVE_AND_AIM 0"
" TASK_WAIT_FOR_MOVEMENT 0"
" TASK_COMBINE_IGNORE_ATTACKS 0.0"
""
" Interrupts "
" COND_NEW_ENEMY"
" COND_ENEMY_DEAD"
" COND_ENEMY_UNREACHABLE"
" COND_CAN_RANGE_ATTACK1"
" COND_CAN_MELEE_ATTACK1"
" COND_CAN_RANGE_ATTACK2"
" COND_CAN_MELEE_ATTACK2"
" COND_TOO_FAR_TO_ATTACK"
" COND_HEAR_DANGER"
" COND_HEAR_MOVE_AWAY"
)
DEFINE_SCHEDULE
(
SCHED_COMBINE_ESTABLISH_LINE_OF_FIRE,
" Tasks "
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_FAIL_ESTABLISH_LINE_OF_FIRE"
" TASK_SET_TOLERANCE_DISTANCE 48"
" TASK_GET_PATH_TO_ENEMY_LKP_LOS 0"
" TASK_SPEAK_SENTENCE 1"
" TASK_RUN_PATH 0"
" TASK_WAIT_FOR_MOVEMENT 0"
" TASK_COMBINE_IGNORE_ATTACKS 0.0"
" TASK_SET_SCHEDULE SCHEDULE:SCHED_COMBAT_FACE"
" "
" Interrupts "
" COND_NEW_ENEMY"
" COND_ENEMY_DEAD"
//" COND_CAN_RANGE_ATTACK1"
//" COND_CAN_RANGE_ATTACK2"
" COND_CAN_MELEE_ATTACK1"
" COND_CAN_MELEE_ATTACK2"
" COND_HEAR_DANGER"
" COND_HEAR_MOVE_AWAY"
" COND_HEAVY_DAMAGE"
)
//=========================================================
// SCHED_COMBINE_PRESS_ATTACK
//=========================================================
DEFINE_SCHEDULE
(
SCHED_COMBINE_PRESS_ATTACK,
" Tasks "
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_COMBINE_ESTABLISH_LINE_OF_FIRE"
" TASK_SET_TOLERANCE_DISTANCE 48"
" TASK_GET_PATH_TO_ENEMY_LKP 0"
" TASK_RUN_PATH 0"
" TASK_WAIT_FOR_MOVEMENT 0"
""
" Interrupts "
" COND_NEW_ENEMY"
" COND_ENEMY_DEAD"
" COND_ENEMY_UNREACHABLE"
" COND_NO_PRIMARY_AMMO"
" COND_LOW_PRIMARY_AMMO"
" COND_TOO_CLOSE_TO_ATTACK"
" COND_ENEMY_OCCLUDED"
" COND_CAN_MELEE_ATTACK1"
" COND_CAN_MELEE_ATTACK2"
" COND_HEAR_DANGER"
" COND_HEAR_MOVE_AWAY"
)
//=========================================================
// SCHED_COMBINE_COMBAT_FACE
//=========================================================
DEFINE_SCHEDULE
(
SCHED_COMBINE_COMBAT_FACE,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE"
" TASK_FACE_ENEMY 0"
" TASK_WAIT 1.5"
//" TASK_SET_SCHEDULE SCHEDULE:SCHED_COMBINE_SWEEP"
""
" Interrupts"
" COND_NEW_ENEMY"
" COND_ENEMY_DEAD"
" COND_CAN_RANGE_ATTACK1"
" COND_CAN_RANGE_ATTACK2"
)
//=========================================================
// SCHED_HIDE_AND_RELOAD
//=========================================================
DEFINE_SCHEDULE
(
SCHED_COMBINE_HIDE_AND_RELOAD,
" Tasks"
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_RELOAD"
" TASK_FIND_COVER_FROM_ENEMY 0"
" TASK_RUN_PATH 0"
" TASK_WAIT_FOR_MOVEMENT 0"
" TASK_REMEMBER MEMORY:INCOVER"
" TASK_FACE_ENEMY 0"
" TASK_RELOAD 0"
""
" Interrupts"
" COND_CAN_MELEE_ATTACK1"
" COND_CAN_MELEE_ATTACK2"
" COND_HEAVY_DAMAGE"
" COND_HEAR_DANGER"
" COND_HEAR_MOVE_AWAY"
)
//=========================================================
// SCHED_COMBINE_SIGNAL_SUPPRESS
// don't stop shooting until the clip is
// empty or combine gets hurt.
//=========================================================
DEFINE_SCHEDULE
(
SCHED_COMBINE_SIGNAL_SUPPRESS,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_FACE_IDEAL 0"
" TASK_PLAY_SEQUENCE_FACE_ENEMY ACTIVITY:ACT_SIGNAL_GROUP"
" TASK_WAIT 0.5"
" TASK_RANGE_ATTACK1 0"
""
" Interrupts"
" COND_ENEMY_DEAD"
" COND_LIGHT_DAMAGE"
" COND_HEAVY_DAMAGE"
" COND_NO_PRIMARY_AMMO"
" COND_WEAPON_BLOCKED_BY_FRIEND"
" COND_WEAPON_SIGHT_OCCLUDED"
" COND_HEAR_DANGER"
" COND_HEAR_MOVE_AWAY"
" COND_COMBINE_NO_FIRE"
)
//=========================================================
// SCHED_COMBINE_SUPPRESS
//=========================================================
DEFINE_SCHEDULE
(
SCHED_COMBINE_SUPPRESS,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_FACE_ENEMY 0"
" TASK_WAIT 0.5"
" TASK_RANGE_ATTACK1 0"
""
" Interrupts"
" COND_ENEMY_DEAD"
" COND_LIGHT_DAMAGE"
" COND_HEAVY_DAMAGE"
" COND_NO_PRIMARY_AMMO"
" COND_HEAR_DANGER"
" COND_HEAR_MOVE_AWAY"
" COND_COMBINE_NO_FIRE"
" COND_WEAPON_BLOCKED_BY_FRIEND"
)
//=========================================================
// SCHED_COMBINE_WAIT_IN_COVER
// we don't allow danger or the ability
// to attack to break a combine's run to cover schedule but
// when a combine is in cover we do want them to attack if they can.
//=========================================================
DEFINE_SCHEDULE
(
SCHED_COMBINE_WAIT_IN_COVER,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE" // Translated to cover
" TASK_WAIT_FACE_ENEMY 1"
""
" Interrupts"
" COND_NEW_ENEMY"
" COND_CAN_RANGE_ATTACK1"
" COND_CAN_RANGE_ATTACK2"
" COND_CAN_MELEE_ATTACK1"
" COND_CAN_MELEE_ATTACK2"
" COND_HEAR_DANGER"
" COND_HEAR_MOVE_AWAY"
)
//=========================================================
// SCHED_COMBINE_TAKE_COVER1
//=========================================================
DEFINE_SCHEDULE
(
SCHED_COMBINE_TAKE_COVER1 ,
" Tasks"
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_COMBINE_TAKECOVER_FAILED"
" TASK_STOP_MOVING 0"
" TASK_WAIT 0.2"
" TASK_FIND_COVER_FROM_ENEMY 0"
" TASK_RUN_PATH 0"
" TASK_WAIT_FOR_MOVEMENT 0"
" TASK_REMEMBER MEMORY:INCOVER"
" TASK_SET_SCHEDULE SCHEDULE:SCHED_COMBINE_WAIT_IN_COVER"
""
" Interrupts"
)
DEFINE_SCHEDULE
(
SCHED_COMBINE_TAKECOVER_FAILED,
" Tasks"
" TASK_STOP_MOVING 0"
""
" Interrupts"
)
//=========================================================
// SCHED_COMBINE_GRENADE_COVER1
//=========================================================
DEFINE_SCHEDULE
(
SCHED_COMBINE_GRENADE_COVER1,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_FIND_COVER_FROM_ENEMY 99"
" TASK_FIND_FAR_NODE_COVER_FROM_ENEMY 384"
" TASK_PLAY_SEQUENCE ACTIVITY:ACT_SPECIAL_ATTACK2"
" TASK_CLEAR_MOVE_WAIT 0"
" TASK_RUN_PATH 0"
" TASK_WAIT_FOR_MOVEMENT 0"
" TASK_SET_SCHEDULE SCHEDULE:SCHED_COMBINE_WAIT_IN_COVER"
""
" Interrupts"
)
//=========================================================
// SCHED_COMBINE_TOSS_GRENADE_COVER1
//
// drop grenade then run to cover.
//=========================================================
DEFINE_SCHEDULE
(
SCHED_COMBINE_TOSS_GRENADE_COVER1,
" Tasks"
" TASK_FACE_ENEMY 0"
" TASK_RANGE_ATTACK2 0"
" TASK_SET_SCHEDULE SCHEDULE:SCHED_TAKE_COVER_FROM_ENEMY"
""
" Interrupts"
)
//=========================================================
// SCHED_COMBINE_RANGE_ATTACK1
//=========================================================
DEFINE_SCHEDULE
(
SCHED_COMBINE_RANGE_ATTACK1,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_FACE_ENEMY 0"
" TASK_ANNOUNCE_ATTACK 1" // 1 = primary attack
" TASK_WAIT_RANDOM 0.3"
" TASK_RANGE_ATTACK1 0"
" TASK_COMBINE_IGNORE_ATTACKS 0.5"
""
" Interrupts"
" COND_NEW_ENEMY"
" COND_ENEMY_DEAD"
" COND_HEAVY_DAMAGE"
" COND_LOW_PRIMARY_AMMO"
" COND_NO_PRIMARY_AMMO"
" COND_WEAPON_BLOCKED_BY_FRIEND"
" COND_TOO_CLOSE_TO_ATTACK"
" COND_GIVE_WAY"
" COND_HEAR_DANGER"
" COND_HEAR_MOVE_AWAY"
" COND_COMBINE_NO_FIRE"
""
// Enemy_Occluded Don't interrupt on this. Means
// comibine will fire where player was after
// he has moved for a little while. Good effect!!
// WEAPON_SIGHT_OCCLUDED Don't block on this! Looks better for railings, etc.
)
//=========================================================
// AR2 Alt Fire Attack
//=========================================================
DEFINE_SCHEDULE
(
SCHED_COMBINE_AR2_ALTFIRE,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_ANNOUNCE_ATTACK 1"
" TASK_COMBINE_PLAY_SEQUENCE_FACE_ALTFIRE_TARGET ACTIVITY:ACT_COMBINE_AR2_ALTFIRE"
""
" Interrupts"
)
//=========================================================
// SCHED_COMBINE_RANGE_ATTACK2
//
// secondary range attack. Overriden because base class stops attacking when the enemy is occluded.
// combines's grenade toss requires the enemy be occluded.
//=========================================================
DEFINE_SCHEDULE
(
SCHED_COMBINE_RANGE_ATTACK2,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_COMBINE_FACE_TOSS_DIR 0"
" TASK_ANNOUNCE_ATTACK 2" // 2 = grenade
" TASK_PLAY_SEQUENCE ACTIVITY:ACT_RANGE_ATTACK2"
" TASK_COMBINE_DEFER_SQUAD_GRENADES 0"
" TASK_SET_SCHEDULE SCHEDULE:SCHED_COMBINE_WAIT_IN_COVER" // don't run immediately after throwing grenade.
""
" Interrupts"
)
//=========================================================
// Throw a grenade, then run off and reload.
//=========================================================
DEFINE_SCHEDULE
(
SCHED_COMBINE_GRENADE_AND_RELOAD,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_COMBINE_FACE_TOSS_DIR 0"
" TASK_ANNOUNCE_ATTACK 2" // 2 = grenade
" TASK_PLAY_SEQUENCE ACTIVITY:ACT_RANGE_ATTACK2"
" TASK_COMBINE_DEFER_SQUAD_GRENADES 0"
" TASK_SET_SCHEDULE SCHEDULE:SCHED_HIDE_AND_RELOAD" // don't run immediately after throwing grenade.
""
" Interrupts"
)
DEFINE_SCHEDULE
(
SCHED_COMBINE_PATROL,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_WANDER 900540"
" TASK_WALK_PATH 0"
" TASK_WAIT_FOR_MOVEMENT 0"
" TASK_STOP_MOVING 0"
" TASK_FACE_REASONABLE 0"
" TASK_WAIT 3"
" TASK_WAIT_RANDOM 3"
" TASK_SET_SCHEDULE SCHEDULE:SCHED_COMBINE_PATROL" // keep doing it
""
" Interrupts"
" COND_ENEMY_DEAD"
" COND_LIGHT_DAMAGE"
" COND_HEAVY_DAMAGE"
" COND_HEAR_DANGER"
" COND_HEAR_MOVE_AWAY"
" COND_NEW_ENEMY"
" COND_SEE_ENEMY"
" COND_CAN_RANGE_ATTACK1"
" COND_CAN_RANGE_ATTACK2"
)
DEFINE_SCHEDULE
(
SCHED_COMBINE_BUGBAIT_DISTRACTION,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_RESET_ACTIVITY 0"
" TASK_PLAY_SEQUENCE ACTIVITY:ACT_COMBINE_BUGBAIT"
""
" Interrupts"
""
)
//=========================================================
// SCHED_COMBINE_CHARGE_TURRET
//
// Used to run straight at enemy turrets to knock them over.
// Prevents squadmates from throwing grenades during.
//=========================================================
DEFINE_SCHEDULE
(
SCHED_COMBINE_CHARGE_TURRET,
" Tasks"
" TASK_COMBINE_DEFER_SQUAD_GRENADES 0"
" TASK_STOP_MOVING 0"
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_CHASE_ENEMY_FAILED"
" TASK_GET_CHASE_PATH_TO_ENEMY 300"
" TASK_RUN_PATH 0"
" TASK_WAIT_FOR_MOVEMENT 0"
" TASK_FACE_ENEMY 0"
""
" Interrupts"
" COND_NEW_ENEMY"
" COND_ENEMY_DEAD"
" COND_ENEMY_UNREACHABLE"
" COND_CAN_MELEE_ATTACK1"
" COND_CAN_MELEE_ATTACK2"
" COND_TOO_CLOSE_TO_ATTACK"
" COND_TASK_FAILED"
" COND_LOST_ENEMY"
" COND_BETTER_WEAPON_AVAILABLE"
" COND_HEAR_DANGER"
)
//=========================================================
// SCHED_COMBINE_CHARGE_PLAYER
//
// Used to run straight at enemy player since physgun combat
// is more fun when the enemies are close
//=========================================================
DEFINE_SCHEDULE
(
SCHED_COMBINE_CHARGE_PLAYER,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_CHASE_ENEMY_FAILED"
" TASK_COMBINE_CHASE_ENEMY_CONTINUOUSLY 192"
" TASK_FACE_ENEMY 0"
""
" Interrupts"
" COND_NEW_ENEMY"
" COND_ENEMY_DEAD"
" COND_ENEMY_UNREACHABLE"
" COND_CAN_MELEE_ATTACK1"
" COND_CAN_MELEE_ATTACK2"
" COND_TASK_FAILED"
" COND_LOST_ENEMY"
" COND_HEAR_DANGER"
)
//=========================================================
// SCHED_COMBINE_DROP_GRENADE
//
// Place a grenade at my feet
//=========================================================
DEFINE_SCHEDULE
(
SCHED_COMBINE_DROP_GRENADE,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_PLAY_SEQUENCE ACTIVITY:ACT_SPECIAL_ATTACK2"
" TASK_FIND_COVER_FROM_ENEMY 99"
" TASK_FIND_FAR_NODE_COVER_FROM_ENEMY 384"
" TASK_CLEAR_MOVE_WAIT 0"
" TASK_RUN_PATH 0"
" TASK_WAIT_FOR_MOVEMENT 0"
""
" Interrupts"
)
//=========================================================
// SCHED_COMBINE_PATROL_ENEMY
//
// Used instead if SCHED_COMBINE_PATROL if I have an enemy.
// Wait for the enemy a bit in the hopes of ambushing him.
//=========================================================
DEFINE_SCHEDULE
(
SCHED_COMBINE_PATROL_ENEMY,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_WAIT_FACE_ENEMY 1"
" TASK_WAIT_FACE_ENEMY_RANDOM 3"
""
" Interrupts"
" COND_ENEMY_DEAD"
" COND_LIGHT_DAMAGE"
" COND_HEAVY_DAMAGE"
" COND_HEAR_DANGER"
" COND_HEAR_MOVE_AWAY"
" COND_NEW_ENEMY"
" COND_SEE_ENEMY"
" COND_CAN_RANGE_ATTACK1"
" COND_CAN_RANGE_ATTACK2"
)
DEFINE_SCHEDULE
(
SCHED_COMBINE_BURNING_STAND,
" Tasks"
" TASK_WAIT_RANDOM 0.3" // Randomise start time so combine don't all dance in synch
" TASK_SET_ACTIVITY ACTIVITY:ACT_COMBINE_BUGBAIT"
" TASK_WAIT 2"
" TASK_WAIT_RANDOM 3"
" TASK_COMBINE_DIE_INSTANTLY DMG_BURN"
" TASK_WAIT 1.0"
" "
" Interrupts"
)
AI_END_CUSTOM_NPC()
| 412 | 0.995702 | 1 | 0.995702 | game-dev | MEDIA | 0.99351 | game-dev | 0.713325 | 1 | 0.713325 |
SonicEraZoR/Portal-Base | 2,104 | sp/src/game/shared/hl2/hl2_usermessages.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "cbase.h"
#include "usermessages.h"
#include "shake.h"
#include "voice_gamemgr.h"
// NVNT include to register in haptic user messages
#include "haptics/haptic_msgs.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
void RegisterUserMessages( void )
{
usermessages->Register( "Geiger", 1 );
usermessages->Register( "Train", 1 );
usermessages->Register( "HudText", -1 );
usermessages->Register( "SayText", -1 );
usermessages->Register( "SayText2", -1 );
usermessages->Register( "TextMsg", -1 );
usermessages->Register( "HudMsg", -1 );
usermessages->Register( "ResetHUD", 1); // called every respawn
usermessages->Register( "GameTitle", 0 );
usermessages->Register( "ItemPickup", -1 );
usermessages->Register( "ShowMenu", -1 );
usermessages->Register( "Shake", 13 );
usermessages->Register( "Fade", 10 );
usermessages->Register( "VGUIMenu", -1 ); // Show VGUI menu
usermessages->Register( "Rumble", 3 ); // Send a rumble to a controller
usermessages->Register( "Battery", 2 );
usermessages->Register( "Damage", 18 ); // BUG: floats are sent for coords, no variable bitfields in hud & fixed size Msg
usermessages->Register( "VoiceMask", VOICE_MAX_PLAYERS_DW*4 * 2 + 1 );
usermessages->Register( "RequestState", 0 );
usermessages->Register( "CloseCaption", -1 ); // Show a caption (by string id number)(duration in 10th of a second)
usermessages->Register( "HintText", -1 ); // Displays hint text display
usermessages->Register( "KeyHintText", -1 ); // Displays hint text display
usermessages->Register( "SquadMemberDied", 0 );
usermessages->Register( "AmmoDenied", 2 );
usermessages->Register( "CreditsMsg", 1 );
usermessages->Register( "LogoTimeMsg", 4 );
usermessages->Register( "AchievementEvent", -1 );
usermessages->Register( "UpdateJalopyRadar", -1 );
#ifndef _X360
// NVNT register haptic user messages
RegisterHapticMessages();
#endif
} | 412 | 0.937602 | 1 | 0.937602 | game-dev | MEDIA | 0.545734 | game-dev | 0.549122 | 1 | 0.549122 |
artclarke/xuggle-xuggler | 28,518 | captive/libvpx/csrc/examples/includes/geshi/geshi/lsl2.php | <?php
/*************************************************************************************
* lsl2.php
* --------
* Author: William Fry (william.fry@nyu.edu)
* Copyright: (c) 2009 William Fry
* Release Version: 1.0.8.3
* Date Started: 2009/02/04
*
* Linden Scripting Language (LSL2) language file for GeSHi.
*
* Data derived and validated against the following:
* http://wiki.secondlife.com/wiki/LSL_Portal
* http://www.lslwiki.net/lslwiki/wakka.php?wakka=HomePage
* http://rpgstats.com/wiki/index.php?title=Main_Page
*
* CHANGES
* -------
* 2009/02/05 (1.0.0)
* - First Release
*
* TODO (updated 2009/02/05)
* -------------------------
*
*************************************************************************************
*
* This file is part of GeSHi.
*
* GeSHi 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.
*
* GeSHi 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 GeSHi; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
************************************************************************************/
$language_data = array (
'LANG_NAME' => 'LSL2',
'COMMENT_SINGLE' => array(1 => '//'),
'COMMENT_MULTI' => array(),
'CASE_KEYWORDS' => GESHI_CAPS_NO_CHANGE,
'QUOTEMARKS' => array('"'),
'ESCAPE_CHAR' => '\\',
'KEYWORDS' => array(
1 => array( // flow control
'do',
'else',
'for',
'if',
'jump',
'return',
'state',
'while',
),
2 => array( // manifest constants
'ACTIVE',
'AGENT',
'AGENT_ALWAYS_RUN',
'AGENT_ATTACHMENTS',
'AGENT_AWAY',
'AGENT_BUSY',
'AGENT_CROUCHING',
'AGENT_FLYING',
'AGENT_IN_AIR',
'AGENT_MOUSELOOK',
'AGENT_ON_OBJECT',
'AGENT_SCRIPTED',
'AGENT_SITTING',
'AGENT_TYPING',
'AGENT_WALKING',
'ALL_SIDES',
'ANIM_ON',
'ATTACH_BACK',
'ATTACH_BELLY',
'ATTACH_CHEST',
'ATTACH_CHIN',
'ATTACH_HEAD',
'ATTACH_HUD_BOTTOM',
'ATTACH_HUD_BOTTOM_LEFT',
'ATTACH_HUD_BOTTOM_RIGHT',
'ATTACH_HUD_CENTER_1',
'ATTACH_HUD_CENTER_2',
'ATTACH_HUD_TOP_CENTER',
'ATTACH_HUD_TOP_LEFT',
'ATTACH_HUD_TOP_RIGHT',
'ATTACH_LEAR',
'ATTACH_LEYE',
'ATTACH_LFOOT',
'ATTACH_LHAND',
'ATTACH_LHIP',
'ATTACH_LLARM',
'ATTACH_LLLEG',
'ATTACH_LPEC',
'ATTACH_LSHOULDER',
'ATTACH_LUARM',
'ATTACH_LULEG',
'ATTACH_MOUTH',
'ATTACH_NOSE',
'ATTACH_PELVIS',
'ATTACH_REAR',
'ATTACH_REYE',
'ATTACH_RFOOT',
'ATTACH_RHAND',
'ATTACH_RHIP',
'ATTACH_RLARM',
'ATTACH_RLLEG',
'ATTACH_RPEC',
'ATTACH_RSHOULDER',
'ATTACH_RUARM',
'ATTACH_RULEG',
'CAMERA_ACTIVE',
'CAMERA_BEHINDNESS_ANGLE',
'CAMERA_BEHINDNESS_LAG',
'CAMERA_DISTANCE',
'CAMERA_FOCUS',
'CAMERA_FOCUS_LAG',
'CAMERA_FOCUS_LOCKED',
'CAMERA_FOCUS_OFFSET',
'CAMERA_FOCUS_THRESHOLD',
'CAMERA_PITCH',
'CAMERA_POSITION',
'CAMERA_POSITION_LAG',
'CAMERA_POSITION_LOCKED',
'CAMERA_POSITION_THRESHOLD',
'CHANGED_ALLOWED_DROP',
'CHANGED_COLOR',
'CHANGED_INVENTORY',
'CHANGED_LINK',
'CHANGED_OWNER',
'CHANGED_REGION',
'CHANGED_SCALE',
'CHANGED_SHAPE',
'CHANGED_TELEPORT',
'CHANGED_TEXTURE',
'CLICK_ACTION_NONE',
'CLICK_ACTION_OPEN',
'CLICK_ACTION_OPEN_MEDIA',
'CLICK_ACTION_PAY',
'CLICK_ACTION_SIT',
'CLICK_ACTION_TOUCH',
'CONTROL_BACK',
'CONTROL_DOWN',
'CONTROL_FWD',
'CONTROL_LBUTTON',
'CONTROL_LEFT',
'CONTROL_ML_LBUTTON',
'CONTROL_RIGHT',
'CONTROL_ROT_LEFT',
'CONTROL_ROT_RIGHT',
'CONTROL_UP',
'DATA_BORN',
'DATA_NAME',
'DATA_ONLINE',
'DATA_PAYINFO',
'DATA_RATING',
'DATA_SIM_POS',
'DATA_SIM_RATING',
'DATA_SIM_STATUS',
'DEBUG_CHANNEL',
'DEG_TO_RAD',
'EOF',
'FALSE',
'HTTP_BODY_MAXLENGTH',
'HTTP_BODY_TRUNCATED',
'HTTP_METHOD',
'HTTP_MIMETYPE',
'HTTP_VERIFY_CERT',
'INVENTORY_ALL',
'INVENTORY_ANIMATION',
'INVENTORY_BODYPART',
'INVENTORY_CLOTHING',
'INVENTORY_GESTURE',
'INVENTORY_LANDMARK',
'INVENTORY_NONE',
'INVENTORY_NOTECARD',
'INVENTORY_OBJECT',
'INVENTORY_SCRIPT',
'INVENTORY_SOUND',
'INVENTORY_TEXTURE',
'LAND_LEVEL',
'LAND_LOWER',
'LAND_NOISE',
'LAND_RAISE',
'LAND_REVERT',
'LAND_SMOOTH',
'LINK_ALL_CHILDREN',
'LINK_ALL_OTHERS',
'LINK_ROOT',
'LINK_SET',
'LINK_THIS',
'LIST_STAT_GEOMETRIC_MEAN',
'LIST_STAT_MAX',
'LIST_STAT_MEAN',
'LIST_STAT_MEDIAN',
'LIST_STAT_MIN',
'LIST_STAT_NUM_COUNT',
'LIST_STAT_RANGE',
'LIST_STAT_STD_DEV',
'LIST_STAT_SUM',
'LIST_STAT_SUM_SQUARES',
'LOOP',
'MASK_BASE',
'MASK_EVERYONE',
'MASK_GROUP',
'MASK_NEXT',
'MASK_OWNER',
'NULL_KEY',
'OBJECT_CREATOR',
'OBJECT_DESC',
'OBJECT_GROUP',
'OBJECT_NAME',
'OBJECT_OWNER',
'OBJECT_POS',
'OBJECT_ROT',
'OBJECT_UNKNOWN_DETAIL',
'OBJECT_VELOCITY',
'PARCEL_DETAILS_AREA',
'PARCEL_DETAILS_DESC',
'PARCEL_DETAILS_GROUP',
'PARCEL_DETAILS_NAME',
'PARCEL_DETAILS_OWNER',
'PARCEL_FLAG_ALLOW_ALL_OBJECT_ENTRY',
'PARCEL_FLAG_ALLOW_CREATE_GROUP_OBJECTS',
'PARCEL_FLAG_ALLOW_CREATE_OBJECTS',
'PARCEL_FLAG_ALLOW_DAMAGE',
'PARCEL_FLAG_ALLOW_FLY',
'PARCEL_FLAG_ALLOW_GROUP_OBJECT_ENTRY',
'PARCEL_FLAG_ALLOW_GROUP_SCRIPTS',
'PARCEL_FLAG_ALLOW_LANDMARK',
'PARCEL_FLAG_ALLOW_SCRIPTS',
'PARCEL_FLAG_ALLOW_TERRAFORM',
'PARCEL_FLAG_LOCAL_SOUND_ONLY',
'PARCEL_FLAG_RESTRICT_PUSHOBJECT',
'PARCEL_FLAG_USE_ACCESS_GROUP',
'PARCEL_FLAG_USE_ACCESS_LIST',
'PARCEL_FLAG_USE_BAN_LIST',
'PARCEL_FLAG_USE_LAND_PASS_LIST',
'PARCEL_MEDIA_COMMAND_AGENT',
'PARCEL_MEDIA_COMMAND_AUTO_ALIGN',
'PARCEL_MEDIA_COMMAND_DESC',
'PARCEL_MEDIA_COMMAND_LOOP_SET',
'PARCEL_MEDIA_COMMAND_PAUSE',
'PARCEL_MEDIA_COMMAND_PLAY',
'PARCEL_MEDIA_COMMAND_SIZE',
'PARCEL_MEDIA_COMMAND_STOP',
'PARCEL_MEDIA_COMMAND_TEXTURE',
'PARCEL_MEDIA_COMMAND_TIME',
'PARCEL_MEDIA_COMMAND_TYPE',
'PARCEL_MEDIA_COMMAND_URL',
'PASSIVE',
'PAYMENT_INFO_ON_FILE',
'PAYMENT_INFO_USED',
'PAY_DEFAULT',
'PAY_HIDE',
'PERMISSION_ATTACH',
'PERMISSION_CHANGE_LINKS',
'PERMISSION_CONTROL_CAMERA',
'PERMISSION_DEBIT',
'PERMISSION_TAKE_CONTROLS',
'PERMISSION_TRACK_CAMERA',
'PERMISSION_TRIGGER_ANIMATION',
'PERM_ALL',
'PERM_COPY',
'PERM_MODIFY',
'PERM_MOVE',
'PERM_TRANSFER',
'PI',
'PI_BY_TWO',
'PRIM_BUMP_BARK',
'PRIM_BUMP_BLOBS',
'PRIM_BUMP_BRICKS',
'PRIM_BUMP_BRIGHT',
'PRIM_BUMP_CHECKER',
'PRIM_BUMP_CONCRETE',
'PRIM_BUMP_DARK',
'PRIM_BUMP_DISKS',
'PRIM_BUMP_GRAVEL',
'PRIM_BUMP_LARGETILE',
'PRIM_BUMP_NONE',
'PRIM_BUMP_SHINY',
'PRIM_BUMP_SIDING',
'PRIM_BUMP_STONE',
'PRIM_BUMP_STUCCO',
'PRIM_BUMP_SUCTION',
'PRIM_BUMP_TILE',
'PRIM_BUMP_WEAVE',
'PRIM_BUMP_WOOD',
'PRIM_COLOR',
'PRIM_FULLBRIGHT',
'PRIM_HOLE_CIRCLE',
'PRIM_HOLE_DEFAULT',
'PRIM_HOLE_SQUARE',
'PRIM_HOLE_TRIANGLE',
'PRIM_MATERIAL',
'PRIM_MATERIAL_FLESH',
'PRIM_MATERIAL_GLASS',
'PRIM_MATERIAL_LIGHT',
'PRIM_MATERIAL_METAL',
'PRIM_MATERIAL_PLASTIC',
'PRIM_MATERIAL_RUBBER',
'PRIM_MATERIAL_STONE',
'PRIM_MATERIAL_WOOD',
'PRIM_PHANTOM',
'PRIM_PHYSICS',
'PRIM_POSITION',
'PRIM_ROTATION',
'PRIM_SHINY_HIGH',
'PRIM_SHINY_LOW',
'PRIM_SHINY_MEDIUM',
'PRIM_SHINY_NONE',
'PRIM_SIZE',
'PRIM_TEMP_ON_REZ',
'PRIM_TEXTURE',
'PRIM_TYPE',
'PRIM_TYPE_BOX',
'PRIM_TYPE_CYLINDER',
'PRIM_TYPE_PRISM',
'PRIM_TYPE_RING',
'PRIM_TYPE_SPHERE',
'PRIM_TYPE_TORUS',
'PRIM_TYPE_TUBE',
'PSYS_PART_BOUNCE_MASK',
'PSYS_PART_EMISSIVE_MASK',
'PSYS_PART_END_ALPHA',
'PSYS_PART_END_COLOR',
'PSYS_PART_END_SCALE',
'PSYS_PART_FLAGS',
'PSYS_PART_FOLLOW_SRC_MASK',
'PSYS_PART_FOLLOW_VELOCITY_MASK',
'PSYS_PART_INTERP_COLOR_MASK',
'PSYS_PART_INTERP_SCALE_MASK',
'PSYS_PART_MAX_AGE',
'PSYS_PART_START_ALPHA',
'PSYS_PART_START_COLOR',
'PSYS_PART_START_SCALE',
'PSYS_PART_TARGET_LINEAR_MASK',
'PSYS_PART_TARGET_POS_MASK',
'PSYS_PART_WIND_MASK',
'PSYS_SRC_ACCEL',
'PSYS_SRC_ANGLE_BEGIN',
'PSYS_SRC_ANGLE_END',
'PSYS_SRC_BURST_PART_COUNT',
'PSYS_SRC_BURST_RADIUS',
'PSYS_SRC_BURST_RATE',
'PSYS_SRC_BURST_SPEED_MAX',
'PSYS_SRC_BURST_SPEED_MIN',
'PSYS_SRC_INNERANGLE',
'PSYS_SRC_MAX_AGE',
'PSYS_SRC_OMEGA',
'PSYS_SRC_OUTERANGLE',
'PSYS_SRC_PATTERN',
'PSYS_SRC_PATTERN_ANGLE',
'PSYS_SRC_PATTERN_ANGLE_CONE',
'PSYS_SRC_PATTERN_ANGLE_CONE_EMPTY',
'PSYS_SRC_PATTERN_DROP',
'PSYS_SRC_PATTERN_EXPLODE',
'PSYS_SRC_TARGET_KEY',
'PSYS_SRC_TEXTURE',
'RAD_TO_DEG',
'REMOTE_DATA_CHANNEL',
'REMOTE_DATA_REQUEST',
'SCRIPTED',
'SQRT2',
'STATUS_BLOCK_GRAB',
'STATUS_DIE_AT_EDGE',
'STATUS_PHANTOM',
'STATUS_PHYSICS',
'STATUS_RETURN_AT_EDGE',
'STATUS_ROTATE_X',
'STATUS_ROTATE_Y',
'STATUS_ROTATE_Z',
'STATUS_SANDBOX',
'TRUE',
'TWO_PI',
'VEHICLE_ANGULAR_DEFLECTION_EFFICIENCY',
'VEHICLE_ANGULAR_DEFLECTION_TIMESCALE',
'VEHICLE_ANGULAR_FRICTION_TIMESCALE',
'VEHICLE_ANGULAR_MOTOR_DECAY_TIMESCALE',
'VEHICLE_ANGULAR_MOTOR_DIRECTION',
'VEHICLE_ANGULAR_MOTOR_TIMESCALE',
'VEHICLE_BANKING_EFFICIENCY',
'VEHICLE_BANKING_MIX',
'VEHICLE_BANKING_TIMESCALE',
'VEHICLE_BUOYANCY',
'VEHICLE_FLAG_CAMERA_DECOUPLED',
'VEHICLE_FLAG_HOVER_GLOBAL_HEIGHT',
'VEHICLE_FLAG_HOVER_TERRAIN_ONLY',
'VEHICLE_FLAG_HOVER_UP_ONLY',
'VEHICLE_FLAG_HOVER_WATER_ONLY',
'VEHICLE_FLAG_LIMIT_MOTOR_UP',
'VEHICLE_FLAG_LIMIT_ROLL_ONLY',
'VEHICLE_FLAG_MOUSELOOK_BANK',
'VEHICLE_FLAG_MOUSELOOK_STEER',
'VEHICLE_FLAG_NO_DEFLECTION_UP',
'VEHICLE_HOVER_EFFICIENCY',
'VEHICLE_HOVER_HEIGHT',
'VEHICLE_HOVER_TIMESCALE',
'VEHICLE_LINEAR_DEFLECTION_EFFICIENCY',
'VEHICLE_LINEAR_DEFLECTION_TIMESCALE',
'VEHICLE_LINEAR_FRICTION_TIMESCALE',
'VEHICLE_LINEAR_MOTOR_DECAY_TIMESCALE',
'VEHICLE_LINEAR_MOTOR_DIRECTION',
'VEHICLE_LINEAR_MOTOR_OFFSET',
'VEHICLE_LINEAR_MOTOR_TIMESCALE',
'VEHICLE_REFERENCE_FRAME',
'VEHICLE_TYPE_AIRPLANE',
'VEHICLE_TYPE_BALLOON',
'VEHICLE_TYPE_BOAT',
'VEHICLE_TYPE_CAR',
'VEHICLE_TYPE_NONE',
'VEHICLE_TYPE_SLED',
'VEHICLE_VERTICAL_ATTRACTION_EFFICIENCY',
'VEHICLE_VERTICAL_ATTRACTION_TIMESCALE',
'ZERO_ROTATION',
'ZERO_VECTOR',
),
3 => array( // handlers
'at_rot_target',
'at_target',
'attached',
'changed',
'collision',
'collision_end',
'collision_start',
'control',
'dataserver',
'email',
'http_response',
'land_collision',
'land_collision_end',
'land_collision_start',
'link_message',
'listen',
'money',
'moving_end',
'moving_start',
'no_sensor',
'not_at_rot_target',
'not_at_target',
'object_rez',
'on_rez',
'remote_data',
'run_time_permissions',
'sensor',
'state_entry',
'state_exit',
'timer',
'touch',
'touch_end',
'touch_start',
),
4 => array( // data types
'float',
'integer',
'key',
'list',
'rotation',
'string',
'vector',
),
5 => array( // library
'default',
'llAbs',
'llAcos',
'llAddToLandBanList',
'llAddToLandPassList',
'llAdjustSoundVolume',
'llAllowInventoryDrop',
'llAngleBetween',
'llApplyImpulse',
'llApplyRotationalImpulse',
'llAsin',
'llAtan2',
'llAttachToAvatar',
'llAvatarOnSitTarget',
'llAxes2Rot',
'llAxisAngle2Rot',
'llBase64ToInteger',
'llBase64ToString',
'llBreakAllLinks',
'llBreakLink',
'llCeil',
'llClearCameraParams',
'llCloseRemoteDataChannel',
'llCloud',
'llCollisionFilter',
'llCollisionSound',
'llCollisionSprite',
'llCos',
'llCreateLink',
'llCSV2List',
'llDeleteSubList',
'llDeleteSubString',
'llDetachFromAvatar',
'llDetectedGrab',
'llDetectedGroup',
'llDetectedKey',
'llDetectedLinkNumber',
'llDetectedName',
'llDetectedOwner',
'llDetectedPos',
'llDetectedRot',
'llDetectedTouchBinormal',
'llDetectedTouchFace',
'llDetectedTouchNormal',
'llDetectedTouchPos',
'llDetectedTouchST',
'llDetectedTouchUV',
'llDetectedType',
'llDetectedVel',
'llDialog',
'llDie',
'llDumpList2String',
'llEdgeOfWorld',
'llEjectFromLand',
'llEmail',
'llEscapeURL',
'llEuler2Rot',
'llFabs',
'llFloor',
'llForceMouselook',
'llFrand',
'llGetAccel',
'llGetAgentInfo',
'llGetAgentLanguage',
'llGetAgentSize',
'llGetAlpha',
'llGetAndResetTime',
'llGetAnimation',
'llGetAnimationList',
'llGetAttached',
'llGetBoundingBox',
'llGetCameraPos',
'llGetCameraRot',
'llGetCenterOfMass',
'llGetColor',
'llGetCreator',
'llGetDate',
'llGetEnergy',
'llGetForce',
'llGetFreeMemory',
'llGetGeometricCenter',
'llGetGMTclock',
'llGetInventoryCreator',
'llGetInventoryKey',
'llGetInventoryName',
'llGetInventoryNumber',
'llGetInventoryPermMask',
'llGetInventoryType',
'llGetKey',
'llGetLandOwnerAt',
'llGetLinkKey',
'llGetLinkName',
'llGetLinkNumber',
'llGetListEntryType',
'llGetListLength',
'llGetLocalPos',
'llGetLocalRot',
'llGetMass',
'llGetNextEmail',
'llGetNotecardLine',
'llGetNumberOfNotecardLines',
'llGetNumberOfPrims',
'llGetNumberOfSides',
'llGetObjectDesc',
'llGetObjectDetails',
'llGetObjectMass',
'llGetObjectName',
'llGetObjectPermMask',
'llGetObjectPrimCount',
'llGetOmega',
'llGetOwner',
'llGetOwnerKey',
'llGetParcelDetails',
'llGetParcelFlags',
'llGetParcelMaxPrims',
'llGetParcelPrimCount',
'llGetParcelPrimOwners',
'llGetPermissions',
'llGetPermissionsKey',
'llGetPos',
'llGetPrimitiveParams',
'llGetRegionAgentCount',
'llGetRegionCorner',
'llGetRegionFlags',
'llGetRegionFPS',
'llGetRegionName',
'llGetRegionTimeDilation',
'llGetRootPosition',
'llGetRootRotation',
'llGetRot',
'llGetScale',
'llGetScriptName',
'llGetScriptState',
'llGetSimulatorHostname',
'llGetStartParameter',
'llGetStatus',
'llGetSubString',
'llGetSunDirection',
'llGetTexture',
'llGetTextureOffset',
'llGetTextureRot',
'llGetTextureScale',
'llGetTime',
'llGetTimeOfDay',
'llGetTimestamp',
'llGetTorque',
'llGetUnixTime',
'llGetVel',
'llGetWallclock',
'llGiveInventory',
'llGiveInventoryList',
'llGiveMoney',
'llGround',
'llGroundContour',
'llGroundNormal',
'llGroundRepel',
'llGroundSlope',
'llHTTPRequest',
'llInsertString',
'llInstantMessage',
'llIntegerToBase64',
'llKey2Name',
'llList2CSV',
'llList2Float',
'llList2Integer',
'llList2Key',
'llList2List',
'llList2ListStrided',
'llList2Rot',
'llList2String',
'llList2Vector',
'llListen',
'llListenControl',
'llListenRemove',
'llListFindList',
'llListInsertList',
'llListRandomize',
'llListReplaceList',
'llListSort',
'llListStatistics',
'llLoadURL',
'llLog',
'llLog10',
'llLookAt',
'llLoopSound',
'llLoopSoundMaster',
'llLoopSoundSlave',
'llMapDestination',
'llMD5String',
'llMessageLinked',
'llMinEventDelay',
'llModifyLand',
'llModPow',
'llMoveToTarget',
'llOffsetTexture',
'llOpenRemoteDataChannel',
'llOverMyLand',
'llOwnerSay',
'llParcelMediaCommandList',
'llParcelMediaQuery',
'llParseString2List',
'llParseStringKeepNulls',
'llParticleSystem',
'llPassCollisions',
'llPassTouches',
'llPlaySound',
'llPlaySoundSlave',
'llPow',
'llPreloadSound',
'llPushObject',
'llRegionSay',
'llReleaseControls',
'llRemoteDataReply',
'llRemoteDataSetRegion',
'llRemoteLoadScriptPin',
'llRemoveFromLandBanList',
'llRemoveFromLandPassList',
'llRemoveInventory',
'llRemoveVehicleFlags',
'llRequestAgentData',
'llRequestInventoryData',
'llRequestPermissions',
'llRequestSimulatorData',
'llResetLandBanList',
'llResetLandPassList',
'llResetOtherScript',
'llResetScript',
'llResetTime',
'llRezAtRoot',
'llRezObject',
'llRot2Angle',
'llRot2Axis',
'llRot2Euler',
'llRot2Fwd',
'llRot2Left',
'llRot2Up',
'llRotateTexture',
'llRotBetween',
'llRotLookAt',
'llRotTarget',
'llRotTargetRemove',
'llRound',
'llSameGroup',
'llSay',
'llScaleTexture',
'llScriptDanger',
'llSendRemoteData',
'llSensor',
'llSensorRemove',
'llSensorRepeat',
'llSetAlpha',
'llSetBuoyancy',
'llSetCameraAtOffset',
'llSetCameraEyeOffset',
'llSetCameraParams',
'llSetClickAction',
'llSetColor',
'llSetDamage',
'llSetForce',
'llSetForceAndTorque',
'llSetHoverHeight',
'llSetLinkAlpha',
'llSetLinkColor',
'llSetLinkPrimitiveParams',
'llSetLinkTexture',
'llSetLocalRot',
'llSetObjectDesc',
'llSetObjectName',
'llSetParcelMusicURL',
'llSetPayPrice',
'llSetPos',
'llSetPrimitiveParams',
'llSetRemoteScriptAccessPin',
'llSetRot',
'llSetScale',
'llSetScriptState',
'llSetSitText',
'llSetSoundQueueing',
'llSetSoundRadius',
'llSetStatus',
'llSetText',
'llSetTexture',
'llSetTextureAnim',
'llSetTimerEvent',
'llSetTorque',
'llSetTouchText',
'llSetVehicleFlags',
'llSetVehicleFloatParam',
'llSetVehicleRotationParam',
'llSetVehicleType',
'llSetVehicleVectorParam',
'llSHA1String',
'llShout',
'llSin',
'llSitTarget',
'llSleep',
'llSqrt',
'llStartAnimation',
'llStopAnimation',
'llStopHover',
'llStopLookAt',
'llStopMoveToTarget',
'llStopSound',
'llStringLength',
'llStringToBase64',
'llStringTrim',
'llSubStringIndex',
'llTakeControls',
'llTan',
'llTarget',
'llTargetOmega',
'llTargetRemove',
'llTeleportAgentHome',
'llToLower',
'llToUpper',
'llTriggerSound',
'llTriggerSoundLimited',
'llUnescapeURL',
'llUnSit',
'llVecDist',
'llVecMag',
'llVecNorm',
'llVolumeDetect',
'llWater',
'llWhisper',
'llWind',
'llXorBase64StringsCorrect',
),
6 => array( // deprecated
'llMakeExplosion',
'llMakeFire',
'llMakeFountain',
'llMakeSmoke',
'llSound',
'llSoundPreload',
'llXorBase64Strings',
),
7 => array( // unimplemented
'llPointAt',
'llRefreshPrimURL',
'llReleaseCamera',
'llRemoteLoadScript',
'llSetPrimURL',
'llStopPointAt',
'llTakeCamera',
'llTextBox',
),
8 => array( // God mode
'llGodLikeRezObject',
'llSetInventoryPermMask',
'llSetObjectPermMask',
),
),
'SYMBOLS' => array(
'{', '}', '(', ')', '[', ']',
'=', '+', '-', '*', '/',
'+=', '-=', '*=', '/=', '++', '--',
'!', '%', '&', '|', '&&', '||',
'==', '!=', '<', '>', '<=', '>=',
'~', '<<', '>>', '^', ':',
),
'CASE_SENSITIVE' => array(
GESHI_COMMENTS => true,
1 => true,
2 => true,
3 => true,
4 => true,
5 => true,
6 => true,
7 => true,
8 => true,
),
'STYLES' => array(
'KEYWORDS' => array(
1 => 'color: #0000ff;',
2 => 'color: #000080;',
3 => 'color: #008080;',
4 => 'color: #228b22;',
5 => 'color: #b22222;',
6 => 'color: #8b0000; background-color: #ffff00;',
7 => 'color: #8b0000; background-color: #fa8072;',
8 => 'color: #000000; background-color: #ba55d3;',
),
'COMMENTS' => array(
1 => 'color: #ff7f50; font-style: italic;',
),
'ESCAPE_CHAR' => array(
0 => 'color: #000099;'
),
'BRACKETS' => array(
0 => 'color: #000000;'
),
'STRINGS' => array(
0 => 'color: #006400;'
),
'NUMBERS' => array(
0 => 'color: #000000;'
),
'METHODS' => array(
),
'SYMBOLS' => array(
0 => 'color: #000000;'
),
'REGEXPS' => array(
),
'SCRIPT' => array(
)
),
'URLS' => array(
1 => '',
2 => '',
3 => 'http://www.lslwiki.net/lslwiki/wakka.php?wakka={FNAME}', // http://wiki.secondlife.com/wiki/{FNAME}
4 => 'http://www.lslwiki.net/lslwiki/wakka.php?wakka={FNAME}', // http://wiki.secondlife.com/wiki/{FNAME}
5 => 'http://www.lslwiki.net/lslwiki/wakka.php?wakka={FNAME}', // http://wiki.secondlife.com/wiki/{FNAME}
6 => 'http://www.lslwiki.net/lslwiki/wakka.php?wakka={FNAME}', // http://wiki.secondlife.com/wiki/{FNAME}
7 => 'http://www.lslwiki.net/lslwiki/wakka.php?wakka={FNAME}', // http://wiki.secondlife.com/wiki/{FNAME}
8 => 'http://www.lslwiki.net/lslwiki/wakka.php?wakka={FNAME}', // http://wiki.secondlife.com/wiki/{FNAME}
),
'OOLANG' => false,
'OBJECT_SPLITTERS' => array(),
'REGEXPS' => array(
),
'STRICT_MODE_APPLIES' => GESHI_NEVER,
'SCRIPT_DELIMITERS' => array(
),
'HIGHLIGHT_STRICT_BLOCK' => array(
)
);
?> | 412 | 0.778584 | 1 | 0.778584 | game-dev | MEDIA | 0.213734 | game-dev | 0.715333 | 1 | 0.715333 |
OpenLoco/OpenLoco | 6,283 | src/OpenLoco/src/GameCommands/Vehicles/VehiclePlaceAir.cpp | #include "VehiclePlaceAir.h"
#include "Economy/Expenditures.h"
#include "Entities/EntityManager.h"
#include "Localisation/StringIds.h"
#include "Map/StationElement.h"
#include "Map/TileManager.h"
#include "Objects/AirportObject.h"
#include "Objects/ObjectManager.h"
#include "Objects/VehicleObject.h"
#include "Random.h"
#include "Vehicles/Vehicle.h"
#include "ViewportManager.h"
#include "World/StationManager.h"
using namespace OpenLoco::Literals;
namespace OpenLoco::Vehicles
{
// TODO: MOVE TO SOMEWHERE ELSE
// 0x0048B11D
void playPlacedownSound(const World::Pos3 pos)
{
const auto frequency = gPrng2().randNext(20003, 24095);
Audio::playSound(Audio::SoundId::vehiclePlace, pos, -600, frequency);
}
}
namespace OpenLoco::GameCommands
{
// 0x004267BE
static uint32_t vehiclePlaceAir(const VehicleAirPlacementArgs& args, uint8_t flags)
{
setExpenditureType(ExpenditureType::AircraftRunningCosts);
auto* station = StationManager::get(args.stationId);
if (station == nullptr)
{
return FAILURE;
}
const auto pos = station->airportStartPos;
setPosition(pos);
auto* head = EntityManager::get<Vehicles::VehicleHead>(args.head);
if (head == nullptr)
{
return FAILURE;
}
if (!sub_431E6A(head->owner))
{
return FAILURE;
}
Vehicles::Vehicle train(head->id);
if (!args.convertGhost)
{
if (head->tileX != -1)
{
setErrorText(StringIds::empty);
return FAILURE;
}
if (train.cars.empty())
{
setErrorText(StringIds::empty);
return FAILURE;
}
}
if (args.convertGhost)
{
train.applyToComponents([](auto& component) {
component.var_38 &= ~Vehicles::Flags38::isGhost;
Ui::ViewportManager::invalidate(&component, ZoomLevel::eighth);
});
}
else
{
auto* elStation = [pos]() -> World::StationElement* {
const auto tile = World::TileManager::get(pos);
for (auto& el : tile)
{
auto* elStation = el.as<World::StationElement>();
if (elStation == nullptr)
{
continue;
}
if (elStation->baseHeight() != pos.z)
{
continue;
}
return elStation;
}
return nullptr;
}();
if (elStation == nullptr)
{
return FAILURE;
}
if (elStation->isGhost() || elStation->isAiAllocated())
{
return FAILURE;
}
auto* airportObj = ObjectManager::get<AirportObject>(elStation->objectId());
const auto movementEdges = airportObj->getMovementEdges();
auto previousEdgeId = 0;
for (; previousEdgeId < airportObj->numMovementEdges; ++previousEdgeId)
{
if (movementEdges[previousEdgeId].nextNode == args.airportNode)
{
break;
}
}
if (previousEdgeId == airportObj->numMovementEdges)
{
return FAILURE;
}
auto& previousMovEdge = movementEdges[previousEdgeId];
if (station->airportMovementOccupiedEdges & previousMovEdge.mustBeClearEdges)
{
setErrorText(StringIds::vehicle_approaching_or_in_the_way);
return FAILURE;
}
if (station->airportMovementOccupiedEdges & airportObj->var_B6)
{
setErrorText(StringIds::vehicle_approaching_or_in_the_way);
return FAILURE;
}
if (!sub_431E6A(station->owner))
{
return FAILURE;
}
if ((airportObj->flags & train.cars.firstCar.front->getCompatibleAirportType()) == AirportObjectFlags::none)
{
setErrorText(StringIds::airport_type_not_suitable_for_aircraft);
return FAILURE;
}
if (!(flags & Flags::apply))
{
return 0;
}
const auto placePos = getAirportMovementNodeLoc(args.stationId, args.airportNode);
const auto previousNodePos = getAirportMovementNodeLoc(args.stationId, previousMovEdge.curNode);
if (!placePos.has_value() || !previousNodePos.has_value())
{
return FAILURE;
}
auto yaw = Vehicles::calculateYaw1FromVector(placePos->x - previousNodePos->x, placePos->y - previousNodePos->y);
auto reverseYaw = yaw ^ (1U << 5);
auto* vehicleObj = ObjectManager::get<VehicleObject>(train.cars.firstCar.front->objectId);
const auto pitch = vehicleObj->hasFlags(VehicleObjectFlags::aircraftIsTaildragger) ? Pitch::up12deg : Pitch::flat;
head->movePlaneTo(*placePos, reverseYaw, pitch);
head->status = Vehicles::Status::stopped;
head->vehicleFlags |= VehicleFlags::commandStop;
head->stationId = args.stationId;
head->airportMovementEdge = previousEdgeId;
station->airportMovementOccupiedEdges |= (1U << previousEdgeId);
train.veh1->var_48 |= Vehicles::Flags48::flag2;
train.veh2->currentSpeed = 0.0_mph;
train.veh2->motorState = Vehicles::MotorState::stopped;
if (flags & Flags::ghost)
{
train.applyToComponents([](auto& component) {
component.var_38 |= Vehicles::Flags38::isGhost;
});
}
}
if ((flags & Flags::apply) && !(flags & Flags::ghost))
{
Vehicles::playPlacedownSound(pos);
}
return 0;
}
void vehiclePlaceAir(registers& regs)
{
regs.ebx = vehiclePlaceAir(VehicleAirPlacementArgs(regs), regs.bl);
}
}
| 412 | 0.898786 | 1 | 0.898786 | game-dev | MEDIA | 0.799848 | game-dev | 0.978612 | 1 | 0.978612 |
Tesserex/C--MegaMan-Engine | 1,408 | IO/Xml/GameXmlException.cs | using System;
using System.Xml;
using System.Xml.Linq;
namespace MegaMan.IO.Xml
{
public class GameXmlException : Exception
{
public string File { get; set; }
public int Line { get; set; }
public int Position { get; set; }
public string Entity { get; set; }
public string Tag { get; set; }
public string Attribute { get; set; }
public GameXmlException(XElement element, string message)
: base(message)
{
Line = (element as IXmlLineInfo).LineNumber;
Position = (element as IXmlLineInfo).LinePosition;
Tag = element.Name.LocalName;
}
public GameXmlException(XAttribute attribute, string message)
: this(attribute.Parent, message)
{
Attribute = attribute.Name.LocalName;
}
public GameXmlException(string file, int line, string entity, string tag, string attribute, string message) : base(message)
{
File = file;
Line = line;
Entity = entity;
Tag = tag;
Attribute = attribute;
}
public override string ToString()
{
return base.ToString();
}
}
public class GameEntityException : Exception
{
public GameEntityException(string message)
: base(message)
{
}
}
}
| 412 | 0.712792 | 1 | 0.712792 | game-dev | MEDIA | 0.331266 | game-dev | 0.688434 | 1 | 0.688434 |
dreamCirno/Hollow-Knight-Imitation | 4,161 | Assets/Demigiant/DOTween/Modules/DOTweenModuleSprite.cs | // Author: Daniele Giardini - http://www.demigiant.com
// Created: 2018/07/13
#if true && (UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_5 || UNITY_2017_1_OR_NEWER) // MODULE_MARKER
using System;
using UnityEngine;
using DG.Tweening.Core;
using DG.Tweening.Plugins.Options;
#pragma warning disable 1591
namespace DG.Tweening
{
public static class DOTweenModuleSprite
{
#region Shortcuts
#region SpriteRenderer
/// <summary>Tweens a SpriteRenderer's color to the given value.
/// Also stores the spriteRenderer as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
public static TweenerCore<Color, Color, ColorOptions> DOColor(this SpriteRenderer target, Color endValue, float duration)
{
TweenerCore<Color, Color, ColorOptions> t = DOTween.To(() => target.color, x => target.color = x, endValue, duration);
t.SetTarget(target);
return t;
}
/// <summary>Tweens a Material's alpha color to the given value.
/// Also stores the spriteRenderer as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param>
public static TweenerCore<Color, Color, ColorOptions> DOFade(this SpriteRenderer target, float endValue, float duration)
{
TweenerCore<Color, Color, ColorOptions> t = DOTween.ToAlpha(() => target.color, x => target.color = x, endValue, duration);
t.SetTarget(target);
return t;
}
/// <summary>Tweens a SpriteRenderer's color using the given gradient
/// (NOTE 1: only uses the colors of the gradient, not the alphas - NOTE 2: creates a Sequence, not a Tweener).
/// Also stores the image as the tween's target so it can be used for filtered operations</summary>
/// <param name="gradient">The gradient to use</param><param name="duration">The duration of the tween</param>
public static Sequence DOGradientColor(this SpriteRenderer target, Gradient gradient, float duration)
{
Sequence s = DOTween.Sequence();
GradientColorKey[] colors = gradient.colorKeys;
int len = colors.Length;
for (int i = 0; i < len; ++i) {
GradientColorKey c = colors[i];
if (i == 0 && c.time <= 0) {
target.color = c.color;
continue;
}
float colorDuration = i == len - 1
? duration - s.Duration(false) // Verifies that total duration is correct
: duration * (i == 0 ? c.time : c.time - colors[i - 1].time);
s.Append(target.DOColor(c.color, colorDuration).SetEase(Ease.Linear));
}
s.SetTarget(target);
return s;
}
#endregion
#region Blendables
#region SpriteRenderer
/// <summary>Tweens a SpriteRenderer's color to the given value,
/// in a way that allows other DOBlendableColor tweens to work together on the same target,
/// instead than fight each other as multiple DOColor would do.
/// Also stores the SpriteRenderer as the tween's target so it can be used for filtered operations</summary>
/// <param name="endValue">The value to tween to</param><param name="duration">The duration of the tween</param>
public static Tweener DOBlendableColor(this SpriteRenderer target, Color endValue, float duration)
{
endValue = endValue - target.color;
Color to = new Color(0, 0, 0, 0);
return DOTween.To(() => to, x => {
Color diff = x - to;
to = x;
target.color += diff;
}, endValue, duration)
.Blendable().SetTarget(target);
}
#endregion
#endregion
#endregion
}
}
#endif
| 412 | 0.833711 | 1 | 0.833711 | game-dev | MEDIA | 0.824776 | game-dev | 0.951131 | 1 | 0.951131 |
MrCrayfish/MrCrayfishGunMod | 3,769 | src/main/java/com/mrcrayfish/guns/common/ShootTracker.java | package com.mrcrayfish.guns.common;
import com.google.common.collect.Maps;
import com.mrcrayfish.guns.item.GunItem;
import com.mrcrayfish.guns.util.GunEnchantmentHelper;
import com.mrcrayfish.guns.util.GunModifierHelper;
import net.minecraft.Util;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.context.UseOnContext;
import org.apache.commons.lang3.tuple.Pair;
import java.util.Map;
import java.util.WeakHashMap;
/**
* A simple class to track and control weapon cooldowns
* <p>
* Author: MrCrayfish
*/
public class ShootTracker
{
/**
* A custom implementation of the cooldown tracker in order to provide the best experience for
* players. On servers, Minecraft's cooldown tracker is sent to the client but the latency creates
* an awkward experience as the cooldown applies to the item after the packet has traveled to the
* server then back to the client. To fix this and still apply security, we just handle the
* cooldown tracker quietly and not send cooldown packet back to client. The cooldown is still
* applied on the client in {@link GunItem#onItemUseFirst(ItemStack, UseOnContext)} and {@link GunItem#onUsingTick}.
*/
private static final Map<Player, ShootTracker> SHOOT_TRACKER_MAP = new WeakHashMap<>();
private final Map<Item, Pair<Long, Integer>> cooldownMap = Maps.newHashMap();
/**
* Gets the cooldown tracker for the specified player UUID.
*
* @param player the player instance
* @return a cooldown tracker get
*/
public static ShootTracker getShootTracker(Player player)
{
return SHOOT_TRACKER_MAP.computeIfAbsent(player, player1 -> new ShootTracker());
}
/**
* Puts a cooldown for the specified gun item. This stores the time it was fired and the rate
* of the weapon to determine when it's allowed to fire again.
*
* @param item a gun item
* @param modifiedGun the modified gun get of the specified gun
*/
public void putCooldown(ItemStack weapon, GunItem item, Gun modifiedGun)
{
int rate = GunEnchantmentHelper.getRate(weapon, modifiedGun);
rate = GunModifierHelper.getModifiedRate(weapon, rate);
this.cooldownMap.put(item, Pair.of(Util.getMillis(), rate * 50));
}
/**
* Checks if the specified item has an active cooldown. If a cooldown is active, it means that
* the weapon can not be fired until it has finished. This method provides leeway as sometimes a
* weapon is ready to fire but the cooldown is not completely finished, rather it's in the last
* 50 milliseconds or 1 game tick.
*
* @param item a gun item
* @return if the specified gun item has an active cooldown
*/
public boolean hasCooldown(GunItem item)
{
Pair<Long, Integer> pair = this.cooldownMap.get(item);
if(pair != null)
{
/* Give a 50 millisecond leeway as most of the time the cooldown has finished, just not exactly to the millisecond */
return Util.getMillis() - pair.getLeft() < pair.getRight() - 50;
}
return false;
}
/**
* Gets the remaining milliseconds before the weapon is allowed to shoot again. This doesn't
* take into account the leeway given in {@link #hasCooldown(GunItem)}.
*
* @param item a gun item
* @return the remaining time in milliseconds
*/
public long getRemaining(GunItem item)
{
Pair<Long, Integer> pair = this.cooldownMap.get(item);
if(pair != null)
{
return pair.getRight() - (Util.getMillis() - pair.getLeft());
}
return 0;
}
}
| 412 | 0.894801 | 1 | 0.894801 | game-dev | MEDIA | 0.903241 | game-dev | 0.894978 | 1 | 0.894978 |
OwlGamingCommunity/V | 5,171 | Source/owl_admin.client/AdminCheck.Client.cs | using System;
public class AdminCheck
{
private CGUIAdminCheck m_AdminCheckUI = new CGUIAdminCheck(OnUILoaded);
private AdminCheckDetails m_CachedDetails = null;
private RAGE.Elements.Player m_CachedPlayer = null;
public AdminCheck()
{
NetworkEvents.AdminCheck += OnAdminCheck;
RageEvents.RAGE_OnTick_OncePerSecond += UpdateCheck;
}
private static void OnUILoaded()
{
}
private void UpdateCheck()
{
if (m_AdminCheckUI.IsVisible())
{
ApplyCheckDetails();
}
}
public void OnCloseCheck()
{
m_AdminCheckUI.SetVisible(false, false, false);
}
public void OnSaveAdminNotes(string strNotes)
{
NetworkEventSender.SendNetworkEvent_SaveAdminNotes(strNotes, DataHelper.GetEntityData<int>(m_CachedPlayer, EDataNames.ACCOUNT_ID));
}
private void ApplyCheckDetails()
{
int latency = DataHelper.GetEntityData<int>(m_CachedPlayer, EDataNames.PING);
int playerID = DataHelper.GetEntityData<int>(m_CachedPlayer, EDataNames.PLAYER_ID);
EAdminLevel adminLevel = DataHelper.GetEntityData<EAdminLevel>(m_CachedPlayer, EDataNames.ADMIN_LEVEL);
string strTitle = Helpers.GetAdminLevelName(adminLevel);
float fMoney = DataHelper.GetEntityData<float>(m_CachedPlayer, EDataNames.MONEY);
float fBankMoney = DataHelper.GetEntityData<float>(m_CachedPlayer, EDataNames.BANK_MONEY);
// What do we want to do with this? it's just dimension...
string strInterior = m_CachedPlayer.Dimension == 0 ? "World" : m_CachedPlayer.Dimension.ToString();
// SKIN
bool bIsCustom = DataHelper.GetEntityData<bool>(m_CachedPlayer, EDataNames.IS_CUSTOM);
string strSkin = Helpers.FormatString("{0} (Custom: {1})", m_CachedPlayer.Model, bIsCustom ? "Yes" : "No");
// FACTIONS
int factionIndex = 0;
string strFactions = "";
foreach (CFactionTransmit faction in m_CachedDetails.Factions)
{
if (factionIndex > 0)
{
strFactions += ", ";
}
strFactions += Helpers.FormatString("{0} ({1})", faction.Name, faction.ShortName);
++factionIndex;
}
// WEAPONS
string strWeapon = "Unarmed";
int currentWeaponHash = 0;
if (m_CachedPlayer.GetCurrentWeapon(ref currentWeaponHash, false))
{
EItemID itemID = EItemID.None;
foreach (var kvPair in ItemWeaponDefinitions.g_DictItemIDToWeaponHash)
{
if (kvPair.Value == (WeaponHash)currentWeaponHash)
{
itemID = kvPair.Key;
}
}
if (itemID != EItemID.None)
{
var itemDef = ItemDefinitions.g_ItemDefinitions[itemID];
if (itemDef != null)
{
strWeapon = Helpers.FormatString("{0} (Ammo: {1})", itemDef.GetNameIgnoreGenericItems(), m_CachedPlayer.GetAmmoInWeapon((unchecked((uint)currentWeaponHash))));
}
}
}
// VEHICLE
string strCurrentVehicle = "On-Foot";
RAGE.Elements.Vehicle vehicle = m_CachedPlayer.Vehicle;
if (vehicle != null)
{
CVehicleDefinition vehicleDef = VehicleDefinitions.GetVehicleDefinitionFromHash(vehicle.Model);
if (vehicleDef != null)
{
strCurrentVehicle = Helpers.FormatString("{0} {1} ({2})", vehicleDef.Manufacturer, vehicleDef.Name, vehicleDef.Class);
}
}
// LOCATION
int streetNameID = -1;
int crossroadNameID = -1;
string strStreetName = String.Empty;
string strCrossroadName = String.Empty;
RAGE.Game.Pathfind.GetStreetNameAtCoord(m_CachedPlayer.Position.X, m_CachedPlayer.Position.Y, m_CachedPlayer.Position.Z, ref streetNameID, ref crossroadNameID);
if (streetNameID != -1)
{
strStreetName = RAGE.Game.Ui.GetStreetNameFromHashKey((uint)streetNameID);
}
if (crossroadNameID != -1)
{
strCrossroadName = RAGE.Game.Ui.GetStreetNameFromHashKey((uint)crossroadNameID);
}
string strZoneName = RAGE.Game.Zone.GetNameOfZone(m_CachedPlayer.Position.X, m_CachedPlayer.Position.Y, m_CachedPlayer.Position.Z);
string strRealZoneName = ZoneNameHelper.ZoneNames.ContainsKey(strZoneName) ? ZoneNameHelper.ZoneNames[strZoneName] : "San Andreas";
string strLocation = String.Empty;
if (strCrossroadName == String.Empty)
{
strLocation = Helpers.FormatString("{0}, {1}", strStreetName, strRealZoneName);
}
else
{
strLocation = Helpers.FormatString("{0} & {1}, {2}", strStreetName, strCrossroadName, strRealZoneName);
}
m_AdminCheckUI.SetDetails(m_CachedDetails.Username, m_CachedDetails.CharacterName, playerID, m_CachedDetails.IpAddress, strTitle, latency, m_CachedDetails.GameCoins, fMoney, fBankMoney, m_CachedPlayer.GetHealth(), m_CachedPlayer.GetArmour(), strFactions, strCurrentVehicle,
m_CachedPlayer.Position.X, m_CachedPlayer.Position.Y, m_CachedPlayer.Position.Z, strInterior, m_CachedPlayer.Dimension, m_CachedDetails.HoursPlayed_Account, m_CachedDetails.HoursPlayed_Character, strSkin, strWeapon, m_CachedDetails.NumPunishmentPointsActive, m_CachedDetails.NumPunishmentPointsLifetime, strLocation);
}
private void OnAdminCheck(RAGE.Elements.Player targetPlayer, AdminCheckDetails playerDetails)
{
m_AdminCheckUI.SetVisible(true, true, false);
m_CachedPlayer = targetPlayer;
m_CachedDetails = playerDetails;
m_AdminCheckUI.SetAdminNotes(playerDetails.AdminNotes);
m_AdminCheckUI.ResetAdminHistory();
m_AdminCheckUI.SetAdminHistory(playerDetails.AdminHistory);
ApplyCheckDetails();
}
} | 412 | 0.945692 | 1 | 0.945692 | game-dev | MEDIA | 0.901699 | game-dev | 0.989757 | 1 | 0.989757 |
QuilibriumNetwork/monorepo | 8,283 | go-libp2p/p2p/net/connmgr/decay.go | package connmgr
import (
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/libp2p/go-libp2p/core/connmgr"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/benbjohnson/clock"
)
// DefaultResolution is the default resolution of the decay tracker.
var DefaultResolution = 1 * time.Minute
// bumpCmd represents a bump command.
type bumpCmd struct {
peer peer.ID
tag *decayingTag
delta int
}
// removeCmd represents a tag removal command.
type removeCmd struct {
peer peer.ID
tag *decayingTag
}
// decayer tracks and manages all decaying tags and their values.
type decayer struct {
cfg *DecayerCfg
mgr *BasicConnMgr
clock clock.Clock // for testing.
tagsMu sync.Mutex
knownTags map[string]*decayingTag
// lastTick stores the last time the decayer ticked. Guarded by atomic.
lastTick atomic.Pointer[time.Time]
// bumpTagCh queues bump commands to be processed by the loop.
bumpTagCh chan bumpCmd
removeTagCh chan removeCmd
closeTagCh chan *decayingTag
// closure thingies.
closeCh chan struct{}
doneCh chan struct{}
err error
}
var _ connmgr.Decayer = (*decayer)(nil)
// DecayerCfg is the configuration object for the Decayer.
type DecayerCfg struct {
Resolution time.Duration
Clock clock.Clock
}
// WithDefaults writes the default values on this DecayerConfig instance,
// and returns itself for chainability.
//
// cfg := (&DecayerCfg{}).WithDefaults()
// cfg.Resolution = 30 * time.Second
// t := NewDecayer(cfg, cm)
func (cfg *DecayerCfg) WithDefaults() *DecayerCfg {
cfg.Resolution = DefaultResolution
return cfg
}
// NewDecayer creates a new decaying tag registry.
func NewDecayer(cfg *DecayerCfg, mgr *BasicConnMgr) (*decayer, error) {
// use real time if the Clock in the config is nil.
if cfg.Clock == nil {
cfg.Clock = clock.New()
}
d := &decayer{
cfg: cfg,
mgr: mgr,
clock: cfg.Clock,
knownTags: make(map[string]*decayingTag),
bumpTagCh: make(chan bumpCmd, 128),
removeTagCh: make(chan removeCmd, 128),
closeTagCh: make(chan *decayingTag, 128),
closeCh: make(chan struct{}),
doneCh: make(chan struct{}),
}
now := d.clock.Now()
d.lastTick.Store(&now)
// kick things off.
go d.process()
return d, nil
}
func (d *decayer) RegisterDecayingTag(name string, interval time.Duration, decayFn connmgr.DecayFn, bumpFn connmgr.BumpFn) (connmgr.DecayingTag, error) {
d.tagsMu.Lock()
defer d.tagsMu.Unlock()
if _, ok := d.knownTags[name]; ok {
return nil, fmt.Errorf("decaying tag with name %s already exists", name)
}
if interval < d.cfg.Resolution {
log.Warn("decay interval was lower than tracker's resolution; overridden to resolution",
"name", name,
"interval", interval,
"resolution", d.cfg.Resolution)
interval = d.cfg.Resolution
}
if interval%d.cfg.Resolution != 0 {
log.Warn("decay interval for tag is not a multiple of tracker's resolution; some precision may be lost",
"tag", name, "interval", interval, "resolution", d.cfg.Resolution)
}
lastTick := d.lastTick.Load()
tag := &decayingTag{
trkr: d,
name: name,
interval: interval,
nextTick: lastTick.Add(interval),
decayFn: decayFn,
bumpFn: bumpFn,
}
d.knownTags[name] = tag
return tag, nil
}
// Close closes the Decayer. It is idempotent.
func (d *decayer) Close() error {
select {
case <-d.doneCh:
return d.err
default:
}
close(d.closeCh)
<-d.doneCh
return d.err
}
// process is the heart of the tracker. It performs the following duties:
//
// 1. Manages decay.
// 2. Applies score bumps.
// 3. Yields when closed.
func (d *decayer) process() {
defer close(d.doneCh)
ticker := d.clock.Ticker(d.cfg.Resolution)
defer ticker.Stop()
var (
bmp bumpCmd
visit = make(map[*decayingTag]struct{})
)
for {
select {
case <-ticker.C:
now := d.clock.Now()
d.lastTick.Store(&now)
d.tagsMu.Lock()
for _, tag := range d.knownTags {
if tag.nextTick.After(now) {
// skip the tag.
continue
}
// Mark the tag to be updated in this round.
visit[tag] = struct{}{}
}
d.tagsMu.Unlock()
// Visit each peer, and decay tags that need to be decayed.
for _, s := range d.mgr.segments.buckets {
s.Lock()
// Entered a segment that contains peers. Process each peer.
for _, p := range s.peers {
for tag, v := range p.decaying {
if _, ok := visit[tag]; !ok {
// skip this tag.
continue
}
// ~ this value needs to be visited. ~
var delta int
if after, rm := tag.decayFn(*v); rm {
// delete the value and move on to the next tag.
delta -= v.Value
delete(p.decaying, tag)
} else {
// accumulate the delta, and apply the changes.
delta += after - v.Value
v.Value, v.LastVisit = after, now
}
p.value += delta
}
}
s.Unlock()
}
// Reset each tag's next visit round, and clear the visited set.
for tag := range visit {
tag.nextTick = tag.nextTick.Add(tag.interval)
delete(visit, tag)
}
case bmp = <-d.bumpTagCh:
var (
now = d.clock.Now()
peer, tag = bmp.peer, bmp.tag
)
s := d.mgr.segments.get(peer)
s.Lock()
p := s.tagInfoFor(peer, d.clock.Now())
v, ok := p.decaying[tag]
if !ok {
v = &connmgr.DecayingValue{
Tag: tag,
Peer: peer,
LastVisit: now,
Added: now,
Value: 0,
}
p.decaying[tag] = v
}
prev := v.Value
v.Value, v.LastVisit = v.Tag.(*decayingTag).bumpFn(*v, bmp.delta), now
p.value += v.Value - prev
s.Unlock()
case rm := <-d.removeTagCh:
s := d.mgr.segments.get(rm.peer)
s.Lock()
p := s.tagInfoFor(rm.peer, d.clock.Now())
v, ok := p.decaying[rm.tag]
if !ok {
s.Unlock()
continue
}
p.value -= v.Value
delete(p.decaying, rm.tag)
s.Unlock()
case t := <-d.closeTagCh:
// Stop tracking the tag.
d.tagsMu.Lock()
delete(d.knownTags, t.name)
d.tagsMu.Unlock()
// Remove the tag from all peers that had it in the connmgr.
for _, s := range d.mgr.segments.buckets {
// visit all segments, and attempt to remove the tag from all the peers it stores.
s.Lock()
for _, p := range s.peers {
if dt, ok := p.decaying[t]; ok {
// decrease the value of the tagInfo, and delete the tag.
p.value -= dt.Value
delete(p.decaying, t)
}
}
s.Unlock()
}
case <-d.closeCh:
return
}
}
}
// decayingTag represents a decaying tag, with an associated decay interval, a
// decay function, and a bump function.
type decayingTag struct {
trkr *decayer
name string
interval time.Duration
nextTick time.Time
decayFn connmgr.DecayFn
bumpFn connmgr.BumpFn
// closed marks this tag as closed, so that if it's bumped after being
// closed, we can return an error.
closed atomic.Bool
}
var _ connmgr.DecayingTag = (*decayingTag)(nil)
func (t *decayingTag) Name() string {
return t.name
}
func (t *decayingTag) Interval() time.Duration {
return t.interval
}
// Bump bumps a tag for this peer.
func (t *decayingTag) Bump(p peer.ID, delta int) error {
if t.closed.Load() {
return fmt.Errorf("decaying tag %s had been closed; no further bumps are accepted", t.name)
}
bmp := bumpCmd{peer: p, tag: t, delta: delta}
select {
case t.trkr.bumpTagCh <- bmp:
return nil
default:
return fmt.Errorf(
"unable to bump decaying tag for peer %s, tag %s, delta %d; queue full (len=%d)",
p, t.name, delta, len(t.trkr.bumpTagCh))
}
}
func (t *decayingTag) Remove(p peer.ID) error {
if t.closed.Load() {
return fmt.Errorf("decaying tag %s had been closed; no further removals are accepted", t.name)
}
rm := removeCmd{peer: p, tag: t}
select {
case t.trkr.removeTagCh <- rm:
return nil
default:
return fmt.Errorf(
"unable to remove decaying tag for peer %s, tag %s; queue full (len=%d)",
p, t.name, len(t.trkr.removeTagCh))
}
}
func (t *decayingTag) Close() error {
if !t.closed.CompareAndSwap(false, true) {
log.Warn("duplicate decaying tag closure; skipping", "tag", t.name)
return nil
}
select {
case t.trkr.closeTagCh <- t:
return nil
default:
return fmt.Errorf("unable to close decaying tag %s; queue full (len=%d)", t.name, len(t.trkr.closeTagCh))
}
}
| 412 | 0.972112 | 1 | 0.972112 | game-dev | MEDIA | 0.814087 | game-dev | 0.960496 | 1 | 0.960496 |
Herschel/Swivel | 4,585 | huey/src/com/huey/ui/Component.hx | /*
* Swivel
* Copyright (C) 2012-2017, Newgrounds.com, Inc.
* https://github.com/Herschel/Swivel
*
* Swivel 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.
*
* Swivel 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 Swivel. If not, see <http://www.gnu.org/licenses/>.
*/
package com.huey.ui;
import com.huey.events.Dispatcher;
import com.huey.binding.Binding;
@:autoBuild(com.huey.macros.Macros.build())
interface UIBase {
}
class Component extends Binding.Bindable implements UIBase {
public var parent(default, null) : Container;
public var root(get_root, null) : Container;
private function get_root() {
var c = this;
while (c.parent != null) c = c.parent;
return c.root;
}
@bindable public var enabled(default, set_enabled) : Bool;
private function set_enabled(v) {
if (Std.is(_implComponent, flash.display.InteractiveObject)) {
untyped _implComponent.mouseEnabled = v;
untyped _implComponent.tabEnabled = v;
untyped _implComponent.mouseChildren = v;
}
_implComponent.alpha = if (v) 1.0 else 0.5;
return enabled = v;
}
@forward(_implComponent) public var visible : Bool;
@forward(_implComponent) public var x : Float;
@forward(_implComponent) public var y : Float;
@forward(_implComponent) public var alpha : Float;
public var depth(default, set_depth) : Float;
private function set_depth(v) {
depth = v;
//if(parent != null) parent.needDepthSort();
return depth;
}
public var hitArea(default, set_hitArea) : HitArea;
public function set_hitArea(v) {
hitArea = v;
if(Std.is(_implComponent, flash.display.Sprite))
{
untyped { _implComponent.graphics.clear(); }
switch(hitArea) {
case Self:
untyped{ _implComponent.hitArea = null; }
case Rectangle(x, y, width, height):
untyped {
_implComponent.graphics.beginFill(0, 0);
_implComponent.graphics.drawRect(x, y, width, height);
_implComponent.graphics.endFill();
}
}
}
return hitArea;
}
public var width(get_width, set_width) : Float;
private function get_width() return _implComponent.width;
private function set_width(v) return _implComponent.width = v;
public var height(get_height, set_height) : Float;
private function get_height() return _implComponent.height;
private function set_height(v) return _implComponent.height = v;
// ===== EVENTS =====
public var onClick : Dispatcher<UIEvent>;
public var onMouseOver : Dispatcher<UIEvent>;
public var onMouseOut : Dispatcher<UIEvent>;
public var onMouseDown(default, null) : Dispatcher<UIEvent>;
public var onMouseUp(default, null) : Dispatcher<UIEvent>;
public function new(implComponent : flash.display.DisplayObject) {
super();
_implComponent = implComponent;
visible = true;
x = 0.0;
y = 0.0;
depth = 0.0;
hitArea = Self;
onClick = new Dispatcher();
_implComponent.addEventListener(flash.events.MouseEvent.CLICK, function(_) onClick.dispatch( { source: this } ) );
onMouseOver = new Dispatcher();
_implComponent.addEventListener(flash.events.MouseEvent.ROLL_OVER, function(e) {
onMouseOver.dispatch( { source: this } );
e.updateAfterEvent();
} );
onMouseOut = new Dispatcher();
_implComponent.addEventListener(flash.events.MouseEvent.ROLL_OUT, function(e) {
onMouseOut.dispatch( { source: this } );
e.updateAfterEvent();
} );
onMouseDown = new Dispatcher();
_implComponent.addEventListener(flash.events.MouseEvent.MOUSE_DOWN, mouseDownInternalHandler );
onMouseUp = new Dispatcher();
}
private var _implComponent : flash.display.DisplayObject;
private function mouseDownInternalHandler(e) {
flash.Lib.current.stage.addEventListener(flash.events.MouseEvent.MOUSE_UP, mouseUpInternalHandler, false, 0, true);
onMouseDown.dispatch({source: this});
// e.updateAfterEvent();
}
private function mouseUpInternalHandler(e) {
flash.Lib.current.stage.removeEventListener(flash.events.MouseEvent.MOUSE_UP, mouseUpInternalHandler);
onMouseUp.dispatch({source: this});
//e.updateAfterEvent();
}
}
enum HitArea {
Self;
Rectangle(x : Float, y : Float, width : Float, height : Float);
} | 412 | 0.771976 | 1 | 0.771976 | game-dev | MEDIA | 0.495586 | game-dev | 0.965605 | 1 | 0.965605 |
ddiakopoulos/polymer | 4,266 | third_party/bullet3/src/BulletCollision/Gimpact/btContactProcessing.cpp |
/*
This source file is part of GIMPACT Library.
For the latest info, see http://gimpact.sourceforge.net/
Copyright (c) 2007 Francisco Leon Najera. C.C. 80087371.
email: projectileman@yahoo.com
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 "btContactProcessing.h"
#define MAX_COINCIDENT 8
struct CONTACT_KEY_TOKEN
{
unsigned int m_key;
int m_value;
CONTACT_KEY_TOKEN()
{
}
CONTACT_KEY_TOKEN(unsigned int key,int token)
{
m_key = key;
m_value = token;
}
CONTACT_KEY_TOKEN(const CONTACT_KEY_TOKEN& rtoken)
{
m_key = rtoken.m_key;
m_value = rtoken.m_value;
}
inline bool operator <(const CONTACT_KEY_TOKEN& other) const
{
return (m_key < other.m_key);
}
inline bool operator >(const CONTACT_KEY_TOKEN& other) const
{
return (m_key > other.m_key);
}
};
class CONTACT_KEY_TOKEN_COMP
{
public:
bool operator() ( const CONTACT_KEY_TOKEN& a, const CONTACT_KEY_TOKEN& b ) const
{
return ( a < b );
}
};
void btContactArray::merge_contacts(
const btContactArray & contacts, bool normal_contact_average)
{
clear();
int i;
if(contacts.size()==0) return;
if(contacts.size()==1)
{
push_back(contacts[0]);
return;
}
btAlignedObjectArray<CONTACT_KEY_TOKEN> keycontacts;
keycontacts.reserve(contacts.size());
//fill key contacts
for ( i = 0;i<contacts.size() ;i++ )
{
keycontacts.push_back(CONTACT_KEY_TOKEN(contacts[i].calc_key_contact(),i));
}
//sort keys
keycontacts.quickSort(CONTACT_KEY_TOKEN_COMP());
// Merge contacts
int coincident_count=0;
btVector3 coincident_normals[MAX_COINCIDENT];
unsigned int last_key = keycontacts[0].m_key;
unsigned int key = 0;
push_back(contacts[keycontacts[0].m_value]);
GIM_CONTACT * pcontact = &(*this)[0];
for( i=1;i<keycontacts.size();i++)
{
key = keycontacts[i].m_key;
const GIM_CONTACT * scontact = &contacts[keycontacts[i].m_value];
if(last_key == key)//same points
{
//merge contact
if(pcontact->m_depth - CONTACT_DIFF_EPSILON > scontact->m_depth)//)
{
*pcontact = *scontact;
coincident_count = 0;
}
else if(normal_contact_average)
{
if(btFabs(pcontact->m_depth - scontact->m_depth)<CONTACT_DIFF_EPSILON)
{
if(coincident_count<MAX_COINCIDENT)
{
coincident_normals[coincident_count] = scontact->m_normal;
coincident_count++;
}
}
}
}
else
{//add new contact
if(normal_contact_average && coincident_count>0)
{
pcontact->interpolate_normals(coincident_normals,coincident_count);
coincident_count = 0;
}
push_back(*scontact);
pcontact = &(*this)[this->size()-1];
}
last_key = key;
}
}
void btContactArray::merge_contacts_unique(const btContactArray & contacts)
{
clear();
if(contacts.size()==0) return;
if(contacts.size()==1)
{
push_back(contacts[0]);
return;
}
GIM_CONTACT average_contact = contacts[0];
for (int i=1;i<contacts.size() ;i++ )
{
average_contact.m_point += contacts[i].m_point;
average_contact.m_normal += contacts[i].m_normal * contacts[i].m_depth;
}
//divide
btScalar divide_average = 1.0f/((btScalar)contacts.size());
average_contact.m_point *= divide_average;
average_contact.m_normal *= divide_average;
average_contact.m_depth = average_contact.m_normal.length();
average_contact.m_normal /= average_contact.m_depth;
}
| 412 | 0.914758 | 1 | 0.914758 | game-dev | MEDIA | 0.653172 | game-dev,testing-qa | 0.943178 | 1 | 0.943178 |
PetterS/monolith | 1,142 | minimum/nonlinear/data/coconut/global/ex8_5_3.mod | # NLP written by GAMS Convert at 07/05/02 23:00:40
#
# Equation counts
# Total E G L N X C
# 7 5 2 0 0 0 0
#
# Variable counts
# x b i s1s s2s sc si
# Total cont binary integer sos1 sos2 scont sint
# 6 6 0 0 0 0 0 0
# FX 0 0 0 0 0 0 0 0
#
# Nonzero counts
# Total const NL DLL
# 20 10 10 0
#
# Reformualtion has removed 1 variable and 1 equation
var x2 := 0.5, >= 0;
var x3 := 0.5, >= 0;
var x4 := 2, >= 0;
var x5;
var x6 := 1, >= 0;
minimize obj: x2*log(x2) + x3*log(x3) - log(x4 - x6) + x4 - x5*log(1 + x6/x4)/
x6 + 5.0464317551216*x2 + 0.366877055769689*x3 - 1;
subject to
e2: x4^3 - x4^2 + (-x6^2 - x6 + x5)*x4 - x5*x6 = 0;
e3: - (1.04633*x2*x2 + 0.579822*x2*x3 + 0.579822*x3*x2 + 0.379615*x3*x3) + x5
= 0;
e4: - 0.0771517*x2 - 0.0765784*x3 + x6 = 0;
e5: x2 + x3 = 1;
e6: x4 - x6 >= 0;
e7: x2 >= 0.05;
| 412 | 0.651674 | 1 | 0.651674 | game-dev | MEDIA | 0.752555 | game-dev | 0.775893 | 1 | 0.775893 |
HoraceHuang-ui/MiHOYO-MiXED-Launcher | 39,121 | src/pages/ZZZPage/Components/ZZZInfoCard.vue | <script setup lang="ts">
import {
computed,
defineModel,
inject,
onBeforeUnmount,
onMounted,
PropType,
Ref,
ref,
} from 'vue'
import { translate } from '../../../i18n'
import { useDialog } from '../../../utils/template-dialog'
import MyTag from '../../../components/MyTag.vue'
import ScrollWrapper from '../../../components/ScrollWrapper.vue'
import MyCarousel from '../../../components/MyCarousel.vue'
import CustomUIDInput from '../../../components/CustomUIDInput.vue'
import { useStore } from '../../../store'
import TextScroll from '../../../components/TextScroll.vue'
import StatIcon from '../../../components/StatIcon.vue'
import ZZZCharDetailsDialog from './ZZZCharDetailsDialog.vue'
import MyTooltip from '../../../components/MyTooltip.vue'
import GamepadIcon from '../../../components/GamepadIcon.vue' // import rankMap from '../textMaps/character_ranks.json' with { type: 'json' }
// import rankMap from '../textMaps/character_ranks.json' with { type: 'json' }
const gamepadMode = defineModel({
type: String as PropType<
| 'main'
| 'settings'
| 'window-action'
| 'gs-player'
| 'sr-player'
| 'zzz-player'
| 'dialog'
| 'accounts'
| 'out'
>,
required: false,
})
const store = useStore()
const playerInfo = ref(store.game.zzz.playerInfo)
const playerInfoLoading = ref(false)
const playerInfoFailed = ref(false)
const uidInput = ref('')
const uidInputDom = ref()
let uid = ''
const charsPage = ref(0)
const pages = computed(() =>
playerInfo.value &&
playerInfo.value.ShowcaseAgents &&
playerInfo.value.ShowcaseAgents.length > 10
? Math.floor((playerInfo.value.ShowcaseAgents.length - 10) / 6 - 0.1) + 1
: 0,
)
const hScale = inject<Ref<number>>('hScale')
const vScale = inject<Ref<number>>('vScale')
const gpType = inject<Ref<string>>('gpType')
const charsScrollbar = ref()
const cardsCarouselRef = ref()
const showcaseIdx = ref(0)
const relicIdx = ref(0)
const initReady = ref(false)
const headerMode = ref(playerInfo.value ? 0 : 1) // 0: Player info, 1: UID Input
const finalStatsOrder = [
'HpMax',
'Atk',
'Def',
'Crit',
'CritDmg',
'BreakStun',
'ElementAbnormalPower',
'ElementMystery',
]
const rAF = window.requestAnimationFrame
let rAFId: number | null = null
let inThrottle = false
const gameLoop = () => {
const gamepads = navigator.getGamepads()
let gp: Gamepad | null = null
for (let i = 0; i < gamepads.length; i++) {
if (gamepads[i]) {
gp = gamepads[i]
break
}
}
if (!gp) {
return
}
if (!document.hasFocus()) {
rAF(gameLoop)
return
}
// A: Request user info
if (gamepadMode.value === 'zzz-player' && gp.buttons[0].pressed) {
if (!inThrottle) {
inThrottle = true
if (headerMode.value == 1) requestInfo()
setTimeout(() => {
inThrottle = false
}, 300)
}
}
// Y: Focus on CustomUIDInput's input
if (gamepadMode.value === 'zzz-player' && gp.buttons[3].pressed) {
if (!inThrottle) {
inThrottle = true
if (playerInfo.value) headerMode.value = (headerMode.value + 1) % 2
setTimeout(() => {
uidInputDom.value?.focusInput()
}, 500)
setTimeout(() => {
inThrottle = false
}, 300)
}
}
// X: Open details dialog
if (
gamepadMode.value === 'zzz-player' &&
gp.buttons[2].pressed &&
playerInfo.value
) {
if (!inThrottle) {
inThrottle = true
showCharDetails(showcaseIdx.value)
setTimeout(() => {
inThrottle = false
}, 300)
}
}
// LS Horizontal: Select character
if (
gamepadMode.value === 'zzz-player' &&
gp.axes[0] < -0.9 &&
playerInfo.value
) {
if (!inThrottle) {
inThrottle = true
if (showcaseIdx.value > 0) {
setShowcase(showcaseIdx.value - 1)
}
setTimeout(() => {
inThrottle = false
}, 150)
}
}
if (
gamepadMode.value === 'zzz-player' &&
gp.axes[0] > 0.9 &&
playerInfo.value
) {
if (!inThrottle) {
inThrottle = true
if (showcaseIdx.value < playerInfo.value.ShowcaseAgents.length - 1) {
setShowcase(showcaseIdx.value + 1)
}
setTimeout(() => {
inThrottle = false
}, 150)
}
}
// RS Horizontal: Select Relics
if (
gamepadMode.value === 'zzz-player' &&
gp.axes[2] < -0.9 &&
playerInfo.value
) {
if (!inThrottle) {
inThrottle = true
if (relicIdx.value == 0) {
relicIdx.value =
playerInfo.value.ShowcaseAgents[showcaseIdx.value].EquippedDiscs
.length - 1
} else {
relicIdx.value--
}
setTimeout(() => {
inThrottle = false
}, 150)
}
}
if (
gamepadMode.value === 'zzz-player' &&
gp.axes[2] > 0.9 &&
playerInfo.value
) {
if (!inThrottle) {
inThrottle = true
if (
relicIdx.value ==
playerInfo.value.ShowcaseAgents[showcaseIdx.value].EquippedDiscs
.length -
1
) {
relicIdx.value = 0
} else {
relicIdx.value++
}
setTimeout(() => {
inThrottle = false
}, 150)
}
}
if (rAFId) {
rAFId = rAF(gameLoop)
}
}
onMounted(() => {
if (playerInfo.value) {
uid = playerInfo.value.Uid
uidInput.value = uid
} else if (gamepadMode.value) {
uidInputDom.value?.focusInput()
}
initReady.value = true
if (gamepadMode.value) {
rAFId = rAF(gameLoop)
}
})
const mergeToPlayerinfo = (newArr: any[]) => {
if (!playerInfo.value) {
return
}
for (let i = newArr.length - 1; i >= 0; i--) {
let newChar = newArr[i]
let exists = false
// for (let j = playerInfo.value.ShowcaseAgents.length - 1; j >= 0; j--) {
for (let j = 0; j < playerInfo.value.ShowcaseAgents.length; j++) {
let oldChar = playerInfo.value.ShowcaseAgents[j]
if (oldChar.Id == newChar.Id) {
playerInfo.value.ShowcaseAgents[j] = newChar
exists = true
break
}
}
if (!exists) {
playerInfo.value.ShowcaseAgents.push(newChar)
}
}
}
onBeforeUnmount(() => {
rAFId = null
})
const requestInfo = () => {
uid = uidInput.value
playerInfoFailed.value = false
window.axios
.post('http://1.92.84.11:5004/Enka', {
// .post('http://0.0.0.0:5004/Enka', {
game: 2,
lang: translate('zzz_enkaLangCode'),
uid,
})
.then(resp => {
console.log(resp)
if (playerInfo.value && playerInfo.value.Uid == resp.playerInfo.Uid) {
console.log('uid equal')
const { ShowcaseAgents, ...rest } = resp.playerInfo
mergeToPlayerinfo(ShowcaseAgents)
for (const key in rest) {
playerInfo.value[key] = rest[key]
}
} else {
console.log('uid not equal')
playerInfo.value = resp.playerInfo
}
if (!playerInfo.value) {
playerInfoLoading.value = false
return
}
playerInfo.value.ShowcaseAgents.sort(function (a: any, b: any) {
// 等级
if (a.Level < b.Level) {
return 1
} else if (a.Level > b.Level) {
return -1
} else {
// 突破等级
if (a.PromotionLevel < b.PromotionLevel) {
return 1
} else if (a.PromotionLevel > b.PromotionLevel) {
return -1
} else {
// 行迹总等级
if (totalSkillLvs(a) < totalSkillLvs(b)) {
return 1
} else {
return -1
}
}
}
})
store.game.zzz.playerInfo = playerInfo.value
playerInfoLoading.value = false
headerMode.value = 0
})
.catch(err => {
console.error(err)
playerInfoLoading.value = false
playerInfoFailed.value = true
})
playerInfoLoading.value = true
console.log(uid)
}
const totalSkillLvs = (c: any) => {
let res = 0
for (const skill in c.SkillLevels) {
res += c.SkillLevels[skill]
}
return res
}
const setShowcase = (index: number) => {
relicIdx.value = 0
charsPage.value = Math.floor(index / 10)
charsScrollbar.value.scrollTo({
left: charsPage.value * 48 * 6,
top: 0,
behavior: 'smooth',
})
cardsCarouselRef.value?.setPane?.(index)
showcaseIdx.value = index
}
const charsPageNext = () => {
if (charsPage.value < pages.value) {
charsPage.value++
charsScrollbar.value.scrollTo({
// about 48 for each icon, 8 icons on each page
left: charsPage.value * 48 * 6,
top: 0,
behavior: 'smooth',
})
}
}
const charsPagePrev = () => {
if (charsPage.value > 0) {
charsPage.value--
charsScrollbar.value.scrollTo({
left: charsPage.value * 48 * 6,
top: 0,
behavior: 'smooth',
})
}
}
const showCharDetails = (index: number) => {
if (gamepadMode.value) {
gamepadMode.value = 'dialog'
rAFId = null
}
if (!playerInfo.value) {
return
}
useDialog(
ZZZCharDetailsDialog,
{
onCancel: gamepadMode.value
? (dispose: () => void) => {
gamepadMode.value = 'zzz-player'
rAFId = rAF(gameLoop)
dispose()
}
: undefined,
},
{
title:
playerInfo.value.ShowcaseAgents[index].Name +
' ' +
translate('sr_charDetails'),
character: playerInfo.value.ShowcaseAgents[index],
showOk: false,
hScale: hScale,
vScale: vScale,
gamepadMode: !!gamepadMode.value,
gpType: gpType?.value,
},
)
}
</script>
<template>
<div
class="bg-white dark:bg-[#222] mb-3 transition-all"
:class="{ loading: !initReady }"
style="border-radius: 4.5vh 4.5vh 30px 30px"
>
<!-- HEADER -->
<MyCarousel
class="relative w-full h-[9vh] rounded-[4.5vh]"
:autoplay="false"
show-arrow="never"
show-indicator="never"
v-model="headerMode"
>
<div
class="flex flex-row w-full relative justify-between z-50"
style="height: 9vh"
>
<img
v-if="playerInfo"
:src="playerInfo.NameCardIcon"
class="namecard-mask h-[9vh] object-cover absolute top-0 left-1/2 -translate-x-1/2 z-0"
/>
<!-- 左上角头像、昵称 -->
<div
v-if="playerInfo"
class="flex flex-row content-start items-center"
style="width: 35vw"
>
<img
class="rounded-full bg-slate-200 pointer-events-none"
:style="`height: 6vh; margin-left: 1.5vh`"
:src="playerInfo.ProfilePictureIcon"
/>
<div class="font-zzz-bold ml-[1.5vh]">
<div
class="text-left"
:style="`font-size: calc(max(16px * min(${hScale}, ${vScale}), 20px))`"
>
{{ playerInfo.Nickname }}
</div>
<div class="flex flex-row">
<div
class="opacity-60 mt-[-0.5vh]"
:style="`font-size: calc(max(16px * min(${hScale}, ${vScale}), 12px))`"
>
{{ playerInfo.TitleText }}
</div>
<MyTooltip
placement="right"
max-width="400px"
middle
v-for="medal in playerInfo.Medals"
:key="medal.Type"
>
<template #content>
<div class="font-zzz-bold">
<span style="font-family: sans-serif"
>{{ medal.Name }}
</span>
<span> · {{ medal.Value }}</span>
</div>
</template>
<img
:src="medal.Icon"
class="ml-[1vh]"
:style="`height: calc(max(16px * min(${hScale}, ${vScale}), 12px))`"
/>
</MyTooltip>
</div>
</div>
</div>
<div v-else style="width: 35vw" />
<!-- 右侧 WL AR -->
<div v-if="playerInfo" style="width: 35vw; position: relative">
<div
class="h-full flex flex-row justify-end items-center"
:style="`font-size: calc(16px * min(${hScale}, ${vScale}))`"
>
<MyTag class="mr-4">
<div class="flex flex-row font-zzz-bold">
{{ $t('zzz_playerLv') }}
<span style="margin-left: 1ch">
{{ playerInfo.Level }}
</span>
</div>
</MyTag>
<div
class="mr-4 rounded-full bg-[#66666611] hover:bg-[#66666633] dark:bg-[#ffffff22] dark:hover:bg-[#ffffff55] px-[1vw] py-[1vh] transition-all flex flex-row"
@click="headerMode = 1"
>
<GamepadIcon
icon="Y"
v-if="gamepadMode"
class="inline-block mr-2"
:style="`height: calc(20px * min(${hScale}, ${vScale}));
margin-top: calc(2px * min(${hScale}, ${vScale}))`"
/>
<i class="bi bi-arrow-left-right" />
</div>
</div>
</div>
</div>
<div
class="flex flex-row w-full relative justify-between z-50"
style="height: 9vh"
>
<!-- 右上角加载提示 / 报错提示 -->
<div
v-if="playerInfoLoading"
class="absolute top-0 right-0 bottom-0 z-0"
style="margin-left: 1vw; right: 2vw; top: 3vh"
:style="`font-size: calc(max(14px * min(${hScale}, ${vScale}), 16px))`"
>
{{ $t('sr_loadingPlayerInfo') }}
</div>
<div
v-if="playerInfoFailed"
class="absolute bottom-0 z-0 text-red-500"
style="margin-left: 1vw; right: 2vw; top: 3vh"
:style="`font-size: calc(max(14px * min(${hScale}, ${vScale}), 16px))`"
>
{{ $t('sr_playerInfoFailed') }}
</div>
<div class="w-[35vw]">
<div
v-if="playerInfo"
class="ml-4 mt-[2vh] w-fit px-[1vw] py-[1vh] rounded-full bg-[#66666611] hover:bg-[#66666633] dark:bg-[#ffffff22] dark:hover:bg-[#ffffff55] transition-all flex flex-row"
@click="headerMode = 0"
:style="`font-size: calc(16px * min(${hScale}, ${vScale}))`"
>
<GamepadIcon
icon="Y"
v-if="gamepadMode"
class="inline-block mr-2"
:style="`height: calc(20px * min(${hScale}, ${vScale}));
margin-top: calc(2px * min(${hScale}, ${vScale}))`"
/>
<i class="bi bi-arrow-left" />
</div>
</div>
<div class="flex flex-row">
<GamepadIcon
icon="Y"
v-if="gamepadMode && !playerInfo"
class="mt-[2.5vh] mb-[2vh] mb-[1.5vh] mr-2"
/>
<CustomUIDInput
ref="uidInputDom"
v-model="uidInput"
@submit="requestInfo"
:gamepad-mode="!!gamepadMode"
style="margin-top: 2vh; margin-bottom: 1.5vh; z-index: 10"
:style="`font-size: calc(max(14px * min(${hScale}, ${vScale}), 16px))`"
/>
</div>
<div style="width: 35vw" />
</div>
</MyCarousel>
<!-- BODY -->
<div
v-if="playerInfo && playerInfo.ShowcaseAgents.length > 0"
class="relative mt-4"
>
<!-- 角色头像列表 10人一页 -->
<div class="flex flex-row w-full justify-center absolute z-10 top-0">
<div
class="flex flex-row justify-between"
style="width: 690px; transform-origin: center top"
:style="`transform: scale(${gamepadMode ? `min(${hScale}, ${vScale})` : hScale})`"
>
<div class="relative z-50" style="width: 15%">
<div
class="absolute right-2 top-3 rounded-full w-9 h-9 pt-1 bg-white hover:bg-gray-200 active:-translate-x-1 transition-all bg-opacity-80 dark:bg-black dark:hover:bg-gray-700 dark:bg-opacity-80"
@click="charsPagePrev"
:class="charsPage == 0 ? 'disabled' : ''"
>
<i class="bi bi-chevron-left text-lg text-center" />
</div>
</div>
<ScrollWrapper
ref="charsScrollbar"
no-resize
show-bar="never"
width="auto"
style="max-width: 70%"
>
<div class="flex flex-row flex-nowrap w-max">
<div
v-for="(character, index) in playerInfo.ShowcaseAgents"
:key="character.id"
class="relative w-12 h-12 z-50"
@click="setShowcase(index)"
>
<div
class="absolute bottom-0 w-9 h-9 rounded-full transition-all"
:class="{
'bg-green-500 dark:bg-yellow-300': showcaseIdx == index,
}"
style="left: 10px"
></div>
<img
class="absolute left-[2px] bottom-[2px] char-side-icon rounded-full ml-[10px] w-8 h-8 hover:transform hover:scale-110 active:scale-100 transition-all object-cover"
:src="character.CircleIconUrl"
/>
</div>
</div>
</ScrollWrapper>
<div class="relative z-50" style="width: 15%">
<div
class="absolute left-2 top-3 rounded-full w-9 h-9 pt-1 bg-white hover:bg-gray-200 active:translate-x-1 transition-all bg-opacity-80 dark:bg-black dark:hover:bg-gray-700 dark:bg-opacity-80"
@click="charsPageNext"
:class="charsPage == pages ? 'disabled' : ''"
>
<i class="bi bi-chevron-right text-lg text-center" />
</div>
</div>
</div>
</div>
<!-- 角色详情卡片 -->
<div
:style="`height: calc(604px * ${gamepadMode ? `calc(min(${hScale}, ${vScale}) / 616 * 556)` : hScale})`"
/>
<MyCarousel
ref="cardsCarouselRef"
class="absolute left-0"
:autoplay="false"
show-arrow="never"
animation="fade-swipe"
style="
width: 984px;
height: 545px;
transform-origin: left top;
background: #191919;
"
:style="`transform: scale(${gamepadMode ? `calc(min(${hScale}, ${vScale}) / 616 * 556)` : hScale});
border-radius: calc(30px / ${gamepadMode ? `calc(min(${hScale}, ${vScale}) / 616 * 556)` : hScale});
top: calc(64px * ${gamepadMode ? `calc(min(${hScale}, ${vScale}) / 616 * 556)` : hScale})`"
>
<div
v-for="(character, index) in playerInfo.ShowcaseAgents"
:key="character.id"
class="relative w-full"
>
<div
class="w-full absolute top-0 left-0 right-0 transition-all"
style="transition-duration: 300ms; color: #e0e0e0"
:style="`border-radius: calc(30px / ${gamepadMode ? `calc(min(${hScale}, ${vScale}) / 616 * 556)` : hScale})`"
>
<!-- absolute 卡片背景及前景遮罩 -->
<img
class="w-full"
src="../../../assets/zzzCard/bgTexture.png"
:style="`border-radius: calc(30px / ${gamepadMode ? `min(${hScale}, ${vScale})` : hScale}`"
/>
<img
class="absolute z-20 h-full top-0 left-0 pointer-events-none"
src="../../../assets/zzzCard/frame.png"
/>
<svg
class="absolute left-2 top-0 z-[5] h-full rounded-3xl"
viewBox="0 0 822 1250"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M0.0739935 27C0.0739812 12.0883 12.1623 8.30483e-05 27.074 7.65174e-05L794.901 6.90344e-05C812.315 5.89158e-05 825.175 16.2407 821.182 33.1903L539.475 1229.18C536.603 1241.37 525.722 1249.99 513.195 1249.99L27.0739 1249.99C12.1623 1249.99 0.0738917 1237.9 0.0739172 1222.99L0.0739935 27Z"
:fill="character.Colors[0].Accent"
fill-opacity="0.35"
/>
</svg>
<img
src="../../../assets/zzzCard/statsMask.png"
class="h-[99%] absolute top-[1%] left-[300px] z-[7]"
/>
<img
src="../../../assets/zzzCard/fullnameMask.png"
class="h-[99%] absolute top-[1%] left-[246px] z-[8]"
/>
<!-- 立绘 -->
<img
class="absolute z-[6] h-full"
:src="character.ImageUrl"
:style="`left: ${character.Transform.Left}px; top: ${character.Transform.Top}px; transform: scale(${character.Transform.Scale})`"
/>
<!-- 左上人名、属性、命途 -->
<div
class="font-zzz-bold absolute left-4 top-5 z-20 text-3xl text-white justify-between flex flex-row"
style="width: 334px"
>
<div>
{{ character.Name }}
</div>
<div
class="rounded-full bg-gray-900 flex flex-row h-7 mt-1.5 px-1"
>
<StatIcon
class="w-5 h-5 my-1 mx-0.5"
fill="#fff"
:stat="character.Element"
game="zzz"
/>
<img
:src="character.ProfessionIcon"
class="w-5 h-5 my-1 mx-0.5"
/>
</div>
</div>
<!-- 中间斜着lv、全名 -->
<TextScroll
:content="`${character.FullNameEn} `"
container-width="1000px"
font-family="zzz-font, sans-serif"
:text-style="{ color: character.Colors[0].Accent }"
font-size="50px"
container-height="70px"
:duration="15"
:container-style="{
position: 'absolute',
left: '-224px',
bottom: '10px',
'z-index': 8,
transform: 'rotate(-77deg)',
opacity: 0.35,
}"
/>
<div
class="absolute left-[235px] bottom-[70px] text-white z-[50] font-zzz-bold text-xl"
style="transform: rotate(-77deg)"
>
Lv. {{ character.Level }}
<span class="text-white opacity-50"
>/ {{ character.PromotionLevel * 10 }}</span
>
</div>
<!-- 右上命座 -->
<div
class="absolute right-[155px] top-[18px] z-10 flex flex-row h-11 w-[400px] skew-x-[-14deg] z-30"
>
<div
v-for="idx in 6"
:key="idx"
class="flex flex-row"
:class="{
'mr-[6px]': idx == 1,
'ml-[6px]': idx == 6,
'mx-[6px]': idx != 1 && idx != 6,
}"
>
<div
class="w-[22px] h-11"
style="border-radius: 8px 0 0 8px"
:style="
character.TalentLevel >= idx
? {
background: character.Colors[0].Mindscape,
border: `2px solid ${character.Colors[0].Mindscape}`,
}
: {
background: '#626262',
border: `2px solid #626262`,
}
"
></div>
<div
class="w-[55px] h-11 bg-[#191919] font-zzz-bold text-3xl pt-[1px]"
style="border-radius: 0 8px 8px 0"
:style="
character.TalentLevel >= idx
? {
color: '#dfdfdf',
border: `2px solid ${character.Colors[0].Mindscape}`,
}
: {
color: '#666',
border: `2px solid #626262`,
}
"
>
<div style="transform: skewX(14deg)">0{{ idx }}</div>
</div>
</div>
</div>
<!-- 右侧 -->
<div
class="absolute right-[102px] top-[62px] z-10 w-[520px] h-[476px] skew-x-[-14deg]"
>
<!-- 属性表 -->
<div
class="grid grid-cols-3 h-[118px] gap-x-12 z-50 font-zzz-bold px-6 pt-2 pb-2.5 mt-3"
>
<div
v-for="stat in finalStatsOrder"
:key="stat"
class="w-full flex flex-row justify-between pt-0.5"
>
<StatIcon
class="w-5 h-5 mt-0.5 skew-x-[14deg]"
fill="#e0e0e0"
:stat="stat"
game="zzz"
/>
<!-- <div style="font-size: 10px">{{ stat }}</div>-->
<div style="font-size: 18px; transform: skewX(14deg)">
{{ character.FinalStats[stat].statValue.final }}
</div>
</div>
<div
class="bg-white bg-opacity-10 hover:bg-opacity-25 active:bg-opacity-50 active:scale-90 text-[#e0e0e0] rounded my-0.5 text-sm pt-1 transition-all flex flex-row justify-center"
@click="showCharDetails(index)"
>
<GamepadIcon
icon="X"
v-if="gamepadMode"
class="h-[20px] mt-[1px] bg-gray-900 rounded-full mr-2 skew-x-[14deg]"
/>
<div class="mt-[1px]">{{ $t('sr_details') }}</div>
</div>
</div>
<div
class="w-[1px] h-[100px] opacity-50 absolute z-50 top-[18px] right-[344px]"
:style="{ background: character.Colors[0].Accent }"
/>
<div
class="w-[1px] h-[100px] opacity-50 absolute z-50 top-[18px] right-[175px]"
:style="{ background: character.Colors[0].Accent }"
/>
<!-- 武器 -->
<div
v-if="!character.Weapon"
class="w-full skew-x-[14deg] mt-3 text-center h-[88px] pt-9 font-zzz-bold opacity-75"
>
{{ $t('zzz_noWeapon') }}
</div>
<div class="w-full mt-3 flex flex-row relative h-[88px]" v-else>
<div class="w-20 h-[88px] ml-5 mt-2 relative skew-x-[14deg]">
<img class="w-20 h-20" :src="character.Weapon.ImageUrl" />
<img
class="absolute bottom-0 right-0 w-9 h-9 m-[-2px]"
:src="`https://enka.network/ui/zzz/ItemRarity${['C', 'B', 'A', 'S'][character.Weapon.Rarity - 1]}.png`"
/>
</div>
<div
class="grid grid-columns-3 font-zzz-bold skew-x-[14deg] ml-4 w-[320px] gap-x-8 translate-y-2.5"
>
<div
style="grid-column: 1 / 4"
class="truncated text-3xl text-left"
>
{{ character.Weapon.Name }}
</div>
<div
class="w-[100px] flex flex-row justify-between pt-0.5 px-1"
>
<StatIcon
class="w-5 h-5 mt-0.5"
fill="#e0e0e0"
:stat="character.Weapon.FormattedMainStat.Key"
game="zzz"
/>
<div style="font-size: 18px">
{{ character.Weapon.FormattedMainStat.Value }}
</div>
</div>
<div
class="w-[100px] flex flex-row justify-between pt-0.5 px-1"
>
<StatIcon
class="w-5 h-5 mt-0.5"
fill="#e0e0e0"
:stat="character.Weapon.FormattedSecondaryStat.Key"
game="zzz"
/>
<div style="font-size: 18px">
{{ character.Weapon.FormattedSecondaryStat.Value }}
</div>
</div>
</div>
<div
class="absolute right-[-34px] bottom-[8px] rotate-[-89deg]"
>
<div
class="w-full flex flex-row justify-center skew-x-[-14deg]"
>
<img
v-for="idx in 5"
:key="idx"
src="../../../assets/zzzCard/weaponStar.png"
class="mx-[-2px] w-5 h-5"
:class="
5 - character.Weapon.UpgradeLevel < idx
? 'opacity-90'
: 'opacity-25'
"
/>
</div>
<div
class="font-zzz-bold text-black text-center px-3.5 py-2 flex flex-row w-[120px]"
:style="{ background: character.Colors[0].Accent }"
>
<div class="opacity-65 skew-x-[-14deg]">
Lv. {{ character.Weapon.Level }}
</div>
<div class="opacity-35 skew-x-[-14deg]">
/{{ (character.Weapon.BreakLevel + 1) * 10 }}
</div>
</div>
</div>
</div>
<!-- 天赋 -->
<div
class="mt-10 w-full flex flex-row justify-between skew-x-[14deg] pl-4 pr-2"
>
<div v-for="idx in 5" :key="idx" class="flex flex-row w-1/6">
<img
:src="character.SkillInfoList[idx - 1].iconUrl"
class="w-10 h-10"
/>
<div class="font-zzz-bold text-lg ml-1">
<div
class="-translate-y-1"
:style="{
color:
character.SkillInfoList[idx - 1].level ===
character.SkillInfoList[idx - 1].maxLevel
? '#fdba74'
: '#e0e0e0',
}"
>
{{
(character.SkillInfoList[idx - 1].level < 10
? '0'
: '') + character.SkillInfoList[idx - 1].level
}}
</div>
<div class="text-white opacity-40 -translate-y-3">
{{ character.SkillInfoList[idx - 1].maxLevel }}
</div>
</div>
</div>
<div
class="h-full rounded-lg skew-x-[-14deg] -translate-y-0.5"
:style="{
border: `2px solid ${character.CoreSkillEnhancement === 0 ? '#555555' : character.Colors[0].Accent}`,
}"
>
<StatIcon
:fill="
character.CoreSkillEnhancement === 0
? '#555555'
: character.Colors[0].Mindscape
"
:stat="`Core${['A', 'A', 'B', 'C', 'D', 'E', 'F'][character.CoreSkillEnhancement]}`"
game="zzz"
class="w-10 skew-x-[14deg]"
/>
</div>
</div>
<!-- 圣遗物 -->
<div
v-if="character.EquippedDiscs.length == 0"
class="w-full skew-x-[14deg] mt-3 text-center h-[88px] pt-12 font-zzz-bold opacity-75"
>
{{ $t('zzz_noRelic') }}
</div>
<MyCarousel
v-else
v-model="relicIdx"
class="mt-3 h-[130px] relative"
show-arrow="never"
show-indicator="always"
:indicator-bg="false"
:autoplay="false"
>
<div
v-for="(disc, idx) in character.EquippedDiscs"
:key="idx"
class="w-full h-20 flex flex-row py-2 px-1"
>
<div class="ml-5 mt-3 relative h-20">
<svg
class="h-20 skew-x-[14deg] ml-10"
viewBox="0 0 445 220"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M0 40C0 17.9086 17.9086 0 40 0H404.861C431.47 0 450.661 25.4951 443.301 51.0649L403.001 191.065C398.069 208.199 382.391 220 364.562 220H40C17.9086 220 0 202.091 0 180V40Z"
fill="#303030"
/>
</svg>
<div class="w-20 h-20 absolute left-0 top-0 skew-x-[14deg]">
<img :src="disc.IconUrl" class="w-20 h-20" />
<img
class="absolute bottom-0 right-0 w-9 h-9 m-[-2px]"
:src="`https://enka.network/ui/zzz/ItemRarity${['C', 'B', 'A', 'S'][disc.Rarity - 1]}.png`"
/>
</div>
<div
class="absolute right-4 top-1 flex flex-row skew-x-[14deg]"
>
<StatIcon
fill="#e0e0e0"
:stat="disc.FormattedMainStat.Key"
game="zzz"
class="w-4 mr-3 mt-1"
/>
<div class="opacity-85 font-zzz-bold">
Lv. {{ disc.Level }}
</div>
</div>
<div
class="absolute right-4 bottom-1 text-3xl font-zzz-bold"
>
{{ disc.FormattedMainStat.Value }}
</div>
</div>
<div class="grid grid-cols-2 w-full mt-8 h-16 gap-x-10 px-3">
<div
v-for="(substat, idx) in disc.SubStats"
:key="idx"
class="w-full flex flex-row justify-between font-zzz-bold skew-x-[14deg]"
>
<div class="flex flex-row">
<StatIcon
fill="#e0e0e0"
:stat="substat.Key"
game="zzz"
class="w-5"
/>
<div
v-if="disc.SubStatsRaw[idx].Level !== 1"
class="ml-1 text-center font-zzz-bold text-sm opacity-75"
:style="{ color: character.Colors[0].Accent }"
>
+{{ disc.SubStatsRaw[idx].Level - 1 }}
</div>
</div>
<div>
{{ substat.Value }}
</div>
</div>
</div>
<div
class="absolute right-3 top-2 text-white font-zzz-bold opacity-50"
>
{{ disc.SuitName }} [{{ disc.Slot }}]
</div>
<div
class="w-[1px] h-[50px] opacity-50 absolute z-50 top-[42px] right-[147px]"
:style="{ background: character.Colors[0].Accent }"
/>
</div>
</MyCarousel>
</div>
<!-- 右下首次邂逅 -->
<svg
class="absolute z-50 right-3 bottom-3 h-[65%]"
viewBox="0 0 214 927"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M212.5 2C212.5 253.333 212.5 776.7 212.5 859.5C212.5 905 191.5 925 158.5 925C106.5 925 27.5 925 2 925"
:stroke="`url(#decoLine_${character.Id})`"
stroke-width="3"
stroke-linecap="round"
/>
<defs>
<linearGradient
:id="`decoLine_${character.Id}`"
x1="107.25"
y1="2"
x2="107.25"
y2="925"
gradientUnits="userSpaceOnUse"
>
<stop :stop-color="character.Colors[0].Accent + '55'" />
<stop
offset="0.894231"
:stop-color="character.Colors[0].Accent"
/>
</linearGradient>
</defs>
</svg>
<div
class="absolute left-[940px] bottom-[5px] z-50"
style="transform: rotate(-90deg); transform-origin: top left"
:style="`width: calc(616px * ${gamepadMode ? `calc(min(${hScale}, ${vScale}) / 616 * 556)` : hScale})`"
>
<div class="font-zzz-bold text-left" style="color: #a7a7a7">
{{ $t('zzz_firstMet')
}}{{
new Date(character.ObtainmentTimestamp)
.toISOString()
.slice(0, 10)
.replace(/-/g, '-')
}}
</div>
</div>
</div>
</div>
</MyCarousel>
</div>
<div
v-else
class="pt-2 pb-4"
:style="`font-size: calc(max(14px * min(${hScale}, ${vScale}), 16px))`"
>
{{ $t('gs_emptyPlayerTip') }}
</div>
</div>
</template>
<style lang="scss" scoped>
.font-zzz-bold {
font-family: zzz-font, sans-serif;
}
.loading {
@apply translate-y-[300px] opacity-0;
}
.namecard-mask {
-webkit-mask: linear-gradient(
90deg,
transparent 10%,
#ffffff55 25%,
white 45%,
white 55%,
#ffffff55 75%,
transparent 90%
);
}
.char-side-icon {
-webkit-mask: radial-gradient(white 80%, transparent);
}
.gacha-mask {
-webkit-mask: linear-gradient(transparent 1rem, white 3rem);
}
.left-gacha {
-webkit-mask: linear-gradient(270deg, transparent, white 20%);
}
.artifact-mask {
-webkit-mask: linear-gradient(270deg, transparent, white 60%);
}
.disabled {
@apply bg-gray-200 opacity-30 pointer-events-none;
.dark & {
@apply bg-gray-600 opacity-20;
}
}
.truncated {
@apply inline-block max-w-full overflow-ellipsis whitespace-nowrap overflow-hidden;
}
.fade-enter-from {
opacity: 0;
transform: translateY(6px);
}
.fade-leave-to {
opacity: 0;
}
.fade-enter-active {
transition: all 0.3s;
}
.fade-leave-active {
transition: opacity 0.2s;
}
</style>
| 412 | 0.780665 | 1 | 0.780665 | game-dev | MEDIA | 0.951276 | game-dev | 0.947003 | 1 | 0.947003 |
Caverns4/Sonic-2-Retold-PC | 2,570 | Scripts/Enemies/Stegway.gd | extends EnemyBase
const WALK_SPEED = 60 # 1 pixel per frame
const DASH_SPEED = 240 # 4 pixels per frame
const IDLE_TIME = 1.0
const GRAVITY = 600
const DASH_CHARGE_TIME = 0.5 #Time to rev before charaging a player
@onready var animator = $SpriteNode/AnimationPlayer
var revSound = preload("res://Audio/SFX/Player/s2br_SpindashRev.wav")
enum STATES{WALK,IDLE,CHARGE}
var state = 0
var stateTimer = 0
var direction = 1
var dashMem = false
# Physics variables
var ground = false
var movement = Vector2.ZERO
var targets = []
func _ready() -> void:
defaultMovement = false
$VisibleOnScreenEnabler2D.visible = true
$SpriteNode/PlayerCheck.visible = true
$SpriteNode/Flame.visible = false
if direction == 0:
direction = 1
movement.x = direction*WALK_SPEED
super()
func _physics_process(delta: float) -> void:
stateTimer -= delta
# Direction checks
$SpriteNode.scale.x = abs($SpriteNode.scale.x)*-sign(direction)
$FloorCheck.position.x = abs($FloorCheck.position.x)*(direction)
$FloorCheck.force_raycast_update()
match state:
STATES.IDLE:
if stateTimer <= 0.0:
state = STATES.WALK
direction = -direction
position.x += direction
movement.x = direction*WALK_SPEED
animator.play("WALK")
STATES.CHARGE:
if stateTimer <= 0.0 and !dashMem:
movement.x = direction*DASH_SPEED
animator.play("DASH")
dashMem = true
$SpriteNode/Flame.visible = true
EdgeCheck()
_: # Walk
if targets:
var waitTime = DASH_CHARGE_TIME
for i in targets.size():
var node = targets[i]
if (node.get("supTime") != null):
if (node.supTime > 0):
direction = sign(global_position.x - node.global_position.x)
waitTime = DASH_CHARGE_TIME/2.0
#print(direction)
movement.x = 0
stateTimer = waitTime
animator.play("CHARGE")
state = STATES.CHARGE
SoundDriver.play_sound(revSound)
# Edge check
EdgeCheck()
MoveWithGravity(delta)
func EdgeCheck():
# Edge check
if (is_on_wall() or !$FloorCheck.is_colliding()):
stateTimer = IDLE_TIME
state = STATES.IDLE
movement.x = 0
animator.play("RESET")
dashMem = false
$SpriteNode/Flame.visible = false
direction = clamp(direction,-1,1)
func MoveWithGravity(delta):
# Velocity movement
set_velocity(movement)
set_up_direction(Vector2.UP)
move_and_slide()
ground = is_on_floor()
# Gravity
if !is_on_floor():
movement.y += (GRAVITY*delta)
func _on_player_check_body_entered(body: Node2D) -> void:
targets.append(body)
func _on_player_check_body_exited(body: Node2D) -> void:
targets.erase(body)
| 412 | 0.705748 | 1 | 0.705748 | game-dev | MEDIA | 0.963434 | game-dev | 0.973207 | 1 | 0.973207 |
AionGermany/aion-germany | 3,628 | AL-Game-5.8/data/scripts/system/handlers/quest/altgard/_24011FunnyFloatingFungus.java | /**
* This file is part of Aion-Lightning <aion-lightning.org>.
*
* Aion-Lightning 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.
*
* Aion-Lightning 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 Aion-Lightning.
* If not, see <http://www.gnu.org/licenses/>.
*/
package quest.altgard;
import com.aionemu.gameserver.model.gameobjects.Npc;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.questEngine.handlers.QuestHandler;
import com.aionemu.gameserver.questEngine.model.QuestEnv;
import com.aionemu.gameserver.questEngine.model.QuestState;
import com.aionemu.gameserver.questEngine.model.QuestStatus;
/**
* @author aioncool
*/
public class _24011FunnyFloatingFungus extends QuestHandler {
private final static int questId = 24011;
public _24011FunnyFloatingFungus() {
super(questId);
}
@Override
public void register() {
int[] talkNpcs = { 203558, 203572, 203558 };
qe.registerQuestNpc(700092).addOnKillEvent(questId);
qe.registerOnEnterZoneMissionEnd(questId);
qe.registerOnLevelUp(questId);
for (int id : talkNpcs)
qe.registerQuestNpc(id).addOnTalkEvent(questId);
}
@Override
public boolean onKillEvent(QuestEnv env) {
Player player = env.getPlayer();
QuestState qs = player.getQuestStateList().getQuestState(questId);
if (qs == null)
return false;
int var = qs.getQuestVarById(0);
int targetId = 0;
if (env.getVisibleObject() instanceof Npc)
targetId = ((Npc) env.getVisibleObject()).getNpcId();
if (qs.getStatus() != QuestStatus.START)
return false;
if (targetId == 700092) {
if (var >= 2 && var <= 5) {
qs.setQuestVarById(0, qs.getQuestVarById(0) + 1);
updateQuestStatus(env);
return true;
}
else if (var == 6) {
changeQuestStep(env, 6, 6, true); // reward
return true;
}
}
return false;
}
@Override
public boolean onDialogEvent(QuestEnv env) {
final Player player = env.getPlayer();
QuestState qs = player.getQuestStateList().getQuestState(questId);
if (qs == null)
return false;
int var = qs.getQuestVarById(0);
int targetId = 0;
if (env.getVisibleObject() instanceof Npc)
targetId = ((Npc) env.getVisibleObject()).getNpcId();
if (qs.getStatus() == QuestStatus.START) {
if (targetId == 203558) {
switch (env.getDialog()) {
case QUEST_SELECT:
if (var == 0)
return sendQuestDialog(env, 1011);
case SETPRO1:
return defaultCloseDialog(env, 0, 1); // 1
default:
break;
}
}
else if (targetId == 203572) {
switch (env.getDialog()) {
case QUEST_SELECT:
if (var == 1)
return sendQuestDialog(env, 1352);
case SETPRO2:
playQuestMovie(env, 60);
return defaultCloseDialog(env, 1, 2); // 2
default:
break;
}
}
}
else if (qs.getStatus() == QuestStatus.REWARD) {
if (targetId == 203558) {
return sendQuestEndDialog(env);
}
}
return false;
}
@Override
public boolean onZoneMissionEndEvent(QuestEnv env) {
return defaultOnZoneMissionEndEvent(env);
}
@Override
public boolean onLvlUpEvent(QuestEnv env) {
return defaultOnLvlUpEvent(env, 24010, true);
}
}
| 412 | 0.953065 | 1 | 0.953065 | game-dev | MEDIA | 0.97433 | game-dev | 0.982661 | 1 | 0.982661 |
OCA/stock-logistics-warehouse | 2,730 | stock_storage_category_capacity_name/tests/test_capacity_name.py | # Copyright 2023 ACSONE SA/NV
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo.tests.common import TransactionCase
class TestStockStorageCategoryCapacity(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.product = cls.env["product.product"].create(
{
"name": "Product Test",
}
)
def test_storage_capacity_display_package(self):
package_type = self.env["stock.package.type"].create(
{
"name": "Super Pallet",
}
)
stor_category = self.env["stock.storage.category"].create(
{
"name": "Super Storage Category",
"max_weight": 100,
}
)
stor_capacity = self.env["stock.storage.category.capacity"].create(
{
"storage_category_id": stor_category.id,
"package_type_id": package_type.id,
"quantity": 1,
}
)
self.assertEqual(
stor_capacity.display_name,
"Super Storage Category x 1.0 (Package: Super Pallet)",
)
def test_storage_capacity_display_product(self):
stor_category = self.env["stock.storage.category"].create(
{
"name": "Super Storage Category",
"max_weight": 100,
}
)
stor_capacity = self.env["stock.storage.category.capacity"].create(
{
"storage_category_id": stor_category.id,
"product_id": self.product.id,
"quantity": 1,
}
)
self.assertEqual(
stor_capacity.display_name,
"Super Storage Category x 1.0 (Product: Product Test)",
)
def test_storage_capacity_display_both(self):
package_type = self.env["stock.package.type"].create(
{
"name": "Super Pallet",
}
)
stor_category = self.env["stock.storage.category"].create(
{
"name": "Super Storage Category",
"max_weight": 100,
}
)
stor_capacity = self.env["stock.storage.category.capacity"].create(
{
"storage_category_id": stor_category.id,
"product_id": self.product.id,
"package_type_id": package_type.id,
"quantity": 1,
}
)
self.assertEqual(
stor_capacity.display_name,
(
"Super Storage Category x 1.0 "
"(Product: Product Test - Package: Super Pallet)"
),
)
| 412 | 0.678092 | 1 | 0.678092 | game-dev | MEDIA | 0.324879 | game-dev | 0.69463 | 1 | 0.69463 |
ghtalpo/py_amazfit_tools | 1,215 | watchFaceParser/models/elements/common/coordinatesElement.py | import logging
from watchFaceParser.models.elements.basic.compositeElement import CompositeElement
from watchFaceParser.utils.integerConverter import uint2int
class CoordinatesElement(CompositeElement):
def __init__(self, parameter, parent, name = None):
self._x = None
self._y = None
super(CoordinatesElement, self).__init__(parameters = None, parameter = parameter, parent = parent, name = name)
def getX(self):
return self._x
def getY(self):
return self._y
def createChildForParameter(self, parameter):
parameterId = parameter.getId()
if parameterId == 1:
from watchFaceParser.models.elements.basic.valueElement import ValueElement
self._x = uint2int(parameter.getValue())
return ValueElement(parameter = parameter, parent = self, name = '?X?')
elif parameterId == 2:
from watchFaceParser.models.elements.basic.valueElement import ValueElement
self._y = uint2int(parameter.getValue())
return ValueElement(parameter = parameter, parent = self, name = '?Y?')
else:
super(CoordinatesElement, self).createChildForParameter(parameter)
| 412 | 0.615524 | 1 | 0.615524 | game-dev | MEDIA | 0.634062 | game-dev | 0.595664 | 1 | 0.595664 |
OpenTTD/OpenTTD-Deprecated | 8,161 | src/script/script_instance.hpp | /* $Id$ */
/*
* This file is part of OpenTTD.
* OpenTTD 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.
* OpenTTD 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 OpenTTD. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file script_instance.hpp The ScriptInstance tracks a script. */
#ifndef SCRIPT_INSTANCE_HPP
#define SCRIPT_INSTANCE_HPP
#include <squirrel.h>
#include "script_suspend.hpp"
#include "../command_type.h"
#include "../company_type.h"
#include "../fileio_type.h"
static const uint SQUIRREL_MAX_DEPTH = 25; ///< The maximum recursive depth for items stored in the savegame.
/** Runtime information about a script like a pointer to the squirrel vm and the current state. */
class ScriptInstance {
public:
friend class ScriptObject;
friend class ScriptController;
/**
* Create a new script.
*/
ScriptInstance(const char *APIName);
virtual ~ScriptInstance();
/**
* Initialize the script and prepare it for its first run.
* @param main_script The full path of the script to load.
* @param instance_name The name of the instance out of the script to load.
* @param company Which company this script is serving.
*/
void Initialize(const char *main_script, const char *instance_name, CompanyID company);
/**
* Get the value of a setting of the current instance.
* @param name The name of the setting.
* @return the value for the setting, or -1 if the setting is not known.
*/
virtual int GetSetting(const char *name) = 0;
/**
* Find a library.
* @param library The library name to find.
* @param version The version the library should have.
* @return The library if found, NULL otherwise.
*/
virtual class ScriptInfo *FindLibrary(const char *library, int version) = 0;
/**
* A script in multiplayer waits for the server to handle his DoCommand.
* It keeps waiting for this until this function is called.
*/
void Continue();
/**
* Run the GameLoop of a script.
*/
void GameLoop();
/**
* Let the VM collect any garbage.
*/
void CollectGarbage() const;
/**
* Get the storage of this script.
*/
class ScriptStorage *GetStorage();
/**
* Get the log pointer of this script.
*/
void *GetLogPointer();
/**
* Return a true/false reply for a DoCommand.
*/
static void DoCommandReturn(ScriptInstance *instance);
/**
* Return a VehicleID reply for a DoCommand.
*/
static void DoCommandReturnVehicleID(ScriptInstance *instance);
/**
* Return a SignID reply for a DoCommand.
*/
static void DoCommandReturnSignID(ScriptInstance *instance);
/**
* Return a GroupID reply for a DoCommand.
*/
static void DoCommandReturnGroupID(ScriptInstance *instance);
/**
* Return a GoalID reply for a DoCommand.
*/
static void DoCommandReturnGoalID(ScriptInstance *instance);
/**
* Return a StoryPageID reply for a DoCommand.
*/
static void DoCommandReturnStoryPageID(ScriptInstance *instance);
/**
* Return a StoryPageElementID reply for a DoCommand.
*/
static void DoCommandReturnStoryPageElementID(ScriptInstance *instance);
/**
* Get the controller attached to the instance.
*/
class ScriptController *GetController() { return controller; }
/**
* Return the "this script died" value
*/
inline bool IsDead() const { return this->is_dead; }
/**
* Call the script Save function and save all data in the savegame.
*/
void Save();
/**
* Don't save any data in the savegame.
*/
static void SaveEmpty();
/**
* Load data from a savegame and store it on the stack.
* @param version The version of the script when saving, or -1 if this was
* not the original script saving the game.
*/
void Load(int version);
/**
* Load and discard data from a savegame.
*/
static void LoadEmpty();
/**
* Suspends the script for the current tick and then pause the execution
* of script. The script will not be resumed from its suspended state
* until the script has been unpaused.
*/
void Pause();
/**
* Checks if the script is paused.
* @return true if the script is paused, otherwise false
*/
bool IsPaused();
/**
* Resume execution of the script. This function will not actually execute
* the script, but set a flag so that the script is executed my the usual
* mechanism that executes the script.
*/
void Unpause();
/**
* Get the number of operations the script can execute before being suspended.
* This function is safe to call from within a function called by the script.
* @return The number of operations to execute.
*/
SQInteger GetOpsTillSuspend();
/**
* DoCommand callback function for all commands executed by scripts.
* @param result The result of the command.
* @param tile The tile on which the command was executed.
* @param p1 p1 as given to DoCommandPInternal.
* @param p2 p2 as given to DoCommandPInternal.
*/
void DoCommandCallback(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p2);
/**
* Insert an event for this script.
* @param event The event to insert.
*/
void InsertEvent(class ScriptEvent *event);
/**
* Check if the instance is sleeping, which either happened because the
* script executed a DoCommand, executed this.Sleep() or it has been
* paused.
*/
bool IsSleeping() { return this->suspend != 0; }
protected:
class Squirrel *engine; ///< A wrapper around the squirrel vm.
const char *versionAPI; ///< Current API used by this script.
/**
* Register all API functions to the VM.
*/
virtual void RegisterAPI();
/**
* Load squirrel scripts to emulate an older API.
* @param api_version: API version to load scripts for
* @param dir Subdirectory to find the scripts in
* @return true iff script loading should proceed
*/
bool LoadCompatibilityScripts(const char *api_version, Subdirectory dir);
/**
* Tell the script it died.
*/
virtual void Died();
/**
* Get the callback handling DoCommands in case of networking.
*/
virtual CommandCallback *GetDoCommandCallback() = 0;
/**
* Load the dummy script.
*/
virtual void LoadDummyScript() = 0;
private:
class ScriptController *controller; ///< The script main class.
class ScriptStorage *storage; ///< Some global information for each running script.
SQObject *instance; ///< Squirrel-pointer to the script main class.
bool is_started; ///< Is the scripts constructor executed?
bool is_dead; ///< True if the script has been stopped.
bool is_save_data_on_stack; ///< Is the save data still on the squirrel stack?
int suspend; ///< The amount of ticks to suspend this script before it's allowed to continue.
bool is_paused; ///< Is the script paused? (a paused script will not be executed until unpaused)
Script_SuspendCallbackProc *callback; ///< Callback that should be called in the next tick the script runs.
/**
* Call the script Load function if it exists and data was loaded
* from a savegame.
*/
bool CallLoad();
/**
* Save one object (int / string / array / table) to the savegame.
* @param vm The virtual machine to get all the data from.
* @param index The index on the squirrel stack of the element to save.
* @param max_depth The maximum depth recursive arrays / tables will be stored
* with before an error is returned.
* @param test If true, don't really store the data but only check if it is
* valid.
* @return True if the saving was successful.
*/
static bool SaveObject(HSQUIRRELVM vm, SQInteger index, int max_depth, bool test);
/**
* Load all objects from a savegame.
* @return True if the loading was successful.
*/
static bool LoadObjects(HSQUIRRELVM vm);
};
#endif /* SCRIPT_INSTANCE_HPP */
| 412 | 0.691837 | 1 | 0.691837 | game-dev | MEDIA | 0.427449 | game-dev | 0.578957 | 1 | 0.578957 |
CyanLaser/CyanEmu | 3,466 | CyanEmu/Scripts/CyanEmuInputModule.cs | using UnityEngine;
using UnityEngine.EventSystems;
namespace VRCPrefabs.CyanEmu
{
[AddComponentMenu("")]
public class CyanEmuInputModule : StandaloneInputModule
{
private const int UILayer = 5;
private const int UIMenuLayer = 12;
private CursorLockMode currentLockState_ = CursorLockMode.None;
private CyanEmuBaseInput baseInput_;
public static void DisableOtherInputModules()
{
EventSystem[] systems = FindObjectsOfType<EventSystem>();
foreach (EventSystem system in systems)
{
system.enabled = false;
}
}
protected override void Start()
{
m_InputOverride = baseInput_ = GetComponent<CyanEmuBaseInput>();
eventSystem.sendNavigationEvents = false;
base.Start();
}
public override void Process()
{
currentLockState_ = Cursor.lockState;
Cursor.lockState = CursorLockMode.None;
base.Process();
Cursor.lockState = currentLockState_;
}
// Prevent clicking on menus on the ui layer if your menu is not open
protected override MouseState GetMousePointerEventData(int id)
{
var pointerEventData = base.GetMousePointerEventData(id);
var leftEventData = pointerEventData.GetButtonState(PointerEventData.InputButton.Left).eventData;
var pointerRaycast = leftEventData.buttonData.pointerCurrentRaycast;
var obj = pointerRaycast.gameObject;
if (obj == null)
{
return pointerEventData;
}
bool isMenuLayer = obj.layer == UILayer || obj.layer == UIMenuLayer;
if (isMenuLayer ^ baseInput_.isMenuOpen)
{
//Debug.Log("Found menu that you shouldn't interact with!");
leftEventData.buttonData.pointerCurrentRaycast = new RaycastResult()
{
depth = pointerRaycast.depth,
distance = pointerRaycast.distance,
index = pointerRaycast.index,
module = pointerRaycast.module,
gameObject = null,
screenPosition = pointerRaycast.screenPosition,
sortingLayer = pointerRaycast.sortingLayer,
sortingOrder = pointerRaycast.sortingOrder,
worldNormal = pointerRaycast.worldNormal,
worldPosition = pointerRaycast.worldPosition
};
}
return pointerEventData;
}
}
class CyanEmuBaseInput : BaseInput
{
public bool isMenuOpen;
private Vector2 lastMousePos_;
private Vector2 mouseDelta_;
public static Vector2 GetScreenCenter()
{
return new Vector2(Screen.width, Screen.height) * 0.5f;
}
public override Vector2 mousePosition
{
get
{
if (isMenuOpen)
{
return base.mousePosition;
}
return GetScreenCenter() - mouseDelta_;
}
}
private void Update()
{
Vector2 curPos = base.mousePosition;
mouseDelta_ = curPos - lastMousePos_;
lastMousePos_ = curPos;
}
}
}
| 412 | 0.925747 | 1 | 0.925747 | game-dev | MEDIA | 0.612887 | game-dev | 0.678222 | 1 | 0.678222 |
magefree/mage | 1,684 | Mage.Sets/src/mage/cards/r/RushingRiver.java | package mage.cards.r;
import mage.abilities.condition.common.KickedCondition;
import mage.abilities.costs.common.SacrificeTargetCost;
import mage.abilities.effects.common.ReturnToHandTargetEffect;
import mage.abilities.keyword.KickerAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.filter.StaticFilters;
import mage.target.common.TargetNonlandPermanent;
import mage.target.targetadjustment.ConditionalTargetAdjuster;
import java.util.UUID;
/**
* @author LevelX2
*/
public final class RushingRiver extends CardImpl {
public RushingRiver(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.INSTANT}, "{2}{U}");
// Kicker-Sacrifice a land.
this.addAbility(new KickerAbility(new SacrificeTargetCost(StaticFilters.FILTER_LAND)));
// Return target nonland permanent to its owner's hand. If Rushing River was kicked, return another target nonland permanent to its owner's hand.
this.getSpellAbility().addEffect(new ReturnToHandTargetEffect()
.setText("Return target nonland permanent to its owner's hand. " +
"If this spell was kicked, return another target nonland permanent to its owner's hand"));
this.getSpellAbility().addTarget(new TargetNonlandPermanent());
this.getSpellAbility().setTargetAdjuster(new ConditionalTargetAdjuster(KickedCondition.ONCE,
new TargetNonlandPermanent(2)));
}
private RushingRiver(final RushingRiver card) {
super(card);
}
@Override
public RushingRiver copy() {
return new RushingRiver(this);
}
}
| 412 | 0.961953 | 1 | 0.961953 | game-dev | MEDIA | 0.965654 | game-dev | 0.995362 | 1 | 0.995362 |
OpenXRay/xray-15 | 4,640 | cs/engine/xrGame/moving_objects_static.cpp | ////////////////////////////////////////////////////////////////////////////
// Module : moving_objects_static.cpp
// Created : 27.03.2007
// Modified : 14.05.2007
// Author : Dmitriy Iassenev
// Description : moving objects with static objects, i.e stable dynamic objects
////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "moving_objects.h"
#include "ai_space.h"
#include "level_graph.h"
#include "moving_object.h"
#include "moving_objects_impl.h"
bool moving_objects::collided_static (const Fvector &position, const float &radius)
{
NEAREST_STATIC::const_iterator I = m_nearest_static.begin();
NEAREST_STATIC::const_iterator E = m_nearest_static.end();
for ( ; I != E; ++I) {
if (collided(*I,position,radius))
return (true);
}
return (false);
}
bool moving_objects::collided_static (moving_object *object, const Fvector &dest_position)
{
float radius = object->radius() + ai().level_graph().header().cell_size()*.5f;
float linear_velocity = dest_position.distance_to(object->position())/time_to_check;
float distance_to_check = time_to_check*linear_velocity;
u32 step_count = iFloor(distance_to_check/step_to_check + .5f);
for (u32 i=0; i<step_count; ++i) {
if (!i) {
if (collided_static(object->position(),radius))
return (true);
continue;
}
if ((i + 1) == step_count) {
if (collided_static(dest_position,radius))
return (true);
continue;
}
if (collided_static(object->predict_position(i*step_to_check),radius))
return (true);
}
return (false);
}
void moving_objects::fill_static (obstacles_query &query)
{
NEAREST_STATIC::const_iterator I = m_nearest_static.begin();
NEAREST_STATIC::const_iterator E = m_nearest_static.end();
for ( ; I != E; ++I)
query.add (smart_cast<const CGameObject*>(*I));
}
void moving_objects::fill_static (obstacles_query &query, const Fvector &position, const float &radius)
{
NEAREST_STATIC::const_iterator I = m_nearest_static.begin();
NEAREST_STATIC::const_iterator E = m_nearest_static.end();
for ( ; I != E; ++I) {
if (!collided(*I,position,radius))
continue;
query.add (smart_cast<const CGameObject*>(*I));
}
}
void moving_objects::fill_all_static (moving_object *object, const Fvector &dest_position)
{
float radius = object->radius() + ai().level_graph().header().cell_size()*.5f;
float linear_velocity = dest_position.distance_to(object->position())/time_to_check;
float distance_to_check = time_to_check*linear_velocity;
u32 step_count = iFloor(distance_to_check/step_to_check + .5f);
for (u32 i=0; i<step_count; ++i) {
if (!i) {
fill_static (object->static_query(),object->position(),radius);
continue;
}
if ((i + 1) == step_count) {
fill_static (object->static_query(),dest_position,radius);
continue;
}
fill_static (object->static_query(),object->predict_position(i*step_to_check),radius);
}
}
class ignore_predicate {
private:
moving_object *m_object;
public:
IC ignore_predicate(moving_object *object) :
m_object (object)
{
}
IC bool operator() (const CObject *object) const
{
if (m_object->ignored(object))
return (true);
const CGameObject *game_object = smart_cast<const CGameObject*>(object);
VERIFY (game_object);
if (!game_object->is_ai_obstacle())
return (true);
return (false);
}
};
void moving_objects::fill_nearest_list (const Fvector &position, const float &radius, moving_object *object)
{
Level().ObjectSpace.GetNearest (
m_spatial_objects,
m_nearest_static,
position,
radius,
const_cast<CEntityAlive*>(&object->object())
);
m_nearest_static.erase (
std::remove_if(
m_nearest_static.begin(),
m_nearest_static.end(),
ignore_predicate(object)
),
m_nearest_static.end()
);
}
void moving_objects::query_action_static (moving_object *object, const Fvector &_start_position, const Fvector &dest_position)
{
Fvector start_position = _start_position;
start_position.average (dest_position);
fill_nearest_list (
start_position,
dest_position.distance_to(start_position) + EPS,
object
);
if (m_nearest_static.empty())
return;
if (!collided_static(object,dest_position))
return;
fill_nearest_list (
start_position,
dest_position.distance_to(start_position) + additional_radius + EPS,
object
);
fill_static (object->static_query());
// fill_all_static (object,dest_position);
}
void moving_objects::query_action_static (moving_object *object)
{
query_action_static (object,object->position(),object->predict_position(time_to_check));
}
| 412 | 0.801528 | 1 | 0.801528 | game-dev | MEDIA | 0.316626 | game-dev | 0.980123 | 1 | 0.980123 |
amnoah/BetterAnticheat | 2,908 | core/src/main/java/better/anticheat/core/check/impl/dig/MultiBreakCheck.java | package better.anticheat.core.check.impl.dig;
import better.anticheat.core.BetterAnticheat;
import better.anticheat.core.check.Check;
import better.anticheat.core.check.CheckInfo;
import com.github.retrooper.packetevents.event.simple.PacketPlayReceiveEvent;
import com.github.retrooper.packetevents.protocol.packettype.PacketType;
import com.github.retrooper.packetevents.util.Vector3i;
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientPlayerDigging;
/**
* This check looks for multiple blocks being dug at once.
*/
@CheckInfo(name = "MultiBreak", category = "dig")
public class MultiBreakCheck extends Check {
private boolean hasStarted = false;
private Vector3i latestStartPosition;
public MultiBreakCheck(BetterAnticheat plugin) {
super(plugin);
}
@Override
public void handleReceivePlayPacket(PacketPlayReceiveEvent event) {
/*
* This check patches a very interesting bypass mechanic in some cheats.
*
* Some clients bypass classic fast break checks by following this process:
* Start1 -> Start2 -> Finish1 -> Start3 -> Finish2 -> Start4 -> etc
*
* It starts digging multiple blocks at the same time, waiting until the proper time has passed to finish any.
* This also isn't easily detectable by checking if the last action and current action are starts because the
* vanilla client does that when breaking insta-break blocks. This doesn't seem to be as common anymore, but I'm
* still including it regardless.
*
* Interesting note for 1.21+! I've noticed behavior where if a block is next to an insta-break block in a
* WorldGuard protected area, you can mine the block through the insta-break. The client will only ever Start
* digging the insta-break, but will finish the other block.
*/
if (event.getPacketType() != PacketType.Play.Client.PLAYER_DIGGING) return;
WrapperPlayClientPlayerDigging wrapper = new WrapperPlayClientPlayerDigging(event);
switch (wrapper.getAction()) {
case START_DIGGING:
latestStartPosition = wrapper.getBlockPosition();
hasStarted = true;
break;
case FINISHED_DIGGING:
if (hasStarted) {
// Use Manhattan Distance to ensure blocks are within 1 block of the finished block.
int difX = Math.abs(wrapper.getBlockPosition().getX() - latestStartPosition.getX());
int difY = Math.abs(wrapper.getBlockPosition().getY() - latestStartPosition.getY());
int difZ = Math.abs(wrapper.getBlockPosition().getZ() - latestStartPosition.getZ());
if ((difX + difY + difZ) <= 1) return;
fail();
}
break;
}
}
}
| 412 | 0.918313 | 1 | 0.918313 | game-dev | MEDIA | 0.364432 | game-dev | 0.859773 | 1 | 0.859773 |
gnuplot/gnuplot-old | 13,341 | demo/finance.dem | # 10 May 2005
#
# Though gnuplot is primarily a scientific plotting program, it can do a great
# job of plotting finance charts as well. The primary challenge is the irregular
# nature of financial time series. Stocks don't trade every day, so when you set
# the x-axis to time gaps appear for non-trading days. Investors and traders
# generally prefer that these gaps be omitted. Another challenge is that finance
# charts are best presented in semi-log form (log y-axis, linear x-axis),
# but gnuplot wants to span decades in its log scaling, something that stocks
# rarely do. These and other challenges are met in finance.dem, a short
# demonstration script that proves that gnuplot can really shine in this area.
#
# gnuplot plays a central role in our work. Almost all the graphs in "Bollinger
# on Bollinger Bands" were plotted by gnuplot, many gnuplot visuals have
# appeared on CNBC, our in-house analytics use gnuplot for visual display and
# The Capital Growth Letter relies heavily on gnuplot for its charts.
#
# Finally, gnuplot is yet another successful demonstration of a powerful idea,
# open source programming. Thanks to all who made gnuplot possible from the
# earliest days to the present and to all those who will contribute in the
# future. (Special thanks to Hans-Bernhard Broeker whose patience helped me to
# climb the grade and to Ethan Merritt whose recent contributions have been
# invaluable to our work.)
#
# John Bollinger
# www.BollingerBands.com
# a demonstration of gnuplot finance plot styles
# by John Bollinger, CFA, CMT
# www.BollingerBands.com
# BBands@BollingerBands.com
# data and indicators in finance.dat
# data file layout:
# date, open, high, low, close, volume,
# 50-day moving average volume, Intraday Intensity,
# 20-day moving average close,
# upper Bollinger Band, lower Bollinger Band
# last update: 8 May 2005
pause -1 "Click OK to start the Finance Demo"
reset
# set label 1 "Demo of plotting financial data" at screen 0.5, screen 0.95 center
set title "Demo of plotting financial data"
set yrange [75:105]
set ytics (105, 100, 95, 90, 85, 80)
set xrange [50:253]
set lmargin 9
set rmargin 2
plot 'finance.dat' using 0:5 notitle with lines
pause -1 "Turn on the grid"
reset
set title "Turn on grid"
set yrange [75:105]
set ytics (105, 100, 95, 90, 85, 80)
set xrange [50:253]
set lmargin 9
set rmargin 2
set grid
plot 'finance.dat' using 0:5 notitle with lines
pause -1 "Semi-log scaling"
reset
set title "Semi-log scaling"
set yrange [75:105]
set ytics (105, 100, 95, 90, 85, 80)
set xrange [50:253]
set lmargin 9
set rmargin 2
set grid
set logscale y
plot 'finance.dat' using 0:5 notitle with lines
pause -1 "Finance bars"
reset
set title "Finance bars"
set yrange [75:105]
set ytics (105, 100, 95, 90, 85, 80)
set xrange [50:253]
set lmargin 9
set rmargin 2
set grid
set logscale y
plot 'finance.dat' using 0:2:3:4:5 notitle with financebars lt 8
pause -1 "Bollinger Bands"
reset
set title "Bollinger Bands"
set yrange [75:105]
set ytics (105, 100, 95, 90, 85, 80)
set xrange [50:253]
set lmargin 9
set rmargin 2
set grid
set logscale y
plot 'finance.dat' using 0:2:3:4:5 notitle with financebars lt 8, \
'finance.dat' using 0:9 notitle with lines lt 3, \
'finance.dat' using 0:10 notitle with lines lt 1, \
'finance.dat' using 0:11 notitle with lines lt 2
pause -1 "Overlay an indicator on a seperate scale"
reset
set title "Overlay an indicator on a separate scale"
set yrange [75:105]
set ytics (105, 100, 95, 90, 85, 80)
set xrange [50:253]
set lmargin 9
set rmargin 2
set grid
set logscale y
plot 'finance.dat' using 0:2:3:4:5 notitle with financebars lt 8, \
'finance.dat' using 0:9 notitle with lines lt 3, \
'finance.dat' using 0:10 notitle with lines lt 1, \
'finance.dat' using 0:11 notitle with lines lt 2, \
'finance.dat' using 0:8 axes x1y2 notitle with lines lt 4
pause -1 "Add some boiler plate"
reset
set title "Add some boiler plate"
set label "Courtesy of Bollinger Capital" at graph 0.01, 0.07
set label " www.BollingerBands.com" at graph 0.01, 0.03
set yrange [75:105]
set ytics (105, 100, 95, 90, 85, 80)
set xrange [50:253]
set lmargin 9
set rmargin 2
set grid
set logscale y
plot 'finance.dat' using 0:2:3:4:5 notitle with financebars lt 8, \
'finance.dat' using 0:9 notitle with lines lt 3, \
'finance.dat' using 0:10 notitle with lines lt 1, \
'finance.dat' using 0:11 notitle with lines lt 2, \
'finance.dat' using 0:8 axes x1y2 notitle with lines lt 4
pause -1 "Add volume in a seperate clip"
reset
set label "Courtesy of Bollinger Capital" at graph 0.01, 0.07
set label " www.BollingerBands.com" at graph 0.01, 0.03
set logscale y
set yrange [75:105]
set ytics (105, 100, 95, 90, 85, 80)
set xrange [50:253]
set grid
set lmargin 9
set rmargin 2
set format x ""
set xtics (66, 87, 109, 130, 151, 174, 193, 215, 235)
set multiplot
set size 1, 0.7
set origin 0, 0.3
set bmargin 0
set title "Add volume in a separate clip"
plot 'finance.dat' using 0:2:3:4:5 notitle with financebars lt 8, \
'finance.dat' using 0:9 notitle with lines lt 3, \
'finance.dat' using 0:10 notitle with lines lt 1, \
'finance.dat' using 0:11 notitle with lines lt 2, \
'finance.dat' using 0:8 axes x1y2 notitle with lines lt 4
unset label 1
unset label 2
unset title
set bmargin
set format x
set size 1.0, 0.3
set origin 0.0, 0.0
set tmargin 0
unset logscale y
set autoscale y
set format y "%1.0f"
set ytics 500
plot 'finance.dat' using 0:($6/10000) notitle with impulses lt 3
unset multiplot
pause -1 "Add average volume"
reset
set label "Courtesy of Bollinger Capital" at graph 0.01, 0.07
set label " www.BollingerBands.com" at graph 0.01, 0.03
set logscale y
set yrange [75:105]
set ytics (105, 100, 95, 90, 85, 80)
set xrange [50:253]
set grid
set lmargin 9
set rmargin 2
set format x ""
set xtics (66, 87, 109, 130, 151, 174, 193, 215, 235)
set multiplot
set title "Add average volume"
set size 1, 0.7
set origin 0, 0.3
set bmargin 0
plot 'finance.dat' using 0:2:3:4:5 notitle with financebars lt 8, \
'finance.dat' using 0:9 notitle with lines lt 3, \
'finance.dat' using 0:10 notitle with lines lt 1, \
'finance.dat' using 0:11 notitle with lines lt 2, \
'finance.dat' using 0:8 axes x1y2 notitle with lines lt 4
unset label 1
unset label 2
unset title
set bmargin
set format x
set size 1.0, 0.3
set origin 0.0, 0.0
set tmargin 0
unset logscale y
set autoscale y
set format y "%1.0f"
set ytics 500
plot 'finance.dat' using 0:($6/10000) notitle with impulses lt 3, \
'finance.dat' using 0:($7/10000) notitle with lines lt 1
unset multiplot
pause -1 "Add date labels to the x axis"
reset
set label "Courtesy of Bollinger Capital" at graph 0.01, 0.07
set label " www.BollingerBands.com" at graph 0.01, 0.03
set logscale y
set yrange [75:105]
set ytics (105, 100, 95, 90, 85, 80)
set xrange [50:253]
set grid
set lmargin 9
set rmargin 2
set format x ""
set xtics (66, 87, 109, 130, 151, 174, 193, 215, 235)
set multiplot
set title "Add date labels to the x axis"
set size 1, 0.7
set origin 0, 0.3
set bmargin 0
plot 'finance.dat' using 0:2:3:4:5 notitle with financebars lt 8, \
'finance.dat' using 0:9 notitle with lines lt 3, \
'finance.dat' using 0:10 notitle with lines lt 1, \
'finance.dat' using 0:11 notitle with lines lt 2, \
'finance.dat' using 0:8 axes x1y2 notitle with lines lt 4
unset label 1
unset label 2
unset title
set bmargin
set format x
set size 1.0, 0.3
set origin 0.0, 0.0
set tmargin 0
unset logscale y
set autoscale y
set format y "%1.0f"
set ytics 500
set xtics ("6/03" 66, "7/03" 87, "8/03" 109, "9/03" 130, "10/03" 151, "11/03" 174, "12/03" 193, "1/04" 215, "2/04" 235)
plot 'finance.dat' using 0:($6/10000) notitle with impulses lt 3, \
'finance.dat' using 0:($7/10000) notitle with lines lt 1
unset multiplot
pause -1 "Add labels for each clip"
reset
set label "Courtesy of Bollinger Capital" at graph 0.01, 0.07
set label " www.BollingerBands.com" at graph 0.01, 0.03
set logscale y
set yrange [75:105]
set ytics (105, 100, 95, 90, 85, 80)
set xrange [50:253]
set grid
set lmargin 9
set rmargin 2
set format x ""
set xtics (66, 87, 109, 130, 151, 174, 193, 215, 235)
set multiplot
set title "Add labels for each clip"
set size 1, 0.7
set origin 0, 0.3
set bmargin 0
set ylabel "price" offset 1
plot 'finance.dat' using 0:2:3:4:5 notitle with financebars lt 8, \
'finance.dat' using 0:9 notitle with lines lt 3, \
'finance.dat' using 0:10 notitle with lines lt 1, \
'finance.dat' using 0:11 notitle with lines lt 2, \
'finance.dat' using 0:8 axes x1y2 notitle with lines lt 4
unset label 1
unset label 2
unset title
set bmargin
set format x
set size 1.0, 0.3
set origin 0.0, 0.0
set tmargin 0
unset logscale y
set autoscale y
set format y "%1.0f"
set ytics 500
set xtics ("6/03" 66, "7/03" 87, "8/03" 109, "9/03" 130, "10/03" 151, "11/03" 174, "12/03" 193, "1/04" 215, "2/04" 235)
set ylabel "volume (0000)" offset 1
plot 'finance.dat' using 0:($6/10000) notitle with impulses lt 3, \
'finance.dat' using 0:($7/10000) notitle with lines lt 1
unset multiplot
pause -1 "Add a title"
reset
set label 1 "Acme Widgets" at graph 0.5, graph 0.9 center front
set label 2 "Courtesy of Bollinger Capital" at graph 0.01, 0.07
set label 3 " www.BollingerBands.com" at graph 0.01, 0.03
set logscale y
set yrange [75:105]
set ytics (105, 100, 95, 90, 85, 80)
set xrange [50:253]
set grid
set lmargin 9
set rmargin 2
set format x ""
set xtics (66, 87, 109, 130, 151, 174, 193, 215, 235)
set multiplot
set title "Add a title"
set size 1, 0.7
set origin 0, 0.3
set bmargin 0
set ylabel "price" offset 1
plot 'finance.dat' using 0:2:3:4:5 notitle with financebars lt 8, \
'finance.dat' using 0:9 notitle with lines lt 3, \
'finance.dat' using 0:10 notitle with lines lt 1, \
'finance.dat' using 0:11 notitle with lines lt 2, \
'finance.dat' using 0:8 axes x1y2 notitle with lines lt 4
unset label 1
unset label 2
unset label 3
unset title
set bmargin
set format x
set size 1.0, 0.3
set origin 0.0, 0.0
set tmargin 0
unset logscale y
set autoscale y
set format y "%1.0f"
set ytics 500
set xtics ("6/03" 66, "7/03" 87, "8/03" 109, "9/03" 130, "10/03" 151, "11/03" 174, "12/03" 193, "1/04" 215, "2/04" 235)
set ylabel "volume (0000)" offset 1
plot 'finance.dat' using 0:($6/10000) notitle with impulses lt 3, \
'finance.dat' using 0:($7/10000) notitle with lines lt 1
unset multiplot
pause -1 " Change to Candlesticks"
reset
set label 1 "Acme Widgets" at graph 0.5, graph 0.9 center front
set label 2 "Courtesy of Bollinger Capital" at graph 0.01, 0.07
set label 3 " www.BollingerBands.com" at graph 0.01, 0.03
set logscale y
set yrange [75:105]
set ytics (105, 100, 95, 90, 85, 80)
set xrange [50:253]
set grid
set lmargin 9
set rmargin 2
set format x ""
set xtics (66, 87, 109, 130, 151, 174, 193, 215, 235)
set multiplot
set title "Change to candlesticks"
set size 1, 0.7
set origin 0, 0.3
set bmargin 0
set ylabel "price" offset 1
plot 'finance.dat' using 0:2:3:4:5 notitle with candlesticks lt 8, \
'finance.dat' using 0:9 notitle with lines lt 3, \
'finance.dat' using 0:10 notitle with lines lt 1, \
'finance.dat' using 0:11 notitle with lines lt 2, \
'finance.dat' using 0:8 axes x1y2 notitle with lines lt 4
unset label 1
unset label 2
unset label 3
unset title
set bmargin
set format x
set size 1.0, 0.3
set origin 0.0, 0.0
set tmargin 0
unset logscale y
set autoscale y
set format y "%1.0f"
set ytics 500
set xtics ("6/03" 66, "7/03" 87, "8/03" 109, "9/03" 130, "10/03" 151, "11/03" 174, "12/03" 193, "1/04" 215, "2/04" 235)
set ylabel "volume (0000)" offset 1
plot 'finance.dat' using 0:($6/10000) notitle with impulses lt 3, \
'finance.dat' using 0:($7/10000) notitle with lines lt 1
unset multiplot
pause -1 "Change to Bollinger Boxes"
reset
set label 1 "Acme Widgets" at graph 0.5, graph 0.9 center front
set label 2 "Courtesy of Bollinger Capital" at graph 0.01, 0.07
set label 3 " www.BollingerBands.com" at graph 0.01, 0.03
set logscale y
set yrange [75:105]
set ytics (105, 100, 95, 90, 85, 80)
set xrange [50:253]
set grid
set lmargin 9
set rmargin 2
set format x ""
set xtics (66, 87, 109, 130, 151, 174, 193, 215, 235)
set multiplot
set title "Change to Bollinger Boxes"
set size 1, 0.7
set origin 0, 0.3
set bmargin 0
set ylabel "price" offset 1
plot 'finance.dat' using 0:3:3:($2>$5?$2:$5):($2>$5?$2:$5) notitle with candlesticks lt 3, \
'finance.dat' using 0:($2<$5?$5:1/0):($2<$5?$5:1/0):($2<$5?$2:1/0):($2<$5?$2:1/0) notitle with candlesticks lt 2, \
'finance.dat' using 0:($2>$5?$2:1/0):($2>$5?$2:1/0):($2>$5?$5:1/0):($2>$5?$5:1/0) notitle with candlesticks lt 1, \
'finance.dat' using 0:($2<$5?$2:$5):($2<$5?$2:$5):4:4 notitle with candlesticks lt 3, \
'finance.dat' using 0:9 notitle with lines lt 3, \
'finance.dat' using 0:10 notitle with lines lt 1, \
'finance.dat' using 0:11 notitle with lines lt 2, \
'finance.dat' using 0:8 axes x1y2 notitle with lines lt 4
unset label 1
unset label 2
unset label 3
unset title
set bmargin
set format x
set size 1.0, 0.3
set origin 0.0, 0.0
set tmargin 0
unset logscale y
set autoscale y
set format y "%1.0f"
set ytics 500
set xtics ("6/03" 66, "7/03" 87, "8/03" 109, "9/03" 130, "10/03" 151, "11/03" 174, "12/03" 193, "1/04" 215, "2/04" 235)
set ylabel "volume (0000)" offset 1
plot 'finance.dat' using 0:($6/10000) notitle with impulses lt 3, \
'finance.dat' using 0:($7/10000) notitle with lines lt 1
unset multiplot
pause -1 "all done!"
reset
| 412 | 0.505382 | 1 | 0.505382 | game-dev | MEDIA | 0.339327 | game-dev | 0.558097 | 1 | 0.558097 |
auroramod/h1-mod | 3,319 | src/client/game/game.cpp | #include <std_include.hpp>
#include "game.hpp"
namespace game
{
uint64_t base_address;
int Cmd_Argc()
{
return cmd_args->argc[cmd_args->nesting];
}
const char* Cmd_Argv(const int index)
{
return cmd_args->argv[cmd_args->nesting][index];
}
int SV_Cmd_Argc()
{
return sv_cmd_args->argc[sv_cmd_args->nesting];
}
const char* SV_Cmd_Argv(const int index)
{
return sv_cmd_args->argv[sv_cmd_args->nesting][index];
}
bool VirtualLobby_Loaded()
{
return !game::environment::is_sp() && *mp::virtualLobby_loaded == 1;
}
void SV_GameSendServerCommand(int client_num, svscmd_type type, const char* text)
{
const auto svs_clients = *mp::svs_clients;
if (svs_clients == nullptr)
{
return;
}
if (client_num == -1)
{
SV_SendServerCommand(0, type, "%s", text);
}
else
{
SV_SendServerCommand(&svs_clients[client_num], type, "%s", text);
}
}
void Cbuf_AddText(int local_client_num, int controller_index, const char* cmd)
{
if (game::environment::is_sp())
{
sp::Cbuf_AddText(local_client_num, cmd);
}
else
{
mp::Cbuf_AddText(local_client_num, controller_index, cmd);
}
}
void Cmd_TokenizeString(const char* text)
{
if (game::environment::is_sp())
{
sp::Cmd_TokenizeString(text);
}
else
{
const auto a2 = 512 - *reinterpret_cast<int*>(0x3516F40_b);
mp::Cmd_TokenizeStringWithLimit(text, a2);
}
}
void Cmd_EndTokenizeString()
{
if (game::environment::is_sp())
{
return sp::Cmd_EndTokenizeString();
}
const auto nesting = cmd_args->nesting;
const auto argc = cmd_args->argc[nesting];
--cmd_args->nesting;
cmd_argsPrivate->totalUsedArgvPool -= argc;
cmd_argsPrivate->totalUsedTextPool -= cmd_argsPrivate->usedTextPool[nesting];
}
namespace environment
{
launcher::mode mode = launcher::mode::none;
launcher::mode translate_surrogate(const launcher::mode _mode)
{
switch (_mode)
{
case launcher::mode::survival:
case launcher::mode::zombies:
return launcher::mode::multiplayer;
default:
return _mode;
}
}
launcher::mode get_real_mode()
{
if (mode == launcher::mode::none)
{
//throw std::runtime_error("Launcher mode not valid. Something must be wrong.");
}
return mode;
}
launcher::mode get_mode()
{
return translate_surrogate(get_real_mode());
}
bool is_sp()
{
return get_mode() == launcher::mode::singleplayer;
}
bool is_mp()
{
return get_mode() == launcher::mode::multiplayer;
}
bool is_dedi()
{
return get_mode() == launcher::mode::server;
}
void set_mode(const launcher::mode _mode)
{
mode = _mode;
}
std::string get_string()
{
const auto current_mode = get_real_mode();
switch (current_mode)
{
case launcher::mode::server:
return "Dedicated Server";
case launcher::mode::multiplayer:
return "Multiplayer";
case launcher::mode::singleplayer:
return "Singleplayer";
case launcher::mode::none:
return "None";
default:
return "Unknown (" + std::to_string(static_cast<int>(mode)) + ")";
}
}
}
}
size_t operator"" _b(const size_t ptr)
{
return game::base_address + ptr;
}
size_t reverse_b(const size_t ptr)
{
return ptr - game::base_address;
}
size_t reverse_b(const void* ptr)
{
return reverse_b(reinterpret_cast<size_t>(ptr));
}
| 412 | 0.921073 | 1 | 0.921073 | game-dev | MEDIA | 0.398041 | game-dev | 0.761586 | 1 | 0.761586 |
pwnsky/squick | 1,587 | src/plugin/core/utils/event_module.h | #pragma once
#include "i_event_module.h"
#include <iostream>
class EventModule : public IEventModule {
public:
EventModule(IPluginManager *p) {
is_update_ = true;
pm_ = p;
}
virtual ~EventModule() {}
virtual bool Start();
virtual bool AfterStart();
virtual bool BeforeDestroy();
virtual bool Destroy();
virtual bool Update();
virtual bool DoEvent(const int eventID, const DataList &valueList);
virtual bool ExistEventCallBack(const int eventID);
virtual bool RemoveEventCallBack(const int eventID);
//////////////////////////////////////////////////////////
virtual bool DoEvent(const Guid self, const int eventID, const DataList &valueList);
virtual bool ExistEventCallBack(const Guid self, const int eventID);
virtual bool RemoveEventCallBack(const Guid self, const int eventID);
virtual bool RemoveEventCallBack(const Guid self);
protected:
virtual bool AddEventCallBack(const int eventID, const MODULE_EVENT_FUNCTOR cb);
virtual bool AddEventCallBack(const Guid self, const int eventID, const OBJECT_EVENT_FUNCTOR cb);
virtual bool AddCommonEventCallBack(const OBJECT_EVENT_FUNCTOR cb);
private:
// IWorldModule *m_world_;
private:
// for module
List<int> mModuleRemoveListEx;
MapEx<int, List<MODULE_EVENT_FUNCTOR>> mModuleEventInfoMapEx;
// for object
List<Guid> mObjectRemoveListEx;
MapEx<Guid, MapEx<int, List<OBJECT_EVENT_FUNCTOR>>> mObjectEventInfoMapEx;
// for common event
List<OBJECT_EVENT_FUNCTOR> mCommonEventInfoMapEx;
}; | 412 | 0.743121 | 1 | 0.743121 | game-dev | MEDIA | 0.83069 | game-dev | 0.576554 | 1 | 0.576554 |
neraliu/tainted-phantomjs | 7,804 | src/qt/src/3rdparty/webkit/Source/WebCore/dom/Event.h | /*
* Copyright (C) 2001 Peter Kelly (pmk@post.com)
* Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
* Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
* Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#ifndef Event_h
#define Event_h
#include "Clipboard.h"
#include "DOMTimeStamp.h"
#include <wtf/RefCounted.h>
#include <wtf/text/AtomicString.h>
namespace WebCore {
class EventTarget;
class EventDispatcher;
class Event : public RefCounted<Event> {
public:
enum PhaseType {
CAPTURING_PHASE = 1,
AT_TARGET = 2,
BUBBLING_PHASE = 3
};
enum EventType {
MOUSEDOWN = 1,
MOUSEUP = 2,
MOUSEOVER = 4,
MOUSEOUT = 8,
MOUSEMOVE = 16,
MOUSEDRAG = 32,
CLICK = 64,
DBLCLICK = 128,
KEYDOWN = 256,
KEYUP = 512,
KEYPRESS = 1024,
DRAGDROP = 2048,
FOCUS = 4096,
BLUR = 8192,
SELECT = 16384,
CHANGE = 32768
};
static PassRefPtr<Event> create()
{
return adoptRef(new Event);
}
static PassRefPtr<Event> create(const AtomicString& type, bool canBubble, bool cancelable)
{
return adoptRef(new Event(type, canBubble, cancelable));
}
virtual ~Event();
void initEvent(const AtomicString& type, bool canBubble, bool cancelable);
const AtomicString& type() const { return m_type; }
EventTarget* target() const { return m_target.get(); }
void setTarget(PassRefPtr<EventTarget>);
EventTarget* currentTarget() const { return m_currentTarget; }
void setCurrentTarget(EventTarget* currentTarget) { m_currentTarget = currentTarget; }
unsigned short eventPhase() const { return m_eventPhase; }
void setEventPhase(unsigned short eventPhase) { m_eventPhase = eventPhase; }
bool bubbles() const { return m_canBubble; }
bool cancelable() const { return m_cancelable; }
DOMTimeStamp timeStamp() const { return m_createTime; }
void stopPropagation() { m_propagationStopped = true; }
void stopImmediatePropagation() { m_immediatePropagationStopped = true; }
// IE Extensions
EventTarget* srcElement() const { return target(); } // MSIE extension - "the object that fired the event"
bool returnValue() const { return !defaultPrevented(); }
void setReturnValue(bool returnValue) { setDefaultPrevented(!returnValue); }
Clipboard* clipboardData() const { return isClipboardEvent() ? clipboard() : 0; }
virtual bool isCustomEvent() const;
virtual bool isUIEvent() const;
virtual bool isMouseEvent() const;
virtual bool isMutationEvent() const;
virtual bool isKeyboardEvent() const;
virtual bool isTextEvent() const;
virtual bool isCompositionEvent() const;
virtual bool isDragEvent() const; // a subset of mouse events
virtual bool isClipboardEvent() const;
virtual bool isMessageEvent() const;
virtual bool isWheelEvent() const;
virtual bool isBeforeTextInsertedEvent() const;
virtual bool isOverflowEvent() const;
virtual bool isPageTransitionEvent() const;
virtual bool isPopStateEvent() const;
virtual bool isProgressEvent() const;
virtual bool isXMLHttpRequestProgressEvent() const;
virtual bool isWebKitAnimationEvent() const;
virtual bool isWebKitTransitionEvent() const;
virtual bool isBeforeLoadEvent() const;
virtual bool isHashChangeEvent() const;
#if ENABLE(SVG)
virtual bool isSVGZoomEvent() const;
#endif
#if ENABLE(DOM_STORAGE)
virtual bool isStorageEvent() const;
#endif
#if ENABLE(INDEXED_DATABASE)
virtual bool isIDBVersionChangeEvent() const;
#endif
#if ENABLE(WEB_AUDIO)
virtual bool isAudioProcessingEvent() const;
virtual bool isOfflineAudioCompletionEvent() const;
#endif
virtual bool isErrorEvent() const;
#if ENABLE(TOUCH_EVENTS)
virtual bool isTouchEvent() const;
#endif
#if ENABLE(DEVICE_ORIENTATION)
virtual bool isDeviceMotionEvent() const;
virtual bool isDeviceOrientationEvent() const;
#endif
#if ENABLE(INPUT_SPEECH)
virtual bool isSpeechInputEvent() const;
#endif
bool fromUserGesture();
bool propagationStopped() const { return m_propagationStopped || m_immediatePropagationStopped; }
bool immediatePropagationStopped() const { return m_immediatePropagationStopped; }
bool defaultPrevented() const { return m_defaultPrevented; }
void preventDefault() { if (m_cancelable) m_defaultPrevented = true; }
void setDefaultPrevented(bool defaultPrevented) { m_defaultPrevented = defaultPrevented; }
bool defaultHandled() const { return m_defaultHandled; }
void setDefaultHandled() { m_defaultHandled = true; }
bool cancelBubble() const { return m_cancelBubble; }
void setCancelBubble(bool cancel) { m_cancelBubble = cancel; }
Event* underlyingEvent() const { return m_underlyingEvent.get(); }
void setUnderlyingEvent(PassRefPtr<Event>);
virtual bool storesResultAsString() const;
virtual void storeResult(const String&);
virtual Clipboard* clipboard() const { return 0; }
protected:
Event();
Event(const AtomicString& type, bool canBubble, bool cancelable);
virtual void receivedTarget();
bool dispatched() const { return m_target; }
private:
AtomicString m_type;
bool m_canBubble;
bool m_cancelable;
bool m_propagationStopped;
bool m_immediatePropagationStopped;
bool m_defaultPrevented;
bool m_defaultHandled;
bool m_cancelBubble;
unsigned short m_eventPhase;
EventTarget* m_currentTarget;
RefPtr<EventTarget> m_target;
DOMTimeStamp m_createTime;
RefPtr<Event> m_underlyingEvent;
};
class EventDispatchMediator {
public:
explicit EventDispatchMediator(PassRefPtr<Event>);
virtual ~EventDispatchMediator();
virtual bool dispatchEvent(EventDispatcher*) const;
protected:
EventDispatchMediator();
Event* event() const;
void setEvent(PassRefPtr<Event>);
private:
RefPtr<Event> m_event;
};
inline EventDispatchMediator::EventDispatchMediator()
{
}
inline Event* EventDispatchMediator::event() const
{
return m_event.get();
}
inline void EventDispatchMediator::setEvent(PassRefPtr<Event> event)
{
m_event = event;
}
} // namespace WebCore
#endif // Event_h
| 412 | 0.76427 | 1 | 0.76427 | game-dev | MEDIA | 0.548617 | game-dev | 0.547365 | 1 | 0.547365 |
Secrets-of-Sosaria/World | 1,792 | Data/Scripts/Mobiles/Animals/Bears/GrizzlyBearRiding.cs | using System;
using Server.Mobiles;
namespace Server.Mobiles
{
[CorpseName( "a bear corpse" )]
public class GrizzlyBearRiding : BaseMount
{
[Constructable]
public GrizzlyBearRiding() : this( "a grizzly bear" )
{
}
[Constructable]
public GrizzlyBearRiding( string name ) : base( name, 212, 212, AIType.AI_Animal, FightMode.Aggressor, 10, 1, 0.2, 0.4 )
{
BaseSoundID = 0xA3;
SetStr( 126, 155 );
SetDex( 81, 105 );
SetInt( 16, 40 );
SetHits( 76, 93 );
SetMana( 0 );
SetDamage( 8, 13 );
SetDamageType( ResistanceType.Physical, 100 );
SetResistance( ResistanceType.Physical, 25, 35 );
SetResistance( ResistanceType.Cold, 15, 25 );
SetResistance( ResistanceType.Poison, 5, 10 );
SetResistance( ResistanceType.Energy, 5, 10 );
SetSkill( SkillName.MagicResist, 25.1, 40.0 );
SetSkill( SkillName.Tactics, 70.1, 100.0 );
SetSkill( SkillName.FistFighting, 45.1, 70.0 );
Fame = 1000;
Karma = 0;
VirtualArmor = 24;
Tamable = true;
ControlSlots = 1;
MinTameSkill = 59.1;
}
public override int Meat{ get{ return 2; } }
public override int Hides{ get{ return 16; } }
public override int Cloths{ get{ return 8; } }
public override ClothType ClothType{ get{ return ClothType.Furry; } }
public override FoodType FavoriteFood{ get{ return FoodType.Fish | FoodType.FruitsAndVegies | FoodType.Meat; } }
public override PackInstinct PackInstinct{ get{ return PackInstinct.Bear; } }
public GrizzlyBearRiding( Serial serial ) : base( serial )
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize( writer );
writer.Write( (int) 0 );
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
} | 412 | 0.840391 | 1 | 0.840391 | game-dev | MEDIA | 0.979629 | game-dev | 0.916436 | 1 | 0.916436 |
dfelinto/blender | 67,467 | source/blender/editors/space_clip/tracking_ops.c | /* SPDX-License-Identifier: GPL-2.0-or-later
* Copyright 2011 Blender Foundation. All rights reserved. */
/** \file
* \ingroup spclip
*/
#include "MEM_guardedalloc.h"
#include "DNA_screen_types.h"
#include "DNA_space_types.h"
#include "BLI_blenlib.h"
#include "BLI_ghash.h"
#include "BLI_math.h"
#include "BLI_utildefines.h"
#include "BKE_context.h"
#include "BKE_movieclip.h"
#include "BKE_report.h"
#include "BKE_tracking.h"
#include "DEG_depsgraph.h"
#include "WM_api.h"
#include "WM_types.h"
#include "ED_clip.h"
#include "ED_screen.h"
#include "RNA_access.h"
#include "RNA_define.h"
#include "BLT_translation.h"
#include "clip_intern.h"
#include "tracking_ops_intern.h"
/* -------------------------------------------------------------------- */
/** \name Add Marker Operator
* \{ */
static bool add_marker(const bContext *C, float x, float y)
{
SpaceClip *sc = CTX_wm_space_clip(C);
MovieClip *clip = ED_space_clip_get_clip(sc);
MovieTracking *tracking = &clip->tracking;
ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
ListBase *plane_tracks_base = BKE_tracking_get_active_plane_tracks(tracking);
MovieTrackingTrack *track;
int width, height;
int framenr = ED_space_clip_get_clip_frame_number(sc);
ED_space_clip_get_size(sc, &width, &height);
if (width == 0 || height == 0) {
return false;
}
track = BKE_tracking_track_add(tracking, tracksbase, x, y, framenr, width, height);
BKE_tracking_track_select(tracksbase, track, TRACK_AREA_ALL, 0);
BKE_tracking_plane_tracks_deselect_all(plane_tracks_base);
clip->tracking.act_track = track;
clip->tracking.act_plane_track = NULL;
return true;
}
static int add_marker_exec(bContext *C, wmOperator *op)
{
SpaceClip *sc = CTX_wm_space_clip(C);
MovieClip *clip = ED_space_clip_get_clip(sc);
float pos[2];
ClipViewLockState lock_state;
ED_clip_view_lock_state_store(C, &lock_state);
RNA_float_get_array(op->ptr, "location", pos);
if (!add_marker(C, pos[0], pos[1])) {
return OPERATOR_CANCELLED;
}
ED_clip_view_lock_state_restore_no_jump(C, &lock_state);
WM_event_add_notifier(C, NC_MOVIECLIP | NA_EDITED, clip);
return OPERATOR_FINISHED;
}
static int add_marker_invoke(bContext *C, wmOperator *op, const wmEvent *event)
{
SpaceClip *sc = CTX_wm_space_clip(C);
ARegion *region = CTX_wm_region(C);
if (!RNA_struct_property_is_set(op->ptr, "location")) {
/* If location is not set, use mouse position as default. */
float co[2];
ED_clip_mouse_pos(sc, region, event->mval, co);
RNA_float_set_array(op->ptr, "location", co);
}
return add_marker_exec(C, op);
}
void CLIP_OT_add_marker(wmOperatorType *ot)
{
/* identifiers */
ot->name = "Add Marker";
ot->idname = "CLIP_OT_add_marker";
ot->description = "Place new marker at specified location";
/* api callbacks */
ot->invoke = add_marker_invoke;
ot->exec = add_marker_exec;
ot->poll = ED_space_clip_tracking_poll;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
/* properties */
RNA_def_float_vector(ot->srna,
"location",
2,
NULL,
-FLT_MAX,
FLT_MAX,
"Location",
"Location of marker on frame",
-1.0f,
1.0f);
}
/** \} */
/* -------------------------------------------------------------------- */
/** \name Add Marker Operator
* \{ */
static int add_marker_at_click_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
{
ED_workspace_status_text(C, TIP_("Use LMB click to define location where place the marker"));
/* Add modal handler for ESC. */
WM_event_add_modal_handler(C, op);
return OPERATOR_RUNNING_MODAL;
}
static int add_marker_at_click_modal(bContext *C, wmOperator *UNUSED(op), const wmEvent *event)
{
switch (event->type) {
case MOUSEMOVE:
return OPERATOR_RUNNING_MODAL;
case LEFTMOUSE: {
SpaceClip *sc = CTX_wm_space_clip(C);
MovieClip *clip = ED_space_clip_get_clip(sc);
ARegion *region = CTX_wm_region(C);
float pos[2];
ED_workspace_status_text(C, NULL);
ED_clip_point_stable_pos(sc,
region,
event->xy[0] - region->winrct.xmin,
event->xy[1] - region->winrct.ymin,
&pos[0],
&pos[1]);
if (!add_marker(C, pos[0], pos[1])) {
return OPERATOR_CANCELLED;
}
WM_event_add_notifier(C, NC_MOVIECLIP | NA_EDITED, clip);
return OPERATOR_FINISHED;
}
case EVT_ESCKEY:
ED_workspace_status_text(C, NULL);
return OPERATOR_CANCELLED;
}
return OPERATOR_PASS_THROUGH;
}
void CLIP_OT_add_marker_at_click(wmOperatorType *ot)
{
/* identifiers */
ot->name = "Add Marker at Click";
ot->idname = "CLIP_OT_add_marker_at_click";
ot->description = "Place new marker at the desired (clicked) position";
/* api callbacks */
ot->invoke = add_marker_at_click_invoke;
ot->poll = ED_space_clip_tracking_poll;
ot->modal = add_marker_at_click_modal;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING;
}
/** \} */
/* -------------------------------------------------------------------- */
/** \name Delete Track Operator
* \{ */
static int delete_track_exec(bContext *C, wmOperator *UNUSED(op))
{
SpaceClip *sc = CTX_wm_space_clip(C);
MovieClip *clip = ED_space_clip_get_clip(sc);
MovieTracking *tracking = &clip->tracking;
bool changed = false;
/* Delete selected plane tracks. */
ListBase *plane_tracks_base = BKE_tracking_get_active_plane_tracks(tracking);
for (MovieTrackingPlaneTrack *plane_track = plane_tracks_base->first, *next_plane_track;
plane_track != NULL;
plane_track = next_plane_track) {
next_plane_track = plane_track->next;
if (PLANE_TRACK_VIEW_SELECTED(plane_track)) {
clip_delete_plane_track(C, clip, plane_track);
changed = true;
}
}
/* Remove selected point tracks (they'll also be removed from planes which
* uses them).
*/
ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
for (MovieTrackingTrack *track = tracksbase->first, *next_track; track != NULL;
track = next_track) {
next_track = track->next;
if (TRACK_VIEW_SELECTED(sc, track)) {
clip_delete_track(C, clip, track);
changed = true;
}
}
if (changed) {
WM_event_add_notifier(C, NC_MOVIECLIP | NA_EDITED, clip);
}
return OPERATOR_FINISHED;
}
void CLIP_OT_delete_track(wmOperatorType *ot)
{
/* identifiers */
ot->name = "Delete Track";
ot->idname = "CLIP_OT_delete_track";
ot->description = "Delete selected tracks";
/* api callbacks */
ot->invoke = WM_operator_confirm;
ot->exec = delete_track_exec;
ot->poll = ED_space_clip_tracking_poll;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
/** \} */
/* -------------------------------------------------------------------- */
/** \name Delete Marker Operator
* \{ */
static int delete_marker_exec(bContext *C, wmOperator *UNUSED(op))
{
SpaceClip *sc = CTX_wm_space_clip(C);
MovieClip *clip = ED_space_clip_get_clip(sc);
MovieTracking *tracking = &clip->tracking;
const int framenr = ED_space_clip_get_clip_frame_number(sc);
bool changed = false;
ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
for (MovieTrackingTrack *track = tracksbase->first, *next_track; track != NULL;
track = next_track) {
next_track = track->next;
if (TRACK_VIEW_SELECTED(sc, track)) {
MovieTrackingMarker *marker = BKE_tracking_marker_get_exact(track, framenr);
if (marker != NULL) {
clip_delete_marker(C, clip, track, marker);
changed = true;
}
}
}
ListBase *plane_tracks_base = BKE_tracking_get_active_plane_tracks(tracking);
for (MovieTrackingPlaneTrack *plane_track = plane_tracks_base->first, *plane_track_next;
plane_track != NULL;
plane_track = plane_track_next) {
plane_track_next = plane_track->next;
if (PLANE_TRACK_VIEW_SELECTED(plane_track)) {
MovieTrackingPlaneMarker *plane_marker = BKE_tracking_plane_marker_get_exact(plane_track,
framenr);
if (plane_marker != NULL) {
if (plane_track->markersnr == 1) {
BKE_tracking_plane_track_free(plane_track);
BLI_freelinkN(plane_tracks_base, plane_track);
}
else {
BKE_tracking_plane_marker_delete(plane_track, framenr);
}
changed = true;
}
}
}
if (!changed) {
return OPERATOR_CANCELLED;
}
return OPERATOR_FINISHED;
}
void CLIP_OT_delete_marker(wmOperatorType *ot)
{
/* identifiers */
ot->name = "Delete Marker";
ot->idname = "CLIP_OT_delete_marker";
ot->description = "Delete marker for current frame from selected tracks";
/* api callbacks */
ot->invoke = WM_operator_confirm;
ot->exec = delete_marker_exec;
ot->poll = ED_space_clip_tracking_poll;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
/** \} */
/* -------------------------------------------------------------------- */
/** \name Slide Marker Operator
* \{ */
enum {
SLIDE_ACTION_POS = 0,
SLIDE_ACTION_SIZE,
SLIDE_ACTION_OFFSET,
SLIDE_ACTION_TILT_SIZE,
};
typedef struct {
short area, action;
MovieTrackingTrack *track;
MovieTrackingMarker *marker;
int mval[2];
int width, height;
float *min, *max, *pos, *offset, (*corners)[2];
float spos[2];
bool lock, accurate;
/* Data to restore on cancel. */
float old_search_min[2], old_search_max[2], old_pos[2], old_offset[2];
float old_corners[4][2];
float (*old_markers)[2];
} SlideMarkerData;
static void slide_marker_tilt_slider(const MovieTrackingMarker *marker, float r_slider[2])
{
add_v2_v2v2(r_slider, marker->pattern_corners[1], marker->pattern_corners[2]);
add_v2_v2(r_slider, marker->pos);
}
static SlideMarkerData *create_slide_marker_data(SpaceClip *sc,
MovieTrackingTrack *track,
MovieTrackingMarker *marker,
const wmEvent *event,
int area,
int corner,
int action,
int width,
int height)
{
SlideMarkerData *data = MEM_callocN(sizeof(SlideMarkerData), "slide marker data");
int framenr = ED_space_clip_get_clip_frame_number(sc);
marker = BKE_tracking_marker_ensure(track, framenr);
data->area = area;
data->action = action;
data->track = track;
data->marker = marker;
if (area == TRACK_AREA_POINT) {
data->pos = marker->pos;
data->offset = track->offset;
}
else if (area == TRACK_AREA_PAT) {
if (action == SLIDE_ACTION_SIZE) {
data->corners = marker->pattern_corners;
}
else if (action == SLIDE_ACTION_OFFSET) {
data->pos = marker->pos;
data->offset = track->offset;
data->old_markers = MEM_callocN(sizeof(*data->old_markers) * track->markersnr,
"slide markers");
for (int a = 0; a < track->markersnr; a++) {
copy_v2_v2(data->old_markers[a], track->markers[a].pos);
}
}
else if (action == SLIDE_ACTION_POS) {
data->corners = marker->pattern_corners;
data->pos = marker->pattern_corners[corner];
copy_v2_v2(data->spos, data->pos);
}
else if (action == SLIDE_ACTION_TILT_SIZE) {
data->corners = marker->pattern_corners;
slide_marker_tilt_slider(marker, data->spos);
}
}
else if (area == TRACK_AREA_SEARCH) {
data->min = marker->search_min;
data->max = marker->search_max;
}
data->mval[0] = event->mval[0];
data->mval[1] = event->mval[1];
data->width = width;
data->height = height;
if (action == SLIDE_ACTION_SIZE) {
data->lock = true;
}
/* Backup marker's settings. */
memcpy(data->old_corners, marker->pattern_corners, sizeof(data->old_corners));
copy_v2_v2(data->old_search_min, marker->search_min);
copy_v2_v2(data->old_search_max, marker->search_max);
copy_v2_v2(data->old_pos, marker->pos);
copy_v2_v2(data->old_offset, track->offset);
return data;
}
static float mouse_to_slide_zone_distance_squared(const float co[2],
const float slide_zone[2],
int width,
int height)
{
const float pixel_co[2] = {co[0] * width, co[1] * height},
pixel_slide_zone[2] = {slide_zone[0] * width, slide_zone[1] * height};
return square_f(pixel_co[0] - pixel_slide_zone[0]) + square_f(pixel_co[1] - pixel_slide_zone[1]);
}
static float mouse_to_search_corner_distance_squared(
const MovieTrackingMarker *marker, const float co[2], int corner, int width, int height)
{
float side_zone[2];
if (corner == 0) {
side_zone[0] = marker->pos[0] + marker->search_max[0];
side_zone[1] = marker->pos[1] + marker->search_min[1];
}
else {
side_zone[0] = marker->pos[0] + marker->search_min[0];
side_zone[1] = marker->pos[1] + marker->search_max[1];
}
return mouse_to_slide_zone_distance_squared(co, side_zone, width, height);
}
static float mouse_to_closest_pattern_corner_distance_squared(
const MovieTrackingMarker *marker, const float co[2], int width, int height, int *r_corner)
{
float min_distance_squared = FLT_MAX;
for (int i = 0; i < 4; i++) {
float corner_co[2];
add_v2_v2v2(corner_co, marker->pattern_corners[i], marker->pos);
float distance_squared = mouse_to_slide_zone_distance_squared(co, corner_co, width, height);
if (distance_squared < min_distance_squared) {
min_distance_squared = distance_squared;
*r_corner = i;
}
}
return min_distance_squared;
}
static float mouse_to_offset_distance_squared(const MovieTrackingTrack *track,
const MovieTrackingMarker *marker,
const float co[2],
int width,
int height)
{
float pos[2];
add_v2_v2v2(pos, marker->pos, track->offset);
return mouse_to_slide_zone_distance_squared(co, pos, width, height);
}
static int mouse_to_tilt_distance_squared(const MovieTrackingMarker *marker,
const float co[2],
int width,
int height)
{
float slider[2];
slide_marker_tilt_slider(marker, slider);
return mouse_to_slide_zone_distance_squared(co, slider, width, height);
}
static bool slide_check_corners(float (*corners)[2])
{
float cross = 0.0f;
const float p[2] = {0.0f, 0.0f};
if (!isect_point_quad_v2(p, corners[0], corners[1], corners[2], corners[3])) {
return false;
}
for (int i = 0; i < 4; i++) {
float v1[2], v2[2];
int next = (i + 1) % 4;
int prev = (4 + i - 1) % 4;
sub_v2_v2v2(v1, corners[i], corners[prev]);
sub_v2_v2v2(v2, corners[next], corners[i]);
float cur_cross = cross_v2v2(v1, v2);
if (fabsf(cur_cross) > FLT_EPSILON) {
if (cross == 0.0f) {
cross = cur_cross;
}
else if (cross * cur_cross < 0.0f) {
return false;
}
}
}
return true;
}
MovieTrackingTrack *tracking_marker_check_slide(
bContext *C, const wmEvent *event, int *r_area, int *r_action, int *r_corner)
{
const float distance_clip_squared = 12.0f * 12.0f;
SpaceClip *sc = CTX_wm_space_clip(C);
ARegion *region = CTX_wm_region(C);
MovieClip *clip = ED_space_clip_get_clip(sc);
MovieTrackingTrack *track;
int width, height;
float co[2];
ListBase *tracksbase = BKE_tracking_get_active_tracks(&clip->tracking);
int framenr = ED_space_clip_get_clip_frame_number(sc);
float global_min_distance_squared = FLT_MAX;
/* Sliding zone designator which is the closest to the mouse
* across all the tracks.
*/
int min_action = -1, min_area = 0, min_corner = -1;
MovieTrackingTrack *min_track = NULL;
ED_space_clip_get_size(sc, &width, &height);
if (width == 0 || height == 0) {
return NULL;
}
ED_clip_mouse_pos(sc, region, event->mval, co);
track = tracksbase->first;
while (track) {
if (TRACK_VIEW_SELECTED(sc, track) && (track->flag & TRACK_LOCKED) == 0) {
const MovieTrackingMarker *marker = BKE_tracking_marker_get(track, framenr);
/* Sliding zone designator which is the closest to the mouse for
* the current tracks.
*/
float min_distance_squared = FLT_MAX;
int action = -1, area = 0, corner = -1;
if ((marker->flag & MARKER_DISABLED) == 0) {
float distance_squared;
/* We start checking with whether the mouse is close enough
* to the pattern offset area.
*/
distance_squared = mouse_to_offset_distance_squared(track, marker, co, width, height);
area = TRACK_AREA_POINT;
action = SLIDE_ACTION_POS;
/* NOTE: All checks here are assuming there's no maximum distance
* limit, so checks are quite simple here.
* Actual distance clipping happens later once all the sliding
* zones are checked.
*/
min_distance_squared = distance_squared;
/* If search area is visible, check how close to its sliding
* zones mouse is.
*/
if (sc->flag & SC_SHOW_MARKER_SEARCH) {
distance_squared = mouse_to_search_corner_distance_squared(marker, co, 1, width, height);
if (distance_squared < min_distance_squared) {
area = TRACK_AREA_SEARCH;
action = SLIDE_ACTION_OFFSET;
min_distance_squared = distance_squared;
}
distance_squared = mouse_to_search_corner_distance_squared(marker, co, 0, width, height);
if (distance_squared < min_distance_squared) {
area = TRACK_AREA_SEARCH;
action = SLIDE_ACTION_SIZE;
min_distance_squared = distance_squared;
}
}
/* If pattern area is visible, check which corner is closest to
* the mouse.
*/
if (sc->flag & SC_SHOW_MARKER_PATTERN) {
int current_corner = -1;
distance_squared = mouse_to_closest_pattern_corner_distance_squared(
marker, co, width, height, ¤t_corner);
if (distance_squared < min_distance_squared) {
area = TRACK_AREA_PAT;
action = SLIDE_ACTION_POS;
corner = current_corner;
min_distance_squared = distance_squared;
}
/* Here we also check whether the mouse is actually closer to
* the widget which controls scale and tilt.
*/
distance_squared = mouse_to_tilt_distance_squared(marker, co, width, height);
if (distance_squared < min_distance_squared) {
area = TRACK_AREA_PAT;
action = SLIDE_ACTION_TILT_SIZE;
min_distance_squared = distance_squared;
}
}
if (min_distance_squared < global_min_distance_squared) {
min_area = area;
min_action = action;
min_corner = corner;
min_track = track;
global_min_distance_squared = min_distance_squared;
}
}
}
track = track->next;
}
if (global_min_distance_squared < distance_clip_squared / sc->zoom) {
if (r_area) {
*r_area = min_area;
}
if (r_action) {
*r_action = min_action;
}
if (r_corner) {
*r_corner = min_corner;
}
return min_track;
}
return NULL;
}
static void *slide_marker_customdata(bContext *C, const wmEvent *event)
{
SpaceClip *sc = CTX_wm_space_clip(C);
ARegion *region = CTX_wm_region(C);
MovieTrackingTrack *track;
int width, height;
float co[2];
void *customdata = NULL;
int framenr = ED_space_clip_get_clip_frame_number(sc);
int area, action, corner;
ED_space_clip_get_size(sc, &width, &height);
if (width == 0 || height == 0) {
return NULL;
}
ED_clip_mouse_pos(sc, region, event->mval, co);
track = tracking_marker_check_slide(C, event, &area, &action, &corner);
if (track != NULL) {
MovieTrackingMarker *marker = BKE_tracking_marker_get(track, framenr);
customdata = create_slide_marker_data(
sc, track, marker, event, area, corner, action, width, height);
}
return customdata;
}
static int slide_marker_invoke(bContext *C, wmOperator *op, const wmEvent *event)
{
SlideMarkerData *slidedata = slide_marker_customdata(C, event);
if (slidedata != NULL) {
SpaceClip *sc = CTX_wm_space_clip(C);
MovieClip *clip = ED_space_clip_get_clip(sc);
MovieTracking *tracking = &clip->tracking;
tracking->act_track = slidedata->track;
tracking->act_plane_track = NULL;
op->customdata = slidedata;
clip_tracking_hide_cursor(C);
WM_event_add_modal_handler(C, op);
WM_event_add_notifier(C, NC_GEOM | ND_SELECT, NULL);
return OPERATOR_RUNNING_MODAL;
}
return OPERATOR_PASS_THROUGH;
}
static void cancel_mouse_slide(SlideMarkerData *data)
{
MovieTrackingTrack *track = data->track;
MovieTrackingMarker *marker = data->marker;
memcpy(marker->pattern_corners, data->old_corners, sizeof(marker->pattern_corners));
copy_v2_v2(marker->search_min, data->old_search_min);
copy_v2_v2(marker->search_max, data->old_search_max);
copy_v2_v2(marker->pos, data->old_pos);
copy_v2_v2(track->offset, data->old_offset);
if (data->old_markers != NULL) {
for (int a = 0; a < data->track->markersnr; a++) {
copy_v2_v2(data->track->markers[a].pos, data->old_markers[a]);
}
}
}
static void apply_mouse_slide(bContext *C, SlideMarkerData *data)
{
if (data->area == TRACK_AREA_POINT) {
SpaceClip *sc = CTX_wm_space_clip(C);
MovieClip *clip = ED_space_clip_get_clip(sc);
MovieTracking *tracking = &clip->tracking;
ListBase *plane_tracks_base = BKE_tracking_get_active_plane_tracks(tracking);
int framenr = ED_space_clip_get_clip_frame_number(sc);
for (MovieTrackingPlaneTrack *plane_track = plane_tracks_base->first; plane_track != NULL;
plane_track = plane_track->next) {
if ((plane_track->flag & PLANE_TRACK_AUTOKEY) == 0) {
if (BKE_tracking_plane_track_has_point_track(plane_track, data->track)) {
BKE_tracking_track_plane_from_existing_motion(plane_track, framenr);
}
}
}
}
}
static void free_slide_data(SlideMarkerData *data)
{
if (data->old_markers != NULL) {
MEM_freeN(data->old_markers);
}
MEM_freeN(data);
}
static int slide_marker_modal(bContext *C, wmOperator *op, const wmEvent *event)
{
SpaceClip *sc = CTX_wm_space_clip(C);
ARegion *region = CTX_wm_region(C);
SlideMarkerData *data = (SlideMarkerData *)op->customdata;
float dx, dy, mdelta[2];
switch (event->type) {
case EVT_LEFTCTRLKEY:
case EVT_RIGHTCTRLKEY:
case EVT_LEFTSHIFTKEY:
case EVT_RIGHTSHIFTKEY:
if (data->action == SLIDE_ACTION_SIZE) {
if (ELEM(event->type, EVT_LEFTCTRLKEY, EVT_RIGHTCTRLKEY)) {
data->lock = event->val == KM_RELEASE;
}
}
if (ELEM(event->type, EVT_LEFTSHIFTKEY, EVT_RIGHTSHIFTKEY)) {
data->accurate = event->val == KM_PRESS;
}
ATTR_FALLTHROUGH;
case MOUSEMOVE:
mdelta[0] = event->mval[0] - data->mval[0];
mdelta[1] = event->mval[1] - data->mval[1];
dx = mdelta[0] / data->width / sc->zoom;
if (data->lock) {
dy = -dx / data->height * data->width;
}
else {
dy = mdelta[1] / data->height / sc->zoom;
}
if (data->accurate) {
dx /= 5.0f;
dy /= 5.0f;
}
if (data->area == TRACK_AREA_POINT) {
if (data->action == SLIDE_ACTION_OFFSET) {
data->offset[0] = data->old_offset[0] + dx;
data->offset[1] = data->old_offset[1] + dy;
}
else {
data->pos[0] = data->old_pos[0] + dx;
data->pos[1] = data->old_pos[1] + dy;
}
WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
DEG_id_tag_update(&sc->clip->id, 0);
}
else if (data->area == TRACK_AREA_PAT) {
if (data->action == SLIDE_ACTION_SIZE) {
float start[2], end[2];
float scale;
ED_clip_point_stable_pos(sc, region, data->mval[0], data->mval[1], &start[0], &start[1]);
sub_v2_v2(start, data->old_pos);
if (len_squared_v2(start) != 0.0f) {
float mval[2];
if (data->accurate) {
mval[0] = data->mval[0] + (event->mval[0] - data->mval[0]) / 5.0f;
mval[1] = data->mval[1] + (event->mval[1] - data->mval[1]) / 5.0f;
}
else {
mval[0] = event->mval[0];
mval[1] = event->mval[1];
}
ED_clip_point_stable_pos(sc, region, mval[0], mval[1], &end[0], &end[1]);
sub_v2_v2(end, data->old_pos);
scale = len_v2(end) / len_v2(start);
if (scale > 0.0f) {
for (int a = 0; a < 4; a++) {
mul_v2_v2fl(data->corners[a], data->old_corners[a], scale);
}
}
}
BKE_tracking_marker_clamp(data->marker, CLAMP_PAT_DIM);
}
else if (data->action == SLIDE_ACTION_OFFSET) {
const float d[2] = {dx, dy};
for (int a = 0; a < data->track->markersnr; a++) {
add_v2_v2v2(data->track->markers[a].pos, data->old_markers[a], d);
}
sub_v2_v2v2(data->offset, data->old_offset, d);
}
else if (data->action == SLIDE_ACTION_POS) {
float spos[2];
copy_v2_v2(spos, data->pos);
data->pos[0] = data->spos[0] + dx;
data->pos[1] = data->spos[1] + dy;
if (!slide_check_corners(data->corners)) {
copy_v2_v2(data->pos, spos);
}
/* Currently only patterns are allowed to have such
* combination of event and data.
*/
BKE_tracking_marker_clamp(data->marker, CLAMP_PAT_DIM);
}
else if (data->action == SLIDE_ACTION_TILT_SIZE) {
float start[2], end[2];
float scale = 1.0f, angle = 0.0f;
float mval[2];
if (data->accurate) {
mval[0] = data->mval[0] + (event->mval[0] - data->mval[0]) / 5.0f;
mval[1] = data->mval[1] + (event->mval[1] - data->mval[1]) / 5.0f;
}
else {
mval[0] = event->mval[0];
mval[1] = event->mval[1];
}
sub_v2_v2v2(start, data->spos, data->old_pos);
ED_clip_point_stable_pos(sc, region, mval[0], mval[1], &end[0], &end[1]);
sub_v2_v2(end, data->old_pos);
if (len_squared_v2(start) != 0.0f) {
scale = len_v2(end) / len_v2(start);
if (scale < 0.0f) {
scale = 0.0;
}
}
angle = -angle_signed_v2v2(start, end);
for (int a = 0; a < 4; a++) {
float vec[2];
mul_v2_v2fl(data->corners[a], data->old_corners[a], scale);
copy_v2_v2(vec, data->corners[a]);
vec[0] *= data->width;
vec[1] *= data->height;
data->corners[a][0] = (vec[0] * cosf(angle) - vec[1] * sinf(angle)) / data->width;
data->corners[a][1] = (vec[1] * cosf(angle) + vec[0] * sinf(angle)) / data->height;
}
BKE_tracking_marker_clamp(data->marker, CLAMP_PAT_DIM);
}
}
else if (data->area == TRACK_AREA_SEARCH) {
if (data->action == SLIDE_ACTION_SIZE) {
data->min[0] = data->old_search_min[0] - dx;
data->max[0] = data->old_search_max[0] + dx;
data->min[1] = data->old_search_min[1] + dy;
data->max[1] = data->old_search_max[1] - dy;
BKE_tracking_marker_clamp(data->marker, CLAMP_SEARCH_DIM);
}
else if (data->area == TRACK_AREA_SEARCH) {
const float d[2] = {dx, dy};
add_v2_v2v2(data->min, data->old_search_min, d);
add_v2_v2v2(data->max, data->old_search_max, d);
}
BKE_tracking_marker_clamp(data->marker, CLAMP_SEARCH_POS);
}
data->marker->flag &= ~MARKER_TRACKED;
WM_event_add_notifier(C, NC_MOVIECLIP | NA_EDITED, NULL);
break;
case LEFTMOUSE:
if (event->val == KM_RELEASE) {
apply_mouse_slide(C, op->customdata);
free_slide_data(op->customdata);
clip_tracking_show_cursor(C);
return OPERATOR_FINISHED;
}
break;
case EVT_ESCKEY:
cancel_mouse_slide(op->customdata);
free_slide_data(op->customdata);
clip_tracking_show_cursor(C);
WM_event_add_notifier(C, NC_MOVIECLIP | NA_EDITED, NULL);
return OPERATOR_CANCELLED;
}
return OPERATOR_RUNNING_MODAL;
}
void CLIP_OT_slide_marker(wmOperatorType *ot)
{
/* identifiers */
ot->name = "Slide Marker";
ot->description = "Slide marker areas";
ot->idname = "CLIP_OT_slide_marker";
/* api callbacks */
ot->poll = ED_space_clip_tracking_poll;
ot->invoke = slide_marker_invoke;
ot->modal = slide_marker_modal;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_GRAB_CURSOR_XY | OPTYPE_BLOCKING;
/* properties */
RNA_def_float_vector(ot->srna,
"offset",
2,
NULL,
-FLT_MAX,
FLT_MAX,
"Offset",
"Offset in floating-point units, 1.0 is the width and height of the image",
-FLT_MAX,
FLT_MAX);
}
/** \} */
/* -------------------------------------------------------------------- */
/** \name Clear Track Operator
* \{ */
static int clear_track_path_exec(bContext *C, wmOperator *op)
{
SpaceClip *sc = CTX_wm_space_clip(C);
MovieClip *clip = ED_space_clip_get_clip(sc);
MovieTracking *tracking = &clip->tracking;
ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
int action = RNA_enum_get(op->ptr, "action");
const bool clear_active = RNA_boolean_get(op->ptr, "clear_active");
int framenr = ED_space_clip_get_clip_frame_number(sc);
if (clear_active) {
MovieTrackingTrack *track = BKE_tracking_track_get_active(tracking);
if (track != NULL) {
BKE_tracking_track_path_clear(track, framenr, action);
}
}
else {
for (MovieTrackingTrack *track = tracksbase->first; track != NULL; track = track->next) {
if (TRACK_VIEW_SELECTED(sc, track)) {
BKE_tracking_track_path_clear(track, framenr, action);
}
}
}
BKE_tracking_dopesheet_tag_update(tracking);
WM_event_add_notifier(C, NC_MOVIECLIP | NA_EVALUATED, clip);
return OPERATOR_FINISHED;
}
void CLIP_OT_clear_track_path(wmOperatorType *ot)
{
static const EnumPropertyItem clear_path_actions[] = {
{TRACK_CLEAR_UPTO, "UPTO", 0, "Clear Up To", "Clear path up to current frame"},
{TRACK_CLEAR_REMAINED,
"REMAINED",
0,
"Clear Remained",
"Clear path at remaining frames (after current)"},
{TRACK_CLEAR_ALL, "ALL", 0, "Clear All", "Clear the whole path"},
{0, NULL, 0, NULL, NULL},
};
/* identifiers */
ot->name = "Clear Track Path";
ot->description = "Clear tracks after/before current position or clear the whole track";
ot->idname = "CLIP_OT_clear_track_path";
/* api callbacks */
ot->exec = clear_track_path_exec;
ot->poll = ED_space_clip_tracking_poll;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
/* properties */
RNA_def_enum(ot->srna,
"action",
clear_path_actions,
TRACK_CLEAR_REMAINED,
"Action",
"Clear action to execute");
RNA_def_boolean(ot->srna,
"clear_active",
0,
"Clear Active",
"Clear active track only instead of all selected tracks");
}
/** \} */
/* -------------------------------------------------------------------- */
/** \name Disable Markers Operator
* \{ */
enum {
MARKER_OP_DISABLE = 0,
MARKER_OP_ENABLE = 1,
MARKER_OP_TOGGLE = 2,
};
static int disable_markers_exec(bContext *C, wmOperator *op)
{
SpaceClip *sc = CTX_wm_space_clip(C);
MovieClip *clip = ED_space_clip_get_clip(sc);
MovieTracking *tracking = &clip->tracking;
ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
int action = RNA_enum_get(op->ptr, "action");
int framenr = ED_space_clip_get_clip_frame_number(sc);
for (MovieTrackingTrack *track = tracksbase->first; track != NULL; track = track->next) {
if (TRACK_VIEW_SELECTED(sc, track) && (track->flag & TRACK_LOCKED) == 0) {
MovieTrackingMarker *marker = BKE_tracking_marker_ensure(track, framenr);
switch (action) {
case MARKER_OP_DISABLE:
marker->flag |= MARKER_DISABLED;
break;
case MARKER_OP_ENABLE:
marker->flag &= ~MARKER_DISABLED;
break;
case MARKER_OP_TOGGLE:
marker->flag ^= MARKER_DISABLED;
break;
}
}
}
DEG_id_tag_update(&clip->id, 0);
WM_event_add_notifier(C, NC_MOVIECLIP | NA_EVALUATED, clip);
return OPERATOR_FINISHED;
}
void CLIP_OT_disable_markers(wmOperatorType *ot)
{
static const EnumPropertyItem actions_items[] = {
{MARKER_OP_DISABLE, "DISABLE", 0, "Disable", "Disable selected markers"},
{MARKER_OP_ENABLE, "ENABLE", 0, "Enable", "Enable selected markers"},
{MARKER_OP_TOGGLE, "TOGGLE", 0, "Toggle", "Toggle disabled flag for selected markers"},
{0, NULL, 0, NULL, NULL},
};
/* identifiers */
ot->name = "Disable Markers";
ot->description = "Disable/enable selected markers";
ot->idname = "CLIP_OT_disable_markers";
/* api callbacks */
ot->exec = disable_markers_exec;
ot->poll = ED_space_clip_tracking_poll;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
/* properties */
RNA_def_enum(ot->srna, "action", actions_items, 0, "Action", "Disable action to execute");
}
/** \} */
/* -------------------------------------------------------------------- */
/** \name Set Principal Center Operator
* \{ */
static int set_center_principal_exec(bContext *C, wmOperator *UNUSED(op))
{
SpaceClip *sc = CTX_wm_space_clip(C);
MovieClip *clip = ED_space_clip_get_clip(sc);
int width, height;
BKE_movieclip_get_size(clip, &sc->user, &width, &height);
if (width == 0 || height == 0) {
return OPERATOR_CANCELLED;
}
clip->tracking.camera.principal[0] = ((float)width) / 2.0f;
clip->tracking.camera.principal[1] = ((float)height) / 2.0f;
WM_event_add_notifier(C, NC_MOVIECLIP | NA_EDITED, clip);
return OPERATOR_FINISHED;
}
void CLIP_OT_set_center_principal(wmOperatorType *ot)
{
/* identifiers */
ot->name = "Set Principal to Center";
ot->description = "Set optical center to center of footage";
ot->idname = "CLIP_OT_set_center_principal";
/* api callbacks */
ot->exec = set_center_principal_exec;
ot->poll = ED_space_clip_tracking_poll;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
/** \} */
/* -------------------------------------------------------------------- */
/** \name Hide Tracks Operator
* \{ */
static int hide_tracks_exec(bContext *C, wmOperator *op)
{
SpaceClip *sc = CTX_wm_space_clip(C);
MovieClip *clip = ED_space_clip_get_clip(sc);
MovieTracking *tracking = &clip->tracking;
int unselected;
unselected = RNA_boolean_get(op->ptr, "unselected");
/* Hide point tracks. */
ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
MovieTrackingTrack *act_track = BKE_tracking_track_get_active(tracking);
for (MovieTrackingTrack *track = tracksbase->first; track != NULL; track = track->next) {
if (unselected == 0 && TRACK_VIEW_SELECTED(sc, track)) {
track->flag |= TRACK_HIDDEN;
}
else if (unselected == 1 && !TRACK_VIEW_SELECTED(sc, track)) {
track->flag |= TRACK_HIDDEN;
}
}
if (act_track != NULL && act_track->flag & TRACK_HIDDEN) {
clip->tracking.act_track = NULL;
}
/* Hide place tracks. */
ListBase *plane_tracks_base = BKE_tracking_get_active_plane_tracks(tracking);
MovieTrackingPlaneTrack *act_plane_track = BKE_tracking_plane_track_get_active(tracking);
for (MovieTrackingPlaneTrack *plane_track = plane_tracks_base->first; plane_track != NULL;
plane_track = plane_track->next) {
if (unselected == 0 && plane_track->flag & SELECT) {
plane_track->flag |= PLANE_TRACK_HIDDEN;
}
else if (unselected == 1 && (plane_track->flag & SELECT) == 0) {
plane_track->flag |= PLANE_TRACK_HIDDEN;
}
}
if (act_plane_track != NULL && act_plane_track->flag & TRACK_HIDDEN) {
clip->tracking.act_plane_track = NULL;
}
BKE_tracking_dopesheet_tag_update(tracking);
WM_event_add_notifier(C, NC_MOVIECLIP | ND_DISPLAY, NULL);
return OPERATOR_FINISHED;
}
void CLIP_OT_hide_tracks(wmOperatorType *ot)
{
/* identifiers */
ot->name = "Hide Tracks";
ot->description = "Hide selected tracks";
ot->idname = "CLIP_OT_hide_tracks";
/* api callbacks */
ot->exec = hide_tracks_exec;
ot->poll = ED_space_clip_tracking_poll;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
/* properties */
RNA_def_boolean(ot->srna, "unselected", 0, "Unselected", "Hide unselected tracks");
}
/** \} */
/* -------------------------------------------------------------------- */
/** \name Hide Tracks Clear Operator
* \{ */
static int hide_tracks_clear_exec(bContext *C, wmOperator *UNUSED(op))
{
SpaceClip *sc = CTX_wm_space_clip(C);
MovieClip *clip = ED_space_clip_get_clip(sc);
MovieTracking *tracking = &clip->tracking;
/* Unhide point tracks. */
ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
for (MovieTrackingTrack *track = tracksbase->first; track != NULL; track = track->next) {
track->flag &= ~TRACK_HIDDEN;
}
/* Unhide plane tracks. */
ListBase *plane_tracks_base = BKE_tracking_get_active_plane_tracks(tracking);
for (MovieTrackingPlaneTrack *plane_track = plane_tracks_base->first; plane_track != NULL;
plane_track = plane_track->next) {
plane_track->flag &= ~PLANE_TRACK_HIDDEN;
}
BKE_tracking_dopesheet_tag_update(tracking);
WM_event_add_notifier(C, NC_MOVIECLIP | ND_DISPLAY, NULL);
return OPERATOR_FINISHED;
}
void CLIP_OT_hide_tracks_clear(wmOperatorType *ot)
{
/* identifiers */
ot->name = "Hide Tracks Clear";
ot->description = "Clear hide selected tracks";
ot->idname = "CLIP_OT_hide_tracks_clear";
/* api callbacks */
ot->exec = hide_tracks_clear_exec;
ot->poll = ED_space_clip_tracking_poll;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
/** \} */
/* -------------------------------------------------------------------- */
/** \name Frame Jump Operator
* \{ */
static bool frame_jump_poll(bContext *C)
{
SpaceClip *space_clip = CTX_wm_space_clip(C);
return space_clip != NULL;
}
static int frame_jump_exec(bContext *C, wmOperator *op)
{
Scene *scene = CTX_data_scene(C);
SpaceClip *sc = CTX_wm_space_clip(C);
MovieClip *clip = ED_space_clip_get_clip(sc);
MovieTracking *tracking = &clip->tracking;
int pos = RNA_enum_get(op->ptr, "position");
int delta;
if (pos <= 1) { /* jump to path */
MovieTrackingTrack *track = BKE_tracking_track_get_active(tracking);
if (track == NULL) {
return OPERATOR_CANCELLED;
}
delta = pos == 1 ? 1 : -1;
while (sc->user.framenr + delta >= SFRA && sc->user.framenr + delta <= EFRA) {
int framenr = BKE_movieclip_remap_scene_to_clip_frame(clip, sc->user.framenr + delta);
MovieTrackingMarker *marker = BKE_tracking_marker_get_exact(track, framenr);
if (marker == NULL || marker->flag & MARKER_DISABLED) {
break;
}
sc->user.framenr += delta;
}
}
else { /* to failed frame */
if (tracking->reconstruction.flag & TRACKING_RECONSTRUCTED) {
int framenr = ED_space_clip_get_clip_frame_number(sc);
MovieTrackingObject *object = BKE_tracking_object_get_active(tracking);
delta = pos == 3 ? 1 : -1;
framenr += delta;
while (framenr + delta >= SFRA && framenr + delta <= EFRA) {
MovieReconstructedCamera *cam = BKE_tracking_camera_get_reconstructed(
tracking, object, framenr);
if (cam == NULL) {
sc->user.framenr = BKE_movieclip_remap_clip_to_scene_frame(clip, framenr);
break;
}
framenr += delta;
}
}
}
if (CFRA != sc->user.framenr) {
CFRA = sc->user.framenr;
DEG_id_tag_update(&scene->id, ID_RECALC_FRAME_CHANGE);
WM_event_add_notifier(C, NC_SCENE | ND_FRAME, scene);
}
WM_event_add_notifier(C, NC_MOVIECLIP | ND_DISPLAY, NULL);
return OPERATOR_FINISHED;
}
void CLIP_OT_frame_jump(wmOperatorType *ot)
{
static const EnumPropertyItem position_items[] = {
{0, "PATHSTART", 0, "Path Start", "Jump to start of current path"},
{1, "PATHEND", 0, "Path End", "Jump to end of current path"},
{2, "FAILEDPREV", 0, "Previous Failed", "Jump to previous failed frame"},
{2, "FAILNEXT", 0, "Next Failed", "Jump to next failed frame"},
{0, NULL, 0, NULL, NULL},
};
/* identifiers */
ot->name = "Jump to Frame";
ot->description = "Jump to special frame";
ot->idname = "CLIP_OT_frame_jump";
/* api callbacks */
ot->exec = frame_jump_exec;
ot->poll = frame_jump_poll;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
/* properties */
RNA_def_enum(ot->srna, "position", position_items, 0, "Position", "Position to jump to");
}
/** \} */
/* -------------------------------------------------------------------- */
/** \name Join Tracks Operator
* \{ */
static int join_tracks_exec(bContext *C, wmOperator *op)
{
SpaceClip *sc = CTX_wm_space_clip(C);
MovieClip *clip = ED_space_clip_get_clip(sc);
MovieTracking *tracking = &clip->tracking;
MovieTrackingStabilization *stab = &tracking->stabilization;
ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
ListBase *plane_tracks_base = BKE_tracking_get_active_plane_tracks(tracking);
bool update_stabilization = false;
MovieTrackingTrack *act_track = BKE_tracking_track_get_active(tracking);
if (act_track == NULL) {
BKE_report(op->reports, RPT_ERROR, "No active track to join to");
return OPERATOR_CANCELLED;
}
GSet *point_tracks = BLI_gset_ptr_new(__func__);
for (MovieTrackingTrack *track = tracksbase->first, *next_track; track != NULL;
track = next_track) {
next_track = track->next;
if (TRACK_VIEW_SELECTED(sc, track) && track != act_track) {
BKE_tracking_tracks_join(tracking, act_track, track);
if (track->flag & TRACK_USE_2D_STAB) {
update_stabilization = true;
if ((act_track->flag & TRACK_USE_2D_STAB) == 0) {
act_track->flag |= TRACK_USE_2D_STAB;
}
else {
stab->tot_track--;
}
BLI_assert(0 <= stab->tot_track);
}
if (track->flag & TRACK_USE_2D_STAB_ROT) {
update_stabilization = true;
if ((act_track->flag & TRACK_USE_2D_STAB_ROT) == 0) {
act_track->flag |= TRACK_USE_2D_STAB_ROT;
}
else {
stab->tot_rot_track--;
}
BLI_assert(0 <= stab->tot_rot_track);
}
for (MovieTrackingPlaneTrack *plane_track = plane_tracks_base->first; plane_track != NULL;
plane_track = plane_track->next) {
if (BKE_tracking_plane_track_has_point_track(plane_track, track)) {
BKE_tracking_plane_track_replace_point_track(plane_track, track, act_track);
if ((plane_track->flag & PLANE_TRACK_AUTOKEY) == 0) {
BLI_gset_insert(point_tracks, plane_track);
}
}
}
BKE_tracking_track_free(track);
BLI_freelinkN(tracksbase, track);
}
}
if (update_stabilization) {
WM_event_add_notifier(C, NC_MOVIECLIP | ND_DISPLAY, clip);
}
GSetIterator gs_iter;
int framenr = ED_space_clip_get_clip_frame_number(sc);
GSET_ITER (gs_iter, point_tracks) {
MovieTrackingPlaneTrack *plane_track = BLI_gsetIterator_getKey(&gs_iter);
BKE_tracking_track_plane_from_existing_motion(plane_track, framenr);
}
BLI_gset_free(point_tracks, NULL);
DEG_id_tag_update(&clip->id, 0);
WM_event_add_notifier(C, NC_MOVIECLIP | NA_EDITED, clip);
return OPERATOR_FINISHED;
}
void CLIP_OT_join_tracks(wmOperatorType *ot)
{
/* identifiers */
ot->name = "Join Tracks";
ot->description = "Join selected tracks";
ot->idname = "CLIP_OT_join_tracks";
/* api callbacks */
ot->exec = join_tracks_exec;
ot->poll = ED_space_clip_tracking_poll;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
/** \} */
/* -------------------------------------------------------------------- */
/** \name Average Tracks Operator
* \{ */
static int average_tracks_exec(bContext *C, wmOperator *op)
{
SpaceClip *space_clip = CTX_wm_space_clip(C);
MovieClip *clip = ED_space_clip_get_clip(space_clip);
MovieTracking *tracking = &clip->tracking;
/* Collect source tracks. */
int num_source_tracks;
MovieTrackingTrack **source_tracks = BKE_tracking_selected_tracks_in_active_object(
tracking, &num_source_tracks);
if (num_source_tracks == 0) {
return OPERATOR_CANCELLED;
}
/* Create new empty track, which will be the averaged result.
* Makes it simple to average all selection to it. */
ListBase *tracks_list = BKE_tracking_get_active_tracks(tracking);
MovieTrackingTrack *result_track = BKE_tracking_track_add_empty(tracking, tracks_list);
/* Perform averaging. */
BKE_tracking_tracks_average(result_track, source_tracks, num_source_tracks);
const bool keep_original = RNA_boolean_get(op->ptr, "keep_original");
if (!keep_original) {
for (int i = 0; i < num_source_tracks; i++) {
clip_delete_track(C, clip, source_tracks[i]);
}
}
/* Update selection, making the result track active and selected. */
/* TODO(sergey): Should become some sort of utility function available for all operators. */
BKE_tracking_track_select(tracks_list, result_track, TRACK_AREA_ALL, 0);
ListBase *plane_tracks_list = BKE_tracking_get_active_plane_tracks(tracking);
BKE_tracking_plane_tracks_deselect_all(plane_tracks_list);
clip->tracking.act_track = result_track;
clip->tracking.act_plane_track = NULL;
/* Inform the dependency graph and interface about changes. */
DEG_id_tag_update(&clip->id, 0);
WM_event_add_notifier(C, NC_MOVIECLIP | NA_EDITED, clip);
/* Free memory. */
MEM_freeN(source_tracks);
return OPERATOR_FINISHED;
}
static int average_tracks_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
{
PropertyRNA *prop_keep_original = RNA_struct_find_property(op->ptr, "keep_original");
if (!RNA_property_is_set(op->ptr, prop_keep_original)) {
SpaceClip *space_clip = CTX_wm_space_clip(C);
MovieClip *clip = ED_space_clip_get_clip(space_clip);
MovieTracking *tracking = &clip->tracking;
const int num_selected_tracks = BKE_tracking_count_selected_tracks_in_active_object(tracking);
if (num_selected_tracks == 1) {
RNA_property_boolean_set(op->ptr, prop_keep_original, false);
}
}
return average_tracks_exec(C, op);
}
void CLIP_OT_average_tracks(wmOperatorType *ot)
{
/* Identifiers. */
ot->name = "Average Tracks";
ot->description = "Average selected tracks into active";
ot->idname = "CLIP_OT_average_tracks";
/* API callbacks. */
ot->exec = average_tracks_exec;
ot->invoke = average_tracks_invoke;
ot->poll = ED_space_clip_tracking_poll;
/* Flags. */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
/* Properties. */
PropertyRNA *prop;
prop = RNA_def_boolean(ot->srna, "keep_original", 1, "Keep Original", "Keep original tracks");
RNA_def_property_flag(prop, PROP_SKIP_SAVE);
}
/** \} */
/* -------------------------------------------------------------------- */
/** \name Lock Tracks Operator
* \{ */
enum {
TRACK_ACTION_LOCK = 0,
TRACK_ACTION_UNLOCK = 1,
TRACK_ACTION_TOGGLE = 2,
};
static int lock_tracks_exec(bContext *C, wmOperator *op)
{
SpaceClip *sc = CTX_wm_space_clip(C);
MovieClip *clip = ED_space_clip_get_clip(sc);
MovieTracking *tracking = &clip->tracking;
ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
int action = RNA_enum_get(op->ptr, "action");
for (MovieTrackingTrack *track = tracksbase->first; track != NULL; track = track->next) {
if (TRACK_VIEW_SELECTED(sc, track)) {
switch (action) {
case TRACK_ACTION_LOCK:
track->flag |= TRACK_LOCKED;
break;
case TRACK_ACTION_UNLOCK:
track->flag &= ~TRACK_LOCKED;
break;
case TRACK_ACTION_TOGGLE:
track->flag ^= TRACK_LOCKED;
break;
}
}
}
WM_event_add_notifier(C, NC_MOVIECLIP | NA_EVALUATED, clip);
return OPERATOR_FINISHED;
}
void CLIP_OT_lock_tracks(wmOperatorType *ot)
{
static const EnumPropertyItem actions_items[] = {
{TRACK_ACTION_LOCK, "LOCK", 0, "Lock", "Lock selected tracks"},
{TRACK_ACTION_UNLOCK, "UNLOCK", 0, "Unlock", "Unlock selected tracks"},
{TRACK_ACTION_TOGGLE, "TOGGLE", 0, "Toggle", "Toggle locked flag for selected tracks"},
{0, NULL, 0, NULL, NULL},
};
/* identifiers */
ot->name = "Lock Tracks";
ot->description = "Lock/unlock selected tracks";
ot->idname = "CLIP_OT_lock_tracks";
/* api callbacks */
ot->exec = lock_tracks_exec;
ot->poll = ED_space_clip_tracking_poll;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
/* properties */
RNA_def_enum(ot->srna, "action", actions_items, 0, "Action", "Lock action to execute");
}
/** \} */
/* -------------------------------------------------------------------- */
/** \name Set Keyframe Operator
* \{ */
enum {
SOLVER_KEYFRAME_A = 0,
SOLVER_KEYFRAME_B = 1,
};
static int set_solver_keyframe_exec(bContext *C, wmOperator *op)
{
SpaceClip *sc = CTX_wm_space_clip(C);
MovieClip *clip = ED_space_clip_get_clip(sc);
MovieTracking *tracking = &clip->tracking;
MovieTrackingObject *object = BKE_tracking_object_get_active(tracking);
int keyframe = RNA_enum_get(op->ptr, "keyframe");
int framenr = BKE_movieclip_remap_scene_to_clip_frame(clip, sc->user.framenr);
if (keyframe == SOLVER_KEYFRAME_A) {
object->keyframe1 = framenr;
}
else {
object->keyframe2 = framenr;
}
WM_event_add_notifier(C, NC_MOVIECLIP | ND_DISPLAY, clip);
return OPERATOR_FINISHED;
}
void CLIP_OT_set_solver_keyframe(wmOperatorType *ot)
{
static const EnumPropertyItem keyframe_items[] = {
{SOLVER_KEYFRAME_A, "KEYFRAME_A", 0, "Keyframe A", ""},
{SOLVER_KEYFRAME_B, "KEYFRAME_B", 0, "Keyframe B", ""},
{0, NULL, 0, NULL, NULL},
};
/* identifiers */
ot->name = "Set Solver Keyframe";
ot->description = "Set keyframe used by solver";
ot->idname = "CLIP_OT_set_solver_keyframe";
/* api callbacks */
ot->exec = set_solver_keyframe_exec;
ot->poll = ED_space_clip_tracking_poll;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
/* properties */
RNA_def_enum(ot->srna, "keyframe", keyframe_items, 0, "Keyframe", "Keyframe to set");
}
/** \} */
/* -------------------------------------------------------------------- */
/** \name Track Copy Color Operator
* \{ */
static int track_copy_color_exec(bContext *C, wmOperator *UNUSED(op))
{
SpaceClip *sc = CTX_wm_space_clip(C);
MovieClip *clip = ED_space_clip_get_clip(sc);
MovieTracking *tracking = &clip->tracking;
ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
MovieTrackingTrack *act_track = BKE_tracking_track_get_active(tracking);
if (act_track == NULL) {
return OPERATOR_CANCELLED;
}
for (MovieTrackingTrack *track = tracksbase->first; track != NULL; track = track->next) {
if (TRACK_VIEW_SELECTED(sc, track) && track != act_track) {
track->flag &= ~TRACK_CUSTOMCOLOR;
if (act_track->flag & TRACK_CUSTOMCOLOR) {
copy_v3_v3(track->color, act_track->color);
track->flag |= TRACK_CUSTOMCOLOR;
}
}
}
DEG_id_tag_update(&clip->id, 0);
WM_event_add_notifier(C, NC_MOVIECLIP | ND_DISPLAY, clip);
return OPERATOR_FINISHED;
}
void CLIP_OT_track_copy_color(wmOperatorType *ot)
{
/* identifiers */
ot->name = "Copy Color";
ot->description = "Copy color to all selected tracks";
ot->idname = "CLIP_OT_track_copy_color";
/* api callbacks */
ot->exec = track_copy_color_exec;
ot->poll = ED_space_clip_tracking_poll;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
/** \} */
/* -------------------------------------------------------------------- */
/** \name Clean Tracks Operator
* \{ */
static bool is_track_clean(MovieTrackingTrack *track, int frames, int del)
{
bool ok = true;
int prev = -1, count = 0;
MovieTrackingMarker *markers = track->markers, *new_markers = NULL;
int start_disabled = 0;
int markersnr = track->markersnr;
if (del) {
new_markers = MEM_callocN(markersnr * sizeof(MovieTrackingMarker), "track cleaned markers");
}
for (int a = 0; a < markersnr; a++) {
int end = 0;
if (prev == -1) {
if ((markers[a].flag & MARKER_DISABLED) == 0) {
prev = a;
}
else {
start_disabled = 1;
}
}
if (prev >= 0) {
end = a == markersnr - 1;
end |= (a < markersnr - 1) && (markers[a].framenr != markers[a + 1].framenr - 1 ||
markers[a].flag & MARKER_DISABLED);
}
if (end) {
int segok = 1, len = 0;
if (a != prev && markers[a].framenr != markers[a - 1].framenr + 1) {
len = a - prev;
}
else if (markers[a].flag & MARKER_DISABLED) {
len = a - prev;
}
else {
len = a - prev + 1;
}
if (frames) {
if (len < frames) {
segok = 0;
ok = 0;
if (!del) {
break;
}
}
}
if (del) {
if (segok) {
int t = len;
if (markers[a].flag & MARKER_DISABLED) {
t++;
}
/* Place disabled marker in front of current segment. */
if (start_disabled) {
memcpy(new_markers + count, markers + prev, sizeof(MovieTrackingMarker));
new_markers[count].framenr--;
new_markers[count].flag |= MARKER_DISABLED;
count++;
start_disabled = 0;
}
memcpy(new_markers + count, markers + prev, t * sizeof(MovieTrackingMarker));
count += t;
}
else if (markers[a].flag & MARKER_DISABLED) {
/* Current segment which would be deleted was finished by
* disabled marker, so next segment should be started from
* disabled marker.
*/
start_disabled = 1;
}
}
prev = -1;
}
}
if (del && count == 0) {
ok = 0;
}
if (del) {
MEM_freeN(track->markers);
if (count) {
track->markers = new_markers;
}
else {
track->markers = NULL;
MEM_freeN(new_markers);
}
track->markersnr = count;
}
return ok;
}
static int clean_tracks_exec(bContext *C, wmOperator *op)
{
SpaceClip *sc = CTX_wm_space_clip(C);
MovieClip *clip = ED_space_clip_get_clip(sc);
MovieTracking *tracking = &clip->tracking;
ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
MovieTrackingTrack *act_track = BKE_tracking_track_get_active(tracking);
int frames = RNA_int_get(op->ptr, "frames");
int action = RNA_enum_get(op->ptr, "action");
float error = RNA_float_get(op->ptr, "error");
if (error && action == TRACKING_CLEAN_DELETE_SEGMENT) {
action = TRACKING_CLEAN_DELETE_TRACK;
}
for (MovieTrackingTrack *track = tracksbase->first, *next_track; track != NULL;
track = next_track) {
next_track = track->next;
if ((track->flag & TRACK_HIDDEN) == 0 && (track->flag & TRACK_LOCKED) == 0) {
bool ok;
ok = (is_track_clean(track, frames, action == TRACKING_CLEAN_DELETE_SEGMENT)) &&
((error == 0.0f) || (track->flag & TRACK_HAS_BUNDLE) == 0 || (track->error < error));
if (!ok) {
if (action == TRACKING_CLEAN_SELECT) {
BKE_tracking_track_flag_set(track, TRACK_AREA_ALL, SELECT);
}
else if (action == TRACKING_CLEAN_DELETE_TRACK) {
if (track == act_track) {
clip->tracking.act_track = NULL;
}
BKE_tracking_track_free(track);
BLI_freelinkN(tracksbase, track);
track = NULL;
}
/* Happens when all tracking segments are not long enough. */
if (track && track->markersnr == 0) {
if (track == act_track) {
clip->tracking.act_track = NULL;
}
BKE_tracking_track_free(track);
BLI_freelinkN(tracksbase, track);
}
}
}
}
DEG_id_tag_update(&clip->id, 0);
BKE_tracking_dopesheet_tag_update(tracking);
WM_event_add_notifier(C, NC_MOVIECLIP | ND_SELECT, clip);
return OPERATOR_FINISHED;
}
static int clean_tracks_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
{
SpaceClip *sc = CTX_wm_space_clip(C);
MovieClip *clip = ED_space_clip_get_clip(sc);
if (!RNA_struct_property_is_set(op->ptr, "frames")) {
RNA_int_set(op->ptr, "frames", clip->tracking.settings.clean_frames);
}
if (!RNA_struct_property_is_set(op->ptr, "error")) {
RNA_float_set(op->ptr, "error", clip->tracking.settings.clean_error);
}
if (!RNA_struct_property_is_set(op->ptr, "action")) {
RNA_enum_set(op->ptr, "action", clip->tracking.settings.clean_action);
}
return clean_tracks_exec(C, op);
}
void CLIP_OT_clean_tracks(wmOperatorType *ot)
{
static const EnumPropertyItem actions_items[] = {
{TRACKING_CLEAN_SELECT, "SELECT", 0, "Select", "Select unclean tracks"},
{TRACKING_CLEAN_DELETE_TRACK, "DELETE_TRACK", 0, "Delete Track", "Delete unclean tracks"},
{TRACKING_CLEAN_DELETE_SEGMENT,
"DELETE_SEGMENTS",
0,
"Delete Segments",
"Delete unclean segments of tracks"},
{0, NULL, 0, NULL, NULL},
};
/* identifiers */
ot->name = "Clean Tracks";
ot->description = "Clean tracks with high error values or few frames";
ot->idname = "CLIP_OT_clean_tracks";
/* api callbacks */
ot->exec = clean_tracks_exec;
ot->invoke = clean_tracks_invoke;
ot->poll = ED_space_clip_tracking_poll;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
/* properties */
RNA_def_int(ot->srna,
"frames",
0,
0,
INT_MAX,
"Tracked Frames",
"Effect on tracks which are tracked less than "
"specified amount of frames",
0,
INT_MAX);
RNA_def_float(ot->srna,
"error",
0.0f,
0.0f,
FLT_MAX,
"Reprojection Error",
"Effect on tracks which have got larger reprojection error",
0.0f,
100.0f);
RNA_def_enum(ot->srna, "action", actions_items, 0, "Action", "Cleanup action to execute");
}
/** \} */
/* -------------------------------------------------------------------- */
/** \name Add Tracking Object
* \{ */
static int tracking_object_new_exec(bContext *C, wmOperator *UNUSED(op))
{
SpaceClip *sc = CTX_wm_space_clip(C);
MovieClip *clip = ED_space_clip_get_clip(sc);
MovieTracking *tracking = &clip->tracking;
BKE_tracking_object_add(tracking, "Object");
DEG_id_tag_update(&clip->id, ID_RECALC_COPY_ON_WRITE);
WM_event_add_notifier(C, NC_MOVIECLIP | NA_EDITED, clip);
return OPERATOR_FINISHED;
}
void CLIP_OT_tracking_object_new(wmOperatorType *ot)
{
/* identifiers */
ot->name = "Add Tracking Object";
ot->description = "Add new object for tracking";
ot->idname = "CLIP_OT_tracking_object_new";
/* api callbacks */
ot->exec = tracking_object_new_exec;
ot->poll = ED_space_clip_tracking_poll;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
/** \} */
/* -------------------------------------------------------------------- */
/** \name Remove Tracking Object
* \{ */
static int tracking_object_remove_exec(bContext *C, wmOperator *op)
{
SpaceClip *sc = CTX_wm_space_clip(C);
MovieClip *clip = ED_space_clip_get_clip(sc);
MovieTracking *tracking = &clip->tracking;
MovieTrackingObject *object;
object = BKE_tracking_object_get_active(tracking);
if (object->flag & TRACKING_OBJECT_CAMERA) {
BKE_report(op->reports, RPT_WARNING, "Object used for camera tracking cannot be deleted");
return OPERATOR_CANCELLED;
}
BKE_tracking_object_delete(tracking, object);
DEG_id_tag_update(&clip->id, ID_RECALC_COPY_ON_WRITE);
WM_event_add_notifier(C, NC_MOVIECLIP | NA_EDITED, clip);
return OPERATOR_FINISHED;
}
void CLIP_OT_tracking_object_remove(wmOperatorType *ot)
{
/* identifiers */
ot->name = "Remove Tracking Object";
ot->description = "Remove object for tracking";
ot->idname = "CLIP_OT_tracking_object_remove";
/* api callbacks */
ot->exec = tracking_object_remove_exec;
ot->poll = ED_space_clip_tracking_poll;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
/** \} */
/* -------------------------------------------------------------------- */
/** \name Copy Tracks to Clipboard Operator
* \{ */
static int copy_tracks_exec(bContext *C, wmOperator *UNUSED(op))
{
SpaceClip *sc = CTX_wm_space_clip(C);
MovieClip *clip = ED_space_clip_get_clip(sc);
MovieTracking *tracking = &clip->tracking;
MovieTrackingObject *object = BKE_tracking_object_get_active(tracking);
clip_tracking_clear_invisible_track_selection(sc, clip);
BKE_tracking_clipboard_copy_tracks(tracking, object);
return OPERATOR_FINISHED;
}
void CLIP_OT_copy_tracks(wmOperatorType *ot)
{
/* identifiers */
ot->name = "Copy Tracks";
ot->description = "Copy selected tracks to clipboard";
ot->idname = "CLIP_OT_copy_tracks";
/* api callbacks */
ot->exec = copy_tracks_exec;
ot->poll = ED_space_clip_tracking_poll;
/* flags */
ot->flag = OPTYPE_REGISTER;
}
/** \} */
/* -------------------------------------------------------------------- */
/** \name Paste Tracks From Clipboard Operator
* \{ */
static bool paste_tracks_poll(bContext *C)
{
if (ED_space_clip_tracking_poll(C)) {
return BKE_tracking_clipboard_has_tracks();
}
return 0;
}
static int paste_tracks_exec(bContext *C, wmOperator *UNUSED(op))
{
SpaceClip *sc = CTX_wm_space_clip(C);
MovieClip *clip = ED_space_clip_get_clip(sc);
MovieTracking *tracking = &clip->tracking;
MovieTrackingObject *object = BKE_tracking_object_get_active(tracking);
ListBase *tracks_base = BKE_tracking_object_get_tracks(tracking, object);
BKE_tracking_tracks_deselect_all(tracks_base);
BKE_tracking_clipboard_paste_tracks(tracking, object);
WM_event_add_notifier(C, NC_MOVIECLIP | NA_EDITED, clip);
return OPERATOR_FINISHED;
}
void CLIP_OT_paste_tracks(wmOperatorType *ot)
{
/* identifiers */
ot->name = "Paste Tracks";
ot->description = "Paste tracks from clipboard";
ot->idname = "CLIP_OT_paste_tracks";
/* api callbacks */
ot->exec = paste_tracks_exec;
ot->poll = paste_tracks_poll;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
/** \} */
/* -------------------------------------------------------------------- */
/** \name Insert Track Keyframe Operator
* \{ */
static void keyframe_set_flag(bContext *C, bool set)
{
SpaceClip *sc = CTX_wm_space_clip(C);
MovieClip *clip = ED_space_clip_get_clip(sc);
MovieTracking *tracking = &clip->tracking;
int framenr = ED_space_clip_get_clip_frame_number(sc);
ListBase *tracks_base = BKE_tracking_get_active_tracks(tracking);
for (MovieTrackingTrack *track = tracks_base->first; track != NULL; track = track->next) {
if (TRACK_VIEW_SELECTED(sc, track)) {
if (set) {
MovieTrackingMarker *marker = BKE_tracking_marker_ensure(track, framenr);
marker->flag &= ~MARKER_TRACKED;
}
else {
MovieTrackingMarker *marker = BKE_tracking_marker_get_exact(track, framenr);
if (marker != NULL) {
marker->flag |= MARKER_TRACKED;
}
}
}
}
ListBase *plane_tracks_base = BKE_tracking_get_active_plane_tracks(tracking);
for (MovieTrackingPlaneTrack *plane_track = plane_tracks_base->first; plane_track != NULL;
plane_track = plane_track->next) {
if (PLANE_TRACK_VIEW_SELECTED(plane_track)) {
if (set) {
MovieTrackingPlaneMarker *plane_marker = BKE_tracking_plane_marker_ensure(plane_track,
framenr);
if (plane_marker->flag & PLANE_MARKER_TRACKED) {
plane_marker->flag &= ~PLANE_MARKER_TRACKED;
BKE_tracking_track_plane_from_existing_motion(plane_track, plane_marker->framenr);
}
}
else {
MovieTrackingPlaneMarker *plane_marker = BKE_tracking_plane_marker_get_exact(plane_track,
framenr);
if (plane_marker) {
if ((plane_marker->flag & PLANE_MARKER_TRACKED) == 0) {
plane_marker->flag |= PLANE_MARKER_TRACKED;
BKE_tracking_retrack_plane_from_existing_motion_at_segment(plane_track,
plane_marker->framenr);
}
}
}
}
}
WM_event_add_notifier(C, NC_MOVIECLIP | NA_EDITED, clip);
}
static int keyframe_insert_exec(bContext *C, wmOperator *UNUSED(op))
{
keyframe_set_flag(C, true);
return OPERATOR_FINISHED;
}
void CLIP_OT_keyframe_insert(wmOperatorType *ot)
{
/* identifiers */
ot->name = "Insert Keyframe";
ot->description = "Insert a keyframe to selected tracks at current frame";
ot->idname = "CLIP_OT_keyframe_insert";
/* api callbacks */
ot->poll = ED_space_clip_tracking_poll;
ot->exec = keyframe_insert_exec;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
/** \} */
/* -------------------------------------------------------------------- */
/** \name Delete Track Keyframe Operator
* \{ */
static int keyframe_delete_exec(bContext *C, wmOperator *UNUSED(op))
{
keyframe_set_flag(C, false);
return OPERATOR_FINISHED;
}
void CLIP_OT_keyframe_delete(wmOperatorType *ot)
{
/* identifiers */
ot->name = "Delete Keyframe";
ot->description = "Delete a keyframe from selected tracks at current frame";
ot->idname = "CLIP_OT_keyframe_delete";
/* api callbacks */
ot->poll = ED_space_clip_tracking_poll;
ot->exec = keyframe_delete_exec;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
/** \} */
| 412 | 0.891324 | 1 | 0.891324 | game-dev | MEDIA | 0.455478 | game-dev | 0.506272 | 1 | 0.506272 |
Benimatic/twilightforest | 2,697 | src/main/java/twilightforest/entity/ai/EntityAITFYetiRampage.java | package twilightforest.entity.ai;
import net.minecraft.entity.ai.EntityAIBase;
import twilightforest.entity.boss.EntityTFYetiAlpha;
public class EntityAITFYetiRampage extends EntityAIBase {
private EntityTFYetiAlpha yeti;
private int currentTimeOut;
private int currentDuration;
private int maxTantrumTimeOut;
private int tantrumDuration;
public EntityAITFYetiRampage(EntityTFYetiAlpha entityTFYetiAlpha, int timeout, int duration) {
this.yeti = entityTFYetiAlpha;
this.currentTimeOut = timeout;
this.maxTantrumTimeOut = timeout;
this.tantrumDuration = duration;
this.setMutexBits(5);
}
@Override
public boolean shouldExecute() {
if (this.yeti.getAttackTarget() != null && this.yeti.canRampage()) {
this.currentTimeOut--;
}
//System.out.println("Tantrum time out = " + this.tantrumTimeOut);
return this.currentTimeOut <= 0;
}
/**
* Execute a one shot task or start executing a continuous task
*/
@Override
public void startExecuting()
{
this.currentDuration = this.tantrumDuration;
this.yeti.setRampaging(true);
}
/**
* Returns whether an in-progress EntityAIBase should continue executing
*/
@Override
public boolean continueExecuting()
{
return currentDuration > 0;
}
/**
* Updates the task
*/
@Override
public void updateTask()
{
this.currentDuration--;
// int rx = MathHelper.floor_double(this.yeti.posX);
// int ry = MathHelper.floor_double(this.yeti.posY - 1);
// int rz = MathHelper.floor_double(this.yeti.posZ);
//
// this.yeti.worldObj.playAuxSFX(2004, rx, ry, rz, 0);
if (this.yeti.getAttackTarget() != null) {
this.yeti.getLookHelper().setLookPositionWithEntity(this.yeti.getAttackTarget(), 10.0F, (float)this.yeti.getVerticalFaceSpeed());
}
if (this.yeti.onGround) {
this.yeti.motionX = 0;
this.yeti.motionZ = 0;
this.yeti.motionY = 0.4F;
}
this.yeti.destroyBlocksInAABB(this.yeti.boundingBox.expand(1, 2, 1).offset(0, 2, 0));
// regular falling blocks
if (this.currentDuration % 20 == 0) {
this.yeti.makeRandomBlockFall();
}
// blocks target players
if (this.currentDuration % 40 == 0) {
this.yeti.makeBlockAboveTargetFall();
}
// blocks target players
if (this.currentDuration < 40 && this.currentDuration % 10 == 0) {
this.yeti.makeNearbyBlockFall();
}
//System.out.println("Rampage!");
}
/**
* Resets the task
*/
@Override
public void resetTask()
{
this.currentTimeOut = this.maxTantrumTimeOut;
this.yeti.setRampaging(false);
this.yeti.setTired(true);
}
}
| 412 | 0.802922 | 1 | 0.802922 | game-dev | MEDIA | 0.962745 | game-dev | 0.940334 | 1 | 0.940334 |
mfnalex/ChestSort | 2,299 | src/main/java/de/jeff_media/chestsort/utils/EnchantmentUtils.java | package de.jeff_media.chestsort.utils;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.EnchantmentStorageMeta;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
public class EnchantmentUtils {
public static String getEnchantmentString(ItemStack item) {
StringBuilder builder = new StringBuilder(",");
builder.append(getInversedEnchantmentAmount(item));
if(!item.hasItemMeta()) return builder.toString();
ItemMeta meta = item.getItemMeta();
if(!meta.hasEnchants() && !(meta instanceof EnchantmentStorageMeta)) return builder.toString();
List<Enchantment> sortedEnchants = new ArrayList<>(meta.getEnchants().keySet());
sortedEnchants.sort(Comparator.comparing(o -> o.getKey().getKey()));
for(Enchantment enchantment : sortedEnchants) {
builder.append(",");
builder.append(enchantment.getKey().getKey());
builder.append(",");
builder.append(Integer.MAX_VALUE - meta.getEnchantLevel(enchantment));
}
if(meta instanceof EnchantmentStorageMeta) {
List<Enchantment> sortedStoredEnchants = new ArrayList<>(((EnchantmentStorageMeta)meta).getStoredEnchants().keySet());
for(Enchantment enchantment : sortedStoredEnchants) {
builder.append(",");
builder.append(enchantment.getKey().getKey());
builder.append(",");
builder.append(Integer.MAX_VALUE - meta.getEnchantLevel(enchantment));
}
}
return builder.toString();
}
public static int getInversedEnchantmentAmount(ItemStack item) {
int amount = Integer.MAX_VALUE;
ItemMeta meta = item.getItemMeta();
if(!meta.hasEnchants() && !(meta instanceof EnchantmentStorageMeta)) return amount;
for(int level : meta.getEnchants().values()) {
amount -= level;
}
if(meta instanceof EnchantmentStorageMeta) {
for(int level : ((EnchantmentStorageMeta)meta).getStoredEnchants().values()) {
amount -= level;
}
}
return amount;
}
}
| 412 | 0.835706 | 1 | 0.835706 | game-dev | MEDIA | 0.719737 | game-dev | 0.875437 | 1 | 0.875437 |
EmptyBottleInc/DFU-Tanguy-Multiplayer | 1,312 | Assets/Scripts/Internal/DaggerfallRDBBlock.cs | // Project: Daggerfall Unity
// Copyright: Copyright (C) 2009-2022 Daggerfall Workshop
// Web Site: http://www.dfworkshop.net
// License: MIT License (http://www.opensource.org/licenses/mit-license.php)
// Source Code: https://github.com/Interkarma/daggerfall-unity
// Original Author: Gavin Clayton (interkarma@dfworkshop.net)
// Contributors:
//
// Notes:
//
using UnityEngine;
using System.Collections;
using System.IO;
using DaggerfallConnect;
using DaggerfallConnect.Utility;
using DaggerfallConnect.Arena2;
namespace DaggerfallWorkshop
{
/// <summary>
/// Attached to dungeon blocks.
/// </summary>
public class DaggerfallRDBBlock : MonoBehaviour
{
public Vector2 RDBPosition = new Vector2();
public Bounds RDBBounds = new Bounds();
GameObject[] startMarkers = null;
GameObject[] enterMarkers = null;
public GameObject[] StartMarkers
{
get { return startMarkers; }
}
public GameObject[] EnterMarkers
{
get { return enterMarkers; }
}
public void SetMarkers(GameObject[] startMarkers, GameObject[] enterMarkers)
{
this.startMarkers = startMarkers;
this.enterMarkers = enterMarkers;
}
}
} | 412 | 0.926389 | 1 | 0.926389 | game-dev | MEDIA | 0.917317 | game-dev | 0.845018 | 1 | 0.845018 |
oscargforce/TidyPlates_CleanPlates-Enhanced | 11,499 | TidyPlates_CleanPlates/Libs/AceConfig-3.0/AceConfigRegistry-3.0/AceConfigRegistry-3.0.lua | --- AceConfigRegistry-3.0 handles central registration of options tables in use by addons and modules.\\
-- Options tables can be registered as raw tables, OR as function refs that return a table.\\
-- Such functions receive three arguments: "uiType", "uiName", "appName". \\
-- * Valid **uiTypes**: "cmd", "dropdown", "dialog". This is verified by the library at call time. \\
-- * The **uiName** field is expected to contain the full name of the calling addon, including version, e.g. "FooBar-1.0". This is verified by the library at call time.\\
-- * The **appName** field is the options table name as given at registration time \\
--
-- :IterateOptionsTables() (and :GetOptionsTable() if only given one argument) return a function reference that the requesting config handling addon must call with valid "uiType", "uiName".
-- @class file
-- @name AceConfigRegistry-3.0
-- @release $Id: AceConfigRegistry-3.0.lua 832 2009-09-01 11:03:04Z nevcairiel $
local MAJOR, MINOR = "AceConfigRegistry-3.0", 11
local AceConfigRegistry = LibStub:NewLibrary(MAJOR, MINOR)
if not AceConfigRegistry then return end
AceConfigRegistry.tables = AceConfigRegistry.tables or {}
local CallbackHandler = LibStub:GetLibrary("CallbackHandler-1.0")
if not AceConfigRegistry.callbacks then
AceConfigRegistry.callbacks = CallbackHandler:New(AceConfigRegistry)
end
-----------------------------------------------------------------------
-- Validating options table consistency:
AceConfigRegistry.validated = {
-- list of options table names ran through :ValidateOptionsTable automatically.
-- CLEARED ON PURPOSE, since newer versions may have newer validators
cmd = {},
dropdown = {},
dialog = {},
}
local function err(msg, errlvl, ...)
local t = {}
for i=select("#",...),1,-1 do
tinsert(t, (select(i, ...)))
end
error(MAJOR..":ValidateOptionsTable(): "..table.concat(t,".")..msg, errlvl+2)
end
local isstring={["string"]=true, _="string"}
local isstringfunc={["string"]=true,["function"]=true, _="string or funcref"}
local istable={["table"]=true, _="table"}
local ismethodtable={["table"]=true,["string"]=true,["function"]=true, _="methodname, funcref or table"}
local optstring={["nil"]=true,["string"]=true, _="string"}
local optstringfunc={["nil"]=true,["string"]=true,["function"]=true, _="string or funcref"}
local optnumber={["nil"]=true,["number"]=true, _="number"}
local optmethod={["nil"]=true,["string"]=true,["function"]=true, _="methodname or funcref"}
local optmethodfalse={["nil"]=true,["string"]=true,["function"]=true,["boolean"]={[false]=true}, _="methodname, funcref or false"}
local optmethodnumber={["nil"]=true,["string"]=true,["function"]=true,["number"]=true, _="methodname, funcref or number"}
local optmethodtable={["nil"]=true,["string"]=true,["function"]=true,["table"]=true, _="methodname, funcref or table"}
local optmethodbool={["nil"]=true,["string"]=true,["function"]=true,["boolean"]=true, _="methodname, funcref or boolean"}
local opttable={["nil"]=true,["table"]=true, _="table"}
local optbool={["nil"]=true,["boolean"]=true, _="boolean"}
local optboolnumber={["nil"]=true,["boolean"]=true,["number"]=true, _="boolean or number"}
local basekeys={
type=isstring,
name=isstringfunc,
desc=optstringfunc,
descStyle=optstring,
order=optmethodnumber,
validate=optmethodfalse,
confirm=optmethodbool,
confirmText=optstring,
disabled=optmethodbool,
hidden=optmethodbool,
guiHidden=optmethodbool,
dialogHidden=optmethodbool,
dropdownHidden=optmethodbool,
cmdHidden=optmethodbool,
icon=optstringfunc,
iconCoords=optmethodtable,
handler=opttable,
get=optmethodfalse,
set=optmethodfalse,
func=optmethodfalse,
arg={["*"]=true},
width=optstring,
}
local typedkeys={
header={},
description={
image=optstringfunc,
imageCoords=optmethodtable,
imageHeight=optnumber,
imageWidth=optnumber,
fontSize=optstringfunc,
},
group={
args=istable,
plugins=opttable,
inline=optbool,
cmdInline=optbool,
guiInline=optbool,
dropdownInline=optbool,
dialogInline=optbool,
childGroups=optstring,
},
execute={
image=optstringfunc,
imageCoords=optmethodtable,
imageHeight=optnumber,
imageWidth=optnumber,
},
input={
pattern=optstring,
usage=optstring,
control=optstring,
dialogControl=optstring,
dropdownControl=optstring,
multiline=optboolnumber,
},
toggle={
tristate=optbool,
},
tristate={
},
range={
min=optnumber,
max=optnumber,
step=optnumber,
bigStep=optnumber,
isPercent=optbool,
},
select={
values=ismethodtable,
style={
["nil"]=true,
["string"]={dropdown=true,radio=true},
_="string: 'dropdown' or 'radio'"
},
control=optstring,
dialogControl=optstring,
dropdownControl=optstring,
},
multiselect={
values=ismethodtable,
style=optstring,
tristate=optbool,
control=optstring,
dialogControl=optstring,
dropdownControl=optstring,
},
color={
hasAlpha=optbool,
},
keybinding={
-- TODO
},
}
local function validateKey(k,errlvl,...)
errlvl=(errlvl or 0)+1
if type(k)~="string" then
err("["..tostring(k).."] - key is not a string", errlvl,...)
end
if strfind(k, "[%c\127]") then
err("["..tostring(k).."] - key name contained control characters", errlvl,...)
end
end
local function validateVal(v, oktypes, errlvl,...)
errlvl=(errlvl or 0)+1
local isok=oktypes[type(v)] or oktypes["*"]
if not isok then
err(": expected a "..oktypes._..", got '"..tostring(v).."'", errlvl,...)
end
if type(isok)=="table" then -- isok was a table containing specific values to be tested for!
if not isok[v] then
err(": did not expect "..type(v).." value '"..tostring(v).."'", errlvl,...)
end
end
end
local function validate(options,errlvl,...)
errlvl=(errlvl or 0)+1
-- basic consistency
if type(options)~="table" then
err(": expected a table, got a "..type(options), errlvl,...)
end
if type(options.type)~="string" then
err(".type: expected a string, got a "..type(options.type), errlvl,...)
end
-- get type and 'typedkeys' member
local tk = typedkeys[options.type]
if not tk then
err(".type: unknown type '"..options.type.."'", errlvl,...)
end
-- make sure that all options[] are known parameters
for k,v in pairs(options) do
if not (tk[k] or basekeys[k]) then
err(": unknown parameter", errlvl,tostring(k),...)
end
end
-- verify that required params are there, and that everything is the right type
for k,oktypes in pairs(basekeys) do
validateVal(options[k], oktypes, errlvl,k,...)
end
for k,oktypes in pairs(tk) do
validateVal(options[k], oktypes, errlvl,k,...)
end
-- extra logic for groups
if options.type=="group" then
for k,v in pairs(options.args) do
validateKey(k,errlvl,"args",...)
validate(v, errlvl,k,"args",...)
end
if options.plugins then
for plugname,plugin in pairs(options.plugins) do
if type(plugin)~="table" then
err(": expected a table, got '"..tostring(plugin).."'", errlvl,tostring(plugname),"plugins",...)
end
for k,v in pairs(plugin) do
validateKey(k,errlvl,tostring(plugname),"plugins",...)
validate(v, errlvl,k,tostring(plugname),"plugins",...)
end
end
end
end
end
--- Validates basic structure and integrity of an options table \\
-- Does NOT verify that get/set etc actually exist, since they can be defined at any depth
-- @param options The table to be validated
-- @param name The name of the table to be validated (shown in any error message)
-- @param errlvl (optional number) error level offset, default 0 (=errors point to the function calling :ValidateOptionsTable)
function AceConfigRegistry:ValidateOptionsTable(options,name,errlvl)
errlvl=(errlvl or 0)+1
name = name or "Optionstable"
if not options.name then
options.name=name -- bit of a hack, the root level doesn't really need a .name :-/
end
validate(options,errlvl,name)
end
--- Fires a "ConfigTableChange" callback for those listening in on it, allowing config GUIs to refresh.
-- You should call this function if your options table changed from any outside event, like a game event
-- or a timer.
-- @param appName The application name as given to `:RegisterOptionsTable()`
function AceConfigRegistry:NotifyChange(appName)
if not AceConfigRegistry.tables[appName] then return end
AceConfigRegistry.callbacks:Fire("ConfigTableChange", appName)
end
-- -------------------------------------------------------------------
-- Registering and retreiving options tables:
-- validateGetterArgs: helper function for :GetOptionsTable (or, rather, the getter functions returned by it)
local function validateGetterArgs(uiType, uiName, errlvl)
errlvl=(errlvl or 0)+2
if uiType~="cmd" and uiType~="dropdown" and uiType~="dialog" then
error(MAJOR..": Requesting options table: 'uiType' - invalid configuration UI type, expected 'cmd', 'dropdown' or 'dialog'", errlvl)
end
if not strmatch(uiName, "[A-Za-z]%-[0-9]") then -- Expecting e.g. "MyLib-1.2"
error(MAJOR..": Requesting options table: 'uiName' - badly formatted or missing version number. Expected e.g. 'MyLib-1.2'", errlvl)
end
end
--- Register an options table with the config registry.
-- @param appName The application name as given to `:RegisterOptionsTable()`
-- @param options The options table, OR a function reference that generates it on demand. \\
-- See the top of the page for info on arguments passed to such functions.
function AceConfigRegistry:RegisterOptionsTable(appName, options)
if type(options)=="table" then
if options.type~="group" then -- quick sanity checker
error(MAJOR..": RegisterOptionsTable(appName, options): 'options' - missing type='group' member in root group", 2)
end
AceConfigRegistry.tables[appName] = function(uiType, uiName, errlvl)
errlvl=(errlvl or 0)+1
validateGetterArgs(uiType, uiName, errlvl)
if not AceConfigRegistry.validated[uiType][appName] then
AceConfigRegistry:ValidateOptionsTable(options, appName, errlvl) -- upgradable
AceConfigRegistry.validated[uiType][appName] = true
end
return options
end
elseif type(options)=="function" then
AceConfigRegistry.tables[appName] = function(uiType, uiName, errlvl)
errlvl=(errlvl or 0)+1
validateGetterArgs(uiType, uiName, errlvl)
local tab = assert(options(uiType, uiName, appName))
if not AceConfigRegistry.validated[uiType][appName] then
AceConfigRegistry:ValidateOptionsTable(tab, appName, errlvl) -- upgradable
AceConfigRegistry.validated[uiType][appName] = true
end
return tab
end
else
error(MAJOR..": RegisterOptionsTable(appName, options): 'options' - expected table or function reference", 2)
end
end
--- Returns an iterator of ["appName"]=funcref pairs
function AceConfigRegistry:IterateOptionsTables()
return pairs(AceConfigRegistry.tables)
end
--- Query the registry for a specific options table.
-- If only appName is given, a function is returned which you
-- can call with (uiType,uiName) to get the table.\\
-- If uiType&uiName are given, the table is returned.
-- @param appName The application name as given to `:RegisterOptionsTable()`
-- @param uiType The type of UI to get the table for, one of "cmd", "dropdown", "dialog"
-- @param uiName The name of the library/addon querying for the table, e.g. "MyLib-1.0"
function AceConfigRegistry:GetOptionsTable(appName, uiType, uiName)
local f = AceConfigRegistry.tables[appName]
if not f then
return nil
end
if uiType then
return f(uiType,uiName,1) -- get the table for us
else
return f -- return the function
end
end
| 412 | 0.880248 | 1 | 0.880248 | game-dev | MEDIA | 0.385322 | game-dev | 0.938282 | 1 | 0.938282 |
adamqqqplay/dota2ai | 1,675 | util/lib/Buyback.lua | --
-- Copyright (c) 2023. Ranked Matchmaking AI Developers. All rights reserved.
--
-- SPDX-License-Identifier: GPL-3.0-or-later
--
local X={}
local BattleSituation = require(GetScriptDirectory() .. "/util/lib/BattleSituation")
X['LastTeamBuybackTime'] = -90;
function X.CanBuybackUpperRespawnTime(respawnTime)
local npcBot = GetBot()
if npcBot == nil then
return
end
if (not npcBot:IsAlive() and respawnTime ~= nil and npcBot:GetRespawnTime() >= respawnTime and
npcBot:GetBuybackCooldown() <= 0 and
npcBot:GetGold() > npcBot:GetBuybackCost())
then
return true
end
return false
end
function X.BuybackUsageComplement()
local npcBot = GetBot()
if npcBot == nil then
return
end
if npcBot:GetLevel() <= 15
or npcBot:HasModifier( 'modifier_arc_warden_tempest_double' )
or DotaTime() < X['LastTeamBuybackTime'] + 2.0
then
return
end
if not npcBot:HasBuyback() or npcBot:GetRespawnTime() < 60 then
return
end
if not X.CanBuybackUpperRespawnTime(60) then
return
end
if npcBot:GetLevel() > 24 and npcBot:GetRespawnTime() >= 75
then
local nTeamFightLocation =BattleSituation.GetTeamFightLocation()
if nTeamFightLocation ~= nil
then
X['LastTeamBuybackTime'] = DotaTime()
npcBot:ActionImmediate_Buyback()
return
end
end
local ancient = GetAncient( GetTeam() )
if ancient ~= nil
then
local nEnemyCount = BattleSituation.GetNumEnemyNearby( ancient )
local nAllyCount = BattleSituation.GetNumOfAliveHeroes( false )
if nEnemyCount > 0 and nEnemyCount >= nAllyCount
then
X['LastTeamBuybackTime'] = DotaTime()
npcBot:ActionImmediate_Buyback()
return
end
end
end
return X | 412 | 0.843152 | 1 | 0.843152 | game-dev | MEDIA | 0.912341 | game-dev | 0.975913 | 1 | 0.975913 |
StarKRE22/Atomic | 6,144 | Assets/Examples/RTS/Scripts/GameContext/GameContextAPI.cs | /**
* Code generation. Don't modify!
**/
using Atomic.Entities;
using static Atomic.Entities.EntityNames;
using System.Runtime.CompilerServices;
#if UNITY_EDITOR
using UnityEditor;
#endif
using UnityEngine;
using Atomic.Entities;
using Atomic.Elements;
using System.Collections.Generic;
namespace RTSGame
{
#if UNITY_EDITOR
[InitializeOnLoad]
#endif
public static class GameContextAPI
{
///Values
public static readonly int EntityWorld; // EntityWorld<IGameEntity>
public static readonly int EntityPool; // IMultiEntityPool<string, IGameEntity>
public static readonly int Players; // Dictionary<TeamType, IPlayerContext>
public static readonly int TeamViewConfig; // TeamViewConfig
static GameContextAPI()
{
//Values
EntityWorld = NameToId(nameof(EntityWorld));
EntityPool = NameToId(nameof(EntityPool));
Players = NameToId(nameof(Players));
TeamViewConfig = NameToId(nameof(TeamViewConfig));
}
///Value Extensions
#region EntityWorld
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static EntityWorld<IGameEntity> GetEntityWorld(this IGameContext entity) => entity.GetValueUnsafe<EntityWorld<IGameEntity>>(EntityWorld);
public static ref EntityWorld<IGameEntity> RefEntityWorld(this IGameContext entity) => ref entity.GetValueUnsafe<EntityWorld<IGameEntity>>(EntityWorld);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool TryGetEntityWorld(this IGameContext entity, out EntityWorld<IGameEntity> value) => entity.TryGetValueUnsafe(EntityWorld, out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AddEntityWorld(this IGameContext entity, EntityWorld<IGameEntity> value) => entity.AddValue(EntityWorld, value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool HasEntityWorld(this IGameContext entity) => entity.HasValue(EntityWorld);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool DelEntityWorld(this IGameContext entity) => entity.DelValue(EntityWorld);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void SetEntityWorld(this IGameContext entity, EntityWorld<IGameEntity> value) => entity.SetValue(EntityWorld, value);
#endregion
#region EntityPool
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static IMultiEntityPool<string, IGameEntity> GetEntityPool(this IGameContext entity) => entity.GetValueUnsafe<IMultiEntityPool<string, IGameEntity>>(EntityPool);
public static ref IMultiEntityPool<string, IGameEntity> RefEntityPool(this IGameContext entity) => ref entity.GetValueUnsafe<IMultiEntityPool<string, IGameEntity>>(EntityPool);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool TryGetEntityPool(this IGameContext entity, out IMultiEntityPool<string, IGameEntity> value) => entity.TryGetValueUnsafe(EntityPool, out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AddEntityPool(this IGameContext entity, IMultiEntityPool<string, IGameEntity> value) => entity.AddValue(EntityPool, value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool HasEntityPool(this IGameContext entity) => entity.HasValue(EntityPool);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool DelEntityPool(this IGameContext entity) => entity.DelValue(EntityPool);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void SetEntityPool(this IGameContext entity, IMultiEntityPool<string, IGameEntity> value) => entity.SetValue(EntityPool, value);
#endregion
#region Players
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Dictionary<TeamType, IPlayerContext> GetPlayers(this IGameContext entity) => entity.GetValueUnsafe<Dictionary<TeamType, IPlayerContext>>(Players);
public static ref Dictionary<TeamType, IPlayerContext> RefPlayers(this IGameContext entity) => ref entity.GetValueUnsafe<Dictionary<TeamType, IPlayerContext>>(Players);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool TryGetPlayers(this IGameContext entity, out Dictionary<TeamType, IPlayerContext> value) => entity.TryGetValueUnsafe(Players, out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AddPlayers(this IGameContext entity, Dictionary<TeamType, IPlayerContext> value) => entity.AddValue(Players, value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool HasPlayers(this IGameContext entity) => entity.HasValue(Players);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool DelPlayers(this IGameContext entity) => entity.DelValue(Players);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void SetPlayers(this IGameContext entity, Dictionary<TeamType, IPlayerContext> value) => entity.SetValue(Players, value);
#endregion
#region TeamViewConfig
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static TeamViewConfig GetTeamViewConfig(this IGameContext entity) => entity.GetValueUnsafe<TeamViewConfig>(TeamViewConfig);
public static ref TeamViewConfig RefTeamViewConfig(this IGameContext entity) => ref entity.GetValueUnsafe<TeamViewConfig>(TeamViewConfig);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool TryGetTeamViewConfig(this IGameContext entity, out TeamViewConfig value) => entity.TryGetValueUnsafe(TeamViewConfig, out value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AddTeamViewConfig(this IGameContext entity, TeamViewConfig value) => entity.AddValue(TeamViewConfig, value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool HasTeamViewConfig(this IGameContext entity) => entity.HasValue(TeamViewConfig);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool DelTeamViewConfig(this IGameContext entity) => entity.DelValue(TeamViewConfig);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void SetTeamViewConfig(this IGameContext entity, TeamViewConfig value) => entity.SetValue(TeamViewConfig, value);
#endregion
}
}
| 412 | 0.831953 | 1 | 0.831953 | game-dev | MEDIA | 0.96626 | game-dev | 0.738212 | 1 | 0.738212 |
uber-research/safemutations | 14,107 | mazesim.py | # This file was automatically generated by SWIG (http://www.swig.org).
# Version 2.0.12
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info
if version_info >= (2,6,0):
def swig_import_helper():
from os.path import dirname
import imp
fp = None
try:
fp, pathname, description = imp.find_module('_mazesim', [dirname(__file__)])
except ImportError:
import _mazesim
return _mazesim
if fp is not None:
try:
_mod = imp.load_module('_mazesim', fp, pathname, description)
finally:
fp.close()
return _mod
_mazesim = swig_import_helper()
del swig_import_helper
else:
import _mazesim
del version_info
try:
_swig_property = property
except NameError:
pass # Python < 2.2 doesn't have 'property'.
def _swig_setattr_nondynamic(self,class_type,name,value,static=1):
if (name == "thisown"): return self.this.own(value)
if (name == "this"):
if type(value).__name__ == 'SwigPyObject':
self.__dict__[name] = value
return
method = class_type.__swig_setmethods__.get(name,None)
if method: return method(self,value)
if (not static):
self.__dict__[name] = value
else:
raise AttributeError("You cannot add attributes to %s" % self)
def _swig_setattr(self,class_type,name,value):
return _swig_setattr_nondynamic(self,class_type,name,value,0)
def _swig_getattr(self,class_type,name):
if (name == "thisown"): return self.this.own()
method = class_type.__swig_getmethods__.get(name,None)
if method: return method(self)
raise AttributeError(name)
def _swig_repr(self):
try: strthis = "proxy of " + self.this.__repr__()
except: strthis = ""
return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)
try:
_object = object
_newclass = 1
except AttributeError:
class _object : pass
_newclass = 0
class Environment(_object):
__swig_setmethods__ = {}
__setattr__ = lambda self, name, value: _swig_setattr(self, Environment, name, value)
__swig_getmethods__ = {}
__getattr__ = lambda self, name: _swig_getattr(self, Environment, name)
__repr__ = _swig_repr
def get_range(self, *args): return _mazesim.Environment_get_range(self, *args)
def __init__(self, *args):
this = _mazesim.new_Environment(*args)
try: self.this.append(this)
except: self.this = this
def display(self): return _mazesim.Environment_display(self)
def distance_to_start(self): return _mazesim.Environment_distance_to_start(self)
def distance_to_target(self): return _mazesim.Environment_distance_to_target(self)
def distance_to_poi(self): return _mazesim.Environment_distance_to_poi(self)
def generate_neural_inputs_wrapper(self, *args): return _mazesim.Environment_generate_neural_inputs_wrapper(self, *args)
def generate_neural_inputs(self, *args): return _mazesim.Environment_generate_neural_inputs(self, *args)
def interpret_outputs(self, *args): return _mazesim.Environment_interpret_outputs(self, *args)
def Update(self): return _mazesim.Environment_Update(self)
def collide_lines(self, *args): return _mazesim.Environment_collide_lines(self, *args)
def update_rangefinders(self, *args): return _mazesim.Environment_update_rangefinders(self, *args)
def update_radar(self, *args): return _mazesim.Environment_update_radar(self, *args)
def get_line_count(self): return _mazesim.Environment_get_line_count(self)
def get_line(self, *args): return _mazesim.Environment_get_line(self, *args)
def update_radar_gen(self, *args): return _mazesim.Environment_update_radar_gen(self, *args)
__swig_destroy__ = _mazesim.delete_Environment
__del__ = lambda self : None;
__swig_setmethods__["closest_to_target"] = _mazesim.Environment_closest_to_target_set
__swig_getmethods__["closest_to_target"] = _mazesim.Environment_closest_to_target_get
if _newclass:closest_to_target = _swig_property(_mazesim.Environment_closest_to_target_get, _mazesim.Environment_closest_to_target_set)
__swig_setmethods__["steps"] = _mazesim.Environment_steps_set
__swig_getmethods__["steps"] = _mazesim.Environment_steps_get
if _newclass:steps = _swig_property(_mazesim.Environment_steps_get, _mazesim.Environment_steps_set)
__swig_setmethods__["closest_to_poi"] = _mazesim.Environment_closest_to_poi_set
__swig_getmethods__["closest_to_poi"] = _mazesim.Environment_closest_to_poi_get
if _newclass:closest_to_poi = _swig_property(_mazesim.Environment_closest_to_poi_get, _mazesim.Environment_closest_to_poi_set)
__swig_setmethods__["lines"] = _mazesim.Environment_lines_set
__swig_getmethods__["lines"] = _mazesim.Environment_lines_get
if _newclass:lines = _swig_property(_mazesim.Environment_lines_get, _mazesim.Environment_lines_set)
__swig_setmethods__["hero"] = _mazesim.Environment_hero_set
__swig_getmethods__["hero"] = _mazesim.Environment_hero_get
if _newclass:hero = _swig_property(_mazesim.Environment_hero_get, _mazesim.Environment_hero_set)
__swig_setmethods__["end"] = _mazesim.Environment_end_set
__swig_getmethods__["end"] = _mazesim.Environment_end_get
if _newclass:end = _swig_property(_mazesim.Environment_end_get, _mazesim.Environment_end_set)
__swig_setmethods__["poi"] = _mazesim.Environment_poi_set
__swig_getmethods__["poi"] = _mazesim.Environment_poi_get
if _newclass:poi = _swig_property(_mazesim.Environment_poi_get, _mazesim.Environment_poi_set)
__swig_setmethods__["reachpoi"] = _mazesim.Environment_reachpoi_set
__swig_getmethods__["reachpoi"] = _mazesim.Environment_reachpoi_get
if _newclass:reachpoi = _swig_property(_mazesim.Environment_reachpoi_get, _mazesim.Environment_reachpoi_set)
__swig_setmethods__["reachgoal"] = _mazesim.Environment_reachgoal_set
__swig_getmethods__["reachgoal"] = _mazesim.Environment_reachgoal_get
if _newclass:reachgoal = _swig_property(_mazesim.Environment_reachgoal_get, _mazesim.Environment_reachgoal_set)
def get_sensor_size(self): return _mazesim.Environment_get_sensor_size(self)
__swig_setmethods__["goalattract"] = _mazesim.Environment_goalattract_set
__swig_getmethods__["goalattract"] = _mazesim.Environment_goalattract_get
if _newclass:goalattract = _swig_property(_mazesim.Environment_goalattract_get, _mazesim.Environment_goalattract_set)
Environment_swigregister = _mazesim.Environment_swigregister
Environment_swigregister(Environment)
class Character(_object):
__swig_setmethods__ = {}
__setattr__ = lambda self, name, value: _swig_setattr(self, Character, name, value)
__swig_getmethods__ = {}
__getattr__ = lambda self, name: _swig_getattr(self, Character, name)
__repr__ = _swig_repr
__swig_setmethods__["rangeFinderAngles"] = _mazesim.Character_rangeFinderAngles_set
__swig_getmethods__["rangeFinderAngles"] = _mazesim.Character_rangeFinderAngles_get
if _newclass:rangeFinderAngles = _swig_property(_mazesim.Character_rangeFinderAngles_get, _mazesim.Character_rangeFinderAngles_set)
__swig_setmethods__["radarAngles1"] = _mazesim.Character_radarAngles1_set
__swig_getmethods__["radarAngles1"] = _mazesim.Character_radarAngles1_get
if _newclass:radarAngles1 = _swig_property(_mazesim.Character_radarAngles1_get, _mazesim.Character_radarAngles1_set)
__swig_setmethods__["radarAngles2"] = _mazesim.Character_radarAngles2_set
__swig_getmethods__["radarAngles2"] = _mazesim.Character_radarAngles2_get
if _newclass:radarAngles2 = _swig_property(_mazesim.Character_radarAngles2_get, _mazesim.Character_radarAngles2_set)
__swig_setmethods__["radar"] = _mazesim.Character_radar_set
__swig_getmethods__["radar"] = _mazesim.Character_radar_get
if _newclass:radar = _swig_property(_mazesim.Character_radar_get, _mazesim.Character_radar_set)
__swig_setmethods__["poi_radar"] = _mazesim.Character_poi_radar_set
__swig_getmethods__["poi_radar"] = _mazesim.Character_poi_radar_get
if _newclass:poi_radar = _swig_property(_mazesim.Character_poi_radar_get, _mazesim.Character_poi_radar_set)
__swig_setmethods__["rangeFinders"] = _mazesim.Character_rangeFinders_set
__swig_getmethods__["rangeFinders"] = _mazesim.Character_rangeFinders_get
if _newclass:rangeFinders = _swig_property(_mazesim.Character_rangeFinders_get, _mazesim.Character_rangeFinders_set)
__swig_setmethods__["location"] = _mazesim.Character_location_set
__swig_getmethods__["location"] = _mazesim.Character_location_get
if _newclass:location = _swig_property(_mazesim.Character_location_get, _mazesim.Character_location_set)
__swig_setmethods__["start"] = _mazesim.Character_start_set
__swig_getmethods__["start"] = _mazesim.Character_start_get
if _newclass:start = _swig_property(_mazesim.Character_start_get, _mazesim.Character_start_set)
__swig_setmethods__["collide"] = _mazesim.Character_collide_set
__swig_getmethods__["collide"] = _mazesim.Character_collide_get
if _newclass:collide = _swig_property(_mazesim.Character_collide_get, _mazesim.Character_collide_set)
__swig_setmethods__["collisions"] = _mazesim.Character_collisions_set
__swig_getmethods__["collisions"] = _mazesim.Character_collisions_get
if _newclass:collisions = _swig_property(_mazesim.Character_collisions_get, _mazesim.Character_collisions_set)
__swig_setmethods__["total_spin"] = _mazesim.Character_total_spin_set
__swig_getmethods__["total_spin"] = _mazesim.Character_total_spin_get
if _newclass:total_spin = _swig_property(_mazesim.Character_total_spin_get, _mazesim.Character_total_spin_set)
__swig_setmethods__["heading"] = _mazesim.Character_heading_set
__swig_getmethods__["heading"] = _mazesim.Character_heading_get
if _newclass:heading = _swig_property(_mazesim.Character_heading_get, _mazesim.Character_heading_set)
__swig_setmethods__["speed"] = _mazesim.Character_speed_set
__swig_getmethods__["speed"] = _mazesim.Character_speed_get
if _newclass:speed = _swig_property(_mazesim.Character_speed_get, _mazesim.Character_speed_set)
__swig_setmethods__["ang_vel"] = _mazesim.Character_ang_vel_set
__swig_getmethods__["ang_vel"] = _mazesim.Character_ang_vel_get
if _newclass:ang_vel = _swig_property(_mazesim.Character_ang_vel_get, _mazesim.Character_ang_vel_set)
__swig_setmethods__["radius"] = _mazesim.Character_radius_set
__swig_getmethods__["radius"] = _mazesim.Character_radius_get
if _newclass:radius = _swig_property(_mazesim.Character_radius_get, _mazesim.Character_radius_set)
__swig_setmethods__["rangefinder_range"] = _mazesim.Character_rangefinder_range_set
__swig_getmethods__["rangefinder_range"] = _mazesim.Character_rangefinder_range_get
if _newclass:rangefinder_range = _swig_property(_mazesim.Character_rangefinder_range_get, _mazesim.Character_rangefinder_range_set)
__swig_setmethods__["total_dist"] = _mazesim.Character_total_dist_set
__swig_getmethods__["total_dist"] = _mazesim.Character_total_dist_get
if _newclass:total_dist = _swig_property(_mazesim.Character_total_dist_get, _mazesim.Character_total_dist_set)
def __init__(self):
this = _mazesim.new_Character()
try: self.this.append(this)
except: self.this = this
__swig_destroy__ = _mazesim.delete_Character
__del__ = lambda self : None;
Character_swigregister = _mazesim.Character_swigregister
Character_swigregister(Character)
class Point(_object):
__swig_setmethods__ = {}
__setattr__ = lambda self, name, value: _swig_setattr(self, Point, name, value)
__swig_getmethods__ = {}
__getattr__ = lambda self, name: _swig_getattr(self, Point, name)
__repr__ = _swig_repr
def __init__(self, *args):
this = _mazesim.new_Point(*args)
try: self.this.append(this)
except: self.this = this
def fromfile(self, *args): return _mazesim.Point_fromfile(self, *args)
def angle(self): return _mazesim.Point_angle(self)
def rotate(self, *args): return _mazesim.Point_rotate(self, *args)
def distance(self, *args): return _mazesim.Point_distance(self, *args)
__swig_setmethods__["x"] = _mazesim.Point_x_set
__swig_getmethods__["x"] = _mazesim.Point_x_get
if _newclass:x = _swig_property(_mazesim.Point_x_get, _mazesim.Point_x_set)
__swig_setmethods__["y"] = _mazesim.Point_y_set
__swig_getmethods__["y"] = _mazesim.Point_y_get
if _newclass:y = _swig_property(_mazesim.Point_y_get, _mazesim.Point_y_set)
__swig_destroy__ = _mazesim.delete_Point
__del__ = lambda self : None;
Point_swigregister = _mazesim.Point_swigregister
Point_swigregister(Point)
class Line(_object):
__swig_setmethods__ = {}
__setattr__ = lambda self, name, value: _swig_setattr(self, Line, name, value)
__swig_getmethods__ = {}
__getattr__ = lambda self, name: _swig_getattr(self, Line, name)
__repr__ = _swig_repr
def __init__(self, *args):
this = _mazesim.new_Line(*args)
try: self.this.append(this)
except: self.this = this
def midpoint(self): return _mazesim.Line_midpoint(self)
def intersection(self, *args): return _mazesim.Line_intersection(self, *args)
def distance(self, *args): return _mazesim.Line_distance(self, *args)
def length(self): return _mazesim.Line_length(self)
__swig_setmethods__["a"] = _mazesim.Line_a_set
__swig_getmethods__["a"] = _mazesim.Line_a_get
if _newclass:a = _swig_property(_mazesim.Line_a_get, _mazesim.Line_a_set)
__swig_setmethods__["b"] = _mazesim.Line_b_set
__swig_getmethods__["b"] = _mazesim.Line_b_get
if _newclass:b = _swig_property(_mazesim.Line_b_get, _mazesim.Line_b_set)
__swig_destroy__ = _mazesim.delete_Line
__del__ = lambda self : None;
Line_swigregister = _mazesim.Line_swigregister
Line_swigregister(Line)
# This file is compatible with both classic and new-style classes.
| 412 | 0.842099 | 1 | 0.842099 | game-dev | MEDIA | 0.925749 | game-dev | 0.840971 | 1 | 0.840971 |
AbeerVaishnav13/FrameDinoGame | 3,888 | src/game.lua | -- MIT License
-- Copyright (c) 2024 Abeer Vaishnav
-- 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.
local sprites = require("sprites")
local globals = require("globals")
local Dino = require("dino")
local Ground = require("ground")
local ObstacleGen = require("obstacle_gen")
local function _new_game()
game = {}
game.frames = 0
game.score = 0
game.state = "INTRO"
game.__state_types = { "INTRO", "PLAY", "OVER" }
game.__game_over_messages = { " OUCH! ", "THAT HURT...", "...OH NO... ", " TRY AGAIN? ", " OUCHIE! " }
game.__random_game_over_message = game.__game_over_messages[math.random(1, #game.__game_over_messages)]
game.dino = Dino.new_dino(50)
game.ground = Ground.new_ground()
game.obs_gen = ObstacleGen.new_obstacle_generator()
function game:init()
frame.imu.tap_callback(function()
if game.state == "INTRO" then
game.state = "PLAY"
elseif game.state == "PLAY" then
self.dino:jump()
elseif game.state == "OVER" then
game:reset()
else
error("Error: Invalid game state!")
end
end)
end
function game:render_and_tick()
frame.display.show()
frame.sleep(0.04)
self.frames = (self.frames + 1) % 150
end
function game:set_viewport()
local viewport_block = string.rep("\\xFF", math.ceil(20 * (globals.screenheight / 2) / 8))
frame.display.bitmap(1, globals.screenheight / 2, 20, 2, 15, viewport_block)
end
function game:display_score()
frame.display.text("Score: " .. tostring(self.score), 1, 50, { color = "YELLOW", spacing = 6 })
end
function game:intro()
if self.state == "INTRO" then
frame.display.text("DINO GAME", 200, 150, { color = "GREEN", spacing = 8 })
frame.display.text("Tap to Start!", 200, 300, { color = "WHITE", spacing = 8 })
end
end
function game:play()
self.ground:update(self.dino, self.frames, self.score)
self.ground:draw()
self.dino:update()
self.dino:draw(self.frames)
if self.state == "PLAY" then
if self.dino.hit then
self.state = "OVER"
else
if self.frames % 2 == 0 then
self.score = self.score + 1
end
end
self.obs_gen:update(self.dino, self.frames, self.score)
self.obs_gen:draw(self.frames)
self:set_viewport()
self:display_score()
end
end
function game:over()
if self.state == "OVER" then
self.obs_gen:draw(self.frames)
self:set_viewport()
self:display_score()
frame.display.text(self.__random_game_over_message, 200, 150, { color = "RED", spacing = 8 })
frame.display.bitmap(300, 250, sprites.button.width, 2, globals.colors.green, sprites.button.retry)
end
end
function game:reset()
self.frames = 0
self.score = 0
self.state = "INTRO"
self.obs_gen:reset()
self.dino:reset()
self.__random_game_over_message = self.__game_over_messages[math.random(1, #self.__game_over_messages)]
end
return game
end
Game = {
new_game = _new_game,
}
return Game
| 412 | 0.750417 | 1 | 0.750417 | game-dev | MEDIA | 0.619551 | game-dev | 0.881382 | 1 | 0.881382 |
OGSR/OGSR-Engine | 1,044 | ogsr_engine/xrGame/ui/UIOptionsManager.h | ///////////////////////////////////
// class CUIOptionsManager
///////////////////////////////////
#pragma once
class CUIOptionsItem;
class CUIOptionsManager
{
friend class CUIOptionsItem;
public:
CUIOptionsManager();
void SeveBackupValues(const char* group);
void SetCurrentValues(const char* group);
void SaveValues(const char* group);
bool IsGroupChanged(const char* group);
void UndoGroup(const char* group);
void OptionsPostAccept();
void DoVidRestart();
void DoSndRestart();
void SendMessage2Group(const char* group, const char* message);
protected:
void RegisterItem(CUIOptionsItem* item, const char* group);
void UnRegisterGroup(const char* group);
void UnRegisterItem(CUIOptionsItem* item);
typedef xr_string group_name;
typedef xr_vector<CUIOptionsItem*> items_list;
typedef xr_map<group_name, items_list> groups;
typedef xr_map<group_name, items_list>::iterator groups_it;
groups m_groups;
bool m_b_vid_restart;
bool m_b_snd_restart{};
}; | 412 | 0.926164 | 1 | 0.926164 | game-dev | MEDIA | 0.370774 | game-dev | 0.6346 | 1 | 0.6346 |
mojontwins/MK2 | 9,792 | examples/journey/dev/definitions.h | // MT MK2 ZX v1.0
// Copyleft 2010-2015, 2019 by The Mojon Twins
// definitions.h
// Main definitions
// General defines
#define EST_NORMAL 0
#define EST_PARP 2
#define EST_MUR 4
#define EST_DIZZY 8
#define sgni(n) (n < 0 ? -1 : 1)
#define saturate(n) (n < 0 ? 0 : n)
#define WTOP 1
#define WBOTTOM 2
#define WLEFT 3
#define WRIGHT 4
#define FACING_RIGHT 0
#define FACING_LEFT 2
#define FACING_UP 4
#define FACING_DOWN 6
#define SENG_JUMP 0
#define SENG_SWIM 1
#define SENG_COPT 2
#define SENG_JETP 3
#define SENG_BOOT 4
#define FANTIES_IDLE 0
#define FANTIES_PURSUING 1
#define FANTIES_RETREATING 2
#define GENERAL_DYING 4
#define MAX_FLAGS 32
#define BUFFER_IDX(x,y) x+(y<<4)-y
#define TILE_EVIL 1
#define TILE_HOLE 2
#define MAX_TILANIMS 16
#define TILANIMS_PRIME 3 // Prime to MAX_TILANIMS, ideally /4-1
// Keys
#define KEY_L 0x02bf
#define KEY_M 0x047f
#define KEY_H 0x08bf
#define KEY_Y 0x10df
// General externs
unsigned int asm_int @ SAFE_INT_ADDRESS;
unsigned int asm_int_2 @ SAFE_INT_ADDRESS + 2;
unsigned int safe_byte @ SAFE_INT_ADDRESS + 4;
// Gigaglobals
struct sp_UDK keys;
unsigned char (*joyfunc)(struct sp_UDK *) = sp_JoyKeyboard;
const void *joyfuncs [] = {
sp_JoyKeyboard, sp_JoyKeyboard, sp_JoyKempston, sp_JoySinclair1
};
unsigned char *gen_pt;
void *my_malloc(uint bytes) {
return sp_BlockAlloc(0);
}
void *u_malloc = my_malloc;
void *u_free = sp_FreeBlock;
struct sp_SS *sp_player;
struct sp_SS *sp_moviles [3];
#ifdef PLAYER_CAN_FIRE
struct sp_SS *sp_bullets [MAX_BULLETS];
#endif
#if defined (PLAYER_CAN_PUNCH) || defined (PLAYER_HAZ_SWORD) || defined (PLAYER_HAZ_WHIP)
struct sp_SS *sp_hitter;
#endif
#ifdef ENABLE_SHOOTERS
struct sp_SS *sp_cocos [MAX_COCOS];
#endif
#ifdef ENABLE_FLOATING_OBJECTS
#ifdef ENABLE_FO_CARRIABLE_BOXES
struct sp_SS *sp_carriable;
#endif
#endif
#if defined (PLAYER_GENITAL) && defined (PLAYER_HAS_JUMP)
struct sp_SS *sp_shadow;
#endif
#asm
.vpClipStruct defb VIEWPORT_Y, VIEWPORT_Y + 20, VIEWPORT_X, VIEWPORT_X + 30
.fsClipStruct defb 0, 24, 0, 32
#endasm
unsigned char enoffs;
// Aux
unsigned char half_life = 0;
// Player
signed int p_x, p_y;
#if defined (HANNA_ENGINE)
signed char p_v;
#else
signed char p_vx, p_vy, ptgmx, ptgmy;
#endif
#if defined (PLAYER_GENITAL) && defined (PLAYER_HAS_JUMP)
signed int p_z, p_vz;
unsigned char p_jmp_facing, gpz;
#endif
signed char p_g;
#if defined (PLAYER_NEW_GENITAL) && defined (ENABLE_BEH_64)
signed char p_ax, p_rx;
#endif
#ifdef PLAYER_GENITAL
signed char p_thrust;
#endif
unsigned char p_jmp_ct;
unsigned char *p_c_f, *p_n_f;
unsigned char p_jmp_on;
unsigned char p_frame, p_subframe, p_facing;
unsigned char p_state;
unsigned char p_state_ct;
unsigned char p_gotten;
unsigned char p_life, p_objs, p_keys;
#ifndef BODY_COUNT_ON
unsigned char p_killed;
#endif
unsigned char p_disparando;
#if defined (PLAYER_CAN_PUNCH) || defined (PLAYER_HAZ_SWORD) || defined (PLAYER_HAZ_WHIP)
unsigned char p_hitting;
#endif
#ifdef PLAYER_HAZ_SWORD
unsigned char p_up;
#endif
unsigned char p_facing_v, p_facing_h;
unsigned char p_killme;
#ifdef DIE_AND_RESPAWN
unsigned char p_safe_pant, p_safe_x, p_safe_y;
#endif
#ifdef MAX_AMMO
unsigned char p_ammo;
#endif
#ifdef ENABLE_FO_CARRIABLE_BOXES
unsigned char p_hasbox;
#endif
#ifdef JETPAC_DEPLETES
unsigned char p_fuel;
#endif
#ifdef ENABLE_HOLES
unsigned char p_ct_hole;
#endif
#ifdef ENABLE_KILL_SLOWLY
unsigned char p_ks_gauge;
unsigned char p_ks_fc;
#endif
// Collisions
unsigned char cx1, cx2, cy1, cy2, at1, at2;
unsigned char ptx1, pty1, ptx2, pty2;
// Make some player values variable. Preliminary, just the maximum jump speed...
#ifdef PLAYER_VARIABLE_JUMP
signed int PLAYER_JMP_VY_MAX;
#endif
// Enems on screen
unsigned char en_an_base_frame [3];
//unsigned char en_an_frame [3];
unsigned char en_an_count [3];
unsigned char *en_an_c_f [3], *en_an_n_f [3];
unsigned char en_an_state [3];
#ifdef ENEMY_BACKUP
unsigned char enemy_backup [3 * MAP_W * MAP_H];
#endif
#ifdef PLAYER_CAN_FIRE
unsigned char en_an_morido [3];
#endif
#if defined (RANDOM_RESPAWN) || defined (ENABLE_CUSTOM_FANTIES)
signed int en_an_x [3];
signed int en_an_y [3];
signed char en_an_vx [3];
signed char en_an_vy [3];
#ifdef RANDOM_RESPAWN
unsigned char en_an_fanty_activo [3];
#endif
signed int _en_an_x, _en_an_y;
signed char _en_an_vx, _en_an_vy;
#endif
#ifdef ENABLE_PURSUERS
unsigned char en_an_alive [3];
unsigned char en_an_dead_row [3];
unsigned char en_an_rawv [3];
#endif
#ifdef ENABLE_HANNA_MONSTERS_11
unsigned char en_an_dir [3];
unsigned char _en_cx, _en_cy;
#endif
#if defined (ENABLE_SHOOTERS) || defined (ENABLE_CLOUDS)
unsigned char coco_x [MAX_COCOS], coco_y [MAX_COCOS], coco_s [MAX_COCOS], ctx, cty;
signed char coco_vx [MAX_COCOS], coco_vy [MAX_COCOS];
unsigned char coco_it, coco_d, coco_x0;
#endif
unsigned char pregotten;
#if defined (ENABLE_SHOOTERS) || defined (ENABLE_ARROWS)
unsigned char enemy_shoots;
#endif
#ifdef ENEMS_MAY_DIE
unsigned char enemy_was_killed;
#endif
// Bullets
#ifdef PLAYER_CAN_FIRE
unsigned char bullets_x [MAX_BULLETS];
unsigned char bullets_y [MAX_BULLETS];
signed char bullets_mx [MAX_BULLETS];
signed char bullets_my [MAX_BULLETS];
unsigned char bullets_estado [MAX_BULLETS];
#ifdef LIMITED_BULLETS
unsigned char bullets_life [MAX_BULLETS];
#endif
#endif
#if defined (PLAYER_CAN_PUNCH) || defined (PLAYER_HAZ_SWORD) || defined (PLAYER_HAZ_WHIP)
unsigned char hitter_on;
unsigned char hitter_type;
unsigned char hitter_frame;
unsigned char hitter_x, hitter_y;
unsigned char *hitter_c_f, *hitter_n_f;
unsigned char hitter_hit;
#endif
// Current screen buffers
unsigned char map_attr [150];
// There's XXX bytes free at FREEPOOL according to splib2's doc.
// (240 if in 128K mode, 512 - stack size (do not risk!) in 48K mode)
// Why not use them?
unsigned char map_buff [150] @ FREEPOOL;
//
// Current screen hotspot
unsigned char hotspot_x;
unsigned char hotspot_y;
unsigned char orig_tile;
unsigned char do_respawn;
unsigned char no_draw;
// Flags para scripting
#if defined (ACTIVATE_SCRIPTING) || defined (TILE_GET) || defined (ENABLE_SIM)
unsigned char flags[MAX_FLAGS];
#endif
// Globalized
unsigned char n_pant, o_pant;
unsigned char level = 0;
unsigned char silent_level;
unsigned char is_rendering;
unsigned char maincounter;
// Breakable walls/etc
#if (defined BREAKABLE_WALLS || defined BREAKABLE_WALLS_SIMPLE) && defined BREAKABLE_ANIM
// Store this in the free memory pool (see ^)
unsigned char breaking_x [MAX_BREAKABLE] @ FREEPOOL + 150;
unsigned char breaking_y [MAX_BREAKABLE] @ FREEPOOL + 150 + MAX_BREAKABLE;
unsigned char breaking_f [MAX_BREAKABLE] @ FREEPOOL + 150 + MAX_BREAKABLE + MAX_BREAKABLE;
unsigned char breaking_idx = 0;
unsigned char do_process_breakable = 0;
#endif
#ifdef BREAKABLE_WALLS
unsigned char brk_buff [150];
#endif
// Fire zone
#ifdef ENABLE_FIRE_ZONE
unsigned char fzx1, fzy1, fzx2, fzy2, f_zone_ac;
#endif
// Timer
#ifdef TIMER_ENABLE
typedef struct {
unsigned char on;
unsigned char t;
unsigned char frames;
unsigned char count;
unsigned char zero;
} CTIMER;
CTIMER ctimer;
#endif
#if defined (ACTIVATE_SCRIPTING) && defined (ENABLE_PUSHED_SCRIPTING)
unsigned char just_pushed;
#endif
#ifdef USE_TWO_BUTTONS
signed int key_jump, key_fire;
#endif
#if defined (ENABLE_SIM)
unsigned char key_z_pressed = 0;
#endif
#if defined (PLAYER_CHECK_MAP_BOUNDARIES) || defined (PLAYER_CYCLIC_MAP)
unsigned char x_pant, y_pant;
#endif
unsigned char do_gravity = 1, p_engine;
#ifdef ENABLE_SIM
unsigned char items [SIM_DISPLAY_MAXITEMS];
void display_items (void);
#endif
unsigned char enoffsmasi;
#ifdef SCRIPTING_KEY_FIRE
unsigned char invalidate_fire = 0;
#endif
#ifdef MAP_ATTRIBUTES
unsigned char cur_map_attr = 99;
#endif
// Engine globals (for speed) & size!
unsigned char gpx, gpy, gpd, gpc, gpt, gps, rdx, rdy, rda, rdb;
signed char rds;
unsigned char gpxx, gpyy, gpcx, gpcy;
unsigned char possee, hit_v, hit_h, hit, wall_h, wall_v;
unsigned char gpaux;
unsigned char _en_x, _en_y, _en_x1, _en_y1, _en_x2, _en_y2, _en_t, _en_life;
signed char _en_mx, _en_my;
unsigned char *_baddies_pointer;
unsigned char tocado, active, killable, animate;
unsigned char gpit, gpjt;
unsigned char *map_pointer;
unsigned char enit;
signed int _val, _min, _max;
#if defined USE_AUTO_TILE_SHADOWS || defined USE_AUTO_SHADOWS
unsigned char c1, c2, c3, c4;
unsigned char t1, t2, t3, t4;
unsigned char nocast, _ta;
unsigned char xx, yy;
#endif
#ifdef USE_AUTO_TILE_SHADOWS
unsigned a1, a2, a3;
unsigned char *gen_pt_alt;
unsigned char t_alt;
#endif
// Undo parameters
unsigned char _x, _y, _t, _n;
unsigned char *gp_gen;
#if defined (PLAYER_PUSH_BOXES) || !defined (DEACTIVATE_KEYS)
unsigned char x0, y0, x1, y1;
#endif
#ifdef ENABLE_TILANIMS
unsigned char tait;
unsigned char max_tilanims;
unsigned char tacount;
unsigned char tilanims_xy [MAX_TILANIMS];
unsigned char tilanims_ft [MAX_TILANIMS];
#endif
#ifdef MIN_FAPS_PER_FRAME
unsigned char isrc @ ISRC_ADDRESS;
#endif
unsigned char pad0, pad_this_frame;
#ifdef CUSTOM_HIT
unsigned char was_hit_by_type;
#endif
unsigned char action_pressed;
#ifdef GET_X_MORE
unsigned char *getxmore = " GET X MORE ";
#endif
#ifdef COMPRESSED_LEVELS
unsigned char mlplaying;
#endif
unsigned char success;
unsigned char playing;
#ifdef SHOW_FPS
unsigned char game_frame_counter;
unsigned char tv_frame_counter;
#endif
#ifdef MODE_128K
unsigned char song_playing;
#endif
#ifdef ENABLE_TILANIMS
#if TILANIMS_PERIOD > 1
unsigned char tilanims_counter;
#endif
#if defined (TILANIMS_SEVERAL_TYPES) && !defined (TILANIMS_TYPE_SELECT_FLAG)
unsigned char tilanims_type_select;
#endif
#endif
| 412 | 0.813171 | 1 | 0.813171 | game-dev | MEDIA | 0.64572 | game-dev | 0.549587 | 1 | 0.549587 |
swgemu/Core3 | 1,561 | MMOCoreORB/src/server/zone/managers/creature/SpawnObserverImplementation.cpp |
#include "server/zone/managers/creature/SpawnObserver.h"
#include "server/zone/objects/creature/ai/AiAgent.h"
#include "server/zone/objects/tangible/weapon/WeaponObject.h"
#include "server/zone/managers/gcw/observers/SquadObserver.h"
void SpawnObserverImplementation::despawnSpawns() {
Vector<ManagedReference<AiAgent* > > agents;
for (int i = spawnedCreatures.size() - 1; i >= 0; --i) {
ManagedReference<CreatureObject*> creature = spawnedCreatures.get(i);
spawnedCreatures.remove(i);
if (creature == nullptr) {
continue;
}
auto agent = cast<AiAgent*>(creature.get());
if (agent == nullptr || agent->isPet()) {
continue;
}
agents.add(agent);
}
// info(true) << "SpawnObserverImplementation::despawnSpawns() -- LAIR IS DESTROYED! - Setting " << agents.size() << " agents to despawn!";
for (int i = agents.size() - 1; i >= 0; --i) {
auto agent = agents.get(i);
// Remove it from the list
agents.remove(i);
if (agent != nullptr) {
Core::getTaskManager()->executeTask([agent]() {
if (agent == nullptr)
return;
Locker locker(agent);
SortedVector<ManagedReference<Observer* > > observers = agent->getObservers(ObserverEventType::SQUAD);
for (int i = observers.size() - 1; i >= 0; --i) {
ManagedReference<SquadObserver*> squadObserver = cast<SquadObserver*>(observers.get(i).get());
if (squadObserver != nullptr) {
agent->dropObserver(ObserverEventType::SQUAD, squadObserver);
}
}
agent->setDespawnOnNoPlayerInRange(true);
}, "DespawnSpawnsLambda");
}
}
}
| 412 | 0.911079 | 1 | 0.911079 | game-dev | MEDIA | 0.966072 | game-dev | 0.923713 | 1 | 0.923713 |
CrashRpt/crashrpt2 | 3,832 | reporting/crashrpt/Utility.h | /*************************************************************************************
This file is a part of CrashRpt library.
Copyright (c) 2003-2013 The CrashRpt project authors. All Rights Reserved.
Use of this source code is governed by a BSD-style license
that can be found in the License.txt file in the root of the source
tree. All contributing project authors may
be found in the Authors.txt file in the root of the source tree.
***************************************************************************************/
// File: Utility.h
// Description: Miscellaneous helper functions
// Authors: mikecarruth, zexspectrum
// Date:
#ifndef _UTILITY_H_
#define _UTILITY_H_
#include "stdafx.h"
namespace Utility
{
// Returns base name of the EXE file that launched current process.
CString getAppName();
// Returns the unique tmp file name.
CString getTempFileName();
// Returns the path to the temporary directory.
int getTempDirectory(CString& strTemp);
// Returns path to directory where EXE or DLL module is located.
CString GetModulePath(HMODULE hModule);
// Returns the absolute path and name of the module
CString GetModuleName(HMODULE hModule);
// Generates unique identifier (GUID)
int GenerateGUID(CString& sGUID);
// Returns current system time as string (uses UTC time format).
int GetSystemTimeUTC(CString& sTime);
// Converts UTC string to local time.
void UTC2SystemTime(CString sUTC, SYSTEMTIME& st);
// Returns friendly name of operating system (name, version, service pack)
int GetOSFriendlyName(CString& sOSName);
// Returns TRUE if Windows is 64-bit
BOOL IsOS64Bit();
// Retrieves current geographic location
int GetGeoLocation(CString& sGeoLocation);
// Returns path to a special folder (for example %LOCAL_APP_DATA%)
int GetSpecialFolder(int csidl, CString& sFolderPath);
// Replaces restricted characters in file name
CString ReplaceInvalidCharsInFileName(CString sFileName);
// Moves a file to the Recycle Bin or removes the file permanently
int RecycleFile(CString sFilePath, bool bPermanentDelete);
// Retrieves a string from INI file.
CString GetINIString(LPCTSTR pszFileName, LPCTSTR pszSection, LPCTSTR pszName);
// Adds a string to INI file.
void SetINIString(LPCTSTR pszFileName, LPCTSTR pszSection, LPCTSTR pszName, LPCTSTR pszValue);
// Mirrors the content of a window.
void SetLayoutRTL(HWND hWnd);
// Formats the error message.
CString FormatErrorMsg(DWORD dwErrorCode);
// Parses file path and returns file name.
CString GetFileName(CString sPath);
// Parses file path and returns file name without extension.
CString GetBaseFileName(CString sFileName);
// Parses file path and returns file extension.
CString GetFileExtension(CString sFileName);
// Returns TRUE if the file name is a search pattern (containing ? or * characters).
BOOL IsFileSearchPattern(CString sFileName);
// Retrieves product version info from resources embedded into EXE or DLL
CString GetProductVersion(CString sModuleName);
// Creates a folder. If some intermediate folders in the path do not exist,
// it creates them.
BOOL CreateFolder(CString sFolderName);
// Converts system time to UINT64
ULONG64 SystemTimeToULONG64( const SYSTEMTIME& st );
// Formats a string of file size
CString FileSizeToStr(ULONG64 uFileSize);
// This helper function checks if the string is too long and truncates it with ellipsis (...).
CString AddEllipsis(LPCTSTR szString, int nMaxLength);
// Splits string into list of tokens.
std::vector<CString> ExplodeStr(LPCTSTR szString, LPCTSTR szSeparators);
// Returns file size
long GetFileSize(const TCHAR *fileName);
};
#endif // _UTILITY_H_
| 412 | 0.891821 | 1 | 0.891821 | game-dev | MEDIA | 0.542604 | game-dev | 0.742206 | 1 | 0.742206 |
tbarbanti/OpenFaceUE | 7,567 | ThirdParty/dlib/include/dlib/map/map_kernel_c.h | // Copyright (C) 2003 Davis E. King (davis@dlib.net)
// License: Boost Software License See LICENSE.txt for the full license.
#ifndef DLIB_MAP_KERNEl_C_
#define DLIB_MAP_KERNEl_C_
#include "map_kernel_abstract.h"
#include "../algs.h"
#include "../assert.h"
#include "../interfaces/map_pair.h"
namespace dlib
{
template <
typename map_base
>
class map_kernel_c : public map_base
{
typedef typename map_base::domain_type domain;
typedef typename map_base::range_type range;
public:
void add (
domain& d,
range& r
);
void remove_any (
domain& d,
range& r
);
void remove (
const domain& d,
domain& d_copy,
range& r
);
void destroy (
const domain& d
);
range& operator[] (
const domain& d
);
const range& operator[] (
const domain& d
) const;
const map_pair<domain,range>& element (
) const
{
// make sure requires clause is not broken
DLIB_CASSERT(this->current_element_valid() == true,
"\tconst map_pair<domain,range>& map::element"
<< "\n\tyou can't access the current element if it doesn't exist"
<< "\n\tthis: " << this
);
// call the real function
return map_base::element();
}
map_pair<domain,range>& element (
)
{
// make sure requires clause is not broken
DLIB_CASSERT(this->current_element_valid() == true,
"\tmap_pair<domain,range>& map::element"
<< "\n\tyou can't access the current element if it doesn't exist"
<< "\n\tthis: " << this
);
// call the real function
return map_base::element();
}
};
template <
typename map_base
>
inline void swap (
map_kernel_c<map_base>& a,
map_kernel_c<map_base>& b
) { a.swap(b); }
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
// member function definitions
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
template <
typename map_base
>
void map_kernel_c<map_base>::
add (
domain& d,
range& r
)
{
// make sure requires clause is not broken
DLIB_CASSERT( (!this->is_in_domain(d)) &&
(static_cast<void*>(&d) != static_cast<void*>(&r)),
"\tvoid map::add"
<< "\n\tdomain element being added must not already be in the map"
<< "\n\tand d and r must not be the same variable"
<< "\n\tis_in_domain(d): " << (this->is_in_domain(d) ? "true" : "false")
<< "\n\tthis: " << this
<< "\n\t&d: " << static_cast<void*>(&d)
<< "\n\t&r: " << static_cast<void*>(&r)
);
// call the real function
map_base::add(d,r);
}
// ----------------------------------------------------------------------------------------
template <
typename map_base
>
void map_kernel_c<map_base>::
remove_any (
domain& d,
range& r
)
{
// make sure requires clause is not broken
DLIB_CASSERT( (this->size() > 0) &&
(static_cast<void*>(&d) != static_cast<void*>(&r)),
"\tvoid map::remove_any"
<< "\n\tsize() must be greater than zero if something is going to be removed"
<< "\n\tand d and r must not be the same variable."
<< "\n\tsize(): " << this->size()
<< "\n\tthis: " << this
<< "\n\t&d: " << static_cast<void*>(&d)
<< "\n\t&r: " << static_cast<void*>(&r)
);
// call the real function
map_base::remove_any(d,r);
}
// ----------------------------------------------------------------------------------------
template <
typename map_base
>
void map_kernel_c<map_base>::
remove (
const domain& d,
domain& d_copy,
range& r
)
{
// make sure requires clause is not broken
DLIB_CASSERT( (this->is_in_domain(d)) &&
(static_cast<const void*>(&d) != static_cast<void*>(&r)) &&
(static_cast<void*>(&r) != static_cast<void*>(&d_copy)) &&
(static_cast<const void*>(&d) != static_cast<void*>(&d_copy)),
"\tvoid map::remove"
<< "\n\tcan't remove something that isn't in the map or if the paremeters actually"
<< "\n\tare the same variable. Either way can't remove."
<< "\n\tis_in_domain(d): " << (this->is_in_domain(d) ? "true" : "false")
<< "\n\tthis: " << this
<< "\n\t&d: " << static_cast<const void*>(&d)
<< "\n\t&r: " << static_cast<void*>(&r)
<< "\n\t&d_copy: " << static_cast<void*>(&d_copy)
);
// call the real function
map_base::remove(d,d_copy,r);
}
// ----------------------------------------------------------------------------------------
template <
typename map_base
>
void map_kernel_c<map_base>::
destroy (
const domain& d
)
{
// make sure requires clause is not broken
DLIB_CASSERT(this->is_in_domain(d),
"\tvoid map::destroy"
<< "\n\tcan't remove something that isn't in the map"
<< "\n\tthis: " << this
<< "\n\t&d: " << static_cast<const void*>(&d)
);
// call the real function
map_base::destroy(d);
}
// ----------------------------------------------------------------------------------------
template <
typename map_base
>
typename map_base::range_type& map_kernel_c<map_base>::
operator[] (
const domain& d
)
{
// make sure requires clause is not broken
DLIB_CASSERT( this->is_in_domain(d),
"\trange& map::operator[]"
<< "\n\td must be in the domain of the map"
<< "\n\tthis: " << this
);
// call the real function
return map_base::operator[](d);
}
// ----------------------------------------------------------------------------------------
template <
typename map_base
>
const typename map_base::range_type& map_kernel_c<map_base>::
operator[] (
const domain& d
) const
{
// make sure requires clause is not broken
DLIB_CASSERT( this->is_in_domain(d),
"\tconst range& map::operator[]"
<< "\n\td must be in the domain of the map"
<< "\n\tthis: " << this
);
// call the real function
return map_base::operator[](d);
}
// ----------------------------------------------------------------------------------------
}
#endif // DLIB_MAP_KERNEl_C_
| 412 | 0.948778 | 1 | 0.948778 | game-dev | MEDIA | 0.679668 | game-dev | 0.916354 | 1 | 0.916354 |
FilipRuman/4Form | 1,826 | godot/addons/terrain_3d/extras/import_sgt.gd | # Copyright © 2025 Cory Petkovsek, Roope Palmroos, and Contributors.
# Import From SimpleGrassTextured
#
# This script demonstrates how to import transforms from SimpleGrassTextured. To use it:
#
# 1. Setup the mesh asset you wish to use in the asset dock.
# 1. Select your Terrain3D node.
# 1. In the inspector, click Script (very bottom) and Quick Load import_sgt.gd.
# 1. At the very top, assign your SimpleGrassTextured node.
# 1. Input the desired mesh asset ID.
# 1. Click import. The output window and console will report when finished.
# 1. Clear the script from your Terrain3D node, and save your scene.
#
# The instance transforms are now stored in your region files.
#
# Use clear_instances to erase all instances that match the assign_mesh_id.
#
# The add_transforms function (called by add_multimesh) applies the height_offset specified in the
# Terrain3DMeshAsset.
# Once the transforms are imported, you can reassign any mesh you like into this mesh slot.
@tool
extends Terrain3D
@export var simple_grass_textured: MultiMeshInstance3D
@export var assign_mesh_id: int
@export var import: bool = false : set = import_sgt
@export var clear_instances: bool = false : set = clear_multimeshes
func clear_multimeshes(value: bool) -> void:
get_instancer().clear_by_mesh(assign_mesh_id)
func import_sgt(value: bool) -> void:
var sgt_mm: MultiMesh = simple_grass_textured.multimesh
var global_xform: Transform3D = simple_grass_textured.global_transform
print("Starting to import %d instances from SimpleGrassTextured using mesh id %d" % [ sgt_mm.instance_count, assign_mesh_id])
var time: int = Time.get_ticks_msec()
get_instancer().add_multimesh(assign_mesh_id, sgt_mm, simple_grass_textured.global_transform)
print("Import complete in %.2f seconds" % [ float(Time.get_ticks_msec() - time)/1000. ])
| 412 | 0.630068 | 1 | 0.630068 | game-dev | MEDIA | 0.235618 | game-dev | 0.78059 | 1 | 0.78059 |
apollo-rsps/apollo | 1,252 | game/data/plugins/areas/actions.rb | require 'java'
java_import 'org.apollo.game.message.impl.DisplayCrossbonesMessage'
java_import 'org.apollo.game.model.entity.Player'
# Registers an area action.
def area_action(name, &block)
AREA_ACTIONS[name] = action = AreaAction.new
action.instance_eval(&block)
end
AREA_ACTIONS = {}
private
# An action that is called when a player enters or exits an area.
class AreaAction
# Sets the block to be called when the player enters the area.
def on_entry(&block)
@on_enter = block
end
# Sets the block to be called while the player is in the area.
def while_in(&block)
@while_in = block
end
# Sets the block to be called when the player exits the area.
def on_exit(&block)
@on_exit = block
end
# Called when the player has entered an area this action is registered to.
def entered(player, position)
@on_enter.call(player, position) unless @on_enter.nil?
end
# Called while the player is in area this action is registered to.
def inside(player, position)
@while_in.call(player, position) unless @while_in.nil?
end
# Called when the player has exited an area this action is registered to.
def exited(player, position)
@on_exit.call(player, position) unless @on_exit.nil?
end
end
| 412 | 0.927254 | 1 | 0.927254 | game-dev | MEDIA | 0.847773 | game-dev | 0.643425 | 1 | 0.643425 |
RCInet/LastEpoch_Mods | 1,672 | AssetBundleExport/Library/PackageCache/com.unity.visualscripting@1b53f46e931b/Editor/VisualScripting.Core/Inspection/OptimizedEditor.cs | using System.Collections.Generic;
using UnityEditor;
namespace Unity.VisualScripting
{
public abstract class OptimizedEditor<TIndividual> : UnityEditor.Editor
where TIndividual : IndividualEditor, new()
{
private TIndividual GetIndividualDrawer(SerializedObject serializedObject)
{
var hash = serializedObject.GetHashCode();
if (!individualDrawers.ContainsKey(hash))
{
var individualDrawer = new TIndividual();
individualDrawer.Initialize(serializedObject, this);
individualDrawers.Add(hash, individualDrawer);
}
return individualDrawers[hash];
}
public sealed override void OnInspectorGUI()
{
if (serializedObject.isEditingMultipleObjects)
{
EditorGUILayout.HelpBox("Multi-object editing is not supported.", MessageType.Info);
return;
}
GetIndividualDrawer(serializedObject).OnGUI();
}
static OptimizedEditor()
{
individualDrawers = new Dictionary<int, TIndividual>();
EditorApplicationUtility.onSelectionChange += ClearCache;
}
private static Dictionary<int, TIndividual> individualDrawers;
private static void ClearCache()
{
try
{
foreach (var individualDrawer in individualDrawers.Values)
{
individualDrawer.Dispose();
}
}
finally
{
individualDrawers.Clear();
}
}
}
}
| 412 | 0.795928 | 1 | 0.795928 | game-dev | MEDIA | 0.775467 | game-dev | 0.955276 | 1 | 0.955276 |
Daivuk/PureDOOM | 8,839 | src/DOOM/p_mobj.h | // Emacs style mode select -*- C++ -*-
//-----------------------------------------------------------------------------
//
// $Id:$
//
// Copyright (C) 1993-1996 by id Software, Inc.
//
// This source is available for distribution and/or modification
// only under the terms of the DOOM Source Code License as
// published by id Software. All rights reserved.
//
// The source is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// FITNESS FOR A PARTICULAR PURPOSE. See the DOOM Source Code License
// for more details.
//
// DESCRIPTION:
// Map Objects, MObj, definition and handling.
//
//-----------------------------------------------------------------------------
#ifndef __P_MOBJ__
#define __P_MOBJ__
// Basics.
#include "tables.h"
#include "m_fixed.h"
// We need the thinker_t stuff.
#include "d_think.h"
// We need the WAD data structure for Map things,
// from the THINGS lump.
#include "doomdata.h"
// States are tied to finite states are
// tied to animation frames.
// Needs precompiled tables/data structures.
#include "info.h"
//
// NOTES: mobj_t
//
// mobj_ts are used to tell the refresh where to draw an image,
// tell the world simulation when objects are contacted,
// and tell the sound driver how to position a sound.
//
// The refresh uses the next and prev links to follow
// lists of things in sectors as they are being drawn.
// The sprite, frame, and angle elements determine which patch_t
// is used to draw the sprite if it is visible.
// The sprite and frame values are allmost allways set
// from state_t structures.
// The statescr.exe utility generates the states.h and states.c
// files that contain the sprite/frame numbers from the
// statescr.txt source file.
// The xyz origin point represents a point at the bottom middle
// of the sprite (between the feet of a biped).
// This is the default origin position for patch_ts grabbed
// with lumpy.exe.
// A walking creature will have its z equal to the floor
// it is standing on.
//
// The sound code uses the x,y, and subsector fields
// to do stereo positioning of any sound effited by the mobj_t.
//
// The play simulation uses the blocklinks, x,y,z, radius, height
// to determine when mobj_ts are touching each other,
// touching lines in the map, or hit by trace lines (gunshots,
// lines of sight, etc).
// The mobj_t->flags element has various bit flags
// used by the simulation.
//
// Every mobj_t is linked into a single sector
// based on its origin coordinates.
// The subsector_t is found with R_PointInSubsector(x,y),
// and the sector_t can be found with subsector->sector.
// The sector links are only used by the rendering code,
// the play simulation does not care about them at all.
//
// Any mobj_t that needs to be acted upon by something else
// in the play world (block movement, be shot, etc) will also
// need to be linked into the blockmap.
// If the thing has the MF_NOBLOCK flag set, it will not use
// the block links. It can still interact with other things,
// but only as the instigator (missiles will run into other
// things, but nothing can run into a missile).
// Each block in the grid is 128*128 units, and knows about
// every line_t that it contains a piece of, and every
// interactable mobj_t that has its origin contained.
//
// A valid mobj_t is a mobj_t that has the proper subsector_t
// filled in for its xy coordinates and is linked into the
// sector from which the subsector was made, or has the
// MF_NOSECTOR flag set (the subsector_t needs to be valid
// even if MF_NOSECTOR is set), and is linked into a blockmap
// block or has the MF_NOBLOCKMAP flag set.
// Links should only be modified by the P_[Un]SetThingPosition()
// functions.
// Do not change the MF_NO? flags while a thing is valid.
//
// Any questions?
//
//
// Misc. mobj flags
//
typedef enum
{
// Call P_SpecialThing when touched.
MF_SPECIAL = 1,
// Blocks.
MF_SOLID = 2,
// Can be hit.
MF_SHOOTABLE = 4,
// Don't use the sector links (invisible but touchable).
MF_NOSECTOR = 8,
// Don't use the blocklinks (inert but displayable)
MF_NOBLOCKMAP = 16,
// Not to be activated by sound, deaf monster.
MF_AMBUSH = 32,
// Will try to attack right back.
MF_JUSTHIT = 64,
// Will take at least one step before attacking.
MF_JUSTATTACKED = 128,
// On level spawning (initial position),
// hang from ceiling instead of stand on floor.
MF_SPAWNCEILING = 256,
// Don't apply gravity (every tic),
// that is, object will float, keeping current height
// or changing it actively.
MF_NOGRAVITY = 512,
// Movement flags.
// This allows jumps from high places.
MF_DROPOFF = 0x400,
// For players, will pick up items.
MF_PICKUP = 0x800,
// Player cheat. ???
MF_NOCLIP = 0x1000,
// Player: keep info about sliding along walls.
MF_SLIDE = 0x2000,
// Allow moves to any height, no gravity.
// For active floaters, e.g. cacodemons, pain elementals.
MF_FLOAT = 0x4000,
// Don't cross lines
// ??? or look at heights on teleport.
MF_TELEPORT = 0x8000,
// Don't hit same species, explode on block.
// Player missiles as well as fireballs of various kinds.
MF_MISSILE = 0x10000,
// Dropped by a demon, not level spawned.
// E.g. ammo clips dropped by dying former humans.
MF_DROPPED = 0x20000,
// Use fuzzy draw (shadow demons or spectres),
// temporary player invisibility powerup.
MF_SHADOW = 0x40000,
// Flag: don't bleed when shot (use puff),
// barrels and shootable furniture shall not bleed.
MF_NOBLOOD = 0x80000,
// Don't stop moving halfway off a step,
// that is, have dead bodies slide down all the way.
MF_CORPSE = 0x100000,
// Floating to a height for a move, ???
// don't auto float to target's height.
MF_INFLOAT = 0x200000,
// On kill, count this enemy object
// towards intermission kill total.
// Happy gathering.
MF_COUNTKILL = 0x400000,
// On picking up, count this item object
// towards intermission item total.
MF_COUNTITEM = 0x800000,
// Special handling: skull in flight.
// Neither a cacodemon nor a missile.
MF_SKULLFLY = 0x1000000,
// Don't spawn this object
// in death match mode (e.g. key cards).
MF_NOTDMATCH = 0x2000000,
// Player sprites in multiplayer modes are modified
// using an internal color lookup table for re-indexing.
// If 0x4 0x8 or 0xc,
// use a translation table for player colormaps
MF_TRANSLATION = 0xc000000,
// Hmm ???.
MF_TRANSSHIFT = 26
} mobjflag_t;
// Map Object definition.
typedef struct mobj_s
{
// List: thinker links.
thinker_t thinker;
// Info for drawing: position.
fixed_t x;
fixed_t y;
fixed_t z;
// More list: links in sector (if needed)
struct mobj_s* snext;
struct mobj_s* sprev;
//More drawing info: to determine current sprite.
angle_t angle; // orientation
spritenum_t sprite; // used to find patch_t and flip value
int frame; // might be ORed with FF_FULLBRIGHT
// Interaction info, by BLOCKMAP.
// Links in blocks (if needed).
struct mobj_s* bnext;
struct mobj_s* bprev;
struct subsector_s* subsector;
// The closest interval over all contacted Sectors.
fixed_t floorz;
fixed_t ceilingz;
// For movement checking.
fixed_t radius;
fixed_t height;
// Momentums, used to update position.
fixed_t momx;
fixed_t momy;
fixed_t momz;
// If == validcount, already checked.
int validcount;
mobjtype_t type;
mobjinfo_t* info; // &mobjinfo[mobj->type]
int tics; // state tic counter
state_t* state;
int flags;
int health;
// Movement direction, movement generation (zig-zagging).
int movedir; // 0-7
int movecount; // when 0, select a new dir
// Thing being chased/attacked (or 0),
// also the originator for missiles.
struct mobj_s* target;
// Reaction time: if non 0, don't attack yet.
// Used by player to freeze a bit after teleporting.
int reactiontime;
// If >0, the target will be chased
// no matter what (even if shot)
int threshold;
// Additional info record for player avatars only.
// Only valid if type == MT_PLAYER
struct player_s* player;
// Player number last looked for.
int lastlook;
// For nightmare respawn.
mapthing_t spawnpoint;
// Thing being chased/attacked for tracers.
struct mobj_s* tracer;
} mobj_t;
#endif
//-----------------------------------------------------------------------------
//
// $Log:$
//
//-----------------------------------------------------------------------------
| 412 | 0.643473 | 1 | 0.643473 | game-dev | MEDIA | 0.9872 | game-dev | 0.723455 | 1 | 0.723455 |
space-wizards/space-station-14 | 1,307 | Content.Server/Ghost/Roles/Raffles/IGhostRoleRaffleDecider.cs | using Robust.Shared.Player;
namespace Content.Server.Ghost.Roles.Raffles;
/// <summary>
/// Chooses a winner of a ghost role raffle.
/// </summary>
[ImplicitDataDefinitionForInheritors]
public partial interface IGhostRoleRaffleDecider
{
/// <summary>
/// Chooses a winner of a ghost role raffle draw from the given pool of candidates.
/// </summary>
/// <param name="candidates">The players in the session at the time of drawing.</param>
/// <param name="tryTakeover">
/// Call this with the chosen winner as argument.
/// <ul><li>If <c>true</c> is returned, your winner was able to take over the ghost role, and the drawing is complete.
/// <b>Do not call <see cref="tryTakeover"/> again after true is returned.</b></li>
/// <li>If <c>false</c> is returned, your winner was not able to take over the ghost role,
/// and you must choose another winner, and call <see cref="tryTakeover"/> with the new winner as argument.</li>
/// </ul>
///
/// If <see cref="tryTakeover"/> is not called, or only returns false, the raffle will end without a winner.
/// Do not call <see cref="tryTakeover"/> with the same player several times.
/// </param>
void PickWinner(IEnumerable<ICommonSession> candidates, Func<ICommonSession, bool> tryTakeover);
}
| 412 | 0.805974 | 1 | 0.805974 | game-dev | MEDIA | 0.691782 | game-dev | 0.679204 | 1 | 0.679204 |
long-war-2/lwotc | 31,133 | LongWarOfTheChosen/Src/LW_OfficerPack_Integrated/Classes/UIArmory_LWOfficerPromotion.uc | //---------------------------------------------------------------------------------------
// FILE: UIArmory_LWOfficerPromotion
// AUTHOR: Amineri (Pavonis Interactive)
// PURPOSE: Tweaked ability selection UI for LW officer system
//---------------------------------------------------------------------------------------
class UIArmory_LWOfficerPromotion extends UIArmory_Promotion config(LW_OfficerPack);
var config bool ALWAYSSHOW;
var config bool ALLOWTRAININGINARMORY;
var config bool INSTANTTRAINING;
var UIButton LeadershipButton;
var localized string strLeadershipButton;
var localized string strLeadershipDialogueTitle;
var localized string strLeadershipDialogueData;
// KDM : -1 = unset, 0 = false, 1 = true
var int AbilityInfoTipIsShowing, SelectAbilityTipIsShowing;
simulated function InitPromotion(StateObjectReference UnitRef, optional bool bInstantTransition)
{
// If the AfterAction screen is running, let it position the camera
AfterActionScreen = UIAfterAction(Movie.Stack.GetScreen(class'UIAfterAction'));
if (AfterActionScreen != none)
{
bAfterActionPromotion = true;
PawnLocationTag = AfterActionScreen.GetPawnLocationTag(UnitRef);
CameraTag = AfterActionScreen.GetPromotionBlueprintTag(UnitRef);
DisplayTag = name(AfterActionScreen.GetPromotionBlueprintTag(UnitRef));
}
else
{
CameraTag = GetPromotionBlueprintTag(UnitRef);
DisplayTag = name(GetPromotionBlueprintTag(UnitRef));
}
// Don't show nav help during tutorial, or during the After Action sequence.
bUseNavHelp = class'XComGameState_HeadquartersXCom'.static.IsObjectiveCompleted('T0_M2_WelcomeToArmory') || Movie.Pres.ScreenStack.IsInStack(class'UIAfterAction');
super(UIArmory).InitArmory(UnitRef,,,,,, bInstantTransition);
List = Spawn(class'UIList', self);
List.bAutosizeItems = false;
List.bStickyHighlight = false;
List.OnSelectionChanged = PreviewRow;
List.InitList('', 58, 170, 630, 700);
LeadershipButton = Spawn(class'UIButton', self);
// KDM : Make the Leadership button a hotlink when using a controller.
LeadershipButton.InitButton(, strLeadershipButton, ViewLeadershipStats, eUIButtonStyle_HOTLINK_BUTTON);
// KDM : Add the gamepad icon, right stick click, when a controller is in use.
LeadershipButton.SetGamepadIcon(class'UIUtilities_Input'.static.GetGamepadIconPrefix() $ class'UIUtilities_Input'.const.ICON_RSCLICK_R3);
LeadershipButton.SetPosition(58, 971);
// KDM : Set up the navigator; ClassRowItem is not used for officers, so we can safely ignore it.
Navigator.Clear();
Navigator.LoopSelection = false;
Navigator.AddControl(List);
Navigator.SetSelected(List);
PopulateData();
MC.FunctionVoid("animateIn");
}
simulated function bool CanUnitEnterOTSTraining(XComGameState_Unit Unit)
{
local StaffUnitInfo UnitInfo;
local XComGameState_StaffSlot StaffSlotState;
UnitInfo.UnitRef = Unit.GetReference();
if (`SCREENSTACK.IsInStack(class'UIFacility_Academy'))
{
return true;
}
StaffSlotState = GetEmptyOfficerTrainingStaffSlot();
if (StaffSlotState != none &&
class'X2StrategyElement_LW_OTS_OfficerStaffSlot'.static.IsUnitValidForOTSOfficerSlot(StaffSlotState, UnitInfo))
{
return true;
}
return false;
}
simulated function PopulateData()
{
local bool bHasAbility1, bHasAbility2, DisplayOnly;
local int i, MaxRank, RankToPromote, SelectionIndex;
local string AbilityIcon1, AbilityIcon2, AbilityName1, AbilityName2, HeaderString;
local UIArmory_LWOfficerPromotionItem Item;
local X2AbilityTemplate AbilityTemplate1, AbilityTemplate2;
local X2AbilityTemplateManager AbilityTemplateManager;
local XComGameState_Unit Unit;
local XComGameState_Unit_LWOfficer OfficerState;
AbilityTemplateManager = class'X2AbilityTemplateManager'.static.GetAbilityTemplateManager();
Unit = GetUnit();
DisplayOnly = !CanUnitEnterOTSTraining(Unit);
MaxRank = class'LWOfficerUtilities'.static.GetMaxRank();
SelectionIndex = INDEX_NONE;
if (default.ALLOWTRAININGINARMORY)
{
DisplayOnly = false;
}
// Differentiate header based on whether we are in the Armory or the OTS Facility.
if (DisplayOnly)
{
HeaderString = m_strAbilityHeader;
}
else
{
HeaderString = m_strSelectAbility;
}
// Clear left and right ability titles
AS_SetTitle("", HeaderString, "", "", "");
// Init but then hide the first row, since it's set up for both class and single ability
if (ClassRowItem == none)
{
ClassRowItem = Spawn(class'UIArmory_PromotionItem', self);
ClassRowItem.MCName = 'classRow';
ClassRowItem.InitPromotionItem(0);
}
ClassRowItem.Hide();
// Core, non-selectable, officer abilities are shown as the list's 1st row; these are "Leadership" and "Command".
Item = UIArmory_LWOfficerPromotionItem(List.GetItem(0));
if (Item == none)
{
Item = UIArmory_LWOfficerPromotionItem(List.CreateItem(class'UIArmory_LWOfficerPromotionItem'));
Item.InitPromotionItem(0);
}
Item.Rank = 1;
Item.SetRankData(class'LWOfficerUtilities'.static.GetRankIcon(1), Caps(class'LWOfficerUtilities'.static.GetLWOfficerRankName(1)));
AbilityTemplate1 = AbilityTemplateManager.FindAbilityTemplate(class'LWOfficerUtilities'.default.OfficerAbilityTree[0].AbilityName);
AbilityName1 = Caps(AbilityTemplate1.LocFriendlyName);
AbilityIcon1 = AbilityTemplate1.IconImage;
Item.AbilityName1 = AbilityTemplate1.DataName;
AbilityTemplate2 = AbilityTemplateManager.FindAbilityTemplate(class'LWOfficerUtilities'.default.OfficerAbilityTree[1].AbilityName);
AbilityName2 = Caps(AbilityTemplate2.LocFriendlyName);
AbilityIcon2 = AbilityTemplate2.IconImage;
Item.AbilityName2 = AbilityTemplate2.DataName;
Item.SetAbilityData(AbilityIcon1, AbilityName1, AbilityIcon2, AbilityName2);
Item.SetEquippedAbilities(true, true);
Item.SetPromote(false);
Item.SetDisabled(false);
Item.RealizeVisuals();
// Show the rest of the officer rows; these will have the officer's selectable abilities.
for (i = 1; i <= MaxRank; ++i)
{
Item = UIArmory_LWOfficerPromotionItem(List.GetItem(i));
if (Item == none)
{
Item = UIArmory_LWOfficerPromotionItem(List.CreateItem(class'UIArmory_LWOfficerPromotionItem'));
Item.InitPromotionItem(i);
}
Item.Rank = i;
Item.SetRankData(class'LWOfficerUtilities'.static.GetRankIcon(Item.Rank), Caps(class'LWOfficerUtilities'.static.GetLWOfficerRankName(Item.Rank)));
AbilityTemplate1 = AbilityTemplateManager.FindAbilityTemplate(class'LWOfficerUtilities'.static.GetAbilityName(Item.Rank, 0));
AbilityTemplate2 = AbilityTemplateManager.FindAbilityTemplate(class'LWOfficerUtilities'.static.GetAbilityName(Item.Rank, 1));
OfficerState = class'LWOfficerUtilities'.static.GetOfficerComponent(Unit);
if (OfficerState != none)
{
// KDM : Determines if the officer already has either of these abilities.
bHasAbility1 = OfficerState.HasOfficerAbility(AbilityTemplate1.DataName);
bHasAbility2 = OfficerState.HasOfficerAbility(AbilityTemplate2.DataName);
}
// KDM : Determines which row of officer abilites is the current promotion row.
if (DisplayOnly)
{
RankToPromote = -1;
}
else if (OfficerState == none)
{
RankToPromote = 1;
}
else
{
RankToPromote = OfficerState.GetOfficerRank() + 1;
}
// Left side ability
if (AbilityTemplate1 != none)
{
Item.AbilityName1 = AbilityTemplate1.DataName;
// KDM : Determines whether we show the ability name and icon, or an unknown ability name and icon.
if (default.ALWAYSSHOW || class'XComGameState_LWPerkPackOptions'.static.IsViewLockedStatsEnabled() || Item.Rank <= OfficerState.GetOfficerRank() ||
(!DisplayOnly && Item.Rank == RankToPromote))
{
AbilityName1 = Caps(AbilityTemplate1.LocFriendlyName);
AbilityIcon1 = AbilityTemplate1.IconImage;
}
else
{
AbilityName1 = class'UIUtilities_Text'.static.GetColoredText(m_strAbilityLockedTitle, eUIState_Disabled);
AbilityIcon1 = class'UIUtilities_Image'.const.UnknownAbilityIcon;
}
}
// Right side ability
if (AbilityTemplate2 != none)
{
Item.AbilityName2 = AbilityTemplate2.DataName;
// KDM : Determines whether we show the ability name and icon, or an unknown ability name and icon.
if (default.ALWAYSSHOW || class'XComGameState_LWPerkPackOptions'.static.IsViewLockedStatsEnabled() || Item.Rank <= OfficerState.GetOfficerRank() ||
(!DisplayOnly && Item.Rank == RankToPromote))
{
AbilityName2 = Caps(AbilityTemplate2.LocFriendlyName);
AbilityIcon2 = AbilityTemplate2.IconImage;
}
else
{
AbilityName2 = class'UIUtilities_Text'.static.GetColoredText(m_strAbilityLockedTitle, eUIState_Disabled);
AbilityIcon2 = class'UIUtilities_Image'.const.UnknownAbilityIcon;
}
}
Item.SetAbilityData(AbilityIcon1, AbilityName1, AbilityIcon2, AbilityName2);
Item.SetEquippedAbilities(bHasAbility1, bHasAbility2);
// KDM : If this is the promotion row, highlight it as such; this row will also be given initial focus.
if (Item.Rank == RankToPromote)
{
Item.SetPromote(true);
SelectionIndex = i;
}
else
{
Item.SetPromote(false);
}
if ((Item.Rank <= OfficerState.GetOfficerRank()) || (Item.Rank == RankToPromote) || default.ALWAYSSHOW ||
class'XComGameState_LWPerkPackOptions'.static.IsViewLockedStatsEnabled())
{
Item.SetDisabled(false);
}
else
{
Item.SetDisabled(true);
}
Item.RealizeVisuals();
}
// Update ability summary at the bottom
PopulateAbilitySummary(Unit);
// KDM : If there was no promotion row, select the highest ranking row the officer has attained.
if (SelectionIndex == INDEX_NONE)
{
SelectionIndex = OfficerState.GetOfficerRank();
}
// KDM : Whenever list selection is changed, PreviewRow() is called, due to the setting of OnSelectionChanged within InitPromotion().
// The parameter, bForce, is set to true so that PreviewRow() is called regardless of the list's previously selected index.
// This matters when the next/previous soldier button is clicked, with the 2 soldiers having the same rank and, thus, SelectionIndex.
List.SetSelectedIndex(SelectionIndex, true);
UpdateNavHelp();
}
simulated function PopulateAbilitySummary(XComGameState_Unit Unit)
{
local int i, Index;
local X2AbilityTemplate AbilityTemplate;
local X2AbilityTemplateManager AbilityTemplateManager;
local XComGameState_Unit_LWOfficer OfficerState;
`Log("Populating ability summary for " $ Unit.GetName(eNameType_Full));
Movie.Pres.m_kTooltipMgr.RemoveTooltipsByPartialPath(string(MCPath) $ ".abilitySummaryList");
OfficerState = class'LWOfficerUtilities'.static.GetOfficerComponent(Unit);
if (OfficerState == none || OfficerState.GetOfficerRank() == 0)
{
MC.FunctionVoid("hideAbilityList");
return;
}
MC.FunctionString("setSummaryTitle", class'UIScreenListener_Armory_Promotion_LWOfficerPack'.default.strOfficerMenuOption);
// Populate ability list (multiple param function call: image then title then description)
MC.BeginFunctionOp("setAbilitySummaryList");
Index = 0;
AbilityTemplateManager = class'X2AbilityTemplateManager'.static.GetAbilityTemplateManager();
`Log("Soldier has " $ OfficerState.OfficerAbilities.Length $ " officer abilities");
for (i = 0; i < OfficerState.OfficerAbilities.Length; ++i)
{
AbilityTemplate = AbilityTemplateManager.FindAbilityTemplate(OfficerState.OfficerAbilities[i].AbilityType.AbilityName);
if (AbilityTemplate != none && !AbilityTemplate.bDontDisplayInAbilitySummary)
{
`Log("Adding " $ AbilityTemplate.DataName $ " to the summary");
class'UIUtilities_Strategy'.static.AddAbilityToSummary(self, AbilityTemplate, Index++, Unit, none);
}
}
MC.EndOp();
}
simulated function OnLoseFocus()
{
// KDM : We want the navigation help system to reload itself upon receiving focus.
AbilityInfoTipIsShowing = -1;
SelectAbilityTipIsShowing = -1;
super.OnLoseFocus();
}
simulated function PreviewRow(UIList ContainerList, int ItemIndex)
{
local bool DisplayOnly;
local int i, Rank, EffectiveRank;
local string TmpStr;
local X2AbilityTemplate AbilityTemplate;
local X2AbilityTemplateManager AbilityTemplateManager;
local XComGameState_Unit Unit;
// KDM : EffectiveRank is the rank the officer actually is, while Rank is the rank associated with this particular list item row.
Unit = GetUnit();
DisplayOnly = !CanUnitEnterOTSTraining(Unit);
if (ItemIndex == INDEX_NONE)
{
Rank = 1;
return;
}
else
{
Rank = UIArmory_LWOfficerPromotionItem(List.GetItem(ItemIndex)).Rank;
}
MC.BeginFunctionOp("setAbilityPreview");
if (class'LWOfficerUtilities'.static.GetOfficerComponent(Unit) != none)
{
EffectiveRank = class'LWOfficerUtilities'.static.GetOfficerComponent(Unit).GetOfficerRank();
}
else
{
EffectiveRank = 0;
}
if (!DisplayOnly)
{
EffectiveRank++;
}
// KDM : If the rank associated with this row is greater than the officer's actual rank show locked information and icons.
// This, however, can be negated by ALWAYSSHOW and IsViewLockedStatsEnabled().
if ((Rank > EffectiveRank) && !(default.ALWAYSSHOW || class'XComGameState_LWPerkPackOptions'.static.IsViewLockedStatsEnabled()))
{
for (i = 0; i < NUM_ABILITIES_PER_RANK; ++i)
{
MC.QueueString(class'UIUtilities_Image'.const.LockedAbilityIcon); // Icon
MC.QueueString(class'UIUtilities_Text'.static.GetColoredText(m_strAbilityLockedTitle, eUIState_Disabled)); // Name
MC.QueueString(class'UIUtilities_Text'.static.GetColoredText(m_strAbilityLockedDescription, eUIState_Disabled)); // Description
MC.QueueBoolean(false); // IsClassIcon
}
}
// KDM : We are looking at a row whose associated rank is less than, or equal to, the officer's actual rank.
else
{
AbilityTemplateManager = class'X2AbilityTemplateManager'.static.GetAbilityTemplateManager();
for (i = 0; i < NUM_ABILITIES_PER_RANK; ++i)
{
// KDM : The 1st row corresponds to the officer's core, non-selectable, abilities.
if (ItemIndex == 0)
{
AbilityTemplate = AbilityTemplateManager.FindAbilityTemplate(class'LWOfficerUtilities'.static.GetAbilityName(0, i));
}
else
{
AbilityTemplate = AbilityTemplateManager.FindAbilityTemplate(class'LWOfficerUtilities'.static.GetAbilityName(Rank, i));
}
if (AbilityTemplate != none)
{
MC.QueueString(AbilityTemplate.IconImage); // Icon
TmpStr = AbilityTemplate.LocFriendlyName != "" ? AbilityTemplate.LocFriendlyName : ("Missing 'LocFriendlyName' for " $ AbilityTemplate.DataName);
MC.QueueString(Caps(TmpStr)); // Name
TmpStr = AbilityTemplate.HasLongDescription() ? AbilityTemplate.GetMyLongDescription() : ("Missing 'LocLongDescription' for " $ AbilityTemplate.DataName);
MC.QueueString(TmpStr); // Description
MC.QueueBoolean(false); // IsClassIcon
}
else
{
MC.QueueString(""); // Icon
MC.QueueString(string(class'LWOfficerUtilities'.static.GetAbilityName(Rank, i))); // Name
MC.QueueString("Missing template for ability '" $ class'LWOfficerUtilities'.static.GetAbilityName(Rank, i) $ "'"); // Description
MC.QueueBoolean(false); // IsClassIcon
}
}
}
MC.EndOp();
if (`ISCONTROLLERACTIVE)
{
// KDM : When a new row is selected, preserve the ability selection; this means :
// 1.] If the previous row's left ability was selected, select the left ability for the new row.
// 2.] If the previous row's right ability was selected, select the right ability for the new row.
UIArmory_LWOfficerPromotionItem(List.GetItem(ItemIndex)).SetSelectedAbility(SelectedAbilityIndex);
// KDM : The navigation system should be updated because it might have changed. For example,
// 1.] If a promotion row ability is selected, a "Select" tip needs to be displayed.
// 2.] If an unhidden ability is selected, an "Ability Info" tip needs to be displayed.
UpdateNavHelp();
}
}
simulated function ViewLeadershipStats(UIButton Button)
{
local TDialogueBoxData DialogData;
Movie.Pres.PlayUISound(eSUISound_MenuSelect);
DialogData.eType = eDialog_Normal;
DialogData.strTitle = strLeadershipDialogueTitle;
DialogData.strText = GetFormattedLeadershipText();
DialogData.strCancel = class'UIUtilities_Text'.default.m_strGenericOK;;
Movie.Pres.UIRaiseDialog(DialogData);
}
simulated function string GetFormattedLeadershipText()
{
local int idx, limit;
local string OutString;
local array<LeadershipEntry> LeadershipData;
local LeadershipEntry Entry;
local X2SoldierClassTemplate ClassTemplate;
local XComGameState_Unit OfficerUnit, Unit;
local XComGameState_Unit_LWOfficer OfficerState;
local XComGameStateHistory History;
OutString = "";
OfficerUnit = GetUnit();
if (OfficerUnit == none)
{
return Outstring;
}
OfficerState = class'LWOfficerUtilities'.static.GetOfficerComponent(OfficerUnit);
if (OfficerState == none)
{
return Outstring;
}
LeadershipData = OfficerState.GetLeadershipData_MissionSorted();
History = `XCOMHISTORY;
Limit = 40;
foreach LeaderShipData (Entry, idx)
{
// Limit to the top 40
if (idx >= limit)
{
break;
}
if (Entry.UnitRef.ObjectID == 0)
{
limit += 1;
continue;
}
Unit = XComGameState_Unit(History.GetGameStateForObjectID(Entry.UnitRef.ObjectID));
if (Unit == none)
{
limit += 1;
continue;
}
if (Unit.IsDead())
{
limit += 1;
continue;
}
ClassTemplate = Unit.GetSoldierClassTemplate();
if (ClassTemplate.DataName == 'LWS_RebelSoldier')
{
limit += 1;
continue;
}
OutString $= Entry.SuccessfulMissionCount $ " : ";
OutString $= Unit.GetName(eNameType_RankFull) $ " / ";
Outstring $= ClassTemplate.DisplayName;
Outstring $= "\n";
}
return OutString;
}
simulated function ConfirmAbilitySelection(int Rank, int Branch)
{
local TDialogueBoxData DialogData;
local X2AbilityTemplate AbilityTemplate;
local X2AbilityTemplateManager AbilityTemplateManager;
local XGParamTag LocTag;
PendingRank = Rank;
PendingBranch = Branch;
Movie.Pres.PlayUISound(eSUISound_MenuSelect);
DialogData.eType = eDialog_Alert;
DialogData.bMuteAcceptSound = true;
DialogData.strTitle = m_strConfirmAbilityTitle;
DialogData.strAccept = class'UIUtilities_Text'.default.m_strGenericYes;
DialogData.strCancel = class'UIUtilities_Text'.default.m_strGenericNO;
DialogData.fnCallback = ConfirmAbilityCallback;
AbilityTemplateManager = class'X2AbilityTemplateManager'.static.GetAbilityTemplateManager();
AbilityTemplate = AbilityTemplateManager.FindAbilityTemplate(class'LWOfficerUtilities'.static.GetAbilityName(PendingRank, PendingBranch));
LocTag = XGParamTag(`XEXPANDCONTEXT.FindTag("XGParam"));
LocTag.StrValue0 = AbilityTemplate.LocFriendlyName;
DialogData.strText = `XEXPAND.ExpandString(m_strConfirmAbilityText);
Movie.Pres.UIRaiseDialog(DialogData);
// KDM : Follow the new WotC UIArmory_Promotion and update the navigation help system.
UpdateNavHelp();
}
simulated function ConfirmAbilityCallback(Name Action)
{
local XComGameStateHistory History;
local XComGameState UpdateState;
local XComGameState_Unit UpdatedUnit;
local XComGameState_Unit Unit;
local StaffUnitInfo UnitInfo;
local XComGameStateContext_ChangeContainer ChangeContainer;
local ClassAgnosticAbility NewOfficerAbility;
local SoldierClassAbilityType Ability;
local XComGameState_Unit_LWOfficer OfficerState;
local int NewOfficerRank;
local bool bTrainingSuccess;
local XComGameState_HeadquartersProjectTrainLWOfficer TrainLWOfficerProject;
local XComGameState_StaffSlot StaffSlotState;
if (Action == 'eUIAction_Accept')
{
Unit = GetUnit();
// Build ClassAgnosticAbility to allow instant training into Officer Ability
Ability.AbilityName = class'LWOfficerUtilities'.static.GetAbilityName(PendingRank, PendingBranch);
Ability.ApplyToWeaponSlot = eInvSlot_Unknown;
Ability.UtilityCat = '';
NewOfficerAbility.AbilityType = Ability;
NewOfficerAbility.iRank = PendingRank;
NewOfficerAbility.bUnlocked = true;
// Build GameState change container
History = `XCOMHISTORY;
ChangeContainer = class'XComGameStateContext_ChangeContainer'.static.CreateEmptyChangeContainer("Staffing Train Officer Slot");
UpdateState = History.CreateNewGameState(true, ChangeContainer);
UpdatedUnit = XComGameState_Unit(UpdateState.CreateStateObject(class'XComGameState_Unit', GetUnit().ObjectID));
// Try to retrieve new OfficerComponent from Unit -- note that it may not have been created for non-officers yet
OfficerState = class'LWOfficerUtilities'.static.GetOfficerComponent(Unit);
if (OfficerState == none)
{
// First promotion, create component gamestate and attach it
OfficerState = XComGameState_Unit_LWOfficer(UpdateState.CreateStateObject(class'XComGameState_Unit_LWOfficer'));
OfficerState.InitComponent();
if (default.INSTANTTRAINING)
{
OfficerState.SetOfficerRank(1);
}
else
{
NewOfficerRank = 1;
}
UpdatedUnit.AddComponentObject(OfficerState);
}
else
{
// Subsequent promotion, update existing component gamestate
NewOfficerRank = OfficerState.GetOfficerRank() + 1;
OfficerState = XComGameState_Unit_LWOfficer(UpdateState.CreateStateObject(class'XComGameState_Unit_LWOfficer', OfficerState.ObjectID));
if (default.INSTANTTRAINING)
{
OfficerState.SetOfficerRank(NewOfficerRank);
}
else
{
}
}
if (default.INSTANTTRAINING)
{
`log("LW Officer Pack: Adding ability:" @ NewOfficerAbility.AbilityType.AbilityName);
OfficerState.OfficerAbilities.AddItem(NewOfficerAbility);
UpdatedUnit = class'LWOfficerUtilities'.static.AddInitialAbilities(UpdatedUnit, OfficerState, UpdateState);
bTrainingSuccess = true;
}
else
{
bTrainingSuccess = OfficerState.SetRankTraining(NewOfficerRank, Ability.AbilityName);
}
if (!default.INSTANTTRAINING)
{
StaffSlotState = GetEmptyOfficerTrainingStaffSlot();
if (StaffSlotState != none)
{
UnitInfo.UnitRef = UpdatedUnit.GetReference();
// The Training project is started when the staff slot is filled
StaffSlotState.FillSlot(UnitInfo, UpdateState);
// Find the new Training Project which was just created by filling the staff slot and set the rank and ability
foreach UpdateState.IterateByClassType(class'XComGameState_HeadquartersProjectTrainLWOfficer', TrainLWOfficerProject)
{
// Handle possible cases of multiple officer training slots
if (TrainLWOfficerProject.ProjectFocus.ObjectID == GetUnit().ObjectID)
{
TrainLWOfficerProject.AbilityName = Ability.AbilityName;
TrainLWOfficerProject.NewRank = NewOfficerRank;
// Have to recompute time for project after rank is set in order to handle completion time based on rank
TrainLWOfficerProject.ProjectPointsRemaining = TrainLWOfficerProject.CalculatePointsToTrain();
TrainLWOfficerProject.InitialProjectPoints = TrainLWOfficerProject.CalculatePointsToTrain();
TrainLWOfficerProject.SetProjectedCompletionDateTime(TrainLWOfficerProject.StartDateTime);
break;
}
}
}
else
{
`Redscreen("LW Officer Pack : Failed to find StaffSlot in UIArmory_LWOfficerPromotion.ConfirmAbilityCallback");
bTrainingSuccess = false;
}
}
// Submit or clear update state based on success/failure
if (bTrainingSuccess)
{
UpdateState.AddStateObject(UpdatedUnit);
UpdateState.AddStateObject(OfficerState);
`GAMERULES.SubmitGameState(UpdateState);
Header.PopulateData();
PopulateData();
}
else
{
History.CleanupPendingGameState(UpdateState);
}
Movie.Pres.PlayUISound(eSUISound_SoldierPromotion);
Movie.Pres.ScreenStack.PopUntilClass(class'UIFacility_Academy', true);
}
else
{
Movie.Pres.PlayUISound(eSUISound_MenuClickNegative);
}
}
simulated function XComGameState_StaffSlot GetEmptyOfficerTrainingStaffSlot()
{
local UIScreenStack ScreenStack;
local XComGameState_FacilityXCom FacilityState;
local XComGameState_StaffSlot SlotState;
local UIFacility_Academy AcademyUI;
local UIScreen CurrScreen;
local int idx;
ScreenStack = Movie.Pres.ScreenStack;
// Find the class UIFacilityAcademy that invoked this (just in case there's more than 1)
AcademyUI = UIFacility_Academy(ScreenStack.GetScreen(class'UIFacility_Academy'));
if (AcademyUI == none)
{
// Search for override classes
foreach ScreenStack.Screens(CurrScreen)
{
AcademyUI = UIFacility_Academy(CurrScreen);
if (AcademyUI != none)
{
break;
}
}
}
if (AcademyUI == none)
{
FacilityState = `XCOMHQ.GetFacilityByName('OfficerTrainingSchool');
}
else
{
FacilityState = AcademyUI.GetFacility();
}
for (idx = 0; idx < FacilityState.StaffSlots.Length; idx++)
{
SlotState = FacilityState.GetStaffSlot(idx);
if (SlotState != none && SlotState.GetMyTemplateName() == 'OTSOfficerSlot' && SlotState.IsSlotEmpty() && !SlotState.bIsLocked)
{
return SlotState;
}
}
return none;
}
//==============================================================================
// Soldier cycling
//==============================================================================
simulated function bool IsAllowedToCycleSoldiers()
{
return true;
}
simulated static function bool CanCycleTo(XComGameState_Unit Soldier)
{
return class'LWOfficerUtilities'.static.IsOfficer(Soldier);
}
simulated static function CycleToSoldier(StateObjectReference UnitRef)
{
super(UIArmory).CycleToSoldier(UnitRef);
}
// KDM : Use UIArmory_Promotion --> UpdateNavHelp() as our code base since it has been updated for WotC.
simulated function UpdateNavHelp()
{
local int i, AbilityInfoTipShouldShow, SelectAbilityTipShouldShow;
local string PrevKey, NextKey;
local XGParamTag LocTag;
if (!bIsFocused)
{
return;
}
// KDM : -1 = unset, 0 = false, 1 = true
AbilityInfoTipShouldShow = (!UIArmory_PromotionItem(List.GetSelectedItem()).bIsDisabled) ? 1 : 0;
SelectAbilityTipShouldShow = (UIArmory_PromotionItem(List.GetSelectedItem()).bEligibleForPromotion) ? 1 : 0;
// KDM : Whenever the promotion screen updates its navigation help system, the whole navigation help system flickers off then on;
// this is because it needs to be cleared, recreated, then re-shown. This is mainly an issue for controller users since, for them,
// the navigation system has to refresh whenever a new row is selected, as well as whenever a new ability is selected. The reason is :
// 1.] A 'Select' tip appears when a promotion eligible row is selected, and disappears otherwise.
// 2.] An 'Ability Info' tip appears whenever an unhidden ability is selected, and disappears otherwise.
//
// The easiest solution is to only update the navigation help system when dynamic tips do, in fact, change.
if (`ISCONTROLLERACTIVE && (AbilityInfoTipIsShowing == AbilityInfoTipShouldShow) && (SelectAbilityTipIsShowing == SelectAbilityTipShouldShow))
{
// KDM : The navigation help system has not changed so just get out.
return;
}
else if (`ISCONTROLLERACTIVE && ((AbilityInfoTipIsShowing != AbilityInfoTipShouldShow) || (SelectAbilityTipIsShowing != SelectAbilityTipShouldShow)))
{
// KDM : The navigation help system has changed so let it on through.
AbilityInfoTipIsShowing = AbilityInfoTipShouldShow;
SelectAbilityTipIsShowing = SelectAbilityTipShouldShow;
}
NavHelp = `HQPRES.m_kAvengerHUD.NavHelp;
NavHelp.ClearButtonHelp();
// KDM : From what I can see, the officer promotion screen is not accessible via the post mission squad view, represented by UIAfterAction;
// therefore, the corresponding code has been removed.
NavHelp.AddBackButton(OnCancel);
if (UIArmory_PromotionItem(List.GetSelectedItem()).bEligibleForPromotion)
{
NavHelp.AddSelectNavHelp();
}
if (XComHQPresentationLayer(Movie.Pres) != none)
{
LocTag = XGParamTag(`XEXPANDCONTEXT.FindTag("XGParam"));
LocTag.StrValue0 = Movie.Pres.m_kKeybindingData.GetKeyStringForAction(PC.PlayerInput, eTBC_PrevUnit);
PrevKey = `XEXPAND.ExpandString(PrevSoldierKey);
LocTag.StrValue0 = Movie.Pres.m_kKeybindingData.GetKeyStringForAction(PC.PlayerInput, eTBC_NextUnit);
NextKey = `XEXPAND.ExpandString(NextSoldierKey);
if (class'XComGameState_HeadquartersXCom'.static.GetObjectiveStatus('T0_M7_WelcomeToGeoscape') != eObjectiveState_InProgress &&
RemoveMenuEvent == '' && NavigationBackEvent == '' && !`ScreenStack.IsInStack(class'UISquadSelect'))
{
NavHelp.AddGeoscapeButton();
}
if (Movie.IsMouseActive() && IsAllowedToCycleSoldiers() && class'UIUtilities_Strategy'.static.HasSoldiersToCycleThrough(UnitReference, CanCycleTo))
{
NavHelp.SetButtonType("XComButtonIconPC");
i = eButtonIconPC_Prev_Soldier;
NavHelp.AddCenterHelp( string(i), "", PrevSoldier, false, PrevKey);
i = eButtonIconPC_Next_Soldier;
NavHelp.AddCenterHelp( string(i), "", NextSoldier, false, NextKey);
NavHelp.SetButtonType("");
}
}
// KDM : 'Make poster' help item has been removed.
if (`ISCONTROLLERACTIVE)
{
if (!UIArmory_PromotionItem(List.GetSelectedItem()).bIsDisabled)
{
NavHelp.AddLeftHelp(m_strInfo, class'UIUtilities_Input'.static.GetGamepadIconPrefix() $class'UIUtilities_Input'.const.ICON_LSCLICK_L3);
}
if (IsAllowedToCycleSoldiers() && class'UIUtilities_Strategy'.static.HasSoldiersToCycleThrough(UnitReference, CanCycleTo))
{
NavHelp.AddCenterHelp(m_strTabNavHelp, class'UIUtilities_Input'.static.GetGamepadIconPrefix() $ class'UIUtilities_Input'.const.ICON_LBRB_L1R1);
}
NavHelp.AddCenterHelp(m_strRotateNavHelp, class'UIUtilities_Input'.static.GetGamepadIconPrefix() $ class'UIUtilities_Input'.const.ICON_RSTICK);
}
// KDM : 'Go to Training Center' help item has been removed; might be ok to keep this one though.
NavHelp.Show();
}
simulated function bool OnUnrealCommand(int cmd, int arg)
{
local bool bHandled;
if (!CheckInputIsReleaseOrDirectionRepeat(cmd, arg))
{
return false;
}
// KDM : Give the selected list item the first chance at the input.
if (List.GetSelectedItem().OnUnrealCommand(cmd, arg))
{
UpdateNavHelp();
return true;
}
bHandled = true;
switch(cmd)
{
// KDM : Right stick click opens up the leadership screen for controller users.
case class'UIUtilities_Input'.const.FXS_BUTTON_R3:
if (LeadershipButton.bIsVisible)
{
ViewLeadershipStats(none);
}
break;
case class'UIUtilities_Input'.const.FXS_MOUSE_5:
case class'UIUtilities_Input'.const.FXS_KEY_TAB:
case class'UIUtilities_Input'.const.FXS_BUTTON_RBUMPER:
case class'UIUtilities_Input'.const.FXS_MOUSE_4:
case class'UIUtilities_Input'.const.FXS_KEY_LEFT_SHIFT:
case class'UIUtilities_Input'.const.FXS_BUTTON_LBUMPER:
// Prevent switching soldiers during AfterAction promotion
if (UIAfterAction(Movie.Stack.GetScreen(class'UIAfterAction')) == none)
{
bHandled = false;
}
break;
case class'UIUtilities_Input'.const.FXS_BUTTON_B:
case class'UIUtilities_Input'.const.FXS_KEY_ESCAPE:
case class'UIUtilities_Input'.const.FXS_R_MOUSE_DOWN:
OnCancel();
break;
// KDM : 'Make poster' case has been removed.
// KDM : 'Go to Training Center' case has been removed.
default:
bHandled = false;
break;
}
return bHandled || super(UIArmory).OnUnrealCommand(cmd, arg);
}
defaultproperties
{
// KDM : Select the left ability on initialization.
SelectedAbilityIndex = 0;
AbilityInfoTipIsShowing = -1;
SelectAbilityTipIsShowing = -1;
}
| 412 | 0.884188 | 1 | 0.884188 | game-dev | MEDIA | 0.77994 | game-dev | 0.924575 | 1 | 0.924575 |
Eaglercraft-Archive/EaglercraftX-1.8-workspace | 3,459 | src/game/java/net/minecraft/block/BlockColored.java | package net.minecraft.block;
import java.util.List;
import net.minecraft.block.material.MapColor;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyEnum;
import net.minecraft.block.state.BlockState;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.EnumDyeColor;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
/**+
* This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code.
*
* Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!"
* Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team
*
* EaglercraftX 1.8 patch files (c) 2022-2025 lax1dude, ayunami2000. All Rights Reserved.
*
* 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.
*
*/
public class BlockColored extends Block {
public static final PropertyEnum<EnumDyeColor> COLOR = PropertyEnum.<EnumDyeColor>create("color",
EnumDyeColor.class);
public BlockColored(Material materialIn) {
super(materialIn);
this.setDefaultState(this.blockState.getBaseState().withProperty(COLOR, EnumDyeColor.WHITE));
this.setCreativeTab(CreativeTabs.tabBlock);
}
/**+
* Gets the metadata of the item this Block can drop. This
* method is called when the block gets destroyed. It returns
* the metadata of the dropped item based on the old metadata of
* the block.
*/
public int damageDropped(IBlockState iblockstate) {
return ((EnumDyeColor) iblockstate.getValue(COLOR)).getMetadata();
}
/**+
* returns a list of blocks with the same ID, but different meta
* (eg: wood returns 4 blocks)
*/
public void getSubBlocks(Item item, CreativeTabs var2, List<ItemStack> list) {
EnumDyeColor[] colors = EnumDyeColor.META_LOOKUP;
for (int i = 0; i < colors.length; ++i) {
EnumDyeColor enumdyecolor = colors[i];
list.add(new ItemStack(item, 1, enumdyecolor.getMetadata()));
}
}
/**+
* Get the MapColor for this Block and the given BlockState
*/
public MapColor getMapColor(IBlockState iblockstate) {
return ((EnumDyeColor) iblockstate.getValue(COLOR)).getMapColor();
}
/**+
* Convert the given metadata into a BlockState for this Block
*/
public IBlockState getStateFromMeta(int i) {
return this.getDefaultState().withProperty(COLOR, EnumDyeColor.byMetadata(i));
}
/**+
* Convert the BlockState into the correct metadata value
*/
public int getMetaFromState(IBlockState iblockstate) {
return ((EnumDyeColor) iblockstate.getValue(COLOR)).getMetadata();
}
protected BlockState createBlockState() {
return new BlockState(this, new IProperty[] { COLOR });
}
} | 412 | 0.628017 | 1 | 0.628017 | game-dev | MEDIA | 0.993363 | game-dev | 0.866738 | 1 | 0.866738 |
google/swiftshader | 2,856 | third_party/llvm-16.0/llvm/lib/Target/CSKY/CSKYSubtarget.cpp | //===-- CSKYSubtarget.h - Define Subtarget for the CSKY----------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file declares the CSKY specific subclass of TargetSubtargetInfo.
//
//===----------------------------------------------------------------------===//
#include "CSKYSubtarget.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
using namespace llvm;
#define DEBUG_TYPE "csky-subtarget"
#define GET_SUBTARGETINFO_TARGET_DESC
#define GET_SUBTARGETINFO_CTOR
#include "CSKYGenSubtargetInfo.inc"
void CSKYSubtarget::anchor() {}
CSKYSubtarget &CSKYSubtarget::initializeSubtargetDependencies(
const Triple &TT, StringRef CPUName, StringRef TuneCPUName, StringRef FS) {
if (CPUName.empty())
CPUName = "generic";
if (TuneCPUName.empty())
TuneCPUName = CPUName;
UseHardFloat = false;
UseHardFloatABI = false;
HasFPUv2SingleFloat = false;
HasFPUv2DoubleFloat = false;
HasFPUv3HalfWord = false;
HasFPUv3HalfFloat = false;
HasFPUv3SingleFloat = false;
HasFPUv3DoubleFloat = false;
HasFdivdu = false;
HasFLOATE1 = false;
HasFLOAT1E2 = false;
HasFLOAT1E3 = false;
HasFLOAT3E4 = false;
HasFLOAT7E60 = false;
HasExtendLrw = false;
HasBTST16 = false;
HasTrust = false;
HasJAVA = false;
HasCache = false;
HasNVIC = false;
HasDSP = false;
HasDSP1E2 = false;
HasDSPE60 = false;
HasDSPV2 = false;
HasDSP_Silan = false;
HasDoloop = false;
HasHardwareDivide = false;
HasHighRegisters = false;
HasVDSPV2 = false;
HasVDSP2E3 = false;
HasVDSP2E60F = false;
ReadTPHard = false;
HasVDSPV1_128 = false;
UseCCRT = false;
DumpConstPool = false;
EnableInterruptAttribute = false;
HasPushPop = false;
HasSTM = false;
SmartMode = false;
EnableStackSize = false;
HasE1 = false;
HasE2 = false;
Has2E3 = false;
HasMP = false;
Has3E3r1 = false;
Has3r1E3r2 = false;
Has3r2E3r3 = false;
Has3E7 = false;
HasMP1E2 = false;
Has7E10 = false;
Has10E60 = false;
ParseSubtargetFeatures(CPUName, TuneCPUName, FS);
return *this;
}
CSKYSubtarget::CSKYSubtarget(const Triple &TT, StringRef CPU, StringRef TuneCPU,
StringRef FS, const TargetMachine &TM)
: CSKYGenSubtargetInfo(TT, CPU, TuneCPU, FS),
FrameLowering(initializeSubtargetDependencies(TT, CPU, TuneCPU, FS)),
InstrInfo(*this), RegInfo(), TLInfo(TM, *this) {}
bool CSKYSubtarget::useHardFloatABI() const {
auto FloatABI = getTargetLowering()->getTargetMachine().Options.FloatABIType;
if (FloatABI == FloatABI::Default)
return UseHardFloatABI;
else
return FloatABI == FloatABI::Hard;
}
| 412 | 0.899476 | 1 | 0.899476 | game-dev | MEDIA | 0.382462 | game-dev | 0.931859 | 1 | 0.931859 |
mas-bandwidth/networked-physics-gdc-2015 | 15,309 | external/ode/OPCODE/OPC_MeshInterface.h | ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
* OPCODE - Optimized Collision Detection
* Copyright (C) 2001 Pierre Terdiman
* Homepage: http://www.codercorner.com/Opcode.htm
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Contains a mesh interface.
* \file OPC_MeshInterface.h
* \author Pierre Terdiman
* \date November, 27, 2002
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Include Guard
#ifndef __OPC_MESHINTERFACE_H__
#define __OPC_MESHINTERFACE_H__
struct VertexPointers
{
const Point* Vertex[3];
bool BackfaceCulling(const Point& source)
{
const Point& p0 = *Vertex[0];
const Point& p1 = *Vertex[1];
const Point& p2 = *Vertex[2];
// Compute normal direction
Point Normal = (p2 - p1)^(p0 - p1);
// Backface culling
return (Normal | (source - p0)) >= 0.0f;
}
};
struct VertexPointersEx
{
VertexPointers vp;
dTriIndex Index[3];
};
typedef Point ConversionArea[3];
#ifdef OPC_USE_CALLBACKS
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* User-callback, called by OPCODE to request vertices from the app.
* \param triangle_index [in] face index for which the system is requesting the vertices
* \param triangle [out] triangle's vertices (must be provided by the user)
* \param user_data [in] user-defined data from SetCallback()
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
typedef void (*RequestCallback) (udword triangle_index, VertexPointers& triangle, void* user_data);
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* User-callback, called by OPCODE to request vertex indices from the app.
* \param triangle_index [in] face index for which the system is requesting the vertices
* \param triangle [out] triangle's vertices with indices (must be provided by the user)
* \param user_data [in] user-defined data from SetExCallback()
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
typedef void (*RequestExCallback) (udword triangle_index, VertexPointersEx& triangle, void* user_data);
#endif
class OPCODE_API MeshInterface
{
public:
// Constructor / Destructor
MeshInterface();
~MeshInterface();
// Common settings
inline_ udword GetNbTriangles() const { return mNbTris; }
inline_ udword GetNbVertices() const { return mNbVerts; }
inline_ void SetNbTriangles(udword nb) { mNbTris = nb; }
inline_ void SetNbVertices(udword nb) { mNbVerts = nb; }
#ifdef OPC_USE_CALLBACKS
// Callback settings
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Callback control: setups object callback. Must provide triangle-vertices for a given triangle index.
* \param callback [in] user-defined callback
* \param user_data [in] user-defined data
* \return true if success
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool SetCallback(RequestCallback callback, void* user_data);
inline_ void* GetUserData() const { return mUserData; }
inline_ RequestCallback GetCallback() const { return mObjCallback; }
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Callback control: setups object callback. Must provide triangle-vertices for a given triangle index.
* \param callback [in] user-defined callback
* \param user_data [in] user-defined data
* \return true if success
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool SetExCallback(RequestExCallback callback, void* user_data);
inline_ void* GetExUserData() const { return mExUserData; }
inline_ RequestExCallback GetExCallback() const { return mObjExCallback; }
#else
// Pointers settings
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Pointers control: setups object pointers. Must provide access to faces and vertices for a given object.
* \param tris [in] pointer to triangles
* \param verts [in] pointer to vertices
* \return true if success
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool SetPointers(const IndexedTriangle* tris, const Point* verts);
inline_ const IndexedTriangle* GetTris() const { return mTris; }
inline_ const Point* GetVerts() const { return mVerts; }
#ifdef OPC_USE_STRIDE
// Strides settings
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Strides control
* \param tri_stride [in] size of a triangle in bytes. The first sizeof(IndexedTriangle) bytes are used to get vertex indices.
* \param vertex_stride [in] size of a vertex in bytes. The first sizeof(Point) bytes are used to get vertex position.
* \return true if success
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool SetStrides(udword tri_stride=sizeof(IndexedTriangle), udword vertex_stride=sizeof(Point));
inline_ udword GetTriStride() const { return mTriStride; }
inline_ udword GetVertexStride() const { return mVertexStride; }
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Single/Double control
* \param value [in] Indicates if mesh data is provided as array of \c single values. If \c false, data is expected to contain \c double elements.
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
inline_ void SetSingle(bool value)
{
mFetchTriangle = (value ? &MeshInterface::FetchTriangleFromSingles : &MeshInterface::FetchTriangleFromDoubles);
mFetchExTriangle = (value ? &MeshInterface::FetchExTriangleFromSingles : &MeshInterface::FetchExTriangleFromDoubles);
}
#else
inline_ bool SetStrides(udword tri_stride=sizeof(IndexedTriangle), udword vertex_stride=sizeof(Point)) { return true; }
inline_ void SetSingle(bool value) {}
inline_ udword GetTriStride() const { return sizeof(IndexedTriangle); }
inline_ udword GetVertexStride() const { return sizeof(Point); }
#endif
#endif
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Fetches a triangle given a triangle index.
* \param vp [out] required triangle's vertex pointers
* \param index [in] triangle index
* \param vc [in,out] storage required for data conversion (pass local variable with same scope as \a vp, as \a vp may point to this memory on return)
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
inline_ void GetTriangle(VertexPointers& vp, udword index, ConversionArea vc) const
{
#ifdef OPC_USE_CALLBACKS
(mObjCallback)(index, vp, mUserData);
#else
#ifdef OPC_USE_STRIDE
// Since there was conditional statement "if (Single)" which was unpredictable for compiler
// and required both branches to be always generated what made inlining a questionable
// benefit, I consider it better to introduce a forced call
// but get rig of branching and dead code injection.
((*this).*mFetchTriangle)(vp, index, vc);
#else
const Point* Verts = GetVerts();
const IndexedTriangle* T = &mTris[index];
vp.Vertex[0] = &Verts[T->mVRef[0]];
vp.Vertex[1] = &Verts[T->mVRef[1]];
vp.Vertex[2] = &Verts[T->mVRef[2]];
#endif
#endif
}
inline_ bool GetExTriangle(VertexPointersEx& vpe, udword index, ConversionArea vc) const
{
#ifdef OPC_USE_CALLBACKS
if (mObjExCallback) { (mObjExCallback)(index, vpe, mUserData); return true; }
else { (mObjCallback)(index, vpe.vp, mUserData); return false; }
#else
#ifdef OPC_USE_STRIDE
// Since there was conditional statement "if (Single)" which was unpredictable for compiler
// and required both branches to be always generated what made inlining a questionable
// benefit, I consider it better to introduce a forced call
// but get rig of branching and dead code injection.
((*this).*mFetchExTriangle)(vpe, index, vc);
return true;
#else
const Point* Verts = GetVerts();
const IndexedTriangle* T = &mTris[index];
dTriIndex VertIndex0 = T->mVRef[0];
vpe.Index[0] = VertIndex0;
vpe.vp.Vertex[0] = &Verts[VertIndex0];
dTriIndex VertIndex1 = T->mVRef[1];
vpe.Index[1] = VertIndex1;
vpe.vp.Vertex[1] = &Verts[VertIndex1];
dTriIndex VertIndex2 = T->mVRef[2];
vpe.Index[2] = VertIndex2;
vpe.vp.Vertex[2] = &Verts[VertIndex2];
return true;
#endif
#endif
}
private:
#ifndef OPC_USE_CALLBACKS
#ifdef OPC_USE_STRIDE
void FetchTriangleFromSingles(VertexPointers& vp, udword index, ConversionArea vc) const;
void FetchTriangleFromDoubles(VertexPointers& vp, udword index, ConversionArea vc) const;
void FetchExTriangleFromSingles(VertexPointersEx& vpe, udword index, ConversionArea vc) const;
void FetchExTriangleFromDoubles(VertexPointersEx& vpe, udword index, ConversionArea vc) const;
#endif
#endif
public:
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Remaps client's mesh according to a permutation.
* \param nb_indices [in] number of indices in the permutation (will be checked against number of triangles)
* \param permutation [in] list of triangle indices
* \return true if success
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool RemapClient(udword nb_indices, const dTriIndex* permutation) const;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Checks the mesh interface is valid, i.e. things have been setup correctly.
* \return true if valid
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool IsValid() const;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Checks the mesh itself is valid.
* Currently we only look for degenerate faces.
* \return number of degenerate faces
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
udword CheckTopology() const;
private:
udword mNbTris; //!< Number of triangles in the input model
udword mNbVerts; //!< Number of vertices in the input model
#ifdef OPC_USE_CALLBACKS
// User callback
void* mUserData; //!< User-defined data sent to callback
RequestCallback mObjCallback; //!< Object callback
void* mExUserData; //!< User-defined data sent to ex-callback
RequestExCallback mObjExCallback; //!< Object ex-callback
#else
// User pointers
#ifdef OPC_USE_STRIDE
udword mTriStride; //!< Possible triangle stride in bytes [Opcode 1.3]
udword mVertexStride; //!< Possible vertex stride in bytes [Opcode 1.3]
typedef void (MeshInterface:: *TriangleFetchProc)(VertexPointers& vp, udword index, ConversionArea vc) const;
TriangleFetchProc mFetchTriangle;
typedef void (MeshInterface:: *ExTriangleFetchProc)(VertexPointersEx& vpe, udword index, ConversionArea vc) const;
ExTriangleFetchProc mFetchExTriangle;
#endif
const IndexedTriangle* mTris; //!< Array of indexed triangles
const Point* mVerts; //!< Array of vertices
#endif
};
#endif //__OPC_MESHINTERFACE_H__
| 412 | 0.532448 | 1 | 0.532448 | game-dev | MEDIA | 0.360613 | game-dev | 0.633115 | 1 | 0.633115 |
jdmclark/gorc | 1,425 | src/libs/input/unit-test/input_adapter_test.cpp | #include "test/test.hpp"
#include "input/input_adapter.hpp"
begin_suite(input_adapter_test);
test_case(destructor_called) {
class mock_input_adapter : public gorc::input_adapter {
private:
bool &destructor_called;
public:
mock_input_adapter(bool &destructor_called)
: destructor_called(destructor_called)
{
return;
}
~mock_input_adapter()
{
destructor_called = true;
}
virtual void handle_mouse_cursor(gorc::time_delta, gorc::mouse&) override
{
return;
}
virtual bool wants_mouse_focus() override
{
return false;
}
virtual bool wants_keyboard_focus() override
{
return false;
}
virtual void handle_mouse_input(gorc::time_delta, gorc::mouse&) override
{
return;
}
virtual void handle_keyboard_input(gorc::time_delta, gorc::keyboard&) override
{
return;
}
virtual void handle_text_input(gorc::time_delta, char) override
{
return;
}
};
bool destructor_called = false;
gorc::input_adapter *input_adapter = new mock_input_adapter(destructor_called);
expect_true(!destructor_called);
delete input_adapter;
assert_true(destructor_called);
}
end_suite(input_adapter_test);
| 412 | 0.773422 | 1 | 0.773422 | game-dev | MEDIA | 0.201059 | game-dev | 0.560881 | 1 | 0.560881 |
LostArtefacts/TRX | 4,469 | src/libtrx/game/phase/phase_pause.c | #include "game/phase/phase_pause.h"
#include "game/fader.h"
#include "game/game.h"
#include "game/game_string.h"
#include "game/input.h"
#include "game/interpolation.h"
#include "game/music.h"
#include "game/output.h"
#include "game/overlay.h"
#include "game/shell.h"
#include "game/sound.h"
#include "game/ui.h"
#include "memory.h"
#include <stdint.h>
#define FADE_TIME 0.4
typedef enum {
STATE_FADE_IN,
STATE_WAIT,
STATE_ASK,
STATE_FADE_OUT,
} STATE;
typedef struct {
STATE state;
struct {
bool is_ready;
UI_PAUSE_STATE state;
} ui;
GF_ACTION action;
FADER back_fader;
} M_PRIV;
static void M_RemoveText(M_PRIV *const p)
{
Overlay_SetBottomText(nullptr, false);
}
static void M_FadeIn(M_PRIV *const p)
{
p->state = STATE_FADE_IN;
Fader_Init(
&p->back_fader, FADER_TRANSPARENT, FADER_ALMOST_BLACK, FADE_TIME);
}
static void M_FadeOut(M_PRIV *const p)
{
M_RemoveText(p);
p->ui.is_ready = false;
if (p->action == GF_NOOP) {
Fader_Init(&p->back_fader, FADER_ANY, FADER_TRANSPARENT, FADE_TIME);
} else {
Fader_Init(&p->back_fader, FADER_ANY, FADER_BLACK, FADE_TIME);
}
p->state = STATE_FADE_OUT;
}
static void M_PauseGame(M_PRIV *const p)
{
p->action = GF_NOOP;
Music_Pause();
Sound_PauseAll();
M_FadeIn(p);
}
static void M_ReturnToGame(M_PRIV *const p)
{
Music_Unpause();
Sound_UnpauseAll();
M_FadeOut(p);
}
static void M_ExitToTitle(M_PRIV *const p)
{
p->action = GF_EXIT_TO_TITLE;
M_FadeOut(p);
}
static void M_CreateText(M_PRIV *const p)
{
Overlay_SetBottomTextPtr(GS_PTR(PAUSE_PAUSED), false);
}
static PHASE_CONTROL M_Start(PHASE *const phase)
{
M_PRIV *const p = phase->priv;
p->ui.is_ready = false;
UI_Pause_Init(&p->ui.state);
M_PauseGame(p);
return (PHASE_CONTROL) { .action = PHASE_ACTION_CONTINUE };
}
static void M_End(PHASE *const phase)
{
M_PRIV *const p = phase->priv;
M_RemoveText(p);
UI_Pause_Free(&p->ui.state);
}
static PHASE_CONTROL M_Control(PHASE *const phase)
{
M_PRIV *const p = phase->priv;
Input_Update();
Shell_ProcessInput();
if (p->ui.is_ready) {
UI_Pause_Control(&p->ui.state);
}
switch (p->state) {
case STATE_FADE_IN:
if (g_InputDB.pause) {
M_ReturnToGame(p);
return (PHASE_CONTROL) { .action = PHASE_ACTION_NO_WAIT };
} else if (!Fader_IsActive(&p->back_fader)) {
p->state = STATE_WAIT;
M_CreateText(p);
return (PHASE_CONTROL) { .action = PHASE_ACTION_NO_WAIT };
}
break;
case STATE_WAIT:
if (g_InputDB.pause) {
M_ReturnToGame(p);
return (PHASE_CONTROL) { .action = PHASE_ACTION_NO_WAIT };
} else if (g_InputDB.option) {
p->state = STATE_ASK;
}
break;
case STATE_ASK: {
const UI_PAUSE_EXIT_CHOICE choice = UI_Pause_Control(&p->ui.state);
switch (choice) {
case UI_PAUSE_RESUME_PAUSE:
p->state = STATE_WAIT;
return (PHASE_CONTROL) { .action = PHASE_ACTION_NO_WAIT };
case UI_PAUSE_EXIT_TO_GAME:
M_ReturnToGame(p);
return (PHASE_CONTROL) { .action = PHASE_ACTION_NO_WAIT };
case UI_PAUSE_EXIT_TO_TITLE:
M_ExitToTitle(p);
return (PHASE_CONTROL) { .action = PHASE_ACTION_NO_WAIT };
default:
break;
}
break;
}
case STATE_FADE_OUT:
if (!Fader_IsActive(&p->back_fader)) {
return (PHASE_CONTROL) {
.action = PHASE_ACTION_END,
.gf_cmd = { .action = p->action },
};
}
break;
}
return (PHASE_CONTROL) { .action = PHASE_ACTION_CONTINUE };
}
static void M_Draw(PHASE *const phase)
{
M_PRIV *const p = phase->priv;
Interpolation_Disable();
Game_Draw(false);
Interpolation_Enable();
UI_BeginFade(&p->back_fader, false);
UI_EndFade();
if (p->state == STATE_ASK) {
UI_Pause(&p->ui.state);
}
}
PHASE *Phase_Pause_Create(void)
{
PHASE *const phase = Memory_Alloc(sizeof(PHASE));
phase->priv = Memory_Alloc(sizeof(M_PRIV));
phase->start = M_Start;
phase->end = M_End;
phase->control = M_Control;
phase->draw = M_Draw;
return phase;
}
void Phase_Pause_Destroy(PHASE *phase)
{
Memory_Free(phase->priv);
Memory_Free(phase);
}
| 412 | 0.866756 | 1 | 0.866756 | game-dev | MEDIA | 0.661554 | game-dev | 0.508146 | 1 | 0.508146 |
tebexio/BuycraftX | 4,455 | bukkit-shared/src/main/java/net/buycraft/plugin/bukkit/signs/purchases/RecentPurchaseSignListener.java | package net.buycraft.plugin.bukkit.signs.purchases;
import net.buycraft.plugin.bukkit.BuycraftPluginBase;
import net.buycraft.plugin.bukkit.tasks.RecentPurchaseSignUpdateApplication;
import net.buycraft.plugin.bukkit.tasks.RecentPurchaseSignUpdateFetcher;
import net.buycraft.plugin.bukkit.util.BukkitSerializedBlockLocation;
import net.buycraft.plugin.shared.config.signs.storage.RecentPurchaseSignPosition;
import net.buycraft.plugin.shared.config.signs.storage.SerializedBlockLocation;
import org.apache.commons.lang.StringUtils;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.block.BlockFace;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.SignChangeEvent;
import java.awt.*;
import java.util.Arrays;
public class RecentPurchaseSignListener implements Listener {
private final BuycraftPluginBase plugin;
public RecentPurchaseSignListener(final BuycraftPluginBase plugin) {
this.plugin = plugin;
}
@EventHandler
public void onSignChange(SignChangeEvent event) {
boolean ourSign;
try {
ourSign = Arrays.asList("[buycraft_rp]", "[tebex_rp]").contains(event.getLine(0).toLowerCase());
} catch (IndexOutOfBoundsException e) {
return;
}
if (!ourSign) return;
if (!event.getPlayer().hasPermission("buycraft.admin")) {
event.getPlayer().sendMessage(ChatColor.RED + "You can't create Buycraft signs.");
return;
}
int pos;
try {
pos = Integer.parseInt(StringUtils.trimToEmpty(event.getLine(1)));
} catch (NumberFormatException | IndexOutOfBoundsException e) {
event.getPlayer().sendMessage(ChatColor.RED + "The second line must be a number.");
return;
}
if (pos <= 0) {
event.getPlayer().sendMessage(ChatColor.RED + "The second line can not be negative or zero.");
return;
}
if (pos > 100) {
event.getPlayer().sendMessage(ChatColor.RED + "No more than the 100 most recent purchases can be displayed on signs.");
return;
}
plugin.getRecentPurchaseSignStorage().addSign(new RecentPurchaseSignPosition(BukkitSerializedBlockLocation.create(
event.getBlock().getLocation()), pos));
event.getPlayer().sendMessage(ChatColor.GREEN + "Added new recent purchase sign!");
for (int i = 0; i < 4; i++) {
event.setLine(i, "");
}
plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new RecentPurchaseSignUpdateFetcher(plugin));
}
@EventHandler
public void onBlockBreak(BlockBreakEvent event) {
if (plugin.getPlatform().getSignMaterials().contains(event.getBlock().getType())) {
SerializedBlockLocation location = BukkitSerializedBlockLocation.create(event.getBlock().getLocation());
if (plugin.getRecentPurchaseSignStorage().containsLocation(location)) {
if (!event.getPlayer().hasPermission("buycraft.admin")) {
event.getPlayer().sendMessage(ChatColor.RED + "You don't have permission to break this sign.");
event.setCancelled(true);
return;
}
if (plugin.getRecentPurchaseSignStorage().removeSign(location)) {
event.getPlayer().sendMessage(ChatColor.RED + "Removed recent purchase sign!");
}
}
return;
}
for (BlockFace face : RecentPurchaseSignUpdateApplication.FACES) {
Location onFace = event.getBlock().getRelative(face).getLocation();
SerializedBlockLocation onFaceSbl = BukkitSerializedBlockLocation.create(onFace);
if (plugin.getRecentPurchaseSignStorage().containsLocation(onFaceSbl)) {
if (!event.getPlayer().hasPermission("buycraft.admin")) {
event.getPlayer().sendMessage(ChatColor.RED + "You don't have permission to break this sign.");
event.setCancelled(true);
return;
}
if (plugin.getRecentPurchaseSignStorage().removeSign(onFaceSbl)) {
event.getPlayer().sendMessage(ChatColor.RED + "Removed recent purchase sign!");
}
}
}
}
}
| 412 | 0.972575 | 1 | 0.972575 | game-dev | MEDIA | 0.902878 | game-dev | 0.978803 | 1 | 0.978803 |
MrCheeze/botw-tools | 18,818 | event/Npc_HighMountain011.c | -------- EventFlow: Npc_HighMountain011 --------
Actor: Npc_HighMountain011
entrypoint: None()
actions: ['Demo_Talk', 'Demo_TurnAndLookToObject']
queries: []
params: {'CreateMode': 0, 'IsGrounding': False, 'IsWorld': False, 'PosX': 0.0, 'PosY': 0.0, 'PosZ': 0.0, 'RotX': 0.0, 'RotY': 0.0, 'RotZ': 0.0}
Actor: EventSystemActor
entrypoint: None()
actions: ['Demo_FlagON', 'Demo_FlagOFF', 'Demo_CloseMessageDialog']
queries: ['CheckFlag', 'CheckWeather', 'CheckTimeType', 'GeneralChoice4', 'GeneralChoice2', 'GeneralChoice3']
params: {'CreateMode': 0, 'IsGrounding': False, 'IsWorld': False, 'PosX': 0.0, 'PosY': 0.0, 'PosZ': 0.0, 'RotX': 0.0, 'RotY': 0.0, 'RotZ': 0.0}
Actor: GameRomCamera
entrypoint: None()
actions: ['Demo_MovePosFlow', 'Demo_SavePoint1', 'Demo_ReturnSavePoint_1']
queries: []
params: {'CreateMode': 0, 'IsGrounding': False, 'IsWorld': False, 'PosX': 0.0, 'PosY': 0.0, 'PosZ': 0.0, 'RotX': 0.0, 'RotY': 0.0, 'RotZ': 0.0}
Actor: RemainsWind[RemainsWind_Battle]
entrypoint: None()
actions: ['Demo_Join']
queries: []
params: {'CreateMode': 0, 'IsGrounding': False, 'IsWorld': False, 'PosX': 0.0, 'PosY': 0.0, 'PosZ': 0.0, 'RotX': 0.0, 'RotY': 0.0, 'RotZ': 0.0}
Actor: GameROMPlayer
entrypoint: None()
actions: ['Demo_PlayerTurnAndLookToObject']
queries: []
params: {'Weapon': '', 'DisableWeapon': False, 'Shield': '', 'DisableShield': False, 'Bow': '', 'DisableBow': False, 'DisableSheikPad': False, 'ArmorHead': '', 'ArmorUpper': '', 'ArmorLower': '', 'CreateMode': 0, 'IsGrounding': False, 'IsWorld': False, 'PosX': 0.0, 'PosY': 0.0, 'PosZ': 0.0, 'RotX': 0.0, 'RotY': 0.0, 'RotZ': 0.0}
Actor: TerrainCalcCenterTag
entrypoint: None()
actions: ['Demo_TerrainCalcCenter']
queries: []
params: {'CreateMode': 0, 'IsGrounding': False, 'IsWorld': False, 'PosX': 0.0, 'PosY': 0.0, 'PosZ': 0.0, 'RotX': 0.0, 'RotY': 0.0, 'RotZ': 0.0}
void Talk() {
TerrainCalcCenterTag.Demo_TerrainCalcCenter({'type': 1, 'IsWaitFinish': False, 'pos': [0.0, 0.0, 0.0], 'level': 0, 'meshReso': -1})
call Nazlith_Hello()
if EventSystemActor.CheckFlag({'FlagName': 'Wind_Relic_Activated'}) {
EventSystemActor.Demo_FlagOFF({'FlagName': 'Rito_NPC011_ChoiceTeba', 'IsWaitFinish': True})
}
if EventSystemActor.CheckFlag({'FlagName': 'Rito_NPC011_First'}) {
Npc_HighMountain011.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/Npc_HighMountain011:Talk_17'})
Event40:
switch EventSystemActor.GeneralChoice4() {
case 0:
if EventSystemActor.CheckFlag({'FlagName': 'Rito_NPC011_First_Start'}) {
Npc_HighMountain011.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'MessageId': 'EventFlowMsg/Npc_HighMountain011:Talk_20', 'IsOverWriteLabelActorName': False})
Event87:
EventSystemActor.Demo_CloseMessageDialog({'IsWaitFinish': True})
Npc_HighMountain011.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/Npc_HighMountain011:Talk_21'})
goto Event40
} else {
Npc_HighMountain011.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'MessageId': 'EventFlowMsg/Npc_HighMountain011:Talk_19', 'IsOverWriteLabelActorName': False})
EventSystemActor.Demo_FlagON({'FlagName': 'Rito_NPC011_First_Start', 'IsWaitFinish': True})
goto Event87
}
case 1:
Npc_HighMountain011.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'MessageId': 'EventFlowMsg/Npc_HighMountain011:Talk_02', 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False})
goto Event87
case 2:
EventSystemActor.Demo_CloseMessageDialog({'IsWaitFinish': True})
RemainsWind[RemainsWind_Battle].Demo_Join({'IsWaitFinish': True})
GameRomCamera.Demo_SavePoint1({'IsWaitFinish': True})
Npc_HighMountain011.Demo_TurnAndLookToObject({'IsWaitFinish': True, 'IsValid': True, 'FaceId': 2, 'IsConfront': True, 'PosOffset': [0.0, 0.0, 0.0], 'TurnPosition': [0.0, 0.0, 0.0], 'ObjectId': 1, 'ActorName': 'RemainsWind', 'TurnDirection': 0.0, 'UniqueName': 'RemainsWind_Battle'})
GameROMPlayer.Demo_PlayerTurnAndLookToObject({'IsValid': True, 'FaceId': 2, 'IsWaitFinish': True, 'IsUseSlowTurn': False, 'PosOffset': [0.0, 0.0, 0.0], 'TurnPosition': [0.0, 0.0, 0.0], 'TurnDirection': 0.0, 'ObjectId': 0, 'ActorName': 'RemainsWind', 'UniqueName': 'RemainsWind_Battle', 'IsTurnToLookAtPos': False})
GameRomCamera.Demo_MovePosFlow({'TargetActor1': 3, 'TargetActor2': -1, 'ActorName2': '', 'Cushion': 0.0, 'StartCalcOnly': False, 'CollisionInterpolateSkip': True, 'Pattern1Fovy': 0.0, 'IsWaitFinish': False, 'ActorName1': 'RemainsWind', 'FovyAppendMode': 0, 'Pattern1PosX': -3192.0, 'Pattern1PosY': 300.0, 'Pattern1PosZ': -1891.0, 'LatShiftRange': 0.0, 'LngShiftRange': 0.0, 'UniqueName2': '', 'UniqueName1': 'RemainsWind_Battle', 'ReviseModeEnd': 2, 'AtAppendMode': 2, 'Pattern1AtX': 0.0, 'Pattern1AtY': 0.0, 'Pattern1AtZ': 0.0, 'PosAppendMode': 1, 'Count': 0.0, 'MotionMode': 1, 'ActorIgnoringCollision': -1, 'Accept1FrameDelay': True, 'GameDataVec3fCameraPos': '', 'GameDataVec3fCameraAt': ''})
Npc_HighMountain011.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'MessageId': 'EventFlowMsg/Npc_HighMountain011:Talk_03', 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False})
EventSystemActor.Demo_CloseMessageDialog({'IsWaitFinish': True})
GameRomCamera.Demo_ReturnSavePoint_1({'IsWaitFinish': True, 'Count': 0.0, 'CollisionInterpolateSkip': True, 'ReviseMode': 1})
Npc_HighMountain011.Demo_TurnAndLookToObject({'IsWaitFinish': True, 'IsValid': True, 'FaceId': 2, 'ObjectId': 0, 'IsConfront': True, 'ActorName': '', 'UniqueName': '', 'PosOffset': [0.0, 0.0, 0.0], 'TurnPosition': [0.0, 0.0, 0.0], 'TurnDirection': 0.0})
GameROMPlayer.Demo_PlayerTurnAndLookToObject({'IsValid': True, 'FaceId': 2, 'ObjectId': 0, 'IsWaitFinish': True, 'IsUseSlowTurn': False, 'UniqueName': '', 'PosOffset': [0.0, 0.0, 0.0], 'TurnPosition': [0.0, 0.0, 0.0], 'TurnDirection': 0.0, 'ActorName': 'Npc_HighMountain011', 'IsTurnToLookAtPos': False})
Npc_HighMountain011.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'MessageId': 'EventFlowMsg/Npc_HighMountain011:Talk_07', 'IsOverWriteLabelActorName': False})
goto Event87
case 3:
Npc_HighMountain011.Demo_Talk({'ASName': '', 'MessageId': 'EventFlowMsg/Npc_HighMountain011:Talk_04', 'IsCloseMessageDialog': False, 'IsWaitFinish': True, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False})
}
} else {
Npc_HighMountain011.Demo_Talk({'IsWaitFinish': True, 'MessageId': 'EventFlowMsg/Npc_HighMountain011:Talk_00', 'ASName': '', 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False})
EventSystemActor.Demo_FlagON({'IsWaitFinish': True, 'FlagName': 'Rito_NPC011_First'})
goto Event40
}
}
void Clear_RemainsWind_Talk() {
TerrainCalcCenterTag.Demo_TerrainCalcCenter({'type': 1, 'IsWaitFinish': False, 'pos': [0.0, 0.0, 0.0], 'level': 0, 'meshReso': -1})
call Nazlith_Hello()
if EventSystemActor.CheckFlag({'FlagName': 'HasAoCVer3'})
&& EventSystemActor.CheckFlag({'FlagName': 'BalladOfHeroRito_Finish'}) {
if EventSystemActor.CheckFlag({'FlagName': 'Rito_NPC011_First'}) {
if EventSystemActor.CheckFlag({'FlagName': 'BalladOfHeroRito_NotDragonRingTalk'}) {
Event122:
if EventSystemActor.CheckFlag({'FlagName': 'BalladOfHeroRito_DragonTalk'}) {
Npc_HighMountain011.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/BalladOfHeroRito:Npc_HighMountain011_Talk18'})
Event120:
switch EventSystemActor.GeneralChoice3() {
case 0:
Npc_HighMountain011.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'MessageId': 'EventFlowMsg/Npc_HighMountain011:Talk_15', 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False})
Npc_HighMountain011.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'MessageId': 'EventFlowMsg/Npc_HighMountain011:Talk_16', 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False})
EventSystemActor.Demo_CloseMessageDialog({'IsWaitFinish': True})
Npc_HighMountain011.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/BalladOfHeroRito:Npc_HighMountain011_Talk30'})
goto Event120
case 1:
Event114:
Npc_HighMountain011.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/BalladOfHeroRito:Npc_HighMountain011_Talk20'})
Event115:
switch EventSystemActor.GeneralChoice4() {
case 0:
Npc_HighMountain011.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/BalladOfHeroRito:Npc_HighMountain011_Talk21', 'IsCloseMessageDialog': True})
Event121:
Npc_HighMountain011.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/BalladOfHeroRito:Npc_HighMountain011_Talk25'})
goto Event115
case 1:
Npc_HighMountain011.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/BalladOfHeroRito:Npc_HighMountain011_Talk22', 'IsCloseMessageDialog': True})
goto Event121
case 2:
Npc_HighMountain011.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/BalladOfHeroRito:Npc_HighMountain011_Talk23', 'IsCloseMessageDialog': True})
goto Event121
case 3:
Npc_HighMountain011.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/BalladOfHeroRito:Npc_HighMountain011_Talk24'})
goto Event120
}
case 2:
Event103:
Npc_HighMountain011.Demo_Talk({'ASName': '', 'MessageId': 'EventFlowMsg/Npc_HighMountain011:Talk_04', 'IsCloseMessageDialog': False, 'IsWaitFinish': True, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False})
}
} else {
Npc_HighMountain011.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/BalladOfHeroRito:Npc_HighMountain011_Talk17'})
Event111:
switch EventSystemActor.GeneralChoice3() {
case 0:
Npc_HighMountain011.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'MessageId': 'EventFlowMsg/Npc_HighMountain011:Talk_15', 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False})
Npc_HighMountain011.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'MessageId': 'EventFlowMsg/Npc_HighMountain011:Talk_16', 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False})
EventSystemActor.Demo_CloseMessageDialog({'IsWaitFinish': True})
Npc_HighMountain011.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/BalladOfHeroRito:Npc_HighMountain011_Talk29'})
goto Event111
case 1:
EventSystemActor.Demo_FlagON({'FlagName': 'BalladOfHeroRito_DragonTalk', 'IsWaitFinish': True})
Npc_HighMountain011.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/BalladOfHeroRito:Npc_HighMountain011_Talk19'})
if EventSystemActor.CheckFlag({'FlagName': 'BalladOfHeroRito_Npc_HighMountain011_Talk'}) {
Npc_HighMountain011.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/BalladOfHeroRito:Npc_HighMountain011_Talk31'})
} else {
Npc_HighMountain011.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/BalladOfHeroRito:Npc_HighMountain011_Talk32'})
}
Npc_HighMountain011.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/BalladOfHeroRito:Npc_HighMountain011_Talk33'})
if !EventSystemActor.GeneralChoice2() {
goto Event114
} else {
goto Event103
}
case 2:
goto Event103
}
}
} else
if EventSystemActor.CheckFlag({'FlagName': 'BalladOfHeroRito_Npc_HighMountain011_Talk'}) {
goto Event122
} else {
EventSystemActor.Demo_FlagON({'FlagName': 'BalladOfHeroRito_NotDragonRingTalk', 'IsWaitFinish': True})
Npc_HighMountain011.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/BalladOfHeroRito:Npc_HighMountain011_Talk26'})
goto Event111
}
} else {
EventSystemActor.Demo_FlagON({'IsWaitFinish': True, 'FlagName': 'Rito_NPC011_First'})
EventSystemActor.Demo_FlagON({'FlagName': 'BalladOfHeroRito_NotDragonRingTalk', 'IsWaitFinish': True})
Npc_HighMountain011.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/BalladOfHeroRito:Npc_HighMountain011_Talk27'})
Npc_HighMountain011.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/BalladOfHeroRito:Npc_HighMountain011_Talk28'})
goto Event111
}
} else
if EventSystemActor.CheckFlag({'FlagName': 'Rito_NPC011_First'}) {
Npc_HighMountain011.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'MessageId': 'EventFlowMsg/Npc_HighMountain011:Talk_05', 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False})
Event54:
if !EventSystemActor.GeneralChoice2() {
Npc_HighMountain011.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'MessageId': 'EventFlowMsg/Npc_HighMountain011:Talk_15', 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False})
Npc_HighMountain011.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'MessageId': 'EventFlowMsg/Npc_HighMountain011:Talk_16', 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False})
} else {
Npc_HighMountain011.Demo_Talk({'ASName': '', 'MessageId': 'EventFlowMsg/Npc_HighMountain011:Talk_04', 'IsCloseMessageDialog': False, 'IsWaitFinish': True, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False})
}
} else {
EventSystemActor.Demo_FlagON({'IsWaitFinish': True, 'FlagName': 'Rito_NPC011_First'})
Npc_HighMountain011.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'MessageId': 'EventFlowMsg/Npc_HighMountain011:Talk_14', 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False})
goto Event54
}
}
void Nazlith_Hello() {
call InitTalk.InitTalk({'Arg_Turn': 0, 'Arg_Greeting': 'FollowAISchedule'})
if EventSystemActor.CheckFlag({'FlagName': 'Rito_NPC011_First'}) {
Npc_HighMountain011.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False, 'MessageId': 'EventFlowMsg/Npc_HighMountain011:Talk_01'})
} else
switch EventSystemActor.CheckWeather() {
case 0:
switch EventSystemActor.CheckTimeType() {
case [0, 1, 2, 3, 4, 5]:
Npc_HighMountain011.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'MessageId': 'EventFlowMsg/Npc_HighMountain011:Talk_09', 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False})
case [6, 7]:
Npc_HighMountain011.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'MessageId': 'EventFlowMsg/Npc_HighMountain011:Talk_10', 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False})
}
case [1, 2, 3]:
Npc_HighMountain011.Demo_Talk({'IsWaitFinish': True, 'ASName': '', 'IsCloseMessageDialog': False, 'MessageId': 'EventFlowMsg/Npc_HighMountain011:Talk_11', 'IsBecomingSpeaker': True, 'IsOverWriteLabelActorName': False})
}
}
| 412 | 0.647408 | 1 | 0.647408 | game-dev | MEDIA | 0.974233 | game-dev | 0.622029 | 1 | 0.622029 |
Source2ZE/CS2Fixes | 18,004 | src/customio.cpp | /**
* =============================================================================
* CS2Fixes
* Copyright (C) 2023-2025 Source2ZE
* =============================================================================
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "customio.h"
#include "entity.h"
#include "entity/cbaseentity.h"
#include "entity/ccsplayercontroller.h"
#include "entity/cenventitymaker.h"
#include "entity/clogiccase.h"
#include "entity/cphysthruster.h"
#include "entity/cpointhurt.h"
#include "ctimer.h"
#include <entity/cbasetrigger.h>
#include <string>
#include <vector>
struct AddOutputKey_t
{
AddOutputKey_t(const char* pName, int32_t parts, bool prefix = false) :
m_pName(pName)
{
m_nLength = strlen(pName);
m_nParts = parts;
m_bPrefix = prefix;
}
AddOutputKey_t(const AddOutputKey_t& other) :
m_pName(other.m_pName),
m_nLength(other.m_nLength),
m_nParts(other.m_nParts),
m_bPrefix(other.m_bPrefix) {}
const char* m_pName;
size_t m_nLength;
int32_t m_nParts;
bool m_bPrefix;
};
using AddOutputHandler_t = void (*)(CBaseEntity* pInstance,
CEntityInstance* pActivator,
CEntityInstance* pCaller,
const std::vector<std::string>& vecArgs);
struct AddOutputInfo_t
{
AddOutputInfo_t(const AddOutputKey_t& key, const AddOutputHandler_t& handler) :
m_Key(key), m_Handler(handler) {}
AddOutputKey_t m_Key;
AddOutputHandler_t m_Handler;
};
static void AddOutputCustom_Targetname(CBaseEntity* pInstance, CEntityInstance* pActivator,
CEntityInstance* pCaller,
const std::vector<std::string>& vecArgs)
{
pInstance->SetName(vecArgs[1].c_str());
#ifdef _DEBUG
Message("SetName %s to %d", vecArgs[1].c_str(), pInstance->GetHandle().GetEntryIndex());
#endif
}
static void AddOutputCustom_Origin(CBaseEntity* pInstance,
CEntityInstance* pActivator,
CEntityInstance* pCaller,
const std::vector<std::string>& vecArgs)
{
Vector origin(clamp(Q_atof(vecArgs[1].c_str()), -16384.f, 16384.f),
clamp(Q_atof(vecArgs[2].c_str()), -16384.f, 16384.f),
clamp(Q_atof(vecArgs[3].c_str()), -16384.f, 16384.f));
pInstance->Teleport(&origin, nullptr, nullptr);
#ifdef _DEBUG
Message("SetOrigin %f %f %f for %s", origin.x, origin.y, origin.z, pInstance->GetName());
#endif
}
static void AddOutputCustom_Angles(CBaseEntity* pInstance,
CEntityInstance* pActivator,
CEntityInstance* pCaller,
const std::vector<std::string>& vecArgs)
{
QAngle angles(clamp(Q_atof(vecArgs[1].c_str()), -360.f, 360.f),
clamp(Q_atof(vecArgs[2].c_str()), -360.f, 360.f),
clamp(Q_atof(vecArgs[3].c_str()), -360.f, 360.f));
pInstance->Teleport(nullptr, &angles, nullptr);
#ifdef _DEBUG
Message("SetAngles %f %f %f for %s", angles.x, angles.y, angles.z, pInstance->GetName());
#endif
}
static void AddOutputCustom_MaxHealth(CBaseEntity* pInstance,
CEntityInstance* pActivator,
CEntityInstance* pCaller,
const std::vector<std::string>& vecArgs)
{
pInstance->m_iMaxHealth(clamp(Q_atoi(vecArgs[1].c_str()), 0, INT_MAX));
#ifdef _DEBUG
const int m_iMaxHealth = pInstance->m_iMaxHealth;
Message("SetMaxHealth %d for %s", m_iMaxHealth, pInstance->GetName());
#endif
}
static void AddOutputCustom_Health(CBaseEntity* pInstance,
CEntityInstance* pActivator,
CEntityInstance* pCaller,
const std::vector<std::string>& vecArgs)
{
pInstance->m_iHealth(clamp(Q_atoi(vecArgs[1].c_str()), 0, INT_MAX));
#ifdef _DEBUG
const int m_iHealth = pInstance->m_iHealth;
Message("SetHealth %d for %s", m_iHealth, pInstance->GetName());
#endif
}
static void AddOutputCustom_MoveType(CBaseEntity* pInstance,
CEntityInstance* pActivator,
CEntityInstance* pCaller,
const std::vector<std::string>& vecArgs)
{
static Vector stopVelocity(0, 0, 0);
const auto value = clamp(Q_atoi(vecArgs[1].c_str()), MOVETYPE_NONE, MOVETYPE_LAST);
const auto type = static_cast<MoveType_t>(value);
pInstance->SetMoveType(type);
#ifdef _DEBUG
Message("SetMoveType %d for %s", type, pInstance->GetName());
#endif
}
static void AddOutputCustom_EntityTemplate(CBaseEntity* pInstance,
CEntityInstance* pActivator,
CEntityInstance* pCaller,
const std::vector<std::string>& vecArgs)
{
if (strcmp(pInstance->GetClassname(), "env_entity_maker") == 0)
{
const auto pEntity = reinterpret_cast<CEnvEntityMaker*>(pInstance);
const auto pValue = g_pEntitySystem->AllocPooledString(vecArgs[1].c_str());
pEntity->m_iszTemplate(pValue);
#ifdef _DEBUG
Message("Set EntityTemplate to %s for %s\n", pValue.String(), pInstance->GetName());
#endif
}
else
Message("Only env_entity_maker is supported\n");
}
static void AddOutputCustom_BaseVelocity(CBaseEntity* pInstance,
CEntityInstance* pActivator,
CEntityInstance* pCaller,
const std::vector<std::string>& vecArgs)
{
const Vector velocity(clamp(Q_atof(vecArgs[1].c_str()), -4096.f, 4096.f),
clamp(Q_atof(vecArgs[2].c_str()), -4096.f, 4096.f),
clamp(Q_atof(vecArgs[3].c_str()), -4096.f, 4096.f));
pInstance->SetBaseVelocity(velocity);
#ifdef _DEBUG
Message("SetOrigin %f %f %f for %s", velocity.x, velocity.y, velocity.z, pInstance->GetName());
#endif
}
static void AddOutputCustom_AbsVelocity(CBaseEntity* pInstance,
CEntityInstance* pActivator,
CEntityInstance* pCaller,
const std::vector<std::string>& vecArgs)
{
Vector velocity(clamp(Q_atof(vecArgs[1].c_str()), -4096.f, 4096.f),
clamp(Q_atof(vecArgs[2].c_str()), -4096.f, 4096.f),
clamp(Q_atof(vecArgs[3].c_str()), -4096.f, 4096.f));
pInstance->Teleport(nullptr, nullptr, &velocity);
#ifdef _DEBUG
Message("SetOrigin %f %f %f for %s", velocity.x, velocity.y, velocity.z, pInstance->GetName());
#endif
}
static void AddOutputCustom_Target(CBaseEntity* pInstance,
CEntityInstance* pActivator,
CEntityInstance* pCaller,
const std::vector<std::string>& vecArgs)
{
if (const auto pTarget = UTIL_FindEntityByName(nullptr, vecArgs[1].c_str()))
{
const auto pEntity = pInstance;
pEntity->m_target(pTarget->m_pEntity->m_name);
#ifdef _DEBUG
Message("Set Target to %s for %s\n", pTarget->m_pEntity->m_name.String(), pEntity->m_pEntity->m_name.String());
#endif
}
}
static void AddOutputCustom_FilterName(CBaseEntity* pInstance,
CEntityInstance* pActivator,
CEntityInstance* pCaller,
const std::vector<std::string>& vecArgs)
{
if (V_strncasecmp(pInstance->GetClassname(), "trigger_", 8) == 0)
{
if (const auto pTarget = UTIL_FindEntityByName(nullptr, vecArgs[1].c_str()))
{
if (V_strncasecmp(pTarget->GetClassname(), "filter_", 7) == 0)
{
const auto pTrigger = reinterpret_cast<CBaseTrigger*>(pInstance);
pTrigger->m_iFilterName(pTarget->GetName());
pTrigger->m_hFilter(pTarget->GetRefEHandle());
#ifdef _DEBUG
Message("Set FilterName to %s for %s\n", pTarget->GetName(),
pTrigger->GetName());
#endif
}
}
}
}
static void AddOutputCustom_Force(CBaseEntity* pInstance,
CEntityInstance* pActivator,
CEntityInstance* pCaller,
const std::vector<std::string>& vecArgs)
{
const auto value = Q_atof(vecArgs[1].c_str());
const auto pEntity = reinterpret_cast<CPhysThruster*>(pInstance);
if (V_strcasecmp(pEntity->GetClassname(), "phys_thruster") == 0)
{
pEntity->m_force(value);
#ifdef _DEBUG
Message("Set force to %f for %s\n", value, pEntity->GetName());
#endif
}
}
static void AddOutputCustom_Gravity(CBaseEntity* pInstance,
CEntityInstance* pActivator,
CEntityInstance* pCaller,
const std::vector<std::string>& vecArgs)
{
const auto value = Q_atof(vecArgs[1].c_str());
pInstance->SetGravityScale(value);
#ifdef _DEBUG
Message("Set gravity to %f for %s\n", value, pInstance->GetName());
#endif
}
static void AddOutputCustom_Timescale(CBaseEntity* pInstance,
CEntityInstance* pActivator,
CEntityInstance* pCaller,
const std::vector<std::string>& vecArgs)
{
const auto value = Q_atof(vecArgs[1].c_str());
pInstance->m_flTimeScale = value;
#ifdef _DEBUG
Message("Set timescale to %f for %s\n", value, pInstance->GetName());
#endif
}
static void AddOutputCustom_Friction(CBaseEntity* pInstance,
CEntityInstance* pActivator,
CEntityInstance* pCaller,
const std::vector<std::string>& vecArgs)
{
const auto value = Q_atof(vecArgs[1].c_str());
pInstance->m_flFriction = value;
#ifdef _DEBUG
Message("Set friction to %f for %s\n", value, pInstance->GetName());
#endif
}
static void AddOutputCustom_Speed(CBaseEntity* pInstance,
CEntityInstance* pActivator,
CEntityInstance* pCaller,
const std::vector<std::string>& vecArgs)
{
if (!pInstance->IsPawn())
return;
const auto pPawn = reinterpret_cast<CCSPlayerPawn*>(pInstance);
const auto pController = pPawn->GetOriginalController();
if (!pController || !pController->IsConnected())
return;
const auto value = Q_atof(vecArgs[1].c_str());
pController->GetZEPlayer()->SetSpeedMod(value);
#ifdef _DEBUG
Message("Set speed to %f for %s\n", value, pInstance->GetName());
#endif
}
static void AddOutputCustom_RunSpeed(CBaseEntity* pInstance,
CEntityInstance* pActivator,
CEntityInstance* pCaller,
const std::vector<std::string>& vecArgs)
{
if (!pInstance->IsPawn())
return;
const auto pPawn = reinterpret_cast<CCSPlayerPawn*>(pInstance);
const auto value = Q_atof(vecArgs[1].c_str());
pPawn->m_flVelocityModifier = value;
#ifdef _DEBUG
Message("Set runspeed to %f for %s\n", value, pInstance->GetName());
#endif
}
static void AddOutputCustom_Damage(CBaseEntity* pInstance,
CEntityInstance* pActivator,
CEntityInstance* pCaller,
const std::vector<std::string>& vecArgs)
{
CPointHurt* pEntity = reinterpret_cast<CPointHurt*>(pInstance);
if (!V_strcasecmp(pEntity->GetClassname(), "point_hurt"))
{
const int value = clamp(Q_atoi(vecArgs[1].c_str()), 0, INT_MAX);
pEntity->m_nDamage(value);
#ifdef _DEBUG
Message("Set damage to %d for %s\n", value, pEntity->GetName());
#endif
}
}
static void AddOutputCustom_DamageType(CBaseEntity* pInstance,
CEntityInstance* pActivator,
CEntityInstance* pCaller,
const std::vector<std::string>& vecArgs)
{
CPointHurt* pEntity = reinterpret_cast<CPointHurt*>(pInstance);
if (!V_strcasecmp(pEntity->GetClassname(), "point_hurt"))
{
const int value = clamp(Q_atoi(vecArgs[1].c_str()), 0, INT_MAX);
pEntity->m_bitsDamageType(value);
#ifdef _DEBUG
Message("Set damagetype to %d for %s\n", value, pEntity->GetName());
#endif
}
}
static void AddOutputCustom_DamageRadius(CBaseEntity* pInstance,
CEntityInstance* pActivator,
CEntityInstance* pCaller,
const std::vector<std::string>& vecArgs)
{
CPointHurt* pEntity = reinterpret_cast<CPointHurt*>(pInstance);
if (!V_strcasecmp(pEntity->GetClassname(), "point_hurt"))
{
const float value = Q_atof(vecArgs[1].c_str());
pEntity->m_flRadius(value);
#ifdef _DEBUG
Message("Set damageradius to %f for %s\n", value, pEntity->GetName());
#endif
}
}
static void AddOutputCustom_Case(CBaseEntity* pInstance,
CEntityInstance* pActivator,
CEntityInstance* pCaller,
const std::vector<std::string>& vecArgs)
{
CLogicCase* pEntity = reinterpret_cast<CLogicCase*>(pInstance);
if (!V_strcasecmp(pEntity->GetClassname(), "logic_case"))
{
if (vecArgs[0].length() != 6)
{
Message("%s is an invalid KeyValue input, size must be 6\n", vecArgs[0].c_str());
return;
}
const int iCase = V_StringToInt32(vecArgs[0].substr(4).c_str(), -1);
if (iCase < 1 || iCase > 32)
{
Message("%s is an invalid KeyValue input, case number must be between 01-32\n", vecArgs[0].c_str());
return;
}
const CUtlSymbolLarge pValue = g_pEntitySystem->AllocPooledString(vecArgs[1].c_str());
pEntity->m_nCase()[iCase - 1] = pValue;
#ifdef _DEBUG
Message("Set %s to %s for %s\n", vecArgs[0].c_str(), pValue.String(), pInstance->GetName());
#endif
}
}
const std::vector<AddOutputInfo_t> s_AddOutputHandlers = {
{{"targetname", 2}, AddOutputCustom_Targetname },
{{"origin", 4}, AddOutputCustom_Origin },
{{"angles", 4}, AddOutputCustom_Angles },
{{"max_health", 2}, AddOutputCustom_MaxHealth },
{{"health", 2}, AddOutputCustom_Health },
{{"movetype", 2}, AddOutputCustom_MoveType },
{{"EntityTemplate", 2}, AddOutputCustom_EntityTemplate},
{{"basevelocity", 4}, AddOutputCustom_BaseVelocity },
{{"absvelocity", 4}, AddOutputCustom_AbsVelocity },
{{"target", 2}, AddOutputCustom_Target },
{{"filtername", 2}, AddOutputCustom_FilterName },
{{"force", 2}, AddOutputCustom_Force },
{{"gravity", 2}, AddOutputCustom_Gravity },
{{"timescale", 2}, AddOutputCustom_Timescale },
{{"friction", 2}, AddOutputCustom_Friction },
{{"speed", 2}, AddOutputCustom_Speed },
{{"runspeed", 2}, AddOutputCustom_RunSpeed },
{{"damage", 2}, AddOutputCustom_Damage },
{{"damagetype", 2}, AddOutputCustom_DamageType },
{{"damageradius", 2}, AddOutputCustom_DamageRadius },
{{"Case", 2, true}, AddOutputCustom_Case },
};
inline std::vector<std::string> StringSplit(const char* str, const char* delimiter)
{
std::vector<std::string> result;
std::string_view strV(str);
size_t pos;
while ((pos = strV.find(delimiter)) != std::string_view::npos)
{
result.emplace_back(strV.substr(0, pos));
strV.remove_prefix(pos + std::string_view(delimiter).size());
}
result.emplace_back(strV);
return result;
}
bool CustomIO_HandleInput(CEntityInstance* pInstance,
const char* param,
CEntityInstance* pActivator,
CEntityInstance* pCaller)
{
const auto paramSplit = StringSplit(param, " ");
for (auto& [input, handler] : s_AddOutputHandlers)
{
if (!V_strcasecmp(paramSplit[0].c_str(), input.m_pName) || (input.m_bPrefix && !V_strncasecmp(paramSplit[0].c_str(), input.m_pName, input.m_nLength)))
{
if (paramSplit.size() == input.m_nParts)
{
handler(reinterpret_cast<CBaseEntity*>(pInstance), pActivator, pCaller, paramSplit);
return true;
}
break;
}
}
return false;
}
CConVar<CUtlString> g_cvarBurnParticle("cs2f_burn_particle", FCVAR_NONE, "The particle to use for burning entities", "particles/cs2fixes/napalm_fire.vpcf");
CConVar<float> g_cvarBurnDamage("cs2f_burn_damage", FCVAR_NONE, "The amount of each burn damage ticks", 1.0f, true, 0.0f, false, 0.0f);
CConVar<float> g_cvarBurnSlowdown("cs2f_burn_slowdown", FCVAR_NONE, "The slowdown of each burn damage tick as a multiplier of base speed", 0.6f, true, 0.0f, true, 1.0f);
CConVar<float> g_cvarBurnInterval("cs2f_burn_interval", FCVAR_NONE, "The interval between burn damage ticks", 0.3f, true, 0.0f, false, 0.0f);
bool IgnitePawn(CCSPlayerPawn* pPawn, float flDuration, CBaseEntity* pInflictor, CBaseEntity* pAttacker, CBaseEntity* pAbility, DamageTypes_t nDamageType)
{
if (!GetGlobals())
return false;
auto pParticleEnt = reinterpret_cast<CParticleSystem*>(pPawn->m_hEffectEntity().Get());
// This guy is already burning, don't ignite again
if (pParticleEnt)
{
// Override the end time instead of just adding to it so players who get a ton of ignite inputs don't burn forever
pParticleEnt->m_flDissolveStartTime = GetGlobals()->curtime + flDuration;
return true;
}
const auto vecOrigin = pPawn->GetAbsOrigin();
pParticleEnt = CreateEntityByName<CParticleSystem>("info_particle_system");
pParticleEnt->m_bStartActive(true);
pParticleEnt->m_iszEffectName(g_cvarBurnParticle.Get().String());
pParticleEnt->m_hControlPointEnts[0] = pPawn;
pParticleEnt->m_flDissolveStartTime = GetGlobals()->curtime + flDuration; // Store the end time in the particle itself so we can increment if needed
pParticleEnt->Teleport(&vecOrigin, nullptr, nullptr);
pParticleEnt->DispatchSpawn();
pParticleEnt->SetParent(pPawn);
pPawn->m_hEffectEntity = pParticleEnt;
CHandle<CCSPlayerPawn> hPawn(pPawn);
CHandle<CBaseEntity> hInflictor(pInflictor);
CHandle<CBaseEntity> hAttacker(pAttacker);
CHandle<CBaseEntity> hAbility(pAbility);
CTimer::Create(0.f, TIMERFLAG_MAP | TIMERFLAG_ROUND, [hPawn, hInflictor, hAttacker, hAbility, nDamageType]() {
CCSPlayerPawn* pPawn = hPawn.Get();
if (!pPawn || !GetGlobals())
return -1.f;
const auto pParticleEnt = reinterpret_cast<CParticleSystem*>(pPawn->m_hEffectEntity().Get());
if (!pParticleEnt)
return -1.f;
if (V_strncmp(pParticleEnt->GetClassname(), "info_part", 9) != 0)
{
// This should never happen but just in case
Panic("Found unexpected entity %s while burning a pawn!\n", pParticleEnt->GetClassname());
return -1.f;
}
if (pParticleEnt->m_flDissolveStartTime() <= GetGlobals()->curtime || !pPawn->IsAlive())
{
pParticleEnt->AcceptInput("Stop");
UTIL_AddEntityIOEvent(pParticleEnt, "Kill"); // Kill on the next frame
return -1.f;
}
CTakeDamageInfo info(hInflictor, hAttacker, hAbility, g_cvarBurnDamage.Get(), nDamageType);
// Damage doesn't apply if the inflictor is null
if (!hInflictor.Get())
info.m_hInflictor.Set(hAttacker);
pPawn->TakeDamage(info);
pPawn->m_flVelocityModifier = g_cvarBurnSlowdown.Get();
return g_cvarBurnInterval.Get();
});
return true;
}
| 412 | 0.981297 | 1 | 0.981297 | game-dev | MEDIA | 0.395512 | game-dev | 0.942997 | 1 | 0.942997 |
nhat-phan/merge-request-integration | 1,882 | merge-request-integration/src/main/kotlin/net/ntworld/mergeRequestIntegration/provider/gitlab/GitlabMergeRequestApiCache.kt | package net.ntworld.mergeRequestIntegration.provider.gitlab
import net.ntworld.mergeRequest.MergeRequest
import net.ntworld.mergeRequest.api.*
import net.ntworld.mergeRequest.query.GetMergeRequestFilter
import net.ntworld.mergeRequestIntegration.internal.ApiOptionsImpl
import net.ntworld.mergeRequestIntegration.provider.MergeRequestApiDecorator
import org.joda.time.DateTime
class GitlabMergeRequestApiCache(
private val api: MergeRequestApi,
private val cache: Cache
) : MergeRequestApiDecorator(api) {
var options: ApiOptions = ApiOptionsImpl.DEFAULT
override fun findOrFail(projectId: String, mergeRequestId: String): MergeRequest {
if (!options.enableRequestCache) {
return super.findOrFail(projectId, mergeRequestId)
}
val key = makeFindCacheKey(mergeRequestId)
return cache.getOrRun(key) {
val mergeRequest = super.findOrFail(projectId, mergeRequestId)
cache.set(key, mergeRequest)
mergeRequest
}
}
override fun search(
projectId: String,
currentUserId: String,
filterBy: GetMergeRequestFilter,
orderBy: MergeRequestOrdering,
page: Int,
itemsPerPage: Int
): MergeRequestApi.SearchResult {
val result = super.search(projectId, currentUserId, filterBy, orderBy, page, itemsPerPage)
if (options.enableRequestCache) {
result.data.forEach {
try {
val key = makeFindCacheKey(it.id)
if (cache.isExpiredAfter(key, DateTime(it.updatedAt))) {
cache.remove(key)
}
} catch (cacheNotFound: CacheNotFoundException) {
}
}
}
return result
}
private fun makeFindCacheKey(mergeRequestId: String) = "MR:find:$mergeRequestId"
} | 412 | 0.880438 | 1 | 0.880438 | game-dev | MEDIA | 0.735576 | game-dev | 0.794988 | 1 | 0.794988 |
espertechinc/nesper | 17,589 | src/NEsper.Common/common/internal/epl/updatehelper/EventBeanUpdateHelperForgeFactory.cs | ///////////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2006-2024 Esper Team. All rights reserved. /
// http://esper.codehaus.org /
// ---------------------------------------------------------------------------------- /
// The software in this package is published under the terms of the GPL license /
// a copy of which has been included with this distribution in the license.txt file. /
///////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using com.espertech.esper.common.client;
using com.espertech.esper.common.@internal.compile.stage1.spec;
using com.espertech.esper.common.@internal.epl.expression.assign;
using com.espertech.esper.common.@internal.epl.expression.core;
using com.espertech.esper.common.@internal.epl.expression.visitor;
using com.espertech.esper.common.@internal.@event.avro;
using com.espertech.esper.common.@internal.@event.core;
using com.espertech.esper.common.@internal.util;
using com.espertech.esper.compat;
using com.espertech.esper.compat.collections;
namespace com.espertech.esper.common.@internal.epl.updatehelper
{
public class EventBeanUpdateHelperForgeFactory
{
public static EventBeanUpdateHelperForge Make(
string updatedWindowOrTableName,
EventTypeSPI eventTypeSPI,
IList<OnTriggerSetAssignment> assignments,
string updatedAlias,
EventType optionalTriggeringEventType,
bool isCopyOnWrite,
string statementName,
EventTypeAvroHandler avroHandler)
{
IList<EventBeanUpdateItemForge> updateItems = new List<EventBeanUpdateItemForge>();
IList<string> properties = new List<string>();
var typeWidenerCustomizer = avroHandler.GetTypeWidenerCustomizer(eventTypeSPI);
for (var i = 0; i < assignments.Count; i++) {
var desc = assignments[i];
var assignment = desc.Validated;
if (assignment == null) {
throw new IllegalStateException("Assignment has not been validated");
}
try {
EventBeanUpdateItemForge updateItem;
if (assignment is ExprAssignmentStraight straight) {
// handle assignment "property = value"
if (straight.Lhs is ExprAssignmentLHSIdent ident) {
var propertyName = ident.Ident;
var writableProperty = eventTypeSPI.GetWritableProperty(propertyName);
// check assignment to indexed or mapped property
if (writableProperty == null) {
var nameWriteablePair = CheckIndexedOrMappedProp(
propertyName,
updatedWindowOrTableName,
updatedAlias,
eventTypeSPI);
propertyName = nameWriteablePair.First;
writableProperty = nameWriteablePair.Second;
}
var type = writableProperty.PropertyType;
var rhsExpr = straight.Rhs;
var rhsForge = rhsExpr.Forge;
var writer = eventTypeSPI.GetWriter(propertyName);
bool notNullableField = type.CanNotBeNull();
properties.Add(propertyName);
TypeWidenerSPI widener;
var evalType = rhsForge.EvaluationType;
try {
widener = TypeWidenerFactory.GetCheckPropertyAssignType(
ExprNodeUtilityPrint.ToExpressionStringMinPrecedenceSafe(rhsExpr),
evalType,
writableProperty.PropertyType,
propertyName,
false,
typeWidenerCustomizer,
statementName);
}
catch (TypeWidenerException ex) {
throw new ExprValidationException(ex.Message, ex);
}
// check event type assignment
var useUntypedAssignment = false;
var useTriggeringEvent = false;
if (optionalTriggeringEventType != null) {
// handle RHS is ident node
if (rhsExpr is ExprIdentNode node) {
var fragmentRHS =
optionalTriggeringEventType.GetFragmentType(node.ResolvedPropertyName);
var fragmentLHS = eventTypeSPI.GetFragmentType(propertyName);
if (fragmentRHS != null && fragmentLHS != null) {
if (!EventTypeUtility.IsTypeOrSubTypeOf(
fragmentRHS.FragmentType,
fragmentLHS.FragmentType)) {
throw MakeEventTypeMismatch(
propertyName,
fragmentLHS.FragmentType,
fragmentRHS.FragmentType);
}
}
// we don't need to cast if it is a self-assignment and LHS is an event and target needs no writer
if (node.StreamId == 0 &&
fragmentLHS != null &&
eventTypeSPI is BaseNestableEventType) {
useUntypedAssignment = true;
}
}
// handle RHS is a stream of the triggering event itself
if (rhsExpr is ExprStreamUnderlyingNode und) {
if (und.StreamId == 1) {
var fragmentLHS = eventTypeSPI.GetFragmentType(propertyName);
if (fragmentLHS != null &&
optionalTriggeringEventType is BaseNestableEventType &&
!EventTypeUtility.IsTypeOrSubTypeOf(
optionalTriggeringEventType,
fragmentLHS.FragmentType)) {
throw MakeEventTypeMismatch(
propertyName,
fragmentLHS.FragmentType,
optionalTriggeringEventType);
}
// we use the event itself for assignment and target needs no writer
if (eventTypeSPI is BaseNestableEventType) {
useUntypedAssignment = true;
useTriggeringEvent = true;
}
}
}
}
updateItem = new EventBeanUpdateItemForge(
rhsForge,
propertyName,
writer,
notNullableField,
widener,
useUntypedAssignment,
useTriggeringEvent,
null);
}
else if (straight.Lhs is ExprAssignmentLHSArrayElement arrayElementLhs) {
// handle "property[expr] = value"
var arrayPropertyName = arrayElementLhs.Ident;
var rhs = straight.Rhs;
var evaluationType = rhs.Forge.EvaluationType;
var propertyType = eventTypeSPI.GetPropertyType(arrayPropertyName);
if (!eventTypeSPI.IsProperty(arrayPropertyName)) {
throw new ExprValidationException(
"Property '" + arrayPropertyName + "' could not be found");
}
if (propertyType == null || !propertyType.IsArray) {
throw new ExprValidationException(
"Property '" + arrayPropertyName + "' is not an array");
}
if (evaluationType == null) {
throw new ExprValidationException(
"Right-hand-side evaluation returns null-typed value for '" +
arrayPropertyName +
"'");
}
var evaluationClass = evaluationType;
var propertyClass = propertyType;
var getter = eventTypeSPI.GetGetterSPI(arrayPropertyName);
Type componentType = propertyClass.GetComponentType();
if (!evaluationClass.IsAssignmentCompatible(componentType)) {
throw new ExprValidationException(
"Invalid assignment to property '" +
arrayPropertyName +
"' component type '" +
componentType.CleanName() +
"' from expression returning '" +
evaluationType.CleanName() +
"'");
}
TypeWidenerSPI widener;
try {
widener = TypeWidenerFactory.GetCheckPropertyAssignType(
ExprNodeUtilityPrint.ToExpressionStringMinPrecedenceSafe(straight.Rhs),
evaluationType,
componentType,
arrayPropertyName,
false,
typeWidenerCustomizer,
statementName);
}
catch (TypeWidenerException ex) {
throw new ExprValidationException(ex.Message, ex);
}
var arrayInfo = new EventBeanUpdateItemArray(
arrayPropertyName,
arrayElementLhs.IndexExpression,
propertyClass,
getter);
updateItem = new EventBeanUpdateItemForge(
rhs.Forge,
arrayPropertyName,
null,
false,
widener,
false,
false,
arrayInfo);
}
else {
throw new IllegalStateException("Unrecognized LHS assignment " + straight);
}
}
else if (assignment is ExprAssignmentCurly dot) {
// handle non-assignment, i.e. UDF or other expression
updateItem = new EventBeanUpdateItemForge(
dot.Expression.Forge,
null,
null,
false,
null,
false,
false,
null);
}
else {
throw new IllegalStateException("Unrecognized assignment " + assignment);
}
updateItems.Add(updateItem);
}
catch (ExprValidationException ex) {
throw new ExprValidationException(
"Failed to validate assignment expression '" +
ExprNodeUtilityPrint.ToExpressionStringMinPrecedenceSafe(assignment.OriginalExpression) +
"': " +
ex.Message,
ex);
}
}
// copy-on-write is the default event semantics as events are immutable
EventBeanCopyMethodForge copyMethod;
if (isCopyOnWrite) {
// obtain copy method
IList<string> propertiesUniqueList = new List<string>(new HashSet<string>(properties));
var propertiesArray = propertiesUniqueList.ToArray();
copyMethod = eventTypeSPI.GetCopyMethodForge(propertiesArray);
if (copyMethod == null) {
throw new ExprValidationException("Event type does not support event bean copy");
}
}
else {
// for in-place update, determine assignment expressions to use "initial" to access prior-change values
// the copy-method is optional
copyMethod = null;
var propertiesInitialValue = DeterminePropertiesInitialValue(assignments);
if (!propertiesInitialValue.IsEmpty()) {
var propertiesInitialValueArray = propertiesInitialValue.ToArray();
copyMethod = eventTypeSPI.GetCopyMethodForge(propertiesInitialValueArray);
}
}
var updateItemsArray = updateItems.ToArray();
return new EventBeanUpdateHelperForge(eventTypeSPI, copyMethod, updateItemsArray);
}
private static ExprValidationException MakeEventTypeMismatch(
string propertyName,
EventType lhs,
EventType rhs)
{
return new ExprValidationException(
"Invalid assignment to property '" +
propertyName +
"' event type '" +
lhs.Name +
"' from event type '" +
rhs.Name +
"'");
}
private static ISet<string> DeterminePropertiesInitialValue(IList<OnTriggerSetAssignment> assignments)
{
ISet<string> props = new HashSet<string>();
var visitor = new ExprNodeIdentifierCollectVisitor();
foreach (var assignment in assignments) {
assignment.Validated.Accept(visitor);
foreach (var node in visitor.ExprProperties) {
if (node.StreamId == 2) {
props.Add(node.ResolvedPropertyName);
}
}
visitor.Reset();
}
return props;
}
private static Pair<string, EventPropertyDescriptor> CheckIndexedOrMappedProp(
string propertyName,
string updatedWindowOrTableName,
string namedWindowAlias,
EventTypeSPI eventTypeSPI)
{
EventPropertyDescriptor writableProperty = null;
var indexDot = propertyName.IndexOf(".");
if (namedWindowAlias != null && indexDot != -1) {
var prefix = StringValue.UnescapeBacktick(propertyName.Substring(0, indexDot));
var name = propertyName.Substring(indexDot + 1);
if (prefix.Equals(namedWindowAlias)) {
writableProperty = eventTypeSPI.GetWritableProperty(name);
propertyName = name;
}
}
if (writableProperty == null && indexDot != -1) {
var prefix = propertyName.Substring(0, indexDot);
var name = propertyName.Substring(indexDot + 1);
if (prefix.Equals(updatedWindowOrTableName)) {
writableProperty = eventTypeSPI.GetWritableProperty(name);
propertyName = name;
}
}
if (writableProperty == null) {
throw new ExprValidationException("Property '" + propertyName + "' is not available for write access");
}
return new Pair<string, EventPropertyDescriptor>(propertyName, writableProperty);
}
}
} // end of namespace | 412 | 0.943725 | 1 | 0.943725 | game-dev | MEDIA | 0.358904 | game-dev | 0.851014 | 1 | 0.851014 |
amate/Proxydomo | 27,892 | googletest/gtest/internal/gtest-param-util.h | // Copyright 2008 Google Inc.
// All Rights Reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: vladl@google.com (Vlad Losev)
// Type and function utilities for implementing parameterized tests.
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
#include <ctype.h>
#include <iterator>
#include <set>
#include <utility>
#include <vector>
// scripts/fuse_gtest.py depends on gtest's own header being #included
// *unconditionally*. Therefore these #includes cannot be moved
// inside #if GTEST_HAS_PARAM_TEST.
#include "gtest/internal/gtest-internal.h"
#include "gtest/internal/gtest-linked_ptr.h"
#include "gtest/internal/gtest-port.h"
#include "gtest/gtest-printers.h"
#if GTEST_HAS_PARAM_TEST
namespace testing {
// Input to a parameterized test name generator, describing a test parameter.
// Consists of the parameter value and the integer parameter index.
template <class ParamType>
struct TestParamInfo {
TestParamInfo(const ParamType& a_param, size_t an_index) :
param(a_param),
index(an_index) {}
ParamType param;
size_t index;
};
// A builtin parameterized test name generator which returns the result of
// testing::PrintToString.
struct PrintToStringParamName {
template <class ParamType>
std::string operator()(const TestParamInfo<ParamType>& info) const {
return PrintToString(info.param);
}
};
namespace internal {
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
//
// Outputs a message explaining invalid registration of different
// fixture class for the same test case. This may happen when
// TEST_P macro is used to define two tests with the same name
// but in different namespaces.
GTEST_API_ void ReportInvalidTestCaseType(const char* test_case_name,
CodeLocation code_location);
template <typename> class ParamGeneratorInterface;
template <typename> class ParamGenerator;
// Interface for iterating over elements provided by an implementation
// of ParamGeneratorInterface<T>.
template <typename T>
class ParamIteratorInterface {
public:
virtual ~ParamIteratorInterface() {}
// A pointer to the base generator instance.
// Used only for the purposes of iterator comparison
// to make sure that two iterators belong to the same generator.
virtual const ParamGeneratorInterface<T>* BaseGenerator() const = 0;
// Advances iterator to point to the next element
// provided by the generator. The caller is responsible
// for not calling Advance() on an iterator equal to
// BaseGenerator()->End().
virtual void Advance() = 0;
// Clones the iterator object. Used for implementing copy semantics
// of ParamIterator<T>.
virtual ParamIteratorInterface* Clone() const = 0;
// Dereferences the current iterator and provides (read-only) access
// to the pointed value. It is the caller's responsibility not to call
// Current() on an iterator equal to BaseGenerator()->End().
// Used for implementing ParamGenerator<T>::operator*().
virtual const T* Current() const = 0;
// Determines whether the given iterator and other point to the same
// element in the sequence generated by the generator.
// Used for implementing ParamGenerator<T>::operator==().
virtual bool Equals(const ParamIteratorInterface& other) const = 0;
};
// Class iterating over elements provided by an implementation of
// ParamGeneratorInterface<T>. It wraps ParamIteratorInterface<T>
// and implements the const forward iterator concept.
template <typename T>
class ParamIterator {
public:
typedef T value_type;
typedef const T& reference;
typedef ptrdiff_t difference_type;
// ParamIterator assumes ownership of the impl_ pointer.
ParamIterator(const ParamIterator& other) : impl_(other.impl_->Clone()) {}
ParamIterator& operator=(const ParamIterator& other) {
if (this != &other)
impl_.reset(other.impl_->Clone());
return *this;
}
const T& operator*() const { return *impl_->Current(); }
const T* operator->() const { return impl_->Current(); }
// Prefix version of operator++.
ParamIterator& operator++() {
impl_->Advance();
return *this;
}
// Postfix version of operator++.
ParamIterator operator++(int /*unused*/) {
ParamIteratorInterface<T>* clone = impl_->Clone();
impl_->Advance();
return ParamIterator(clone);
}
bool operator==(const ParamIterator& other) const {
return impl_.get() == other.impl_.get() || impl_->Equals(*other.impl_);
}
bool operator!=(const ParamIterator& other) const {
return !(*this == other);
}
private:
friend class ParamGenerator<T>;
explicit ParamIterator(ParamIteratorInterface<T>* impl) : impl_(impl) {}
scoped_ptr<ParamIteratorInterface<T> > impl_;
};
// ParamGeneratorInterface<T> is the binary interface to access generators
// defined in other translation units.
template <typename T>
class ParamGeneratorInterface {
public:
typedef T ParamType;
virtual ~ParamGeneratorInterface() {}
// Generator interface definition
virtual ParamIteratorInterface<T>* Begin() const = 0;
virtual ParamIteratorInterface<T>* End() const = 0;
};
// Wraps ParamGeneratorInterface<T> and provides general generator syntax
// compatible with the STL Container concept.
// This class implements copy initialization semantics and the contained
// ParamGeneratorInterface<T> instance is shared among all copies
// of the original object. This is possible because that instance is immutable.
template<typename T>
class ParamGenerator {
public:
typedef ParamIterator<T> iterator;
explicit ParamGenerator(ParamGeneratorInterface<T>* impl) : impl_(impl) {}
ParamGenerator(const ParamGenerator& other) : impl_(other.impl_) {}
ParamGenerator& operator=(const ParamGenerator& other) {
impl_ = other.impl_;
return *this;
}
iterator begin() const { return iterator(impl_->Begin()); }
iterator end() const { return iterator(impl_->End()); }
private:
linked_ptr<const ParamGeneratorInterface<T> > impl_;
};
// Generates values from a range of two comparable values. Can be used to
// generate sequences of user-defined types that implement operator+() and
// operator<().
// This class is used in the Range() function.
template <typename T, typename IncrementT>
class RangeGenerator : public ParamGeneratorInterface<T> {
public:
RangeGenerator(T begin, T end, IncrementT step)
: begin_(begin), end_(end),
step_(step), end_index_(CalculateEndIndex(begin, end, step)) {}
virtual ~RangeGenerator() {}
virtual ParamIteratorInterface<T>* Begin() const {
return new Iterator(this, begin_, 0, step_);
}
virtual ParamIteratorInterface<T>* End() const {
return new Iterator(this, end_, end_index_, step_);
}
private:
class Iterator : public ParamIteratorInterface<T> {
public:
Iterator(const ParamGeneratorInterface<T>* base, T value, int index,
IncrementT step)
: base_(base), value_(value), index_(index), step_(step) {}
virtual ~Iterator() {}
virtual const ParamGeneratorInterface<T>* BaseGenerator() const {
return base_;
}
virtual void Advance() {
value_ = static_cast<T>(value_ + step_);
index_++;
}
virtual ParamIteratorInterface<T>* Clone() const {
return new Iterator(*this);
}
virtual const T* Current() const { return &value_; }
virtual bool Equals(const ParamIteratorInterface<T>& other) const {
// Having the same base generator guarantees that the other
// iterator is of the same type and we can downcast.
GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
<< "The program attempted to compare iterators "
<< "from different generators." << std::endl;
const int other_index =
CheckedDowncastToActualType<const Iterator>(&other)->index_;
return index_ == other_index;
}
private:
Iterator(const Iterator& other)
: ParamIteratorInterface<T>(),
base_(other.base_), value_(other.value_), index_(other.index_),
step_(other.step_) {}
// No implementation - assignment is unsupported.
void operator=(const Iterator& other);
const ParamGeneratorInterface<T>* const base_;
T value_;
int index_;
const IncrementT step_;
}; // class RangeGenerator::Iterator
static int CalculateEndIndex(const T& begin,
const T& end,
const IncrementT& step) {
int end_index = 0;
for (T i = begin; i < end; i = static_cast<T>(i + step))
end_index++;
return end_index;
}
// No implementation - assignment is unsupported.
void operator=(const RangeGenerator& other);
const T begin_;
const T end_;
const IncrementT step_;
// The index for the end() iterator. All the elements in the generated
// sequence are indexed (0-based) to aid iterator comparison.
const int end_index_;
}; // class RangeGenerator
// Generates values from a pair of STL-style iterators. Used in the
// ValuesIn() function. The elements are copied from the source range
// since the source can be located on the stack, and the generator
// is likely to persist beyond that stack frame.
template <typename T>
class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> {
public:
template <typename ForwardIterator>
ValuesInIteratorRangeGenerator(ForwardIterator begin, ForwardIterator end)
: container_(begin, end) {}
virtual ~ValuesInIteratorRangeGenerator() {}
virtual ParamIteratorInterface<T>* Begin() const {
return new Iterator(this, container_.begin());
}
virtual ParamIteratorInterface<T>* End() const {
return new Iterator(this, container_.end());
}
private:
typedef typename ::std::vector<T> ContainerType;
class Iterator : public ParamIteratorInterface<T> {
public:
Iterator(const ParamGeneratorInterface<T>* base,
typename ContainerType::const_iterator iterator)
: base_(base), iterator_(iterator) {}
virtual ~Iterator() {}
virtual const ParamGeneratorInterface<T>* BaseGenerator() const {
return base_;
}
virtual void Advance() {
++iterator_;
value_.reset();
}
virtual ParamIteratorInterface<T>* Clone() const {
return new Iterator(*this);
}
// We need to use cached value referenced by iterator_ because *iterator_
// can return a temporary object (and of type other then T), so just
// having "return &*iterator_;" doesn't work.
// value_ is updated here and not in Advance() because Advance()
// can advance iterator_ beyond the end of the range, and we cannot
// detect that fact. The client code, on the other hand, is
// responsible for not calling Current() on an out-of-range iterator.
virtual const T* Current() const {
if (value_.get() == NULL)
value_.reset(new T(*iterator_));
return value_.get();
}
virtual bool Equals(const ParamIteratorInterface<T>& other) const {
// Having the same base generator guarantees that the other
// iterator is of the same type and we can downcast.
GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())
<< "The program attempted to compare iterators "
<< "from different generators." << std::endl;
return iterator_ ==
CheckedDowncastToActualType<const Iterator>(&other)->iterator_;
}
private:
Iterator(const Iterator& other)
// The explicit constructor call suppresses a false warning
// emitted by gcc when supplied with the -Wextra option.
: ParamIteratorInterface<T>(),
base_(other.base_),
iterator_(other.iterator_) {}
const ParamGeneratorInterface<T>* const base_;
typename ContainerType::const_iterator iterator_;
// A cached value of *iterator_. We keep it here to allow access by
// pointer in the wrapping iterator's operator->().
// value_ needs to be mutable to be accessed in Current().
// Use of scoped_ptr helps manage cached value's lifetime,
// which is bound by the lifespan of the iterator itself.
mutable scoped_ptr<const T> value_;
}; // class ValuesInIteratorRangeGenerator::Iterator
// No implementation - assignment is unsupported.
void operator=(const ValuesInIteratorRangeGenerator& other);
const ContainerType container_;
}; // class ValuesInIteratorRangeGenerator
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
//
// Default parameterized test name generator, returns a string containing the
// integer test parameter index.
template <class ParamType>
std::string DefaultParamName(const TestParamInfo<ParamType>& info) {
Message name_stream;
name_stream << info.index;
return name_stream.GetString();
}
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
//
// Parameterized test name overload helpers, which help the
// INSTANTIATE_TEST_CASE_P macro choose between the default parameterized
// test name generator and user param name generator.
template <class ParamType, class ParamNameGenFunctor>
ParamNameGenFunctor GetParamNameGen(ParamNameGenFunctor func) {
return func;
}
template <class ParamType>
struct ParamNameGenFunc {
typedef std::string Type(const TestParamInfo<ParamType>&);
};
template <class ParamType>
typename ParamNameGenFunc<ParamType>::Type *GetParamNameGen() {
return DefaultParamName;
}
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
//
// Stores a parameter value and later creates tests parameterized with that
// value.
template <class TestClass>
class ParameterizedTestFactory : public TestFactoryBase {
public:
typedef typename TestClass::ParamType ParamType;
explicit ParameterizedTestFactory(ParamType parameter) :
parameter_(parameter) {}
virtual Test* CreateTest() {
TestClass::SetParam(¶meter_);
return new TestClass();
}
private:
const ParamType parameter_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestFactory);
};
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
//
// TestMetaFactoryBase is a base class for meta-factories that create
// test factories for passing into MakeAndRegisterTestInfo function.
template <class ParamType>
class TestMetaFactoryBase {
public:
virtual ~TestMetaFactoryBase() {}
virtual TestFactoryBase* CreateTestFactory(ParamType parameter) = 0;
};
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
//
// TestMetaFactory creates test factories for passing into
// MakeAndRegisterTestInfo function. Since MakeAndRegisterTestInfo receives
// ownership of test factory pointer, same factory object cannot be passed
// into that method twice. But ParameterizedTestCaseInfo is going to call
// it for each Test/Parameter value combination. Thus it needs meta factory
// creator class.
template <class TestCase>
class TestMetaFactory
: public TestMetaFactoryBase<typename TestCase::ParamType> {
public:
typedef typename TestCase::ParamType ParamType;
TestMetaFactory() {}
virtual TestFactoryBase* CreateTestFactory(ParamType parameter) {
return new ParameterizedTestFactory<TestCase>(parameter);
}
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(TestMetaFactory);
};
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
//
// ParameterizedTestCaseInfoBase is a generic interface
// to ParameterizedTestCaseInfo classes. ParameterizedTestCaseInfoBase
// accumulates test information provided by TEST_P macro invocations
// and generators provided by INSTANTIATE_TEST_CASE_P macro invocations
// and uses that information to register all resulting test instances
// in RegisterTests method. The ParameterizeTestCaseRegistry class holds
// a collection of pointers to the ParameterizedTestCaseInfo objects
// and calls RegisterTests() on each of them when asked.
class ParameterizedTestCaseInfoBase {
public:
virtual ~ParameterizedTestCaseInfoBase() {}
// Base part of test case name for display purposes.
virtual const string& GetTestCaseName() const = 0;
// Test case id to verify identity.
virtual TypeId GetTestCaseTypeId() const = 0;
// UnitTest class invokes this method to register tests in this
// test case right before running them in RUN_ALL_TESTS macro.
// This method should not be called more then once on any single
// instance of a ParameterizedTestCaseInfoBase derived class.
virtual void RegisterTests() = 0;
protected:
ParameterizedTestCaseInfoBase() {}
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseInfoBase);
};
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
//
// ParameterizedTestCaseInfo accumulates tests obtained from TEST_P
// macro invocations for a particular test case and generators
// obtained from INSTANTIATE_TEST_CASE_P macro invocations for that
// test case. It registers tests with all values generated by all
// generators when asked.
template <class TestCase>
class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase {
public:
// ParamType and GeneratorCreationFunc are private types but are required
// for declarations of public methods AddTestPattern() and
// AddTestCaseInstantiation().
typedef typename TestCase::ParamType ParamType;
// A function that returns an instance of appropriate generator type.
typedef ParamGenerator<ParamType>(GeneratorCreationFunc)();
typedef typename ParamNameGenFunc<ParamType>::Type ParamNameGeneratorFunc;
explicit ParameterizedTestCaseInfo(
const char* name, CodeLocation code_location)
: test_case_name_(name), code_location_(code_location) {}
// Test case base name for display purposes.
virtual const string& GetTestCaseName() const { return test_case_name_; }
// Test case id to verify identity.
virtual TypeId GetTestCaseTypeId() const { return GetTypeId<TestCase>(); }
// TEST_P macro uses AddTestPattern() to record information
// about a single test in a LocalTestInfo structure.
// test_case_name is the base name of the test case (without invocation
// prefix). test_base_name is the name of an individual test without
// parameter index. For the test SequenceA/FooTest.DoBar/1 FooTest is
// test case base name and DoBar is test base name.
void AddTestPattern(const char* test_case_name,
const char* test_base_name,
TestMetaFactoryBase<ParamType>* meta_factory) {
tests_.push_back(linked_ptr<TestInfo>(new TestInfo(test_case_name,
test_base_name,
meta_factory)));
}
// INSTANTIATE_TEST_CASE_P macro uses AddGenerator() to record information
// about a generator.
int AddTestCaseInstantiation(const string& instantiation_name,
GeneratorCreationFunc* func,
ParamNameGeneratorFunc* name_func,
const char* file,
int line) {
instantiations_.push_back(
InstantiationInfo(instantiation_name, func, name_func, file, line));
return 0; // Return value used only to run this method in namespace scope.
}
// UnitTest class invokes this method to register tests in this test case
// test cases right before running tests in RUN_ALL_TESTS macro.
// This method should not be called more then once on any single
// instance of a ParameterizedTestCaseInfoBase derived class.
// UnitTest has a guard to prevent from calling this method more then once.
virtual void RegisterTests() {
for (typename TestInfoContainer::iterator test_it = tests_.begin();
test_it != tests_.end(); ++test_it) {
linked_ptr<TestInfo> test_info = *test_it;
for (typename InstantiationContainer::iterator gen_it =
instantiations_.begin(); gen_it != instantiations_.end();
++gen_it) {
const string& instantiation_name = gen_it->name;
ParamGenerator<ParamType> generator((*gen_it->generator)());
ParamNameGeneratorFunc* name_func = gen_it->name_func;
const char* file = gen_it->file;
int line = gen_it->line;
string test_case_name;
if ( !instantiation_name.empty() )
test_case_name = instantiation_name + "/";
test_case_name += test_info->test_case_base_name;
size_t i = 0;
std::set<std::string> test_param_names;
for (typename ParamGenerator<ParamType>::iterator param_it =
generator.begin();
param_it != generator.end(); ++param_it, ++i) {
Message test_name_stream;
std::string param_name = name_func(
TestParamInfo<ParamType>(*param_it, i));
GTEST_CHECK_(IsValidParamName(param_name))
<< "Parameterized test name '" << param_name
<< "' is invalid, in " << file
<< " line " << line << std::endl;
GTEST_CHECK_(test_param_names.count(param_name) == 0)
<< "Duplicate parameterized test name '" << param_name
<< "', in " << file << " line " << line << std::endl;
test_param_names.insert(param_name);
test_name_stream << test_info->test_base_name << "/" << param_name;
MakeAndRegisterTestInfo(
test_case_name.c_str(),
test_name_stream.GetString().c_str(),
NULL, // No type parameter.
PrintToString(*param_it).c_str(),
code_location_,
GetTestCaseTypeId(),
TestCase::SetUpTestCase,
TestCase::TearDownTestCase,
test_info->test_meta_factory->CreateTestFactory(*param_it));
} // for param_it
} // for gen_it
} // for test_it
} // RegisterTests
private:
// LocalTestInfo structure keeps information about a single test registered
// with TEST_P macro.
struct TestInfo {
TestInfo(const char* a_test_case_base_name,
const char* a_test_base_name,
TestMetaFactoryBase<ParamType>* a_test_meta_factory) :
test_case_base_name(a_test_case_base_name),
test_base_name(a_test_base_name),
test_meta_factory(a_test_meta_factory) {}
const string test_case_base_name;
const string test_base_name;
const scoped_ptr<TestMetaFactoryBase<ParamType> > test_meta_factory;
};
typedef ::std::vector<linked_ptr<TestInfo> > TestInfoContainer;
// Records data received from INSTANTIATE_TEST_CASE_P macros:
// <Instantiation name, Sequence generator creation function,
// Name generator function, Source file, Source line>
struct InstantiationInfo {
InstantiationInfo(const std::string &name_in,
GeneratorCreationFunc* generator_in,
ParamNameGeneratorFunc* name_func_in,
const char* file_in,
int line_in)
: name(name_in),
generator(generator_in),
name_func(name_func_in),
file(file_in),
line(line_in) {}
std::string name;
GeneratorCreationFunc* generator;
ParamNameGeneratorFunc* name_func;
const char* file;
int line;
};
typedef ::std::vector<InstantiationInfo> InstantiationContainer;
static bool IsValidParamName(const std::string& name) {
// Check for empty string
if (name.empty())
return false;
// Check for invalid characters
for (std::string::size_type index = 0; index < name.size(); ++index) {
if (!isalnum(name[index]) && name[index] != '_')
return false;
}
return true;
}
const string test_case_name_;
CodeLocation code_location_;
TestInfoContainer tests_;
InstantiationContainer instantiations_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseInfo);
}; // class ParameterizedTestCaseInfo
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
//
// ParameterizedTestCaseRegistry contains a map of ParameterizedTestCaseInfoBase
// classes accessed by test case names. TEST_P and INSTANTIATE_TEST_CASE_P
// macros use it to locate their corresponding ParameterizedTestCaseInfo
// descriptors.
class ParameterizedTestCaseRegistry {
public:
ParameterizedTestCaseRegistry() {}
~ParameterizedTestCaseRegistry() {
for (TestCaseInfoContainer::iterator it = test_case_infos_.begin();
it != test_case_infos_.end(); ++it) {
delete *it;
}
}
// Looks up or creates and returns a structure containing information about
// tests and instantiations of a particular test case.
template <class TestCase>
ParameterizedTestCaseInfo<TestCase>* GetTestCasePatternHolder(
const char* test_case_name,
CodeLocation code_location) {
ParameterizedTestCaseInfo<TestCase>* typed_test_info = NULL;
for (TestCaseInfoContainer::iterator it = test_case_infos_.begin();
it != test_case_infos_.end(); ++it) {
if ((*it)->GetTestCaseName() == test_case_name) {
if ((*it)->GetTestCaseTypeId() != GetTypeId<TestCase>()) {
// Complain about incorrect usage of Google Test facilities
// and terminate the program since we cannot guaranty correct
// test case setup and tear-down in this case.
ReportInvalidTestCaseType(test_case_name, code_location);
posix::Abort();
} else {
// At this point we are sure that the object we found is of the same
// type we are looking for, so we downcast it to that type
// without further checks.
typed_test_info = CheckedDowncastToActualType<
ParameterizedTestCaseInfo<TestCase> >(*it);
}
break;
}
}
if (typed_test_info == NULL) {
typed_test_info = new ParameterizedTestCaseInfo<TestCase>(
test_case_name, code_location);
test_case_infos_.push_back(typed_test_info);
}
return typed_test_info;
}
void RegisterTests() {
for (TestCaseInfoContainer::iterator it = test_case_infos_.begin();
it != test_case_infos_.end(); ++it) {
(*it)->RegisterTests();
}
}
private:
typedef ::std::vector<ParameterizedTestCaseInfoBase*> TestCaseInfoContainer;
TestCaseInfoContainer test_case_infos_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseRegistry);
};
} // namespace internal
} // namespace testing
#endif // GTEST_HAS_PARAM_TEST
#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
| 412 | 0.938778 | 1 | 0.938778 | game-dev | MEDIA | 0.206741 | game-dev | 0.92802 | 1 | 0.92802 |
booksaw/BetterTeams | 2,003 | src/main/java/com/booksaw/betterTeams/commands/team/chest/ChestClaimCommand.java | package com.booksaw.betterTeams.commands.team.chest;
import com.booksaw.betterTeams.*;
import com.booksaw.betterTeams.commands.presets.TeamSubCommand;
import com.booksaw.betterTeams.team.LocationSetComponent;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.command.CommandSender;
import java.util.List;
import java.util.Objects;
public class ChestClaimCommand extends TeamSubCommand {
@Override
public CommandResponse onCommand(TeamPlayer player, String label, String[] args, Team team) {
Location loc = Objects.requireNonNull(player.getPlayer().getPlayer()).getLocation();
Block block = loc.getBlock();
loc = LocationSetComponent.normalise(loc);
if (block.getType() != Material.CHEST) {
return new CommandResponse("chest.claim.noChest");
}
Team claimedBy = Team.getClaimingTeam(block);
if (claimedBy != null) {
return new CommandResponse("chest.claim.claimed");
}
// on a chest
// checking there is no limit on chests
int lim = Main.plugin.getConfig().getInt("levels.l" + team.getLevel() + ".maxChests");
if (lim != -1 && lim <= team.getClaimCount()) {
return new CommandResponse("chest.claim.limit");
}
// they can claim the chest
team.addClaim(loc);
return new CommandResponse(true, "chest.claim.success");
}
@Override
public String getCommand() {
return "claim";
}
@Override
public String getNode() {
return "chest.claim";
}
@Override
public String getHelp() {
return "Claim the chest you are standing on";
}
@Override
public String getArguments() {
return "";
}
@Override
public int getMinimumArguments() {
return 0;
}
@Override
public int getMaximumArguments() {
return 0;
}
@Override
public void onTabComplete(List<String> options, CommandSender sender, String label, String[] args) {
}
@Override
public PlayerRank getDefaultRank() {
return PlayerRank.ADMIN;
}
@Override
public boolean runAsync(String[] args) {
return false;
}
}
| 412 | 0.930609 | 1 | 0.930609 | game-dev | MEDIA | 0.957667 | game-dev | 0.970607 | 1 | 0.970607 |
jarjin/LuaFramework_NGUI | 3,210 | Assets/LuaFramework/ToLua/Core/LuaValueType.cs | /*
Copyright (c) 2015-2017 topameng(topameng@qq.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Collections.Generic;
namespace LuaInterface
{
public partial struct LuaValueType
{
public const int None = 0;
public const int Vector3 = 1;
public const int Quaternion = 2;
public const int Vector2 = 3;
public const int Color = 4;
public const int Vector4 = 5;
public const int Ray = 6;
public const int Bounds = 7;
public const int Touch = 8;
public const int LayerMask = 9;
public const int RaycastHit = 10;
public const int Int64 = 11;
public const int UInt64 = 12;
public const int Max = 64;
private int type;
public LuaValueType(int value)
{
type = value;
}
public static implicit operator int(LuaValueType mask)
{
return mask.type;
}
public static implicit operator LuaValueType(int intVal)
{
return new LuaValueType(intVal);
}
public override string ToString()
{
return LuaValueTypeName.Get(type);
}
}
public static class LuaValueTypeName
{
public static string[] names = new string[LuaValueType.Max];
static LuaValueTypeName()
{
names[LuaValueType.None] = "None";
names[LuaValueType.Vector3] = "Vector3";
names[LuaValueType.Quaternion] = "Quaternion";
names[LuaValueType.Vector2] = "Vector2";
names[LuaValueType.Color] = "Color";
names[LuaValueType.Vector4] = "Vector4";
names[LuaValueType.Ray] = "Ray";
names[LuaValueType.Bounds] = "Bounds";
names[LuaValueType.Touch] = "Touch";
names[LuaValueType.LayerMask] = "LayerMask";
names[LuaValueType.RaycastHit] = "RaycastHit";
}
static public string Get(int type)
{
if (type >= 0 && type < LuaValueType.Max)
{
return names[type];
}
return "UnKnownType:" + ConstStringTable.GetNumIntern(type);
}
}
}
| 412 | 0.769597 | 1 | 0.769597 | game-dev | MEDIA | 0.463177 | game-dev,graphics-rendering | 0.924275 | 1 | 0.924275 |
OTCv8/otcv8-dev | 22,905 | modules/game_bot/default_configs/vBot_4.7/vBot/extras.lua | setDefaultTab("Main")
-- securing storage namespace
local panelName = "extras"
if not storage[panelName] then
storage[panelName] = {}
end
local settings = storage[panelName]
-- basic elements
extrasWindow = UI.createWindow('ExtrasWindow', rootWidget)
extrasWindow:hide()
extrasWindow.closeButton.onClick = function(widget)
extrasWindow:hide()
end
extrasWindow.onGeometryChange = function(widget, old, new)
if old.height == 0 then return end
settings.height = new.height
end
extrasWindow:setHeight(settings.height or 360)
-- available options for dest param
local rightPanel = extrasWindow.content.right
local leftPanel = extrasWindow.content.left
-- objects made by Kondrah - taken from creature editor, minor changes to adapt
local addCheckBox = function(id, title, defaultValue, dest, tooltip)
local widget = UI.createWidget('ExtrasCheckBox', dest)
widget.onClick = function()
widget:setOn(not widget:isOn())
settings[id] = widget:isOn()
if id == "checkPlayer" then
local label = rootWidget.newHealer.targetSettings.vocations.title
if not widget:isOn() then
label:setColor("#d9321f")
label:setTooltip("! WARNING ! \nTurn on check players in extras to use this feature!")
else
label:setColor("#dfdfdf")
label:setTooltip("")
end
end
end
widget:setText(title)
widget:setTooltip(tooltip)
if settings[id] == nil then
widget:setOn(defaultValue)
else
widget:setOn(settings[id])
end
settings[id] = widget:isOn()
end
local addItem = function(id, title, defaultItem, dest, tooltip)
local widget = UI.createWidget('ExtrasItem', dest)
widget.text:setText(title)
widget.text:setTooltip(tooltip)
widget.item:setTooltip(tooltip)
widget.item:setItemId(settings[id] or defaultItem)
widget.item.onItemChange = function(widget)
settings[id] = widget:getItemId()
end
settings[id] = settings[id] or defaultItem
end
local addTextEdit = function(id, title, defaultValue, dest, tooltip)
local widget = UI.createWidget('ExtrasTextEdit', dest)
widget.text:setText(title)
widget.textEdit:setText(settings[id] or defaultValue or "")
widget.text:setTooltip(tooltip)
widget.textEdit.onTextChange = function(widget,text)
settings[id] = text
end
settings[id] = settings[id] or defaultValue or ""
end
local addScrollBar = function(id, title, min, max, defaultValue, dest, tooltip)
local widget = UI.createWidget('ExtrasScrollBar', dest)
widget.text:setTooltip(tooltip)
widget.scroll.onValueChange = function(scroll, value)
widget.text:setText(title .. ": " .. value)
if value == 0 then
value = 1
end
settings[id] = value
end
widget.scroll:setRange(min, max)
widget.scroll:setTooltip(tooltip)
if max-min > 1000 then
widget.scroll:setStep(100)
elseif max-min > 100 then
widget.scroll:setStep(10)
end
widget.scroll:setValue(settings[id] or defaultValue)
widget.scroll.onValueChange(widget.scroll, widget.scroll:getValue())
end
UI.Button("vBot Settings and Scripts", function()
extrasWindow:show()
extrasWindow:raise()
extrasWindow:focus()
end)
UI.Separator()
---- to maintain order, add options right after another:
--- add object
--- add variables for function (optional)
--- add callback (optional)
--- optionals should be addionaly sandboxed (if true then end)
addItem("rope", "Rope Item", 9596, leftPanel, "This item will be used in various bot related scripts as default rope item.")
addItem("shovel", "Shovel Item", 9596, leftPanel, "This item will be used in various bot related scripts as default shovel item.")
addItem("machete", "Machete Item", 9596, leftPanel, "This item will be used in various bot related scripts as default machete item.")
addItem("scythe", "Scythe Item", 9596, leftPanel, "This item will be used in various bot related scripts as default scythe item.")
addCheckBox("pathfinding", "CaveBot Pathfinding", true, leftPanel, "Cavebot will automatically search for first reachable waypoint after missing 10 goto's.")
addScrollBar("talkDelay", "Global NPC Talk Delay", 0, 2000, 1000, leftPanel, "Breaks between each talk action in cavebot (time in miliseconds).")
addScrollBar("looting", "Max Loot Distance", 0, 50, 40, leftPanel, "Every loot corpse futher than set distance (in sqm) will be ignored and forgotten.")
addScrollBar("huntRoutes", "Hunting Rounds Limit", 0, 300, 50, leftPanel, "Round limit for supply check, if character already made more rounds than set, on next supply check will return to city.")
addScrollBar("killUnder", "Kill monsters below", 0, 100, 1, leftPanel, "Force TargetBot to kill added creatures when they are below set percentage of health - will ignore all other TargetBot settings.")
addScrollBar("gotoMaxDistance", "Max GoTo Distance", 0, 127, 30, leftPanel, "Maximum distance to next goto waypoint for the bot to try to reach.")
addCheckBox("lootLast", "Start loot from last corpse", true, leftPanel, "Looting sequence will be reverted and bot will start looting newest bodies.")
addCheckBox("joinBot", "Join TargetBot and CaveBot", false, leftPanel, "Cave and Target tabs will be joined into one.")
addCheckBox("reachable", "Target only pathable mobs", false, leftPanel, "Ignore monsters that can't be reached.")
addCheckBox("title", "Custom Window Title", true, rightPanel, "Personalize OTCv8 window name according to character specific.")
if true then
local vocText = ""
if voc() == 1 or voc() == 11 then
vocText = "- EK"
elseif voc() == 2 or voc() == 12 then
vocText = "- RP"
elseif voc() == 3 or voc() == 13 then
vocText = "- MS"
elseif voc() == 4 or voc() == 14 then
vocText = "- ED"
end
macro(5000, function()
if settings.title then
if hppercent() > 0 then
g_window.setTitle("Tibia - " .. name() .. " - " .. lvl() .. "lvl " .. vocText)
else
g_window.setTitle("Tibia - " .. name() .. " - DEAD")
end
else
g_window.setTitle("Tibia - " .. name())
end
end)
end
addCheckBox("separatePm", "Open PM's in new Window", false, rightPanel, "PM's will be automatically opened in new tab after receiving one.")
if true then
onTalk(function(name, level, mode, text, channelId, pos)
if mode == 4 and settings.separatePm then
local g_console = modules.game_console
local privateTab = g_console.getTab(name)
if privateTab == nil then
privateTab = g_console.addTab(name, true)
g_console.addPrivateText(g_console.applyMessagePrefixies(name, level, text), g_console.SpeakTypesSettings['private'], name, false, name)
end
return
end
end)
end
addTextEdit("useAll", "Use All Hotkey", "space", rightPanel, "Set hotkey for universal actions - rope, shovel, scythe, use, open doors")
if true then
local useId = { 34847, 1764, 21051, 30823, 6264, 5282, 20453, 20454, 20474, 11708, 11705,
6257, 6256, 2772, 27260, 2773, 1632, 1633, 1948, 435, 6252, 6253, 5007, 4911,
1629, 1630, 5108, 5107, 5281, 1968, 435, 1948, 5542, 31116, 31120, 30742, 31115,
31118, 20474, 5737, 5736, 5734, 5733, 31202, 31228, 31199, 31200, 33262, 30824,
5125, 5126, 5116, 5117, 8257, 8258, 8255, 8256, 5120, 30777, 30776, 23873, 23877,
5736, 6264, 31262, 31130, 31129, 6250, 6249, 5122, 30049, 7131, 7132, 7727 }
local shovelId = { 606, 593, 867, 608 }
local ropeId = { 17238, 12202, 12935, 386, 421, 21966, 14238 }
local macheteId = { 2130, 3696 }
local scytheId = { 3653 }
setDefaultTab("Tools")
-- script
if settings.useAll and settings.useAll:len() > 0 then
hotkey(settings.useAll, function()
if not modules.game_walking.wsadWalking then return end
for _, tile in pairs(g_map.getTiles(posz())) do
if distanceFromPlayer(tile:getPosition()) < 2 then
for _, item in pairs(tile:getItems()) do
-- use
if table.find(useId, item:getId()) then
use(item)
return
elseif table.find(shovelId, item:getId()) then
useWith(settings.shovel, item)
return
elseif table.find(ropeId, item:getId()) then
useWith(settings.rope, item)
return
elseif table.find(macheteId, item:getId()) then
useWith(settings.machete, item)
return
elseif table.find(scytheId, item:getId()) then
useWith(settings.scythe, item)
return
end
end
end
end
end)
end
end
addCheckBox("timers", "MW & WG Timers", true, rightPanel, "Show times for Magic Walls and Wild Growths.")
if true then
local activeTimers = {}
onAddThing(function(tile, thing)
if not settings.timers then return end
if not thing:isItem() then
return
end
local timer = 0
if thing:getId() == 2129 then -- mwall id
timer = 20000 -- mwall time
elseif thing:getId() == 2130 then -- wg id
timer = 45000 -- wg time
else
return
end
local pos = tile:getPosition().x .. "," .. tile:getPosition().y .. "," .. tile:getPosition().z
if not activeTimers[pos] or activeTimers[pos] < now then
activeTimers[pos] = now + timer
end
tile:setTimer(activeTimers[pos] - now)
end)
onRemoveThing(function(tile, thing)
if not settings.timers then return end
if not thing:isItem() then
return
end
if (thing:getId() == 2129 or thing:getId() == 2130) and tile:getGround() then
local pos = tile:getPosition().x .. "," .. tile:getPosition().y .. "," .. tile:getPosition().z
activeTimers[pos] = nil
tile:setTimer(0)
end
end)
end
addCheckBox("antiKick", "Anti - Kick", true, rightPanel, "Turn every 10 minutes to prevent kick.")
if true then
macro(600*1000, function()
if not settings.antiKick then return end
local dir = player:getDirection()
turn((dir + 1) % 4)
schedule(50, function() turn(dir) end)
end)
end
addCheckBox("stake", "Skin Monsters", false, leftPanel, "Automatically skin & stake corpses when cavebot is enabled")
if true then
local knifeBodies = {4286, 4272, 4173, 4011, 4025, 4047, 4052, 4057, 4062, 4112, 4212, 4321, 4324, 4327, 10352, 10356, 10360, 10364}
local stakeBodies = {4097, 4137, 8738, 18958}
local fishingBodies = {9582}
macro(500, function()
if not CaveBot.isOn() or not settings.stake then return end
for i, tile in ipairs(g_map.getTiles(posz())) do
local item = tile:getTopThing()
if item and item:isContainer() then
if table.find(knifeBodies, item:getId()) and findItem(5908) then
CaveBot.delay(550)
useWith(5908, item)
return
end
if table.find(stakeBodies, item:getId()) and findItem(5942) then
CaveBot.delay(550)
useWith(5942, item)
return
end
if table.find(fishingBodies, item:getId()) and findItem(3483) then
CaveBot.delay(550)
useWith(3483, item)
return
end
end
end
end)
end
addCheckBox("oberon", "Auto Reply Oberon", true, rightPanel, "Auto reply to Grand Master Oberon talk minigame.")
if true then
onTalk(function(name, level, mode, text, channelId, pos)
if not settings.oberon then return end
if mode == 34 then
if string.find(text, "world will suffer for") then
say("Are you ever going to fight or do you prefer talking?")
elseif string.find(text, "feet when they see me") then
say("Even before they smell your breath?")
elseif string.find(text, "from this plane") then
say("Too bad you barely exist at all!")
elseif string.find(text, "ESDO LO") then
say("SEHWO ASIMO, TOLIDO ESD")
elseif string.find(text, "will soon rule this world") then
say("Excuse me but I still do not get the message!")
elseif string.find(text, "honourable and formidable") then
say("Then why are we fighting alone right now?")
elseif string.find(text, "appear like a worm") then
say("How appropriate, you look like something worms already got the better of!")
elseif string.find(text, "will be the end of mortal") then
say("Then let me show you the concept of mortality before it!")
elseif string.find(text, "virtues of chivalry") then
say("Dare strike up a Minnesang and you will receive your last accolade!")
end
end
end)
end
addCheckBox("autoOpenDoors", "Auto Open Doors", true, rightPanel, "Open doors when trying to step on them.")
if true then
local doorsIds = { 5007, 8265, 1629, 1632, 5129, 6252, 6249, 7715, 7712, 7714,
7719, 6256, 1669, 1672, 5125, 5115, 5124, 17701, 17710, 1642,
6260, 5107, 4912, 6251, 5291, 1683, 1696, 1692, 5006, 2179, 5116,
1632, 11705, 30772, 30774, 6248, 5735, 5732, 5120, 23873, 5736,
6264, 5122, 30049, 30042, 7727 }
function checkForDoors(pos)
local tile = g_map.getTile(pos)
if tile then
local useThing = tile:getTopUseThing()
if useThing and table.find(doorsIds, useThing:getId()) then
g_game.use(useThing)
end
end
end
onKeyPress(function(keys)
local wsadWalking = modules.game_walking.wsadWalking
if not settings.autoOpenDoors then return end
local pos = player:getPosition()
if keys == 'Up' or (wsadWalking and keys == 'W') then
pos.y = pos.y - 1
elseif keys == 'Down' or (wsadWalking and keys == 'S') then
pos.y = pos.y + 1
elseif keys == 'Left' or (wsadWalking and keys == 'A') then
pos.x = pos.x - 1
elseif keys == 'Right' or (wsadWalking and keys == 'D') then
pos.x = pos.x + 1
elseif wsadWalking and keys == "Q" then
pos.y = pos.y - 1
pos.x = pos.x - 1
elseif wsadWalking and keys == "E" then
pos.y = pos.y - 1
pos.x = pos.x + 1
elseif wsadWalking and keys == "Z" then
pos.y = pos.y + 1
pos.x = pos.x - 1
elseif wsadWalking and keys == "C" then
pos.y = pos.y + 1
pos.x = pos.x + 1
end
checkForDoors(pos)
end)
end
addCheckBox("bless", "Buy bless at login", true, rightPanel, "Say !bless at login.")
if true then
local blessed = false
onTextMessage(function(mode,text)
if not settings.bless then return end
text = text:lower()
if text == "you already have all blessings." then
blessed = true
end
end)
if settings.bless then
if player:getBlessings() == 0 then
say("!bless")
schedule(2000, function()
if g_game.getClientVersion() > 1000 then
if not blessed and player:getBlessings() == 0 then
warn("!! Blessings not bought !!")
end
end
end)
end
end
end
addCheckBox("reUse", "Keep Crosshair", false, rightPanel, "Keep crosshair after using with item")
if true then
local excluded = {268, 237, 238, 23373, 266, 236, 239, 7643, 23375, 7642, 23374, 5908, 5942}
onUseWith(function(pos, itemId, target, subType)
if settings.reUse and not table.find(excluded, itemId) then
schedule(50, function()
item = findItem(itemId)
if item then
modules.game_interface.startUseWith(item)
end
end)
end
end)
end
addCheckBox("suppliesControl", "TargetBot off if low supply", false, leftPanel, "Turn off TargetBot if either one of supply amount is below 50% of minimum.")
if true then
macro(500, function()
if not settings.suppliesControl then return end
if TargetBot.isOff() then return end
if CaveBot.isOff() then return end
if type(hasSupplies()) == 'table' then
TargetBot.setOff()
end
end)
end
addCheckBox("holdMwall", "Hold MW/WG", true, rightPanel, "Mark tiles with below hotkeys to automatically use Magic Wall or Wild Growth")
addTextEdit("holdMwHot", "Magic Wall Hotkey: ", "F5", rightPanel)
addTextEdit("holdWgHot", "Wild Growth Hotkey: ", "F6", rightPanel)
if true then
local hold = 0
local mwHot
local wgHot
local candidates = {}
local m = macro(20, function()
mwHot = settings.holdMwHot
wgHot = settings.holdWgHot
if not settings.holdMwall then return end
if #candidates == 0 then return end
for i, pos in pairs(candidates) do
local tile = g_map.getTile(pos)
if tile then
if tile:getText():len() == 0 then
table.remove(candidates, i)
end
local rune = tile:getText() == "HOLD MW" and 3180 or tile:getText() == "HOLD WG" and 3156
if tile:canShoot() and not isInPz() and tile:isWalkable() and tile:getTopUseThing():getId() ~= 2130 then
if math.abs(player:getPosition().x-tile:getPosition().x) < 8 and math.abs(player:getPosition().y-tile:getPosition().y) < 6 then
return useWith(rune, tile:getTopUseThing())
end
end
end
end
end)
onRemoveThing(function(tile, thing)
if not settings.holdMwall then return end
if thing:getId() ~= 2129 then return end
if tile:getText():find("HOLD") then
table.insert(candidates, tile:getPosition())
local rune = tile:getText() == "HOLD MW" and 3180 or tile:getText() == "HOLD WG" and 3156
if math.abs(player:getPosition().x-tile:getPosition().x) < 8 and math.abs(player:getPosition().y-tile:getPosition().y) < 6 then
return useWith(rune, tile:getTopUseThing())
end
end
end)
onAddThing(function(tile, thing)
if not settings.holdMwall then return end
if m.isOff() then return end
if thing:getId() ~= 2129 then return end
if tile:getText():len() > 0 then
table.remove(candidates, table.find(candidates,tile))
end
end)
onKeyDown(function(keys)
local wsadWalking = modules.game_walking.wsadWalking
if not wsadWalking then return end
if not settings.holdMwall then return end
if m.isOff() then return end
if keys ~= mwHot and keys ~= wgHot then return end
hold = now
local tile = getTileUnderCursor()
if not tile then return end
if tile:getText():len() > 0 then
tile:setText("")
else
if keys == mwHot then
tile:setText("HOLD MW")
else
tile:setText("HOLD WG")
end
table.insert(candidates, tile:getPosition())
end
end)
onKeyPress(function(keys)
local wsadWalking = modules.game_walking.wsadWalking
if not wsadWalking then return end
if not settings.holdMwall then return end
if m.isOff() then return end
if keys ~= mwHot and keys ~= wgHot then return end
if (hold - now) < -1000 then
candidates = {}
for i, tile in ipairs(g_map.getTiles(posz())) do
local text = tile:getText()
if text:find("HOLD") then
tile:setText("")
end
end
end
end)
end
addCheckBox("checkPlayer", "Check Players", true, rightPanel, "Auto look on players and mark level and vocation on character model")
if true then
local found
local function checkPlayers()
for i, spec in ipairs(getSpectators()) do
if spec:isPlayer() and spec:getText() == "" and spec:getPosition().z == posz() and spec ~= player then
g_game.look(spec)
found = now
end
end
end
if settings.checkPlayer then
schedule(500, function()
checkPlayers()
end)
end
onPlayerPositionChange(function(x,y)
if not settings.checkPlayer then return end
if x.z ~= y.z then
schedule(20, function() checkPlayers() end)
end
end)
onCreatureAppear(function(creature)
if not settings.checkPlayer then return end
if creature:isPlayer() and creature:getText() == "" and creature:getPosition().z == posz() and creature ~= player then
g_game.look(creature)
found = now
end
end)
local regex = [[You see ([^\(]*) \(Level ([0-9]*)\)((?:.)* of the ([\w ]*),|)]]
onTextMessage(function(mode, text)
if not settings.checkPlayer then return end
local re = regexMatch(text, regex)
if #re ~= 0 then
local name = re[1][2]
local level = re[1][3]
local guild = re[1][5] or ""
if guild:len() > 10 then
guild = guild:sub(1,10) -- change to proper (last) values
guild = guild.."..."
end
local voc
if text:lower():find("sorcerer") then
voc = "MS"
elseif text:lower():find("druid") then
voc = "ED"
elseif text:lower():find("knight") then
voc = "EK"
elseif text:lower():find("paladin") then
voc = "RP"
end
local creature = getCreatureByName(name)
if creature then
creature:setText("\n"..level..voc.."\n"..guild)
end
if found and now - found < 500 then
modules.game_textmessage.clearMessages()
end
end
end)
end
addCheckBox("nextBackpack", "Open Next Loot Container", true, leftPanel, "Auto open next loot container if full - has to have the same ID.")
local function openNextLootContainer()
if not settings.nextBackpack then return end
local containers = getContainers()
local lootCotaniersIds = CaveBot.GetLootContainers()
for i, container in ipairs(containers) do
local cId = container:getContainerItem():getId()
if containerIsFull(container) then
if table.find(lootCotaniersIds, cId) then
for _, item in ipairs(container:getItems()) do
if item:getId() == cId then
return g_game.open(item, container)
end
end
end
end
end
end
if true then
onContainerOpen(function(container, previousContainer)
schedule(100, function()
openNextLootContainer()
end)
end)
onAddItem(function(container, slot, item, oldItem)
schedule(100, function()
openNextLootContainer()
end)
end)
end
addCheckBox("highlightTarget", "Highlight Current Target", true, rightPanel, "Additionaly hightlight current target with red glow")
if true then
local function forceMarked(creature)
if target() == creature then
creature:setMarked("red")
return schedule(333, function() forceMarked(creature) end)
end
end
onAttackingCreatureChange(function(newCreature, oldCreature)
if not settings.highlightTarget then return end
if oldCreature then
oldCreature:setMarked('')
end
if newCreature then
forceMarked(newCreature)
end
end)
end | 412 | 0.953589 | 1 | 0.953589 | game-dev | MEDIA | 0.830783 | game-dev | 0.983553 | 1 | 0.983553 |
OpenHV/OpenHV | 16,040 | mods/hv/audio/voices.yaml | # License: CC-BY-SA-4.0
GenericVoice1:
DefaultVariant: .ogg
Voices:
Select: generic1_any_instructions_sir, generic1_awaiting_new_orders, generic1_ready, generic1_standing_by, generic1_what_is_your_command, generic1_yes_sir
Move: generic1_acknowledged, generic1_affirmative, generic1_approching_position, generic1_command_received, generic1_following_orders, generic1_heading_out, generic1_moving_out, generic1_on_my_way, generic1_order_understood, generic1_right_away, generic1_sir_yes_sir
Action: generic1_acknowledged, generic1_affirmative, generic1_order_understood, generic1_sir_yes_sir
Attack: generic1_acknowledged, generic1_affirmative, generic1_initiating_assault, generic1_order_understood, generic1_sir_yes_sir, generic1_target_confirmed, generic1_target_in_sight
Guard: guarding
GenericVoice2:
DefaultVariant: .ogg
Voices:
Select: generic2_any_instructions_sir, generic2_awaiting_new_orders, generic2_ready, generic2_standing_by, generic2_what_is_your_command, generic2_yes_sir
Move: generic2_acknowledged, generic2_affirmative, generic2_approching_position, generic2_command_received, generic2_following_orders, generic2_heading_out, generic2_moving_out, generic2_on_my_way, generic2_order_understood, generic2_right_away, generic2_sir_yes_sir
Action: generic2_acknowledged, generic2_affirmative, generic2_order_understood, generic2_sir_yes_sir
Attack: generic2_acknowledged, generic2_affirmative, generic2_initiating_assault, generic2_order_understood, generic2_sir_yes_sir, generic2_target_confirmed, generic2_target_in_sight
Guard: guarding
BeastVoice:
DefaultVariant: .ogg
Voices:
Select: beast_select
Action: beast_move
Die: beast_die
SeedVoice:
DefaultVariant: .ogg
Voices:
Select: seed_select
Action: seed_move
Die: seed_die
WormVoice:
DefaultVariant: .ogg
Voices:
Select:
Action:
Die: worm_death_inspectorj
FlyingMonsterVoice:
DefaultVariant: .ogg
Voices:
Select:
Action:
Move:
Die: flyingmonster_death_robinhood76
GenericVoice3:
DefaultVariant: .ogg
Voices:
Select: awaiting_orders, im_ready, receiving, yes_sir
Move: acknowledged, affirmative, as_you_wish, at_once, en_route, lets_go, move_out, on_my_way, orders_received, ten_four
Action: acknowledged, affirmative, as_you_wish, orders_received
Attack: attack, destroy_them, hit_them_hard, light_em_up, target_locked, you_got_it
Guard: guarding
ShipVoice:
DefaultVariant: .ogg
Voices:
Select: shipselect1, shipselect2, shipselect3, shipselect4, shipselect5
Move: shipmove1, shipmove2, shipmove3, shipmove4, shipmove5
Action: shipmove1, shipmove2, shipmove3, shipmove4, shipmove5
Attack: shipattack1, shipattack2, shipattack3, shipattack4, shipattack5
Guard: guarding
TransportHelicopterVoice:
DefaultVariant: .ogg
Voices:
Select: chopper_aeronautics_operational, chopper_avionics_online, chopper_awaiting_orders
Move: chopper_acknowledged, chopper_affirmative, chopper_heading_to_new_lz, chopper_not_a_problem, chopper_roger_that, chopper_verify_new_coordinate
Action: chopper_acknowledged, chopper_affirmative, chopper_not_a_problem, chopper_ready_for_action, chopper_roger_that, chopper_special_delivery
Guard: guarding
AttackHelicopterVoice:
DefaultVariant: .ogg
Voices:
Select: copter_aeronautics_operational, copter_avionics_online, copter_awaiting_orders
Move: copter_acknowledged, copter_affirmative, copter_not_a_problem, copter_right_away_sir, copter_roger_that, copter_solid_copy
Action: copter_acknowledged, copter_affirmative, copter_not_a_problem, copter_ready_for_action, copter_roger_that, copter_solid_copy, copter_target_acquired
Guard: guarding
SaucerVoice:
DefaultVariant: .ogg
Voices:
Select: saucer_aeronautics_operational, saucer_avionics_online, saucer_awaiting_orders
Move: saucer_acknowledged, saucer_affirmative, saucer_not_a_problem, saucer_roger_that
Action: saucer_quantum_deconstruction, saucer_vaporising_molecular_levels, saucer_atomising_photon_cannon
Guard: guarding
BansheeVoice:
DefaultVariant: .ogg
Voices:
Select: banshee_aeronautics_operational, banshee_avionics_online, banshee_awaiting_orders, banshee_ready_for_action, banshee_reporting_in
Move: banshee_acknowledged, banshee_affirmative, banshee_air_support_inbound, banshee_not_a_problem, banshee_roger_that
Action: banshee_acknowledged, banshee_affirmative, banshee_air_support_inbound, banshee_cleared_to_engage, banshee_not_a_problem, banshee_roger_that
Guard: guarding
GunshipVoice:
DefaultVariant: .ogg
Voices:
Select: ship2_acknowledged, ship2_aeronautics_operational, ship2_awaiting_orders, ship2_ready_for_action
Move: ship2_affirmative, ship2_closing_in, ship2_not_a_problem, ship2_roger_that
Action: ship2_affirmative, ship2_discharging_munitions, ship2_not_a_problem, ship2_roger_that, ship2_sweep_the_area
Guard: guarding
DropshipVoice:
DefaultVariant: .ogg
Voices:
Select: dropship_aeronautics_operational, dropship_avionics_online, dropship_awaiting_orders, dropship_ready_for_action
Move: dropship_acknowledged, dropship_affirmative, dropship_destination_set, dropship_not_a_problem, dropship_roger_that
Action: dropship_acknowledged, dropship_affirmative, dropship_keep_those_skies_clear, dropship_not_a_problem, dropship_roger_that
Unload: dropship_touching_down
Guard: guarding
BalloonVoice:
DefaultVariant: .ogg
Voices:
Select: balloon_aeronautics_operational, balloon_avionics_online, balloon_awaiting_orders, balloon_ready_for_action, balloon_sensors_aligned, balloon_surveillance_active
Move: balloon_acknowledged, balloon_affirmative, balloon_not_a_problem, balloon_optimising_updraft, balloon_roger_that
Guard: guarding
SpeederVoice:
DefaultVariant: .ogg
Voices:
Select: ship1_aeronautics_operational, ship1_avionics_online, ship1_awaiting_orders, ship1_ready_for_action
Move: ship1_acknowledged, ship1_affirmative, ship1_roger_that, ship1_not_a_problem, ship1_thrusters_engaged
Action: ship1_acknowledged, ship1_affirmative, ship1_roger_that, ship1_fire_the_missiles, ship1_intercepting_hostiles
Guard: guarding
DroneVoice:
DefaultVariant: .ogg
Voices:
Select: droneselect1, droneselect2, droneselect3, droneselect4
Move: droneaction1, droneaction2, droneaction3, droneaction4
Action: droneattack1, droneattack2, droneattack3, droneattack4
Guard: guarding
MinerVoice:
DefaultVariant: .ogg
Voices:
Select: miner_any_orders, miner_copy, miner_im_ready, miner_ready_and_waiting, miner_reporting_in, miner_sir
Move: miner_acknowledged, miner_affirmative, miner_at_once, miner_good_copy, miner_enroute, miner_move_orders_confirmed, miner_on_my_way, miner_roger_that, miner_ten_four, miner_yes_sir
Action: miner_yes_sir, miner_acknowledged, miner_affirmative, miner_at_once, miner_roger_that, miner_yes_sir
Deploying: miner_deploying
TechnicianVoice:
DefaultVariant: .ogg
Voices:
Select: technician_copy, technician_ready, technician_roger, technician_sir, technician_technician
Move: technician_acknowledged, technician_affirmitive, technician_going, technician_good_copy, technician_got_it, technician_lets_go, technician_ok, technician_yeap, technician_yes_sir
Action: technician_capturing, technician_gotcha, technician_obtaining, technician_ok, technician_yes_sir
Repair: technician_repairing, technician_fixing, technician_ok, technician_yes_sir, technician_gotcha
StealthTankVoice:
DefaultVariant: .ogg
Voices:
Select: stealthtank_copy, stealthtank_im_waiting, stealthtank_orders, stealthtank_ready, stealthtank_ready_for_action, stealthtank_sir, stealthtank_stealthtank, stealthtank_receiving
Move: stealthtank_acknowledged, stealthtank_affirmative, stealthtank_at_once, stealthtank_good_copy, stealthtank_move_out, stealthtank_moving, stealthtank_they_unseen, stealthtank_quickly
Action: stealthtank_its_already_dead, stealthtank_engaging, stealthtank_leave_no_survivors, stealthtank_missile_barrage, stealthtank_shoot_to_kill, stealthtank_target, stealthtank_fire_the_missiles
Guard: guarding
BuilderVoice:
DefaultVariant: .ogg
Voices:
Select: builder_awaiting_orders, builder_builder_ready, builder_copy, builder_im_ready, builder_ready_to_expand, builder_receiving, builder_sir, builder_orders, builder_ready, builder_standing_by
Move: builder_acknowledged, builder_affirmative, builder_as_you_wish, builder_at_once, builder_enroute, builder_good_copy, builder_lets_go, builder_move_out, builder_on_my_way, builder_yes_sir, builder_right_away, builder_heading_out
Action: builder_acknowledged, builder_affirmative, builder_as_you_wish, builder_at_once, builder_good_copy, builder_yes_sir
Deploying: builder_deploying, builder_expanding, builder_setting_up, builder_taking_position, builder_establishing_outpost
Guard: guarding
FlameVoice:
DefaultVariant: .ogg
Voices:
Select: flamer_copy, flamer_I_need_orders, flamer_im_listening, flamer_need_a_light, flamer_ready_to_burn, flamer_receiving, flamer_tanks_full, flamer_ready_to_ignite
Move: flamer_affirmative, flamer_as_you_wish, flamer_going, flamer_good_copy, flamer_on_my_way, flamer_roger_that, flamer_yes_sir, flamer_ten_four, flamer_right_away
Action: flamer_affirmative, flamer_as_you_wish, flamer_roger_that, flamer_yes_sir
Attack: flamer_burn_alive, flamer_cleansing_fire, flamer_purge_them, flamer_with_pleasure, flamer_set_them_on_fire, flamer_eradicate, flamer_hahaha, flamer_I_love_that_smell
Guard: guarding
BrokerVoice:
DefaultVariant: .ogg
Voices:
Select: broker_copy, broker_broker_ready, broker_im_ready, broker_receiving, broker_waiting, broker_sir, broker_ready
Move: broker_acknowledged, broker_at_once, broker_good_copy, broker_gotcha, broker_lets_go, broker_move_out, broker_moving, broker_yes_sir, broker_as_you_wish, broker_right_away
Action: broker_acknowledged, broker_at_once, broker_good_copy, broker_gotcha, broker_yes_sir, broker_as_you_wish
Deploying: broker_deploying, broker_setting_up, broker_stealing_money, broker_taking_position
Attack: broker_setting_up, broker_stealing_money, broker_taking_position, broker_good_copy
Guard: guarding
JetpackerVoice:
DefaultVariant: .ogg
Voices:
Select: jetpacker_all_systems_ready, jetpacker_avionics_online, jetpacker_awaiting_your_orders, jetpacker_copy, jetpacker_optimal_height, jetpacker_ready, jetpacker_receiving, jetpacker_system_online
Move: jetpacker_acknowledged, jetpacker_as_you_wish, jetpacker_at_once, jetpacker_changing_location, jetpacker_flying_high, jetpacker_good_copy, jetpacker_new_destination_set, jetpacker_on_my_way, jetpacker_orders_recieved, jetpacker_right_away_sir, jetpacker_yes_sir, jetpacker_ten_four
Action: jetpacker_acknowledged, jetpacker_as_you_wish, jetpacker_at_once, jetpacker_orders_recieved, jetpacker_yes_sir
Attack: jetpacker_engaging, jetpacker_lethal_force_engaged, jetpacker_target_locked, jetpacker_weapons_hot, jetpacker_yes_sir, jetpacker_destroy, jetpacker_target_confirmed, jetpacker_death_from_above, jetpacker_enemy_in_sight
Guard: guarding
BlasterVoice:
DefaultVariant: .ogg
Voices:
Select: blaster_select1, blaster_select2, blaster_select3, blaster_select4
Move: blaster_action1, blaster_action2, blaster_action3, blaster_action4
Action: blaster_attack1, blaster_attack2, blaster_attack3, blaster_attack4
Guard: guarding
CivilianVoice:
DefaultVariant: .ogg
Voices:
Select: civilian_yes, civilian_hmmm, civilian_im_here, civilian_whats_up
Move: civilian_going, civilian_ok, civilian_sure, civilian_yep, civilian_aha, civilian_good, civilian_right
Action: civilian_aha, civilian_cool, civilian_good, civilian_sure, civilian_yep, civilian_right
ShockerVoice:
DefaultVariant: .ogg
Voices:
Select: shocker_battery_cells_charged, shocker_capacitors_ready, shocker_copy, shocker_fully_charged, shocker_listening, shocker_ready, shocker_receiving, shocker_sir, shocker_waiting
Move: shocker_acknowledged, shocker_affirmative, shocker_at_once, shocker_good_copy, shocker_moving_out, shocker_yes_sir, shocker_heading_out, shocker_alright, shocker_orders_received
Action: shocker_acknowledged, shocker_affirmative, shocker_at_once, shocker_yes_sir, shocker_alright, shocker_orders_received
Attack: shocker_discharging, shocker_extra_crispy, shocker_its_fried, shocker_lightning_ball, shocker_maxium_power, shocker_short_circuit, shocker_surge_current, shocker_attack, shocker_high_voltage_on, shocker_feel_the_thunder
Guard: guarding
MotherShipVoice:
DefaultVariant: .ogg
Voices:
Select: mothershipselect1, mothershipselect2, mothershipselect3
Move: mothershipaction1, mothershipaction2, mothershipaction3
Action: mothershipattack1, mothershipattack2, mothershipattack3
Guard: guarding
AssaultTankVoice:
DefaultVariant: .ogg
Voices:
Select: assault_tank_copy, assault_tank_ready, assault_tank_receiving, assault_tank_standing_by, assault_tank_tank_ready, assault_tank_vehicle_ready, assault_tank_awaiting_orders
Move: assault_tank_acknowledged, assault_tank_affirmative, assault_tank_at_once, assault_tank_changing_location, assault_tank_command_received, assault_tank_confirmed, assault_tank_good_copy, assault_tank_heading_out, assault_tank_location_confirmed, assault_tank_moving_out, assault_tank_right_away, assault_tank_sir_yes_sir
Action: assault_tank_acknowledged, assault_tank_affirmative, assault_tank_at_once, assault_tank_command_received, assault_tank_confirmed, assault_tank_good_copy, assault_tank_sir_yes_sir
Attack: assault_tank_destroy, assault_tank_engaging, assault_tank_sir_yes_sir, assault_tank_target_confirmed, assault_tank_target_locked, assault_tank_enemy_in_sight
Guard: guarding
BattleShipVoice:
DefaultVariant: .ogg
Voices:
Select: battleshipselect1, battleshipselect2, battleshipselect3
Move: battleshipaction1, battleshipaction2, battleshipaction3
Action: battleshipattack1, battleshipattack2, battleshipattack3
Guard: guarding
Jet2Voice:
DefaultVariant: .ogg
Voices:
Select: jet2_aeronautics_operational, jet2_avionics_online, jet2_awaiting_orders, jet2_ready_for_action
Move: jet2_acknowledged, jet2_affirmative, jet2_roger_that, jet2_not_a_problem, jet2_thrusters_engaged
Action: jet2_acknowledged, jet2_affirmative, jet2_roger_that, jet2_intercepting_hostiles, jet2_not_a_problem
Guard: guarding
TurtleVoice:
DefaultVariant: .ogg
Voices:
Select: turtle_aeronautics_operational, turtle_avionics_online, turtle_awaiting_orders
Move: turtle_acknowledged, turtle_affirmative, turtle_not_a_problem, turtle_right_away_sir, turtle_roger_that, turtle_solid_copy
Action: turtle_acknowledged, turtle_affirmative, turtle_not_a_problem, turtle_ready_for_action, turtle_roger_that, turtle_solid_copy, turtle_target_acquired
Guard: guarding
ObserverVoice:
DefaultVariant: .ogg
Voices:
Select: observer_aeronautics_operational, observer_avionics_online, observer_awaiting_orders, observer_ready_for_action, observer_sensors_aligned, observer_surveillance_active
Move: observer_acknowledged, observer_affirmative, observer_not_a_problem, observer_optimising_updraft, observer_roger_that
Action: observer_acknowledged, observer_affirmative, observer_not_a_problem, observer_optimising_updraft, observer_roger_that
Guard: guarding
CarVoice:
DefaultVariant: .ogg
Voices:
Select: car_action1, car_action2, car_action3
Move: car_action1, car_action2, car_action3
Action: car_attack1, car_attack2, car_attack3
Guard: guarding
RadarTankVoice:
DefaultVariant: .ogg
Voices:
Select: radar_tank_awaiting_orders, radar_tank_copy, radar_tank_online, radar_tank_ready, radar_tank_standing_by, radar_tank_sir, radar_tank_systems_online
Move: radar_tank_as_you_wish, radar_tank_at_once, radar_tank_good_copy, radar_tank_heading_out, radar_tank_moving_out, radar_tank_on_my_way, radar_tank_understood
Action: radar_tank_as_you_wish, radar_tank_at_once, radar_tank_good_copy, radar_tank_heading_out, radar_tank_moving_out, radar_tank_on_my_way, radar_tank_understood
Deploy: radar_tank_deploying, radar_tank_searching_for_enemies, radar_tank_understood
Guard: guarding
| 412 | 0.72712 | 1 | 0.72712 | game-dev | MEDIA | 0.793884 | game-dev | 0.75403 | 1 | 0.75403 |
geom3trik/tuix | 58,140 | core/src/systems/new_layout.rs | use crate::*;
use crate::{Entity, State};
pub fn apply_transform(state: &mut State, tree: &Tree) {
//println!("Apply Transform");
for entity in tree.into_iter() {
//println!("Entity: {}", entity);
if entity == Entity::root() {
continue;
}
let parent = tree.get_parent(entity).unwrap();
//let parent_origin = state.data.get_origin(parent);
let parent_transform = state.data.get_transform(parent);
state.data.set_transform(entity, Transform2D::identity());
state.data.set_transform(entity, parent_transform);
let bounds = state.data.get_bounds(entity);
//state.data.set_origin(entity, parent_origin);
if let Some(translate) = state.style.translate.get(entity) {
state.data.set_translate(entity, *translate);
}
if let Some(rotate) = state.style.rotate.get(entity) {
let x = bounds.x + (bounds.w / 2.0);
let y = bounds.y + (bounds.h / 2.0);
state.data.set_translate(entity, (x,y));
state.data.set_rotate(entity, (*rotate).to_radians());
state.data.set_translate(entity, (-x,-y));
}
//println!("End");
if let Some(scale) = state.style.scale.get(entity) {
let x = bounds.x + (bounds.w / 2.0);
let y = bounds.y + (bounds.h / 2.0);
state.data.set_translate(entity, (x,y));
state.data.set_scale(entity, *scale);
state.data.set_translate(entity, (-x,-y));
}
}
}
#[derive(Debug)]
enum Axis {
Before,
Size,
After,
}
/*
pub fn apply_layout2(state: &mut State, tree: &Tree) {
//println!("Apply Layout");
let layout_tree = tree.into_iter().collect::<Vec<Entity>>();
// for entity in layout_tree.iter() {
// state.data.set_child_sum(*entity, 0.0);
// state.data.set_child_max(*entity, 0.0);
// }
for parent in layout_tree.iter() {
// Skip non-displayed entities
let parent_display = parent.get_display(state);
if parent_display == Display::None {
continue;
}
let mut found_first = false;
let mut last_child = Entity::null();
state.data.set_child_width_sum(*parent, 0.0);
state.data.set_child_height_sum(*parent, 0.0);
state.data.set_child_width_max(*parent, 0.0);
state.data.set_child_height_max(*parent, 0.0);
state.data
.set_prev_width(*parent, state.data.get_width(*parent));
state
.data
.set_prev_height(*parent, state.data.get_height(*parent));
for child in parent.child_iter(tree) {
let child_display = child.get_display(state);
if child_display == Display::None {
continue;
}
state.data.set_stack_first_child(child, false);
let child_positioning_type = state
.style
.positioning_type
.get(child)
.cloned()
.unwrap_or_default();
match child_positioning_type {
PositionType::ParentDirected => {
if !found_first {
found_first = true;
state.data.set_stack_first_child(child, true);
}
last_child = child;
}
PositionType::SelfDirected => {
state.data.set_stack_first_child(child, true);
state.data.set_stack_last_child(child, true);
}
}
}
state.data.set_stack_last_child(last_child, true);
}
// Walk up the tree
for child in layout_tree.iter().rev() {
// Stop before the window
if *child == Entity::root() {
break;
}
// Skip non-displayed entities
let child_display = child.get_display(state);
if child_display == Display::None {
continue;
}
// Safe to unwrap because every entity in the tree has a parent except window which is skipped
let parent = child.get_parent(state).unwrap();
let parent_layout_type = state
.style
.layout_type
.get(parent)
.cloned()
.unwrap_or_default();
let child_left = state
.style
.child_left
.get(parent)
.cloned()
.unwrap_or_default();
let child_right = state
.style
.child_right
.get(parent)
.cloned()
.unwrap_or_default();
let child_top = state
.style
.child_top
.get(parent)
.cloned()
.unwrap_or_default();
let child_bottom = state
.style
.child_bottom
.get(parent)
.cloned()
.unwrap_or_default();
let child_between = state
.style
.child_between
.get(parent)
.cloned()
.unwrap_or_default();
// TODO - support percentage border
let parent_border_width = parent.get_border_width(state).get_value(0.0);
let parent_width = state.data.get_width(parent) - 2.0 * parent_border_width;
let parent_height = state.data.get_height(parent) - 2.0 * parent_border_width;
let child_border_width = child.get_border_width(state).get_value(parent_width);
let mut left = state.style.left.get(*child).cloned().unwrap_or_default();
let width = state
.style
.width
.get(*child)
.cloned()
.unwrap_or(Units::Stretch(1.0));
let mut right = state.style.right.get(*child).cloned().unwrap_or_default();
let mut top = state.style.top.get(*child).cloned().unwrap_or_default();
let height = state
.style
.height
.get(*child)
.cloned()
.unwrap_or(Units::Stretch(1.0));
let mut bottom = state.style.bottom.get(*child).cloned().unwrap_or_default();
let min_left = state
.style
.min_left
.get(*child)
.cloned()
.unwrap_or_default()
.get_value_or(parent_width, -std::f32::INFINITY);
//let min_width = state.style.min_width.get(*child).cloned().unwrap_or_default().get_value_or(parent_width, 0.0);
let min_right = state
.style
.min_right
.get(*child)
.cloned()
.unwrap_or_default()
.get_value_or(parent_width, -std::f32::INFINITY);
let max_left = state
.style
.max_left
.get(*child)
.cloned()
.unwrap_or_default()
.get_value_or(parent_width, std::f32::INFINITY);
let max_width = state
.style
.max_width
.get(*child)
.cloned()
.unwrap_or_default()
.get_value_or(parent_width, std::f32::INFINITY);
let max_right = state
.style
.max_right
.get(*child)
.cloned()
.unwrap_or_default()
.get_value_or(parent_width, std::f32::INFINITY);
let min_top = state
.style
.min_top
.get(*child)
.cloned()
.unwrap_or_default()
.get_value_or(parent_height, -std::f32::INFINITY);
//let min_height = state.style.min_height.get(*child).cloned().unwrap_or_default().get_value_or(parent_height, 0.0);
let min_bottom = state
.style
.min_bottom
.get(*child)
.cloned()
.unwrap_or_default()
.get_value_or(parent_height, -std::f32::INFINITY);
let max_top = state
.style
.max_top
.get(*child)
.cloned()
.unwrap_or_default()
.get_value_or(parent_height, std::f32::INFINITY);
let max_height = state
.style
.max_height
.get(*child)
.cloned()
.unwrap_or_default()
.get_value_or(parent_height, std::f32::INFINITY);
let max_bottom = state
.style
.max_bottom
.get(*child)
.cloned()
.unwrap_or_default()
.get_value_or(parent_height, std::f32::INFINITY);
let child_layout_type = state
.style
.layout_type
.get(*child)
.cloned()
.unwrap_or_default();
let child_positioning_type = state
.style
.positioning_type
.get(*child)
.cloned()
.unwrap_or_default();
let min_width = state
.style
.min_width
.get(*child)
.cloned()
.unwrap_or_default();
let min_width = match min_width {
Units::Pixels(val) => val,
Units::Percentage(val) => (val * parent_width).round(),
Units::Stretch(_) => 0.0,
Units::Auto => {
//println!("{} Auto", child);
match child_layout_type {
LayoutType::Column => {
state.data.get_child_width_max(*child) + 2.0 * child_border_width
}
LayoutType::Row => state.data.get_child_width_sum(*child) + 2.0 * child_border_width,
LayoutType::Grid => state.data.get_child_width_sum(*child) + 2.0 * child_border_width,
LayoutType::None => 0.0,
}
}
};
let min_height = state
.style
.min_height
.get(*child)
.cloned()
.unwrap_or_default();
let min_height = match min_height {
Units::Pixels(val) => val,
Units::Percentage(val) => (val * parent_height).round(),
Units::Stretch(_) => 0.0,
Units::Auto => match child_layout_type {
LayoutType::Column => state.data.get_child_height_sum(*child) + 2.0 * child_border_width,
LayoutType::Row => state.data.get_child_height_max(*child) + 2.0 * child_border_width,
_ => state.data.get_child_height_sum(*child) + 2.0 * child_border_width,
},
};
//println!("{} Min Width: {}", child, min_width);
// Parent overrides
match parent_layout_type {
LayoutType::Column => {
if state.data.get_stack_child(*child).0 {
if top == Units::Auto {
top = child_top.clone();
}
} else {
if top == Units::Auto {
top = child_between.clone();
}
}
if state.data.get_stack_child(*child).1 {
if bottom == Units::Auto {
bottom = child_bottom.clone();
}
}
if left == Units::Auto {
left = child_left.clone();
}
if right == Units::Auto {
right = child_right.clone();
}
}
LayoutType::Row => {
if state.data.get_stack_child(*child).0 {
if left == Units::Auto {
left = child_left.clone();
}
} else {
if left == Units::Auto {
left = child_between.clone();
}
}
if state.data.get_stack_child(*child).1 {
if right == Units::Auto {
right = child_right.clone();
}
}
if top == Units::Auto {
top = child_top.clone();
}
if bottom == Units::Auto {
bottom = child_bottom.clone();
}
}
_ => {}
}
let mut new_left = 0.0;
let mut new_width = 0.0;
let mut new_right = 0.0;
let mut new_top = 0.0;
let mut new_height = 0.0;
let mut new_bottom = 0.0;
let mut horizontal_used_space = 0.0;
let mut vertical_used_space = 0.0;
match left {
Units::Pixels(val) => {
new_left = val.clamp(min_left, max_left);
horizontal_used_space += new_left;
}
_ => {}
}
match width {
Units::Pixels(val) => {
new_width = val.clamp(min_width, max_width);
horizontal_used_space += new_width;
}
Units::Auto => {
match child_layout_type {
LayoutType::Column => {
new_width = state.data.get_child_width_max(*child) + 2.0 * child_border_width;
}
LayoutType::Row => {
new_width = state.data.get_child_width_sum(*child) + 2.0 * child_border_width;
}
LayoutType::Grid => {
new_width = state.data.get_child_width_sum(*child) + 2.0 * child_border_width;
}
_ => {}
}
horizontal_used_space += new_width;
}
_ => {}
}
match right {
Units::Pixels(val) => {
new_right = val.clamp(min_right, max_right);
horizontal_used_space += new_right;
}
_ => {}
}
match top {
Units::Pixels(val) => {
new_top = val.clamp(min_top, max_top);
vertical_used_space += new_top;
}
_ => {}
}
match height {
Units::Pixels(val) => {
new_height = val.clamp(min_height, max_height);
vertical_used_space += new_height;
}
Units::Auto => {
match child_layout_type {
LayoutType::Column => {
new_height = state.data.get_child_height_sum(*child) + 2.0 * child_border_width;
}
LayoutType::Row => {
new_height = state.data.get_child_height_max(*child) + 2.0 * child_border_width;
}
LayoutType::Grid => {
new_height = state.data.get_child_height_sum(*child) + 2.0 * child_border_width;
}
_ => {}
}
vertical_used_space += new_height;
}
_ => {}
}
match bottom {
Units::Pixels(val) => {
new_bottom = val.clamp(min_bottom, max_bottom);
vertical_used_space += new_bottom;
}
_ => {}
}
// match child_positioning_type {
// PositionType::SelfDirected => {
// horizontal_used_space = 0.0;
// vertical_used_space = 0.0;
// }
// _=> {}
// }
//println!("{} Row used space {}", child, horizontal_used_space);
if child_positioning_type == PositionType::ParentDirected {
state.data.set_child_height_sum(
parent,
state.data.get_child_height_sum(parent) + vertical_used_space,
);
state.data.set_child_height_max(
parent,
vertical_used_space.max(state.data.get_child_height_max(parent)),
);
state.data.set_child_width_sum(
parent,
state.data.get_child_width_sum(parent) + horizontal_used_space,
);
state.data.set_child_width_max(
parent,
horizontal_used_space.max(state.data.get_child_width_max(parent)),
);
}
// match parent_layout_type {
// LayoutType::Column => {
// if child_positioning_type == PositionType::ParentDirected {
// state.data.set_child_height_sum(
// parent,
// state.data.get_child_height_sum(parent) + vertical_used_space,
// );
// state.data.set_child_height_max(
// parent,
// horizontal_used_space.max(state.data.get_child_width_max(parent)),
// );
// }
// }
// LayoutType::Row => {
// if child_positioning_type == PositionType::ParentDirected {
// state.data.set_child_width_sum(
// parent,
// state.data.get_child_width_sum(parent) + horizontal_used_space,
// );
// state.data.set_child_width_max(
// parent,
// vertical_used_space.max(state.data.get_child_width_max(parent)),
// );
// }
// }
// _ => {}
// }
state.data.set_height(*child, new_height);
state.data.set_width(*child, new_width);
state.data.set_space_top(*child, new_top);
state.data.set_space_bottom(*child, new_bottom);
state.data.set_space_left(*child, new_left);
state.data.set_space_right(*child, new_right);
}
// Depth first traversal of all nodes from root
for parent in layout_tree.into_iter() {
// Skip non-displayed entities
let parent_display = parent.get_display(state);
if parent_display == Display::None {
continue;
}
let parent_layout_type = state
.style
.layout_type
.get(parent)
.cloned()
.unwrap_or_default();
let child_left = state
.style
.child_left
.get(parent)
.cloned()
.unwrap_or_default();
let child_right = state
.style
.child_right
.get(parent)
.cloned()
.unwrap_or_default();
let child_top = state
.style
.child_top
.get(parent)
.cloned()
.unwrap_or_default();
let child_bottom = state
.style
.child_bottom
.get(parent)
.cloned()
.unwrap_or_default();
let child_between = state
.style
.child_between
.get(parent)
.cloned()
.unwrap_or_default();
// TODO - support percentage border
let parent_border_width = parent.get_border_width(state).get_value(0.0);
let parent_width = state.data.get_width(parent) - 2.0 * parent_border_width;
let parent_height = state.data.get_height(parent) - 2.0 * parent_border_width;
let (parent_main, parent_cross) = match parent_layout_type {
LayoutType::Column => (parent_height, parent_width),
LayoutType::Row | LayoutType::Grid | LayoutType::None => (parent_width, parent_height),
};
let mut main_free_space = parent_main;
let mut main_stretch_sum: f32 = 0.0;
match parent_layout_type {
LayoutType::Row | LayoutType::Column => {
let mut horizontal_axis = Vec::new();
let mut vertical_axis = Vec::new();
// ////////////////////////////////
// Calculate inflexible children //
///////////////////////////////////
for child in parent.child_iter(&tree) {
let child_display = child.get_display(state);
if child_display == Display::None {
continue;
}
let mut left = state.style.left.get(child).cloned().unwrap_or_default();
let width = state
.style
.width
.get(child)
.cloned()
.unwrap_or(Units::Stretch(1.0));
let mut right = state.style.right.get(child).cloned().unwrap_or_default();
let mut top = state.style.top.get(child).cloned().unwrap_or_default();
let height = state
.style
.height
.get(child)
.cloned()
.unwrap_or(Units::Stretch(1.0));
let mut bottom = state.style.bottom.get(child).cloned().unwrap_or_default();
let min_left = state
.style
.min_left
.get(child)
.cloned()
.unwrap_or_default()
.get_value_or(parent_width, -std::f32::INFINITY);
//let min_width = state.style.min_width.get(child).cloned().unwrap_or_default().get_value_or(parent_width, 0.0);
let min_right = state
.style
.min_right
.get(child)
.cloned()
.unwrap_or_default()
.get_value_or(parent_width, -std::f32::INFINITY);
let max_left = state
.style
.max_left
.get(child)
.cloned()
.unwrap_or_default()
.get_value_or(parent_width, std::f32::INFINITY);
let max_width = state
.style
.max_width
.get(child)
.cloned()
.unwrap_or_default()
.get_value_or(parent_width, std::f32::INFINITY);
let max_right = state
.style
.max_right
.get(child)
.cloned()
.unwrap_or_default()
.get_value_or(parent_width, std::f32::INFINITY);
let min_top = state
.style
.min_top
.get(child)
.cloned()
.unwrap_or_default()
.get_value_or(parent_height, -std::f32::INFINITY);
//let min_height = state.style.min_height.get(child).cloned().unwrap_or_default().get_value_or(parent_height, 0.0);
let min_bottom = state
.style
.min_bottom
.get(child)
.cloned()
.unwrap_or_default()
.get_value_or(parent_height, -std::f32::INFINITY);
let max_top = state
.style
.max_top
.get(child)
.cloned()
.unwrap_or_default()
.get_value_or(parent_height, std::f32::INFINITY);
let max_height = state
.style
.max_height
.get(child)
.cloned()
.unwrap_or_default()
.get_value_or(parent_height, std::f32::INFINITY);
let max_bottom = state
.style
.max_bottom
.get(child)
.cloned()
.unwrap_or_default()
.get_value_or(parent_height, std::f32::INFINITY);
let child_border_width = child.get_border_width(state).get_value(parent_width);
// Parent overrides
match parent_layout_type {
LayoutType::Column => {
if state.data.get_stack_child(child).0 {
if top == Units::Auto {
top = child_top.clone();
}
} else {
if top == Units::Auto {
top = child_between.clone();
}
}
if state.data.get_stack_child(child).1 {
if bottom == Units::Auto {
bottom = child_bottom.clone();
}
}
if left == Units::Auto {
left = child_left.clone();
}
if right == Units::Auto {
right = child_right.clone();
}
}
LayoutType::Row => {
if state.data.get_stack_child(child).0 {
if left == Units::Auto {
left = child_left.clone();
}
} else {
if left == Units::Auto {
left = child_between.clone();
}
}
if state.data.get_stack_child(child).1 {
if right == Units::Auto {
right = child_right.clone();
}
}
if top == Units::Auto {
top = child_top.clone();
}
if bottom == Units::Auto {
bottom = child_bottom.clone();
}
}
_ => {}
}
let mut new_left = 0.0;
let mut new_width = 0.0;
let mut new_right = 0.0;
let mut new_top = 0.0;
let mut new_height = 0.0;
let mut new_bottom = 0.0;
let mut horizontal_stretch_sum = 0.0;
let mut vertical_stretch_sum = 0.0;
let mut horizontal_used_space = 0.0;
let mut vertical_used_space = 0.0;
let mut cross_stretch_sum = 0.0;
let mut cross_free_space = 0.0;
let child_layout_type = state
.style
.layout_type
.get(child)
.cloned()
.unwrap_or_default();
let min_width = state
.style
.min_width
.get(child)
.cloned()
.unwrap_or_default();
let min_width = match min_width {
Units::Pixels(val) => val,
Units::Percentage(val) => (val * parent_width).round(),
Units::Stretch(_) => 0.0,
Units::Auto => {
//println!("{} Auto", child);
match child_layout_type {
LayoutType::Column => {
state.data.get_child_width_max(child) + 2.0 * child_border_width
}
LayoutType::Row | LayoutType::Grid => {
state.data.get_child_width_sum(child) + 2.0 * child_border_width
}
_ => 0.0,
}
}
};
let min_height = state
.style
.min_height
.get(child)
.cloned()
.unwrap_or_default();
let min_height = match min_height {
Units::Pixels(val) => val,
Units::Percentage(val) => (val * parent_height).round(),
Units::Stretch(_) => 0.0,
Units::Auto => match child_layout_type {
LayoutType::Column | LayoutType::Grid => {
state.data.get_child_height_sum(child) + 2.0 * child_border_width
}
LayoutType::Row => {
state.data.get_child_height_max(child) + 2.0 * child_border_width
}
_ => 0.0,
},
};
// TODO - replace all these match' with a function
match left {
Units::Pixels(val) => {
new_left = val.clamp(min_left, max_left);
horizontal_used_space += new_left;
}
Units::Percentage(val) => {
new_left = (val * parent_width).round();
new_left = new_left.clamp(min_left, max_left);
horizontal_used_space += new_left;
}
Units::Stretch(val) => {
horizontal_stretch_sum += val;
horizontal_axis.push((child, val, min_left, max_left, Axis::Before));
}
_ => {}
}
match width {
Units::Pixels(val) => {
new_width = val.clamp(min_width, max_width);
horizontal_used_space += new_width;
}
Units::Percentage(val) => {
new_width = (val * parent_width).round();
new_width = new_width.clamp(min_width, max_width);
horizontal_used_space += new_width;
}
Units::Stretch(val) => {
horizontal_stretch_sum += val;
horizontal_axis.push((child, val, min_width, max_width, Axis::Size));
}
Units::Auto => {
match child_layout_type {
LayoutType::Column => {
new_width =
state.data.get_child_width_max(child) + 2.0 * child_border_width;
}
LayoutType::Row | LayoutType::Grid=> {
new_width =
state.data.get_child_width_sum(child) + 2.0 * child_border_width;
}
_ => {}
}
horizontal_used_space += new_width;
}
}
match right {
Units::Pixels(val) => {
new_right = val.clamp(min_right, max_right);
horizontal_used_space += new_right;
}
Units::Percentage(val) => {
new_right = (val * parent_width).round();
new_right = new_right.clamp(min_right, max_right);
horizontal_used_space += new_right;
}
Units::Stretch(val) => {
horizontal_stretch_sum += val;
horizontal_axis.push((child, val, min_right, max_right, Axis::After));
}
_ => {}
}
match top {
Units::Pixels(val) => {
new_top = val.clamp(min_top, max_top);
vertical_used_space += new_top;
}
Units::Percentage(val) => {
new_top = (val * parent_height).round();
new_top = new_top.clamp(min_top, max_top);
vertical_used_space += new_top;
}
Units::Stretch(val) => {
vertical_stretch_sum += val;
vertical_axis.push((child, val, min_top, max_top, Axis::Before));
}
_ => {}
}
match height {
Units::Pixels(val) => {
new_height = val.clamp(min_height, max_height);
vertical_used_space += new_height;
}
Units::Percentage(val) => {
new_height = (val * parent_height).round();
new_height = new_height.clamp(min_height, max_height);
vertical_used_space += new_height;
}
Units::Stretch(val) => {
vertical_stretch_sum += val;
vertical_axis.push((child, val, min_height, max_height, Axis::Size));
}
Units::Auto => {
match child_layout_type {
LayoutType::Column | LayoutType::Grid => {
new_height =
state.data.get_child_height_sum(child) + 2.0 * child_border_width;
}
LayoutType::Row => {
new_height =
state.data.get_child_height_max(child) + 2.0 * child_border_width;
}
_ => {}
}
vertical_used_space += new_height;
}
}
match bottom {
Units::Pixels(val) => {
new_bottom = val.clamp(min_bottom, max_bottom);
vertical_used_space += val;
}
Units::Percentage(val) => {
new_bottom = (val * parent_height).round();
new_bottom = new_bottom.clamp(min_bottom, max_bottom);
vertical_used_space += new_bottom;
}
Units::Stretch(val) => {
vertical_stretch_sum += val;
vertical_axis.push((child, val, min_bottom, max_bottom, Axis::After));
}
_ => {}
}
state.data.set_height(child, new_height);
state.data.set_width(child, new_width);
state.data.set_space_top(child, new_top);
state.data.set_space_bottom(child, new_bottom);
state.data.set_space_left(child, new_left);
state.data.set_space_right(child, new_right);
let child_positioning_type = state
.style
.positioning_type
.get(child)
.cloned()
.unwrap_or_default();
//horizontal_stretch_sum = horizontal_stretch_sum.max(1.0);
//vertical_stretch_sum = vertical_stretch_sum.max(1.0);
state
.data
.set_horizontal_used_space(child, horizontal_used_space);
state
.data
.set_horizontal_stretch_sum(child, horizontal_stretch_sum);
state
.data
.set_vertical_used_space(child, vertical_used_space);
state
.data
.set_vertical_stretch_sum(child, vertical_stretch_sum);
match parent_layout_type {
LayoutType::Column => {
if child_positioning_type == PositionType::SelfDirected {
vertical_used_space = 0.0;
vertical_stretch_sum = 0.0;
}
cross_stretch_sum += horizontal_stretch_sum;
main_stretch_sum += vertical_stretch_sum;
main_free_space -= vertical_used_space;
cross_free_space = parent_cross - horizontal_used_space;
}
LayoutType::Row => {
if child_positioning_type == PositionType::SelfDirected {
horizontal_used_space = 0.0;
horizontal_stretch_sum = 0.0;
}
cross_stretch_sum += vertical_stretch_sum;
main_stretch_sum += horizontal_stretch_sum;
main_free_space -= horizontal_used_space;
cross_free_space = parent_cross - vertical_used_space;
}
_ => {}
}
if cross_stretch_sum == 0.0 {
cross_stretch_sum = 1.0;
}
state.data.set_cross_stretch_sum(child, cross_stretch_sum);
state.data.set_cross_free_space(child, cross_free_space);
}
if main_stretch_sum == 0.0 {
main_stretch_sum = 1.0;
}
horizontal_axis.sort_by(|a, b| a.3.partial_cmp(&b.3).unwrap());
vertical_axis.sort_by(|a, b| a.3.partial_cmp(&b.3).unwrap());
let mut horizontal_stretch_sum = 0.0;
let mut horizontal_free_space = 0.0;
let mut vertical_stretch_sum = 0.0;
let mut vertical_free_space = 0.0;
// Calculate flexible Row space & size
for (child, value, min_value, max_value, variant) in horizontal_axis.iter() {
let cross_stretch_sum = state.data.get_cross_stretch_sum(*child);
let cross_free_space = state.data.get_cross_free_space(*child);
let child_positioning_type = state
.style
.positioning_type
.get(*child)
.cloned()
.unwrap_or_default();
match child_positioning_type {
PositionType::SelfDirected => {
horizontal_free_space =
parent_width - state.data.get_horizontal_used_space(*child);
horizontal_stretch_sum = state.data.get_horizontal_stretch_sum(*child);
}
PositionType::ParentDirected => {
match parent_layout_type {
LayoutType::Column => {
horizontal_stretch_sum = cross_stretch_sum;
horizontal_free_space = cross_free_space;
}
LayoutType::Row => {
horizontal_free_space = main_free_space;
horizontal_stretch_sum = main_stretch_sum;
}
_ => {}
};
}
}
if horizontal_stretch_sum == 0.0 {
horizontal_stretch_sum = 1.0;
}
let mut new_value = horizontal_free_space * value / horizontal_stretch_sum;
new_value = new_value.clamp(*min_value, *max_value);
match variant {
Axis::Before => {
state.data.set_space_left(*child, new_value);
}
Axis::Size => {
state.data.set_width(*child, new_value);
}
Axis::After => {
state.data.set_space_right(*child, new_value);
}
}
match child_positioning_type {
PositionType::SelfDirected => {
state
.data
.set_horizontal_stretch_sum(*child, horizontal_stretch_sum - value);
state.data.set_horizontal_used_space(
*child,
parent_width - horizontal_free_space + new_value,
);
}
PositionType::ParentDirected => {
match parent_layout_type {
LayoutType::Column => {
state.data.set_cross_stretch_sum(
*child,
horizontal_stretch_sum - value,
);
state.data.set_cross_free_space(
*child,
horizontal_free_space - new_value,
);
}
LayoutType::Row => {
main_free_space -= new_value;
main_stretch_sum -= value;
}
_ => {}
};
}
}
}
// Calculate flexible Column space & size
for (child, value, min_value, max_value, variant) in vertical_axis.iter() {
let cross_stretch_sum = state.data.get_cross_stretch_sum(*child);
let cross_free_space = state.data.get_cross_free_space(*child);
let child_positioning_type = state
.style
.positioning_type
.get(*child)
.cloned()
.unwrap_or_default();
match child_positioning_type {
PositionType::SelfDirected => {
vertical_free_space =
parent_height - state.data.get_vertical_used_space(*child);
vertical_stretch_sum = state.data.get_vertical_stretch_sum(*child);
}
PositionType::ParentDirected => {
match parent_layout_type {
LayoutType::Row => {
vertical_stretch_sum = cross_stretch_sum;
vertical_free_space = cross_free_space;
}
LayoutType::Column => {
vertical_free_space = main_free_space;
vertical_stretch_sum = main_stretch_sum;
}
_ => {}
};
}
}
if vertical_stretch_sum == 0.0 {
vertical_stretch_sum = 1.0;
}
let mut new_value = vertical_free_space * value / vertical_stretch_sum;
new_value = new_value.clamp(*min_value, *max_value);
match variant {
Axis::Before => {
state.data.set_space_top(*child, new_value);
}
Axis::Size => {
state.data.set_height(*child, new_value);
}
Axis::After => {
state.data.set_space_bottom(*child, new_value);
}
}
match child_positioning_type {
PositionType::SelfDirected => {
state
.data
.set_vertical_stretch_sum(*child, vertical_stretch_sum - value);
state.data.set_vertical_used_space(
*child,
parent_height - vertical_free_space + new_value,
);
}
PositionType::ParentDirected => {
match parent_layout_type {
LayoutType::Row => {
state.data.set_cross_stretch_sum(
*child,
vertical_stretch_sum - value,
);
state.data.set_cross_free_space(
*child,
vertical_free_space - new_value,
);
}
LayoutType::Column => {
main_free_space -= new_value;
main_stretch_sum -= value;
}
_ => {}
};
}
}
}
let mut current_posx = 0.0;
let mut current_posy = 0.0;
// TODO - support percentage border
let parent_border_width = parent.get_border_width(state).get_value(0.0);
let parent_posx = state.data.get_posx(parent) + parent_border_width;
let parent_posy = state.data.get_posy(parent) + parent_border_width;
///////////////////////
// Position Children //
///////////////////////
for child in parent.child_iter(&tree) {
let child_display = child.get_display(state);
if child_display == Display::None {
continue;
}
let space = state.data.get_space(child);
let width = state.data.get_width(child);
let height = state.data.get_height(child);
let child_positioning_type = state
.style
.positioning_type
.get(child)
.cloned()
.unwrap_or_default();
let (new_posx, new_posy) = match child_positioning_type {
PositionType::SelfDirected => {
(parent_posx + space.left, parent_posy + space.top)
}
PositionType::ParentDirected => {
let new_posx = parent_posx + current_posx + space.left;
let new_posy = parent_posy + current_posy + space.top;
match parent_layout_type {
LayoutType::Column => {
current_posy += space.top + height + space.bottom;
}
LayoutType::Row => {
current_posx += space.left + width + space.right;
}
_ => {}
}
(new_posx, new_posy)
}
};
state.data.set_posx(child, new_posx);
state.data.set_posy(child, new_posy);
}
let prev_width = state.data.get_prev_width(parent);
let prev_height = state.data.get_prev_height(parent);
let new_width = state.data.get_width(parent);
let new_height = state.data.get_height(parent);
let mut geometry_changed = GeometryChanged::default();
if new_width != prev_width {
geometry_changed.width = true;
}
if new_height != prev_height {
geometry_changed.height = true;
}
if geometry_changed.width || geometry_changed.height {
state.insert_event(
Event::new(WindowEvent::GeometryChanged(geometry_changed))
.target(parent)
.propagate(Propagation::Down),
);
}
}
LayoutType::Grid => {
let grid_rows = state
.style
.grid_rows
.get(parent)
.cloned()
.unwrap_or_default();
let grid_cols = state
.style
.grid_cols
.get(parent)
.cloned()
.unwrap_or_default();
let mut row_heights = vec![(0.0, 0.0, 0.0, 0.0); grid_rows.len() + 1];
let mut col_widths = vec![(0.0, 0.0, 0.0, 0.0); grid_cols.len() + 1];
let mut row_free_space = state.data.get_height(parent);
let mut col_free_space = state.data.get_width(parent);
let mut row_stretch_sum = 0.0;
let mut col_stretch_sum = 0.0;
let row_between = match state.style.row_between
.get(parent)
.cloned()
.unwrap_or_default() {
Units::Pixels(val) => val,
_=> 0.0,
};
let col_between = match state.style.col_between
.get(parent)
.cloned()
.unwrap_or_default() {
Units::Pixels(val) => val,
_=> 0.0,
};
for (i, row) in grid_rows.iter().enumerate() {
match row {
&Units::Pixels(val) => {
row_heights[i].1 = val;
row_free_space -= val;
}
&Units::Stretch(val) => {
row_stretch_sum += val;
}
_ => {}
}
}
for (i, col) in grid_cols.iter().enumerate() {
match col {
&Units::Pixels(val) => {
col_widths[i].1 = val;
col_free_space -= val;
}
&Units::Stretch(val) => {
col_stretch_sum += val;
}
_ => {}
}
}
if row_stretch_sum == 0.0 {
row_stretch_sum = 1.0;
}
if col_stretch_sum == 0.0 {
col_stretch_sum = 1.0;
}
let mut current_row_pos = state.data.get_posy(parent);
let mut current_col_pos = state.data.get_posx(parent);
for (i, row) in grid_rows.iter().enumerate() {
match row {
&Units::Stretch(val) => {
row_heights[i].1 = row_free_space * val / row_stretch_sum;
}
_ => {}
}
row_heights[i].0 = current_row_pos;
current_row_pos += row_heights[i].1;
}
let row_heights_len = row_heights.len() - 1;
row_heights[row_heights_len].0 = current_row_pos;
for (i, col) in grid_cols.iter().enumerate() {
match col {
&Units::Stretch(val) => {
col_widths[i].1 = col_free_space * val / col_stretch_sum;
}
_ => {}
}
col_widths[i].0 = current_col_pos;
current_col_pos += col_widths[i].1;
}
let col_widths_len = col_widths.len() - 1;
col_widths[col_widths_len].0 = current_col_pos;
for child in parent.child_iter(&tree) {
let child_display = child.get_display(state);
if child_display == Display::None {
continue;
}
let grid_item = state
.style
.grid_item
.get(child)
.cloned()
.unwrap_or_default();
let row_start = grid_item.row_index as usize;
let row_end = row_start + grid_item.row_span as usize;
let col_start = grid_item.col_index as usize;
let col_end = col_start + grid_item.col_span as usize;
if col_start == 0 {
state.data.set_posx(child, col_widths[col_start].0);
state.data.set_width(
child,
(col_widths[col_end].0 - col_widths[col_start].0)
- col_between / 2.0,
);
} else if col_end + 1 == col_widths.len() {
state
.data
.set_posx(child, col_widths[col_start].0 + (col_between / 2.0));
state.data.set_width(
child,
(col_widths[col_end].0 - col_widths[col_start].0)
- col_between / 2.0,
);
} else {
state
.data
.set_posx(child, col_widths[col_start].0 + (col_between / 2.0));
state.data.set_width(
child,
(col_widths[col_end].0 - col_widths[col_start].0) - col_between,
);
}
if row_start == 0 {
state.data.set_posy(child, row_heights[row_start].0);
state.data.set_height(
child,
(row_heights[row_end].0 - row_heights[row_start].0)
- row_between / 2.0,
);
} else if row_end + 1 == row_heights.len() {
state
.data
.set_posy(child, row_heights[row_start].0 + (row_between / 2.0));
state.data.set_height(
child,
(row_heights[row_end].0 - row_heights[row_start].0)
- row_between / 2.0,
);
} else {
state
.data
.set_posy(child, row_heights[row_start].0 + (row_between / 2.0));
state.data.set_height(
child,
(row_heights[row_end].0 - row_heights[row_start].0) - row_between,
);
}
}
}
_ => {}
}
}
}
*/ | 412 | 0.726659 | 1 | 0.726659 | game-dev | MEDIA | 0.377992 | game-dev | 0.908233 | 1 | 0.908233 |
Sigma-Skidder-Team/SigmaRemap | 4,044 | src/main/java/mapped/Class4306.java | package mapped;
import com.mentalfrostbyte.jello.gui.screens.JelloMainMenuScreen;
import com.mentalfrostbyte.jello.unmapped.CustomGuiScreen;
import com.mentalfrostbyte.jello.util.MultiUtilities;
import com.mentalfrostbyte.jello.util.ClientColors;
import net.minecraft.client.Minecraft;
public class Class4306 extends CustomGuiScreen {
private static String[] field20927;
public float field20928;
public float field20929;
public float field20930;
public float field20931;
public float field20932 = -9999.0F;
public float field20933 = -9999.0F;
public float field20934;
public int field20935 = 0;
public int field20936;
public int field20937;
public int field20938 = 114;
public Class4306(CustomGuiScreen var1, String var2, int var3, int var4, int var5, int var6, int var7) {
super(var1, var2, var3, var4, var5, var5);
this.field20928 = this.field20930 = (float) var6;
this.field20929 = this.field20931 = (float) var7;
this.field20932 = (float) var3;
this.field20933 = (float) var4;
}
@Override
public void updatePanelDimensions(int newHeight, int newWidth) {
if (this.field20932 == -9999.0F || this.field20933 == -9999.0F) {
this.field20932 = (float) this.xA;
this.field20933 = (float) this.yA;
}
this.field20932 = this.field20932 + this.field20928 * JelloMainMenuScreen.field20982;
this.field20933 = this.field20933 + this.field20929 * JelloMainMenuScreen.field20982;
this.xA = Math.round(this.field20932);
this.yA = Math.round(this.field20933);
if (!(this.field20932 + (float) this.widthA < 0.0F)) {
if (this.field20932 > (float) Minecraft.getInstance().mainWindow.getWidth()) {
this.field20932 = (float) (0 - this.widthA);
}
} else {
this.field20932 = (float) Minecraft.getInstance().mainWindow.getWidth();
}
if (!(this.field20933 + (float) this.heightA < 0.0F)) {
if (this.field20933 > (float) Minecraft.getInstance().mainWindow.getHeight()) {
this.field20933 = (float) (0 - this.heightA);
}
} else {
this.field20933 = (float) Minecraft.getInstance().mainWindow.getHeight();
}
float var5 = (float) (newHeight - this.method13271());
float var6 = (float) (newWidth - this.method13272());
this.field20934 = (float) (1.0 - Math.sqrt((double) (var5 * var5 + var6 * var6)) / (double) this.field20938);
if (!(Math.sqrt((double) (var5 * var5 + var6 * var6)) < (double) this.field20938)) {
this.field20928 = this.field20928
- (this.field20928 - this.field20930) * 0.05F * JelloMainMenuScreen.field20982;
this.field20929 = this.field20929
- (this.field20929 - this.field20931) * 0.05F * JelloMainMenuScreen.field20982;
} else {
float var7 = this.field20932 - (float) newHeight;
float var8 = this.field20933 - (float) newWidth;
float var9 = (float) Math.sqrt((double) (var7 * var7 + var8 * var8));
float var10 = var9 / 2.0F;
float var11 = var7 / var10;
float var12 = var8 / var10;
this.field20928 = this.field20928 + var11 / (1.0F + this.field20934) * JelloMainMenuScreen.field20982;
this.field20929 = this.field20929 + var12 / (1.0F + this.field20934) * JelloMainMenuScreen.field20982;
}
this.field20936 = newHeight;
this.field20937 = newWidth;
}
@Override
public void draw(float partialTicks) {
float var4 = 0.07F;
float var5 = 0.3F;
RenderUtil.drawFilledArc(
(float) this.xA,
(float) this.yA,
(float) this.getWidthA(),
MultiUtilities.applyAlpha(ClientColors.LIGHT_GREYISH_BLUE.getColor(),
0.07F + (!(this.field20934 > 0.0F) ? 0.0F : this.field20934 * 0.3F)));
float var6 = (float) (this.field20936 - this.method13271());
float var7 = (float) (this.field20937 - this.method13272());
super.draw(partialTicks);
}
}
| 412 | 0.583293 | 1 | 0.583293 | game-dev | MEDIA | 0.878488 | game-dev | 0.641618 | 1 | 0.641618 |
facebookresearch/habitat-sim | 11,111 | src/esp/metadata/managers/ObjectAttributesManager.h | // Copyright (c) Meta Platforms, Inc. and its affiliates.
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
#ifndef ESP_METADATA_MANAGERS_OBJECTATTRIBUTEMANAGER_H_
#define ESP_METADATA_MANAGERS_OBJECTATTRIBUTEMANAGER_H_
#include <Corrade/Utility/Assert.h>
#include <utility>
#include "AbstractObjectAttributesManager.h"
#include "esp/metadata/attributes/ObjectAttributes.h"
namespace esp {
namespace metadata {
namespace managers {
/**
* @brief single instance class managing templates describing physical objects
*/
class ObjectAttributesManager
: public AbstractObjectAttributesManager<attributes::ObjectAttributes,
ManagedObjectAccess::Copy> {
public:
ObjectAttributesManager()
: AbstractObjectAttributesManager<attributes::ObjectAttributes,
ManagedObjectAccess::Copy>::
AbstractObjectAttributesManager("Object", "object_config.json") {
// build this manager's copy constructor map
this->copyConstructorMap_["ObjectAttributes"] =
&ObjectAttributesManager::createObjCopyCtorMapEntry<
attributes::ObjectAttributes>;
}
/**
* @brief Creates an instance of an object template described by passed
* string, which should be a reference to an existing primitive asset template
* to be used in the construction of the object (as render and collision
* mesh). It returns created instance if successful, and nullptr if fails.
*
* @param primAttrTemplateHandle The handle to an existing primitive asset
* template. Fails if does not.
* @param registerTemplate whether to add this template to the library.
* If the user is going to edit this template, this should be false - any
* subsequent editing will require re-registration. Defaults to true.
* @return a reference to the desired template, or nullptr if fails.
*/
attributes::ObjectAttributes::ptr createPrimBasedAttributesTemplate(
const std::string& primAttrTemplateHandle,
bool registerTemplate = true) override;
/**
* @brief Method to take an existing attributes and set its values from passed
* json config file.
* @param attribs (out) an existing attributes to be modified.
* @param jsonConfig json document to parse
*/
void setValsFromJSONDoc(attributes::ObjectAttributes::ptr attribs,
const io::JsonGenericValue& jsonConfig) override;
// ======== File-based and primitive-based partition functions ========
/**
* @brief Gets the number of file-based loaded object templates stored in the
* @ref physicsFileObjTmpltLibByID_.
*
* @return The number of entries in @ref physicsFileObjTmpltLibByID_ that are
* loaded from files.
*/
int getNumFileTemplateObjects() const {
return physicsFileObjTmpltLibByID_.size();
}
/**
* @brief Get a random loaded attribute handle for the loaded file-based
* object templates
*
* @return a randomly selected handle corresponding to a file-based object
* attributes template, or empty string if none loaded
*/
std::string getRandomFileTemplateHandle() const {
return this->getRandomObjectHandlePerType(physicsFileObjTmpltLibByID_,
"file-based ");
}
/**
* @brief Get a list of all file-based templates whose origin handles contain
* subStr, ignoring subStr's case
* @param subStr substring to search for within existing file-based object
* templates
* @param contains whether to search for keys containing, or not containing,
* subStr
* @param sorted whether the return vector values are sorted
* @return vector of 0 or more template handles containing the passed
* substring
*/
std::vector<std::string> getFileTemplateHandlesBySubstring(
const std::string& subStr = "",
bool contains = true,
bool sorted = true) const {
return this->getObjectHandlesBySubStringPerType(physicsFileObjTmpltLibByID_,
subStr, contains, sorted);
}
/**
* @brief Gets the number of synthesized (primitive-based) template objects
* stored in the @ref physicsSynthObjTmpltLibByID_.
*
* @return The number of entries in @ref physicsSynthObjTmpltLibByID_ that
* describe primitives.
*/
int getNumSynthTemplateObjects() const {
return physicsSynthObjTmpltLibByID_.size();
}
/**
* @brief Get a random loaded attribute handle for the loaded synthesized
* (primitive-based) object templates
*
* @return a randomly selected handle corresponding to the a primitive
* attributes template, or empty string if none loaded
*/
std::string getRandomSynthTemplateHandle() const {
return this->getRandomObjectHandlePerType(physicsSynthObjTmpltLibByID_,
"synthesized ");
}
/**
* @brief Get a list of all synthesized (primitive-based) object templates
* whose origin handles contain subStr, ignoring subStr's case
* @param subStr substring to search for within existing primitive object
* templates
* @param contains whether to search for keys containing, or not containing,
* subStr
* @param sorted whether the return vector values are sorted
* @return vector of 0 or more template handles containing the passed
* substring
*/
std::vector<std::string> getSynthTemplateHandlesBySubstring(
const std::string& subStr = "",
bool contains = true,
bool sorted = true) const {
return this->getObjectHandlesBySubStringPerType(
physicsSynthObjTmpltLibByID_, subStr, contains, sorted);
}
/**
* @brief This function will be called to finalize attributes' paths before
* registration, moving fully qualified paths to the appropriate hidden
* attribute fields. This can also be called without registration to make sure
* the paths specified in an attributes are properly configured.
* @param attributes The attributes to be filtered.
*/
void finalizeAttrPathsBeforeRegister(
const attributes::ObjectAttributes::ptr& attributes) const override;
// ======== End File-based and primitive-based partition functions ========
protected:
/**
* @brief Create and save default primitive asset-based object templates,
* saving their handles as non-deletable default handles.
*/
void createDefaultPrimBasedAttributesTemplates() override;
/**
* @brief Perform file-name-based attributes initialization. This is to
* take the place of the AssetInfo::fromPath functionality, and is only
* intended to provide default values and other help if certain mistakes
* are made by the user, such as specifying an asset handle in json but not
* specifying the asset type corresponding to that handle. These settings
* should not restrict anything, only provide defaults.
*
* @param attributes The AbstractObjectAttributes object to be configured
* @param setFrame whether the frame should be set or not (only for render
* assets in scenes)
* @param meshHandle Mesh Handle to check.
* @param assetTypeSetter Setter for mesh type.
*/
void setDefaultAssetNameBasedAttributes(
attributes::ObjectAttributes::ptr attributes,
bool setFrame,
const std::string& meshHandle,
const std::function<void(AssetType)>& assetTypeSetter) override;
/**
* @brief Used Internally. Create and configure newly-created attributes
* with any default values, before any specific values are set.
*
* @param handleName handle name to be assigned to attributes
* @param builtFromConfig Whether this object attributes is being
* constructed from a config file or from some other source.
* @return Newly created but unregistered ObjectAttributes pointer, with
* only default values set.
*/
attributes::ObjectAttributes::ptr initNewObjectInternal(
const std::string& handleName,
bool builtFromConfig) override;
/**
* @brief This method will perform any necessary updating that is
* AbstractAttributesManager-specific upon template removal, such as removing
* a specific template handle from the list of file-based template handles in
* ObjectAttributesManager. This should only be called @ref
* esp::core::managedContainers::ManagedContainerBase.
*
* @param templateID the ID of the template to remove
* @param templateHandle the string key of the attributes desired.
*/
void deleteObjectInternalFinalize(
int templateID,
CORRADE_UNUSED const std::string& templateHandle) override {
physicsFileObjTmpltLibByID_.erase(templateID);
physicsSynthObjTmpltLibByID_.erase(templateID);
}
/**
* @brief This method will perform any essential updating to the managed
* object before registration is performed. If this updating fails,
* registration will also fail.
*
* @param attributesTemplate The attributes template.
* @param attributesTemplateHandle The key for referencing the template in
* the
* @ref objectLibrary_. Will be set as origin handle for template.
* @param forceRegistration Will register object even if conditional
* registration checks fail.
* @return Whether the preregistration has succeeded and what handle to use to
* register the object if it has.
*/
core::managedContainers::ManagedObjectPreregistration
preRegisterObjectFinalize(
attributes::ObjectAttributes::ptr attributesTemplate,
const std::string& attributesTemplateHandle,
bool forceRegistration) override;
/**
* @brief This method will perform any final manager-related handling after
* successfully registering an object.
*
* @param objectID the ID of the successfully registered managed object
* @param objectHandle The name of the managed object
*/
void postRegisterObjectHandling(int objectID,
const std::string& objectHandle) override;
/**
* @brief Any object-attributes-specific resetting that needs to happen on
* reset.
*/
void resetFinalize() override {
physicsFileObjTmpltLibByID_.clear();
physicsSynthObjTmpltLibByID_.clear();
}
// ======== Typedefs and Instance Variables ========
// create a ref to the partition map of either prims or file-based objects to
// place a ref to the object template being regsitered during registration.
std::unordered_map<int, std::string>* mapToAddTo_ = nullptr;
/**
* @brief Maps loaded object template IDs to the appropriate template
* handles
*/
std::unordered_map<int, std::string> physicsFileObjTmpltLibByID_;
/**
* @brief Maps synthesized, primitive-based object template IDs to the
* appropriate template handles
*/
std::unordered_map<int, std::string> physicsSynthObjTmpltLibByID_;
public:
ESP_SMART_POINTERS(ObjectAttributesManager)
}; // ObjectAttributesManager
} // namespace managers
} // namespace metadata
} // namespace esp
#endif // ESP_METADATA_MANAGERS_OBJECTATTRIBUTEMANAGER_H_
| 412 | 0.947143 | 1 | 0.947143 | game-dev | MEDIA | 0.181577 | game-dev | 0.833009 | 1 | 0.833009 |
ModificationStation/StationAPI | 2,046 | station-world-events-v0/src/main/java/net/modificationstation/stationapi/mixin/world/ServerChunkCacheMixin.java | package net.modificationstation.stationapi.mixin.world;
import net.minecraft.class_326;
import net.minecraft.class_51;
import net.minecraft.world.World;
import net.modificationstation.stationapi.api.StationAPI;
import net.modificationstation.stationapi.api.event.world.gen.WorldGenEvent;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.util.Random;
@Mixin(class_326.class)
class ServerChunkCacheMixin {
@Shadow
private World field_1231;
@Shadow
private class_51 field_1227;
@Unique
private Random modRandom;
@Inject(
method = "method_1803",
at = @At(
value = "INVOKE",
target = "Lnet/minecraft/class_51;method_1803(Lnet/minecraft/class_51;II)V",
shift = At.Shift.AFTER
)
)
private void stationapi_onPopulate(class_51 worldSource, int chunkX, int chunkZ, CallbackInfo ci) {
int blockX = chunkX * 16;
int blockZ = chunkZ * 16;
if (modRandom == null)
modRandom = new Random();
modRandom.setSeed(field_1231.getSeed());
long xRandomMultiplier = (modRandom.nextLong() / 2L) * 2L + 1L;
long zRandomMultiplier = (modRandom.nextLong() / 2L) * 2L + 1L;
modRandom.setSeed((long) chunkX * xRandomMultiplier + (long) chunkZ * zRandomMultiplier ^ field_1231.getSeed());
StationAPI.EVENT_BUS.post(
WorldGenEvent.ChunkDecoration.builder()
.world(field_1231)
.worldSource(this.field_1227)
.biome(field_1231.method_1781().method_1787(blockX + 16, blockZ + 16))
.x(blockX).z(blockZ)
.random(modRandom)
.build()
);
}
}
| 412 | 0.740203 | 1 | 0.740203 | game-dev | MEDIA | 0.988267 | game-dev | 0.742186 | 1 | 0.742186 |
devs-immortal/Paradise-Lost | 4,373 | src/main/java/net/id/paradiselost/mixin/block/FlowerPotBlockMixin.java | package net.id.paradiselost.mixin.block;
import net.id.paradiselost.blocks.ParadiseLostBlocks;
import net.id.paradiselost.blocks.decorative.CalciteFlowerPotBlock;
import net.id.paradiselost.items.ParadiseLostItems;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.block.FlowerPotBlock;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.BlockItem;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.loot.context.LootContextParameterSet;
import net.minecraft.stat.Stats;
import net.minecraft.state.StateManager;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Hand;
import net.minecraft.util.ItemActionResult;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.event.GameEvent;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import java.util.List;
import java.util.Map;
@Mixin(FlowerPotBlock.class)
public abstract class FlowerPotBlockMixin extends Block {
@Final
@Shadow
private static Map<Block, Block> CONTENT_TO_POTTED;
@Shadow
protected abstract boolean isEmpty();
public FlowerPotBlockMixin(Settings settings) {
super(settings);
}
@Inject(method = "<init>", at = @At("TAIL"))
public void init(Block content, Settings settings, CallbackInfo ci) {
this.setDefaultState(this.getDefaultState().with(CalciteFlowerPotBlock.IS_CALCITE, false));
}
@Inject(method = "onUseWithItem", at = @At(value = "HEAD"), cancellable = true)
public void onUseWithItem(ItemStack stack, BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit, CallbackInfoReturnable<ItemActionResult> cir) {
if (state.isOf(ParadiseLostBlocks.CALCITE_FLOWER_POT)) {
BlockState blockState = (stack.getItem() instanceof BlockItem blockItem
? CONTENT_TO_POTTED.getOrDefault(blockItem.getBlock(), Blocks.AIR)
: Blocks.AIR)
.getDefaultState();
if (blockState.isAir()) {
cir.setReturnValue(ItemActionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION);
} else if (!this.isEmpty()) {
cir.setReturnValue(ItemActionResult.CONSUME);
} else {
world.setBlockState(pos, blockState.with(CalciteFlowerPotBlock.IS_CALCITE, true), Block.NOTIFY_ALL);
world.emitGameEvent(player, GameEvent.BLOCK_CHANGE, pos);
player.incrementStat(Stats.POT_FLOWER);
stack.decrementUnlessCreative(1, player);
cir.setReturnValue(ItemActionResult.success(world.isClient));
}
cir.cancel();
}
}
@Inject(method = "onUse", at = @At(value = "RETURN"))
public void onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, BlockHitResult hit, CallbackInfoReturnable<ActionResult> cir) {
if (!this.isEmpty() && state.get(CalciteFlowerPotBlock.IS_CALCITE)) {
world.setBlockState(pos, ParadiseLostBlocks.CALCITE_FLOWER_POT.getDefaultState(), Block.NOTIFY_ALL);
}
}
@Override
protected List<ItemStack> getDroppedStacks(BlockState state, LootContextParameterSet.Builder builder) {
var drops = super.getDroppedStacks(state, builder);
if (state.get(CalciteFlowerPotBlock.IS_CALCITE)) {
return drops.stream().map(itemStack -> {
if (itemStack.isOf(Items.FLOWER_POT)) {
return new ItemStack(ParadiseLostItems.CALCITE_FLOWER_POT, itemStack.getCount());
} else {
return itemStack;
}
}).toList();
} else {
return drops;
}
}
@Override
protected void appendProperties(StateManager.Builder<Block, BlockState> builder) {
builder.add(CalciteFlowerPotBlock.IS_CALCITE);
}
}
| 412 | 0.919782 | 1 | 0.919782 | game-dev | MEDIA | 0.996286 | game-dev | 0.975486 | 1 | 0.975486 |
DBloodworth95/packet-updater | 3,995 | nonfree/gamepacks/225/px.java | import java.util.Locale;
@pi
@nh
public class px implements ps {
static final px af;
static final px ae;
public static final px ag;
public static final px ac;
static final px ax;
public static final px aq;
static final px am;
public static final int ad = 1;
final int ar;
final String au;
static final px[] al;
static String ce;
final String at;
static final int bn = 1;
static final String ao = ",";
static px[] ar() {
return new px[]{af, ac, ag, aq, am, ax, ae};
}
public String toString() {
try {
return this.aq(-1280956978).toLowerCase(Locale.ENGLISH);
} catch (RuntimeException var1) {
throw vk.ae(var1, "px.toString(" + ')');
}
}
String aq(int var1) {
try {
return this.au;
} catch (RuntimeException var2) {
throw vk.ae(var2, "px.aq(" + ')');
}
}
public int ac(int var1) {
try {
return 1433910639 * this.ar;
} catch (RuntimeException var2) {
throw vk.ae(var2, "px.ac(" + ')');
}
}
public static px af(int var0, int var1) {
try {
if (var0 >= 0) {
if (var0 < al.length) {
return al[var0];
}
if (var1 <= 1819017324) {
throw new IllegalStateException();
}
}
return null;
} catch (RuntimeException var2) {
throw vk.ae(var2, "px.af(" + ')');
}
}
public static px aa(int var0) {
return var0 >= 0 && var0 < al.length ? al[var0] : null;
}
static px[] al() {
return new px[]{af, ac, ag, aq, am, ax, ae};
}
public int ae() {
return 1433910639 * this.ar;
}
public int ag() {
return 1433910639 * this.ar;
}
static px[] ax(int var0) {
try {
return new px[]{af, ac, ag, aq, am, ax, ae};
} catch (RuntimeException var1) {
throw vk.ae(var1, "px.ax(" + ')');
}
}
public int am() {
return 1433910639 * this.ar;
}
public String amp() {
return this.aq(-1414792767).toLowerCase(Locale.ENGLISH);
}
public String ame() {
return this.aq(141351781).toLowerCase(Locale.ENGLISH);
}
static px[] at() {
return new px[]{af, ac, ag, aq, am, ax, ae};
}
static px[] au() {
return new px[]{af, ac, ag, aq, am, ax, ae};
}
px(String var1, String var2, String var3, pc var4, int var5, String var6) {
try {
super();
this.at = var1;
this.au = var2;
this.ar = 1530675599 * var5;
if (var6 != null) {
new Locale(var2.substring(0, 2), var6);
} else {
new Locale(var2.substring(0, 2));
}
} catch (RuntimeException var7) {
throw vk.ae(var7, "px.<init>(" + ')');
}
}
public String aml() {
return this.aq(271209032).toLowerCase(Locale.ENGLISH);
}
String ad() {
return this.au;
}
String ah() {
return this.au;
}
String ap() {
return this.au;
}
String ab() {
return this.au;
}
public static px az(int var0) {
return var0 >= 0 && var0 < al.length ? al[var0] : null;
}
static {
ac = new px("EN", "en", "English", pc.ac, 0, "GB");
ae = new px("DE", "de", "German", pc.ac, 1, "DE");
ag = new px("FR", "fr", "French", pc.ac, 2, "FR");
am = new px("PT", "pt", "Portuguese", pc.ac, 3, "BR");
ax = new px("NL", "nl", "Dutch", pc.am, 4, "NL");
aq = new px("ES", "es", "Spanish", pc.am, 5, "ES");
af = new px("ES_MX", "es-mx", "Spanish (Latin American)", pc.ac, 6, "MX");
px[] var0 = ax(-419870162);
al = new px[var0.length];
px[] var1 = var0;
for(int var2 = 0; var2 < var1.length; ++var2) {
px var3 = var1[var2];
if (null != al[1433910639 * var3.ar]) {
throw new IllegalStateException();
}
al[var3.ar * 1433910639] = var3;
}
}
}
| 412 | 0.795097 | 1 | 0.795097 | game-dev | MEDIA | 0.582255 | game-dev,networking | 0.820041 | 1 | 0.820041 |
InertSteak/Pokermon | 15,253 | pokemon/pokejokers_18.lua | -- Pansage 511
local pansage = {
name = "pansage",
pos = { x = 3, y = 1 },
config = { extra = {} },
loc_vars = function(self, info_queue, card)
type_tooltip(self, info_queue, card)
info_queue[#info_queue + 1] = { set = 'Joker', key = 'j_shortcut', config = {} }
info_queue[#info_queue + 1] = G.P_CENTERS.c_poke_leafstone
return { vars = {} }
end,
rarity = 2,
cost = 5,
stage = "Basic",
ptype = "Grass",
atlas = "Pokedex5",
gen = 5,
item_req = "leafstone",
blueprint_compat = false,
calculate = function(self, card, context)
return item_evo(self, card, context, "j_poke_simisage")
end,
}
-- Simisage 512
local simisage = {
name = "simisage",
pos = { x = 4, y = 1 },
config = { extra = { num = 1, dem = 3 } },
loc_vars = function(self, info_queue, card)
type_tooltip(self, info_queue, card)
info_queue[#info_queue + 1] = { set = 'Joker', key = 'j_shortcut', config = {} }
info_queue[#info_queue + 1] = G.P_CENTERS.m_lucky
local num, dem = SMODS.get_probability_vars(card, card.ability.extra.num, card.ability.extra.dem, 'simisage')
return { vars = { num, dem } }
end,
rarity = 'poke_safari',
cost = 8,
stage = "One",
ptype = "Grass",
atlas = "Pokedex5",
gen = 5,
blueprint_compat = false,
calculate = function(self, card, context)
if context.before and context.cardarea == G.jokers and not context.blueprint then
local stall_for_effects = false
for _, v in ipairs(context.full_hand) do
if v.config.center == G.P_CENTERS.c_base then
if SMODS.pseudorandom_probability(card, 'simisage', card.ability.extra.num, card.ability.extra.dem, 'simisage') then
stall_for_effects = true
v:set_ability(G.P_CENTERS.m_lucky, nil, true)
G.E_MANAGER:add_event(Event({
func = function()
v:juice_up()
return true
end
}))
end
end
end
if stall_for_effects then
return {
message = localize('k_upgrade_ex'),
colour = G.C.GREEN
}
end
end
end,
}
-- Pansear 513
local pansear = {
name = "pansear",
pos = { x = 5, y = 1 },
config = { extra = {} },
loc_vars = function(self, info_queue, card)
type_tooltip(self, info_queue, card)
info_queue[#info_queue + 1] = { set = 'Joker', key = 'j_four_fingers', config = {} }
info_queue[#info_queue + 1] = G.P_CENTERS.c_poke_firestone
return { vars = {} }
end,
rarity = 2,
cost = 5,
stage = "Basic",
ptype = "Fire",
atlas = "Pokedex5",
gen = 5,
item_req = "firestone",
blueprint_compat = false,
calculate = function(self, card, context)
return item_evo(self, card, context, "j_poke_simisear")
end,
}
-- Simisear 514
local simisear = {
name = "simisear",
pos = { x = 6, y = 1 },
config = { extra = { destroy = false} },
loc_vars = function(self, info_queue, card)
type_tooltip(self, info_queue, card)
info_queue[#info_queue + 1] = { set = 'Joker', key = 'j_four_fingers', config = {} }
info_queue[#info_queue + 1] = G.P_CENTERS.c_empress
local active = G.GAME and G.GAME.current_round and G.GAME.current_round.hands_played == 0
return { vars = {active and "("..localize('k_active_ex')..")" or '' } }
end,
rarity = 'poke_safari',
cost = 8,
stage = "One",
ptype = "Fire",
atlas = "Pokedex5",
gen = 5,
blueprint_compat = false,
calculate = function(self, card, context)
if context.first_hand_drawn then
local eval = function() return G.GAME.current_round.hands_played == 0 end
juice_card_until(card, eval, true)
end
if context.cardarea == G.jokers and context.scoring_hand then
if context.joker_main and (next(context.poker_hands['Straight']) or next(context.poker_hands['Flush'])) and G.GAME.current_round.hands_played == 0 then
card.ability.extra.destroy = true
if #G.consumeables.cards + G.GAME.consumeable_buffer < G.consumeables.config.card_limit then
G.GAME.consumeable_buffer = G.GAME.consumeable_buffer + 1
return {
extra = {focus = card, message = localize('k_plus_tarot'), colour = G.C.PURPLE, func = function()
G.E_MANAGER:add_event(Event({
trigger = 'before',
delay = 0.0,
func = function()
local card_type = 'Tarot'
local _card = create_card(card_type,G.consumeables, nil, nil, nil, nil, "c_empress")
_card:add_to_deck()
G.consumeables:emplace(_card)
G.GAME.consumeable_buffer = 0
return true
end
}))
end},
}
end
end
if context.after and card.ability.extra.destroy and not context.blueprint then
card.ability.extra.destroy = nil
for k, v in pairs(context.full_hand) do
if not SMODS.in_scoring(v, context.scoring_hand) then
poke_remove_card(v, card)
end
end
end
end
end,
}
-- Panpour 515
local panpour = {
name = "panpour",
pos = { x = 7, y = 1 },
config = { extra = {} },
loc_vars = function(self, info_queue, card)
type_tooltip(self, info_queue, card)
info_queue[#info_queue + 1] = { set = 'Joker', key = 'j_pareidolia', config = {} }
info_queue[#info_queue + 1] = G.P_CENTERS.c_poke_waterstone
return { vars = {} }
end,
rarity = 2,
cost = 5,
stage = "Basic",
ptype = "Water",
atlas = "Pokedex5",
gen = 5,
item_req = "waterstone",
blueprint_compat = false,
calculate = function(self, card, context)
return item_evo(self, card, context, "j_poke_simipour")
end,
}
-- Simipour 516
local simipour = {
name = "simipour",
pos = { x = 8, y = 1 },
config = { extra = {} },
loc_vars = function(self, info_queue, card)
type_tooltip(self, info_queue, card)
info_queue[#info_queue + 1] = { set = 'Joker', key = 'j_pareidolia', config = {} }
info_queue[#info_queue + 1] = G.P_CENTERS.m_bonus
return { vars = {} }
end,
rarity = 'poke_safari',
cost = 8,
stage = "One",
ptype = "Water",
atlas = "Pokedex5",
gen = 5,
blueprint_compat = false,
calculate = function(self, card, context)
if context.before and context.cardarea == G.jokers and not context.blueprint then
local lowest_card = nil
for _, v in ipairs(context.full_hand) do
if v.config.center == G.P_CENTERS.c_base then
if not lowest_card then
lowest_card = v
elseif v.base.nominal < lowest_card.base.nominal then
lowest_card = v
end
end
end
if lowest_card then
lowest_card:set_ability(G.P_CENTERS.m_bonus, nil, true)
G.E_MANAGER:add_event(Event({
func = function()
lowest_card:juice_up()
return true
end
}))
end
end
end,
}
-- Munna 517
-- Musharna 518
-- Pidove 519
-- Tranquill 520
-- Unfezant 521
-- Blitzle 522
-- Zebstrika 523
-- Roggenrola 524
local roggenrola = {
name = "roggenrola",
pos = {x = 2, y = 2},
config = {extra = {hazards = 4, mult_mod = 4, hazard_triggered = 0}, evo_rqmt = 25},
loc_vars = function(self, info_queue, card)
type_tooltip(self, info_queue, card)
-- just to shorten function
local abbr = card.ability.extra
info_queue[#info_queue+1] = {set = 'Other', key = 'poke_hazards', vars = {abbr.hazards}}
info_queue[#info_queue+1] = G.P_CENTERS.m_poke_hazard
return {vars = {abbr.hazards, abbr.mult_mod, math.max(0, self.config.evo_rqmt - abbr.hazard_triggered)}}
end,
rarity = 1,
cost = 4,
stage = "Basic",
ptype = "Earth",
atlas = "Pokedex5",
gen = 5,
hazard_poke = true,
blueprint_compat = true,
calculate = function(self, card, context)
if context.setting_blind then
poke_set_hazards(card.ability.extra.hazards)
end
if context.individual and not context.end_of_round and context.cardarea == G.hand and SMODS.has_no_rank(context.other_card) then
if context.other_card.debuff then
return {
message = localize('k_debuffed'),
colour = G.C.RED,
card = card,
}
else
if not context.blueprint then
card.ability.extra.hazard_triggered = card.ability.extra.hazard_triggered + 1
end
return {
h_mult = card.ability.extra.mult_mod,
card = card
}
end
end
return scaling_evo(self, card, context, "j_poke_boldore", card.ability.extra.hazard_triggered, self.config.evo_rqmt)
end,
}
-- Boldore 525
local boldore = {
name = "boldore",
pos = {x = 3, y = 2},
config = {extra = {hazards = 4, mult_mod = 8}},
loc_vars = function(self, info_queue, card)
type_tooltip(self, info_queue, card)
-- just to shorten function
local abbr = card.ability.extra
info_queue[#info_queue+1] = {set = 'Other', key = 'poke_hazards', vars = {abbr.hazards}}
info_queue[#info_queue+1] = G.P_CENTERS.m_poke_hazard
if pokermon_config.detailed_tooltips then
info_queue[#info_queue+1] = G.P_CENTERS.c_poke_linkcable
end
return {vars = {abbr.hazards, abbr.mult_mod}}
end,
rarity = 2,
cost = 6,
stage = "One",
ptype = "Earth",
atlas = "Pokedex5",
gen = 5,
item_req = "linkcable",
hazard_poke = true,
blueprint_compat = true,
calculate = function(self, card, context)
if context.setting_blind then
poke_set_hazards(card.ability.extra.hazards)
end
if context.individual and not context.end_of_round and context.cardarea == G.hand and SMODS.has_no_rank(context.other_card) then
if context.other_card.debuff then
return {
message = localize('k_debuffed'),
colour = G.C.RED,
card = card,
}
else
return {
h_mult = card.ability.extra.mult_mod,
card = card
}
end
end
return item_evo(self, card, context, "j_poke_gigalith")
end,
}
-- Gigalith 526
local gigalith = {
name = "gigalith",
pos = {x = 4, y = 2},
config = {extra = {hazards = 4, mult_mod = 6, retriggers = 1}},
loc_vars = function(self, info_queue, card)
type_tooltip(self, info_queue, card)
-- just to shorten function
local abbr = card.ability.extra
info_queue[#info_queue+1] = {set = 'Other', key = 'poke_hazards', vars = {abbr.hazards}}
info_queue[#info_queue+1] = G.P_CENTERS.m_poke_hazard
return {vars = {abbr.hazards, abbr.mult_mod}}
end,
rarity = 'poke_safari',
cost = 10,
stage = "Two",
ptype = "Earth",
atlas = "Pokedex5",
gen = 5,
blueprint_compat = true,
hazard_poke = true,
calculate = function(self, card, context)
if context.setting_blind then
poke_set_hazards(card.ability.extra.hazards)
end
if context.individual and not context.end_of_round and context.cardarea == G.hand and SMODS.has_no_rank(context.other_card) then
if context.other_card.debuff then
return {
message = localize('k_debuffed'),
colour = G.C.RED,
card = card,
}
else
return {
h_mult = card.ability.extra.mult_mod,
card = card
}
end
end
if context.repetition and context.cardarea == G.hand and (next(context.card_effects[1]) or #context.card_effects > 1) and SMODS.has_no_rank(context.other_card) then
return {
message = localize('k_again_ex'),
repetitions = card.ability.extra.retriggers,
card = card
}
end
end,
}
-- Woobat 527
-- Swoobat 528
-- Drilbur 529
local drilbur={
name = "drilbur",
pos = {x = 0, y = 0},
config = {extra = {active = true, stones_destroyed = 0}, evo_rqmt = 4},
loc_vars = function(self, info_queue, center)
type_tooltip(self, info_queue, center)
info_queue[#info_queue+1] = {set = 'Other', key = 'dril_treasure'}
return {vars = {math.max(0, self.config.evo_rqmt - center.ability.extra.stones_destroyed)}}
end,
rarity = 1,
cost = 4,
gen = 5,
enhancement_gate = "m_stone",
stage = "Basic",
ptype = "Earth",
atlas = "Pokedex5",
perishable_compat = true,
blueprint_compat = false,
eternal_compat = true,
calculate = function(self, card, context)
if context.first_hand_drawn and not context.blueprint then
local eval = function(card) return card.ability.extra.active and not G.RESET_JIGGLES end
juice_card_until(card, eval, true)
end
if context.destroying_card then
if not context.blueprint and SMODS.has_enhancement(context.destroying_card, 'm_stone') and card.ability.extra.active then
card.ability.extra.active = false
card.ability.extra.stones_destroyed = card.ability.extra.stones_destroyed + 1
card_eval_status_text(card, 'extra', nil, nil, nil, {message = localize('poke_drill_ex'), colour = G.ARGS.LOC_COLOURS.earth})
poke_create_treasure(card, 'drilbur')
return true
end
end
if context.end_of_round and not context.individual and not context.repetition and not context.blueprint then
card.ability.extra.active = true
end
return scaling_evo(self, card, context, "j_poke_excadrill", card.ability.extra.stones_destroyed, self.config.evo_rqmt)
end,
}
-- Excadrill 530
local excadrill={
name = "excadrill",
pos = {x = 0, y = 0},
config = {extra = {mult_mod = 2},},
loc_vars = function(self, info_queue, center)
type_tooltip(self, info_queue, center)
info_queue[#info_queue+1] = {set = 'Other', key = 'exdril_treasure'}
return {vars = {center.ability.extra.mult_mod, G.GAME.starting_deck_size,
math.max(0, center.ability.extra.mult_mod * (G.playing_cards and (G.GAME.starting_deck_size - #G.playing_cards) or 0))}}
end,
rarity = "poke_safari",
cost = 7,
gen = 5,
stage = "One",
ptype = "Earth",
atlas = "Pokedex5",
perishable_compat = true,
blueprint_compat = true,
eternal_compat = true,
calculate = function(self, card, context)
if context.cardarea == G.jokers and context.scoring_hand then
if context.joker_main then
local Mult = math.max(0, card.ability.extra.mult_mod * (G.GAME.starting_deck_size - #G.playing_cards))
if Mult > 0 then
return {
message = localize{type = 'variable', key = 'a_mult', vars = {Mult}},
colour = G.C.MULT,
mult_mod = Mult
}
end
end
end
if context.destroying_card then
if not context.blueprint and SMODS.has_enhancement(context.destroying_card, 'm_stone') then
card_eval_status_text(card, 'extra', nil, nil, nil, {message = localize('poke_drill_ex'), colour = G.ARGS.LOC_COLOURS.earth})
poke_create_treasure(card, 'excadril', true)
return true
end
end
end,
}
-- Audino 531
-- Timburr 532
-- Gurdurr 533
-- Conkeldurr 534
-- Tympole 535
-- Palpitoad 536
-- Seismitoad 537
-- Throh 538
-- Sawk 539
-- Sewaddle 540
return {
name = "Pokemon Jokers 511-540",
list = {pansage, simisage, pansear, simisear, panpour, simipour, roggenrola, boldore, gigalith, drilbur, excadrill },
}
| 412 | 0.972901 | 1 | 0.972901 | game-dev | MEDIA | 0.968581 | game-dev | 0.941522 | 1 | 0.941522 |
disruptor-net/Disruptor-net | 1,226 | src/Disruptor.Tests/IsValueRingBuffer.cs | using System;
using System.Linq;
using NUnit.Framework.Constraints;
namespace Disruptor.Tests;
public static class IsValueRingBuffer
{
public static Constraint WithEvents<T>(params T[] values)
where T : struct, IEquatable<T>
{
return new HasEventsConstraint<T>(values);
}
private class HasEventsConstraint<T> : Constraint
where T : struct, IEquatable<T>
{
private readonly T[] _values;
public HasEventsConstraint(T[] values)
{
_values = values;
}
public override string Description => $"ValueRingBuffer with events: {string.Join(" ", _values.Select(x => "{" + x + "}"))}";
public override ConstraintResult ApplyTo<TActual>(TActual actual)
{
if (actual is IValueDataProvider<T> ringBuffer)
{
var valid = true;
for (var i = 0; i < _values.Length; i++)
{
var value = _values[i];
valid &= value.Equals(ringBuffer[i]);
}
return new ConstraintResult(this, actual, valid);
}
return new ConstraintResult(this, actual, false);
}
}
}
| 412 | 0.724574 | 1 | 0.724574 | game-dev | MEDIA | 0.349628 | game-dev | 0.732945 | 1 | 0.732945 |
CreativeMD/CreativeCore | 31,545 | src/main/java/team/creative/creativecore/common/config/converation/ConfigTypeConveration.java | package team.creative.creativecore.common.config.converation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.neoforged.api.distmarker.Dist;
import net.neoforged.api.distmarker.OnlyIn;
import team.creative.creativecore.Side;
import team.creative.creativecore.common.config.api.CreativeConfig;
import team.creative.creativecore.common.config.converation.registry.ConfigTypeRegistryObject;
import team.creative.creativecore.common.config.converation.registry.ConfigTypeRegistryObjectList;
import team.creative.creativecore.common.config.converation.registry.ConfigTypeRegistryTag;
import team.creative.creativecore.common.config.converation.registry.ConfigTypeRegistryTagList;
import team.creative.creativecore.common.config.core.ICreativeRegistry;
import team.creative.creativecore.common.config.field.ConfigField;
import team.creative.creativecore.common.config.gui.IGuiConfigParent;
import team.creative.creativecore.common.config.holder.ICreativeConfigHolder;
import team.creative.creativecore.common.config.key.ConfigKey;
import team.creative.creativecore.common.config.premade.MobEffectConfig;
import team.creative.creativecore.common.config.premade.NamedList;
import team.creative.creativecore.common.config.premade.Permission;
import team.creative.creativecore.common.config.premade.SelectableConfig;
import team.creative.creativecore.common.config.premade.SoundConfig;
import team.creative.creativecore.common.config.premade.ToggleableConfig;
import team.creative.creativecore.common.config.premade.registry.RegistryObjectConfig;
import team.creative.creativecore.common.config.premade.registry.RegistryObjectListConfig;
import team.creative.creativecore.common.config.premade.registry.RegistryTagConfig;
import team.creative.creativecore.common.config.premade.registry.RegistryTagListConfig;
import team.creative.creativecore.common.config.sync.ConfigSynchronization;
import team.creative.creativecore.common.gui.GuiParent;
import team.creative.creativecore.common.gui.control.collection.GuiComboBox;
import team.creative.creativecore.common.gui.control.simple.GuiLabel;
import team.creative.creativecore.common.gui.control.simple.GuiSlider;
import team.creative.creativecore.common.gui.control.simple.GuiTextfield;
import team.creative.creativecore.common.gui.flow.GuiFlow;
import team.creative.creativecore.common.util.math.matrix.IntMatrix3;
import team.creative.creativecore.common.util.math.matrix.IntMatrix3c;
import team.creative.creativecore.common.util.text.TextMapBuilder;
import team.creative.creativecore.common.util.type.list.PairList;
public abstract class ConfigTypeConveration<T> {
private static final HashMap<Class, Function<ConfigField, ?>> TYPE_CREATORS = new HashMap<>();
private static final HashMap<Class, Function<ConfigField, Type>> TYPE_GETTERS = new HashMap<>();
private static final HashMap<Class, Function<ConfigField, ?>> COLLECTION_CREATORS = new HashMap<>();
private static final HashMap<Class, ConfigTypeConveration> TYPES = new HashMap<>();
private static final PairList<Predicate<Class>, ConfigTypeConveration> SPECIAL_TYPES = new PairList<>();
public static final ICreativeConfigHolder FAKE_PARENT = new ICreativeConfigHolder() {
@Override
public ConfigSynchronization synchronization() {
return ConfigSynchronization.UNIVERSAL;
}
@Override
public JsonObject save(HolderLookup.Provider provider, boolean saveDefault, boolean ignoreRestart, Side side) {
return null;
}
@Override
public void restoreDefault(Side side, boolean ignoreRestart) {}
@Override
public String[] path() {
return new String[0];
}
@Override
public ICreativeConfigHolder parent() {
return null;
}
@Override
public Collection<String> names() {
return null;
}
@Override
public void load(HolderLookup.Provider provider, boolean loadDefault, boolean ignoreRestart, JsonObject json, Side side) {}
@Override
public boolean isEmptyWithoutForce(Side side) {
return false;
}
@Override
public boolean isEmpty(Side side) {
return false;
}
@Override
public boolean isDefault(Side side) {
return false;
}
@Override
public ConfigKey getField(String key) {
return null;
}
@Override
public Object get(String key) {
return null;
}
@Override
public Collection<? extends ConfigKey> fields() {
return null;
}
@Override
public void configured(Side side) {}
@Override
public ICreativeRegistry getRegistry() {
throw new UnsupportedOperationException("This fake parent should never be used to get the registry");
}
};
public static boolean isTypeCreator(Class clazz) {
return TYPE_CREATORS.containsKey(clazz);
}
public static <T, U extends T> void registerTypeCreator(Class<U> clazz, Function<ConfigField, T> type) {
TYPE_CREATORS.put(clazz, type);
}
public static <T, U extends T> void registerTypeCreator(Class<U> clazz, Supplier<T> type) {
TYPE_CREATORS.put(clazz, x -> type.get());
}
public static void registerTypeGetter(Class clazz, Function<ConfigField, Type> getter) {
TYPE_GETTERS.put(clazz, getter);
}
public static <T, U extends T> void registerCollectionCreator(Class<U> clazz, Function<ConfigField, T> getter) {
COLLECTION_CREATORS.put(clazz, getter);
}
public static <T, U extends T> ConfigTypeConveration<T> registerType(Class<U> clazz, ConfigTypeConveration<T> type) {
TYPES.put(clazz, type);
return type;
}
public static <T> void registerTypes(ConfigTypeConveration<T> type, Class<? extends T>... classes) {
for (int i = 0; i < classes.length; i++)
TYPES.put(classes[i], type);
}
public static void registerSpecialType(Predicate<Class> predicate, ConfigTypeConveration type) {
SPECIAL_TYPES.add(predicate, type);
}
public static boolean has(Class typeClass) {
if (TYPES.containsKey(typeClass))
return true;
if (typeClass.isAnnotationPresent(CreativeConfig.class))
return false;
for (int i = 0; i < SPECIAL_TYPES.size(); i++)
if (SPECIAL_TYPES.get(i).key.test(typeClass))
return true;
return false;
}
public static ConfigTypeConveration get(Class typeClass) {
ConfigTypeConveration converation = TYPES.get(typeClass);
if (converation != null)
return converation;
for (int i = 0; i < SPECIAL_TYPES.size(); i++)
if (SPECIAL_TYPES.get(i).key.test(typeClass))
return SPECIAL_TYPES.get(i).value;
throw new RuntimeException("Could not find converation for " + typeClass.getName());
}
public static ConfigTypeConveration getUnsafe(Class typeClass) {
ConfigTypeConveration converation = TYPES.get(typeClass);
if (converation != null)
return converation;
for (int i = 0; i < SPECIAL_TYPES.size(); i++)
if (SPECIAL_TYPES.get(i).key.test(typeClass))
return SPECIAL_TYPES.get(i).value;
return null;
}
public static Object createObject(ConfigField field) {
Function func = TYPE_CREATORS.get(field.getType());
if (func != null)
return func.apply(field);
try {
return field.getType().getConstructor().newInstance();
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {}
return null;
}
public static Type getGenericType(ConfigField field) {
Function<ConfigField, Type> func = TYPE_GETTERS.get(field.getType());
if (func != null)
return func.apply(field);
Type type = field.getGenericType();
if (type instanceof Class)
return type;
if (type instanceof ParameterizedType p)
return p.getActualTypeArguments()[0];
throw new UnsupportedOperationException("This type is not supported " + type);
}
public static Type getGenericType(ConfigKey key) {
return getGenericType(key.field());
}
public static Object createCollection(ConfigField field) {
Function func = COLLECTION_CREATORS.get(field.getType());
if (func != null)
return func.apply(field);
return null;
}
public static Object createCollection(ConfigKey key) {
return createCollection(key.field());
}
static {
ConfigTypeNumber.init();
registerType(String.class, new SimpleConfigTypeConveration<String>() {
@Override
public String readElement(ConfigKey key, String defaultValue, Side side, JsonElement element) {
if (element.isJsonPrimitive() && ((JsonPrimitive) element).isString())
return element.getAsString();
return defaultValue;
}
@Override
public JsonElement writeElement(String value, ConfigKey key, Side side) {
return new JsonPrimitive(value);
}
@Override
@Environment(EnvType.CLIENT)
@OnlyIn(Dist.CLIENT)
public void createControls(GuiParent parent, ConfigKey key) {
parent.add(new GuiTextfield("data").setDim(30, 8).setExpandableX());
}
@Override
@Environment(EnvType.CLIENT)
@OnlyIn(Dist.CLIENT)
public void loadValue(String value, GuiParent parent) {
GuiTextfield button = parent.get("data");
button.setText(value);
}
@Override
@Environment(EnvType.CLIENT)
@OnlyIn(Dist.CLIENT)
protected String saveValue(GuiParent parent, ConfigKey key) {
GuiTextfield button = parent.get("data");
return button.getText();
}
@Override
public String set(ConfigKey key, String value) {
return value;
}
});
registerTypeCreator(String.class, () -> "");
registerType(ResourceLocation.class, new SimpleConfigTypeConveration<>() {
@Override
public ResourceLocation readElement(ConfigKey key, ResourceLocation defaultValue, Side side, JsonElement element) {
if (element.isJsonPrimitive() && ((JsonPrimitive) element).isString())
return ResourceLocation.parse(element.getAsString());
return defaultValue;
}
@Override
public JsonElement writeElement(ResourceLocation value, ConfigKey key, Side side) {
return new JsonPrimitive(value.toString());
}
@Override
@Environment(EnvType.CLIENT)
@OnlyIn(Dist.CLIENT)
public void createControls(GuiParent parent, ConfigKey key) {
parent.add(new GuiTextfield("data").setDim(30, 8).setExpandableX());
}
@Override
@Environment(EnvType.CLIENT)
@OnlyIn(Dist.CLIENT)
public void loadValue(ResourceLocation value, GuiParent parent) {
GuiTextfield button = parent.get("data");
button.setText(value.toString());
}
@Override
@Environment(EnvType.CLIENT)
@OnlyIn(Dist.CLIENT)
protected ResourceLocation saveValue(GuiParent parent, ConfigKey key) {
GuiTextfield button = parent.get("data");
return ResourceLocation.parse(button.getText());
}
@Override
public ResourceLocation set(ConfigKey key, ResourceLocation value) {
return value;
}
});
registerTypeCreator(ResourceLocation.class, () -> ResourceLocation.withDefaultNamespace(""));
registerType(SoundConfig.class, new ConfigTypeConveration<SoundConfig>() {
@Override
public SoundConfig readElement(HolderLookup.Provider provider, SoundConfig defaultValue, boolean loadDefault, boolean ignoreRestart, JsonElement element, Side side,
ConfigKey key) {
if (element.isJsonObject())
return new SoundConfig(ResourceLocation.parse(element.getAsJsonObject().get("sound").getAsString()), element.getAsJsonObject().get("volume")
.getAsFloat(), element.getAsJsonObject().get("pitch").getAsFloat());
return defaultValue;
}
@Override
public JsonElement writeElement(HolderLookup.Provider provider, SoundConfig value, boolean saveDefault, boolean ignoreRestart, Side side, ConfigKey key) {
JsonObject json = new JsonObject();
json.addProperty("sound", value.event.toString());
json.addProperty("volume", value.volume);
json.addProperty("pitch", value.pitch);
return json;
}
@Override
@Environment(EnvType.CLIENT)
@OnlyIn(Dist.CLIENT)
public void createControls(GuiParent parent, IGuiConfigParent configParent, ConfigKey key, Side side) {
parent.flow = GuiFlow.STACK_Y;
parent.add(new GuiComboBox<>("sound", new TextMapBuilder<ResourceLocation>().addComponent(BuiltInRegistries.SOUND_EVENT.keySet(), x -> {
if (x.getNamespace().equals(ResourceLocation.DEFAULT_NAMESPACE))
return Component.literal(x.getPath());
return Component.literal(x.toString());
})).setSearchbar(true));
GuiParent hBox = new GuiParent(GuiFlow.STACK_X).add(new GuiLabel("volumeLabel").setTranslate("gui.volume")).add(new GuiSlider("volume", 1, 0, 1).setDim(40, 10))
.add(new GuiLabel("pitchLabel").setTranslate("gui.pitch")).add(new GuiSlider("pitch", 1, 0.5, 2).setDim(40, 10));
parent.add(hBox);
}
@Override
@Environment(EnvType.CLIENT)
@OnlyIn(Dist.CLIENT)
public void loadValue(SoundConfig value, SoundConfig defaultValue, GuiParent parent, IGuiConfigParent configParent, ConfigKey key, Side side) {
GuiComboBox<ResourceLocation> box = parent.get("sound");
GuiSlider volume = parent.get("volume");
GuiSlider pitch = parent.get("pitch");
box.select(value.event);
volume.setValue(value.volume);
pitch.setValue(value.pitch);
}
@Override
@Environment(EnvType.CLIENT)
@OnlyIn(Dist.CLIENT)
protected SoundConfig saveValue(GuiParent parent, IGuiConfigParent configParent, ConfigKey key, Side side) {
GuiComboBox<ResourceLocation> box = parent.get("sound");
GuiSlider volume = parent.get("volume");
GuiSlider pitch = parent.get("pitch");
return new SoundConfig(box.selected(), (float) volume.getValue(), (float) pitch.getValue());
}
@Override
public SoundConfig set(ConfigKey key, SoundConfig value) {
return value;
}
});
registerTypeCreator(SoundConfig.class, () -> new SoundConfig(ResourceLocation.withDefaultNamespace("missing")));
registerType(RegistryObjectConfig.class, new ConfigTypeRegistryObject());
registerType(RegistryObjectListConfig.class, new ConfigTypeRegistryObjectList());
registerType(RegistryTagConfig.class, new ConfigTypeRegistryTag());
registerType(RegistryTagListConfig.class, new ConfigTypeRegistryTagList());
registerType(SelectableConfig.class, new ConfigTypeConveration<SelectableConfig>() {
@Override
public SelectableConfig readElement(HolderLookup.Provider provider, SelectableConfig defaultValue, boolean loadDefault, boolean ignoreRestart, JsonElement element,
Side side, ConfigKey key) {
if (element.isJsonPrimitive() && ((JsonPrimitive) element).isNumber())
defaultValue.select(element.getAsInt());
else
defaultValue.reset();
return defaultValue;
}
@Override
public JsonElement writeElement(HolderLookup.Provider provider, SelectableConfig value, boolean saveDefault, boolean ignoreRestart, Side side, ConfigKey key) {
return new JsonPrimitive(value.getSelected());
}
@Override
@Environment(EnvType.CLIENT)
@OnlyIn(Dist.CLIENT)
public void createControls(GuiParent parent, IGuiConfigParent configParent, ConfigKey key, Side side) {
SelectableConfig value = (SelectableConfig) key.get();
configParent.setCustomData(value.getSelected());
parent.add(new GuiComboBox("data", new TextMapBuilder().addComponent(value.getArray(), x -> Component.literal(x.toString()))).setExpandableX());
}
@Override
@Environment(EnvType.CLIENT)
@OnlyIn(Dist.CLIENT)
public void loadValue(SelectableConfig value, SelectableConfig defaultValue, GuiParent parent, IGuiConfigParent configParent, ConfigKey key, Side side) {
GuiComboBox box = parent.get("data");
box.select(value.getSelected());
}
@Override
@Environment(EnvType.CLIENT)
@OnlyIn(Dist.CLIENT)
public void restoreDefault(SelectableConfig value, GuiParent parent, IGuiConfigParent configParent, ConfigKey key, Side side) {
value.reset();
loadValue(value, value, parent, configParent, key, side);
}
@Override
@Environment(EnvType.CLIENT)
@OnlyIn(Dist.CLIENT)
protected SelectableConfig saveValue(GuiParent parent, IGuiConfigParent configParent, ConfigKey key, Side side) {
SelectableConfig config = (SelectableConfig) key.get();
GuiComboBox box = parent.get("data");
config.select(box.selectedIndex());
return config;
}
@Override
public SelectableConfig set(ConfigKey key, SelectableConfig value) {
return value;
}
@Override
@Environment(EnvType.CLIENT)
@OnlyIn(Dist.CLIENT)
public boolean shouldSave(SelectableConfig value, GuiParent parent, IGuiConfigParent configParent, ConfigKey key, Side side) {
return value.getSelected() != (int) configParent.getCustomData();
}
});
registerType(NamedList.class, new ConfigTypeNamedList());
registerType(Permission.class, new ConfigTypePermission());
registerTypeCreator(MobEffectConfig.class, () -> new MobEffectConfig(BuiltInRegistries.MOB_EFFECT, ResourceLocation.withDefaultNamespace("slowness"), 2, 1, false));
registerType(ToggleableConfig.class, new ConfigTypeToggleable());
registerTypes(new SimpleConfigTypeConveration<IntMatrix3c>() {
@Override
public IntMatrix3c readElement(ConfigKey key, IntMatrix3c defaultValue, Side side, JsonElement element) {
if (element instanceof JsonArray a && a.size() == 9) {
int[] array = new int[9];
for (int i = 0; i < array.length; i++)
array[i] = a.get(i).getAsInt();
return new IntMatrix3(array);
}
return new IntMatrix3(defaultValue);
}
@Override
public JsonElement writeElement(IntMatrix3c value, ConfigKey key, Side side) {
JsonArray json = new JsonArray(9);
int[] array = value.getAsArray();
for (int i = 0; i < array.length; i++)
json.add(array[i]);
return json;
}
@Override
@Environment(EnvType.CLIENT)
@OnlyIn(Dist.CLIENT)
public void createControls(GuiParent parent, ConfigKey key) {
parent.flow = GuiFlow.STACK_Y;
GuiParent r = new GuiParent();
parent.add(r);
r.add(new GuiTextfield("m00").setNumbersIncludingNegativeOnly());
r.add(new GuiTextfield("m01").setNumbersIncludingNegativeOnly());
r.add(new GuiTextfield("m02").setNumbersIncludingNegativeOnly());
r = new GuiParent();
parent.add(r);
r.add(new GuiTextfield("m10").setNumbersIncludingNegativeOnly());
r.add(new GuiTextfield("m11").setNumbersIncludingNegativeOnly());
r.add(new GuiTextfield("m12").setNumbersIncludingNegativeOnly());
r = new GuiParent();
parent.add(r);
r.add(new GuiTextfield("m20").setNumbersIncludingNegativeOnly());
r.add(new GuiTextfield("m21").setNumbersIncludingNegativeOnly());
r.add(new GuiTextfield("m22").setNumbersIncludingNegativeOnly());
}
@Override
@Environment(EnvType.CLIENT)
@OnlyIn(Dist.CLIENT)
public void loadValue(IntMatrix3c value, GuiParent parent) {
parent.get("m00", GuiTextfield.class).setText("" + value.m00());
parent.get("m01", GuiTextfield.class).setText("" + value.m01());
parent.get("m02", GuiTextfield.class).setText("" + value.m02());
parent.get("m10", GuiTextfield.class).setText("" + value.m10());
parent.get("m11", GuiTextfield.class).setText("" + value.m11());
parent.get("m12", GuiTextfield.class).setText("" + value.m12());
parent.get("m20", GuiTextfield.class).setText("" + value.m20());
parent.get("m21", GuiTextfield.class).setText("" + value.m21());
parent.get("m22", GuiTextfield.class).setText("" + value.m22());
}
@Override
@Environment(EnvType.CLIENT)
@OnlyIn(Dist.CLIENT)
protected IntMatrix3c saveValue(GuiParent parent, ConfigKey key) {
return new IntMatrix3(parent.get("m00", GuiTextfield.class).parseInteger(), parent.get("m01", GuiTextfield.class).parseInteger(), parent.get("m02",
GuiTextfield.class).parseInteger(), parent.get("m10", GuiTextfield.class).parseInteger(), parent.get("m11", GuiTextfield.class).parseInteger(), parent.get(
"m12", GuiTextfield.class).parseInteger(), parent.get("m20", GuiTextfield.class).parseInteger(), parent.get("m21", GuiTextfield.class)
.parseInteger(), parent.get("m22", GuiTextfield.class).parseInteger());
}
@Override
public IntMatrix3c set(ConfigKey key, IntMatrix3c value) {
return value;
}
}, IntMatrix3c.class, IntMatrix3.class);
registerSpecialType((x) -> {
if (x.isArray()) {
if (has(x.getComponentType()))
return true;
throw new RuntimeException("Array with holders are not permitted");
}
return false;
}, new ConfigTypeArray());
registerSpecialType(Enum.class::isAssignableFrom, new SimpleConfigTypeConveration<Enum>() {
private static Class getEnumClass(Class clazz) {
if (clazz.isEnum())
return clazz;
return clazz.getSuperclass();
}
@Override
public Enum readElement(ConfigKey key, Enum defaultValue, Side side, JsonElement element) {
if (element.isJsonPrimitive() && ((JsonPrimitive) element).isString())
return Enum.valueOf(defaultValue.getDeclaringClass(), element.getAsString());
return defaultValue;
}
@Override
public JsonElement writeElement(Enum value, ConfigKey key, Side side) {
return new JsonPrimitive(value.name());
}
@Override
@Environment(EnvType.CLIENT)
@OnlyIn(Dist.CLIENT)
public void createControls(GuiParent parent, ConfigKey key) {
parent.add(new GuiComboBox<>("data", new TextMapBuilder<>().addComponent(getEnumClass(key.field().getType()).getEnumConstants(), (x) -> Component.literal(((Enum) x)
.name()))));
}
@Override
@Environment(EnvType.CLIENT)
@OnlyIn(Dist.CLIENT)
public void loadValue(Enum value, GuiParent parent) {
GuiComboBox box = parent.get("data");
box.select(value.ordinal());
}
@Override
@Environment(EnvType.CLIENT)
@OnlyIn(Dist.CLIENT)
protected Enum saveValue(GuiParent parent, ConfigKey key) {
GuiComboBox box = parent.get("data");
return (Enum) box.selected();
}
@Override
public Enum set(ConfigKey key, Enum value) {
return value;
}
});
registerSpecialType((x) -> List.class.isAssignableFrom(x) || x == ArrayList.class, new ConfigTypeList());
}
public abstract T readElement(HolderLookup.Provider provider, T defaultValue, boolean loadDefault, boolean ignoreRestart, JsonElement element, Side side, ConfigKey key);
public abstract JsonElement writeElement(HolderLookup.Provider provider, T value, boolean saveDefault, boolean ignoreRestart, Side side, ConfigKey key);
@Environment(EnvType.CLIENT)
@OnlyIn(Dist.CLIENT)
public abstract void createControls(GuiParent parent, IGuiConfigParent configParent, ConfigKey key, Side side);
@Environment(EnvType.CLIENT)
@OnlyIn(Dist.CLIENT)
public abstract void loadValue(T value, T defaultValue, GuiParent parent, IGuiConfigParent configParent, ConfigKey key, Side side);
@Environment(EnvType.CLIENT)
@OnlyIn(Dist.CLIENT)
public void restoreDefault(T value, GuiParent parent, IGuiConfigParent configParent, ConfigKey key, Side side) {
loadValue(value, value, parent, configParent, key, side);
}
@Environment(EnvType.CLIENT)
@OnlyIn(Dist.CLIENT)
public boolean shouldSave(T value, GuiParent parent, IGuiConfigParent configParent, ConfigKey key, Side side) {
return !key.get().equals(value);
}
@Environment(EnvType.CLIENT)
@OnlyIn(Dist.CLIENT)
protected abstract T saveValue(GuiParent parent, IGuiConfigParent configParent, ConfigKey key, Side side);
public abstract T set(ConfigKey key, T value);
@Environment(EnvType.CLIENT)
@OnlyIn(Dist.CLIENT)
public T save(GuiParent parent, IGuiConfigParent configParent, ConfigKey key, Side side) {
T value = saveValue(parent, configParent, key, side);
if (value != null && key != null)
return set(key, value);
return value;
}
public boolean areEqual(T one, T two, ConfigKey key, Side side) {
return one.equals(two);
}
public static abstract class SimpleConfigTypeConveration<T> extends ConfigTypeConveration<T> {
@Override
public T readElement(HolderLookup.Provider provider, T defaultValue, boolean loadDefault, boolean ignoreRestart, JsonElement element, Side side, ConfigKey key) {
return readElement(key, defaultValue, side, element);
}
public abstract T readElement(ConfigKey key, T defaultValue, Side side, JsonElement element);
@Override
public JsonElement writeElement(HolderLookup.Provider provider, T value, boolean ignoreRestart, boolean saveDefault, Side side, ConfigKey key) {
return writeElement(value, key, side);
}
public abstract JsonElement writeElement(T value, ConfigKey key, Side side);
@Override
@Environment(EnvType.CLIENT)
@OnlyIn(Dist.CLIENT)
public void createControls(GuiParent parent, IGuiConfigParent configParent, ConfigKey key, Side side) {
createControls(parent, key);
}
@Environment(EnvType.CLIENT)
@OnlyIn(Dist.CLIENT)
public abstract void createControls(GuiParent parent, ConfigKey key);
@Override
@Environment(EnvType.CLIENT)
@OnlyIn(Dist.CLIENT)
public void loadValue(T value, T defaultValue, GuiParent parent, IGuiConfigParent configParent, ConfigKey key, Side side) {
loadValue(value, parent);
}
@Environment(EnvType.CLIENT)
@OnlyIn(Dist.CLIENT)
public abstract void loadValue(T value, GuiParent parent);
@Override
@Environment(EnvType.CLIENT)
@OnlyIn(Dist.CLIENT)
protected T saveValue(GuiParent parent, IGuiConfigParent configParent, ConfigKey key, Side side) {
return saveValue(parent, key);
}
@Environment(EnvType.CLIENT)
@OnlyIn(Dist.CLIENT)
protected abstract T saveValue(GuiParent parent, ConfigKey key);
}
}
| 412 | 0.949492 | 1 | 0.949492 | game-dev | MEDIA | 0.46237 | game-dev | 0.744315 | 1 | 0.744315 |
CodeSmile-0000011110110111/de.codesmile.luny | 1,630 | Editor/Core/Assets/AssetCollection.cs | // Copyright (C) 2021-2025 Steffen Itterheim
// Refer to included LICENSE file for terms and conditions.
using System;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;
using Object = UnityEngine.Object;
namespace LunyEditor.Core
{
public class AssetCollection<T> where T : Object
{
private static Dictionary<String, T> m_Assets;
public T this[String key] => m_Assets.TryGetValue(key, out var value) ? value : null;
public AssetCollection()
{
if (m_Assets == null)
{
m_Assets = new Dictionary<String, T>();
var assetGuids = AssetDatabase.FindAssets($"t:{typeof(T).Name}");
foreach (var assetGuid in assetGuids)
{
var path = AssetDatabase.GUIDToAssetPath(assetGuid);
var asset = AssetDatabase.LoadAssetAtPath<T>(path);
Debug.Assert(asset != null,
$"Asset load failed! Don't use within Start/StopAssetEditing, [InitializeOnLoad], static ctor! Path: {path}");
m_Assets.Add(path, asset);
}
}
}
public T TryGetAssetByFilename(String filename)
{
foreach (var assetPath in m_Assets.Keys)
{
if (filename == Path.GetFileName(assetPath) || filename == Path.GetFileNameWithoutExtension(assetPath))
return m_Assets[assetPath];
}
return null;
}
public T[] TryGetAssetsByName(String name)
{
var foundAssets = new List<T>();
foreach (var asset in m_Assets.Values)
{
if (name == asset.name)
foundAssets.Add(asset);
}
return foundAssets.ToArray();
}
}
public sealed class AssemblyDefinitionAssets : AssetCollection<AssemblyDefinitionAsset> {}
}
| 412 | 0.783073 | 1 | 0.783073 | game-dev | MEDIA | 0.967504 | game-dev | 0.906479 | 1 | 0.906479 |
elringus/unity-common | 7,140 | Assets/UnityCommon/Runtime/Async/UniTask/Internal/ContinuationQueue.cs | using System;
using System.Threading;
namespace UnityCommon.Async.Internal
{
internal sealed class ContinuationQueue
{
private const int MaxArrayLength = 0X7FEFFFFF;
private const int InitialSize = 16;
private readonly PlayerLoopTiming timing;
private SpinLock gate = new SpinLock(false);
private bool dequing;
private int actionListCount;
private Action[] actionList = new Action[InitialSize];
private int waitingListCount;
private Action[] waitingList = new Action[InitialSize];
public ContinuationQueue (PlayerLoopTiming timing)
{
this.timing = timing;
}
public void Enqueue (Action continuation)
{
bool lockTaken = false;
try
{
gate.Enter(ref lockTaken);
if (dequing)
{
// Ensure Capacity
if (waitingList.Length == waitingListCount)
{
var newLength = waitingListCount * 2;
if ((uint)newLength > MaxArrayLength) newLength = MaxArrayLength;
var newArray = new Action[newLength];
Array.Copy(waitingList, newArray, waitingListCount);
waitingList = newArray;
}
waitingList[waitingListCount] = continuation;
waitingListCount++;
}
else
{
// Ensure Capacity
if (actionList.Length == actionListCount)
{
var newLength = actionListCount * 2;
if ((uint)newLength > MaxArrayLength) newLength = MaxArrayLength;
var newArray = new Action[newLength];
Array.Copy(actionList, newArray, actionListCount);
actionList = newArray;
}
actionList[actionListCount] = continuation;
actionListCount++;
}
}
finally
{
if (lockTaken) gate.Exit(false);
}
}
public int Clear ()
{
var rest = actionListCount + waitingListCount;
actionListCount = 0;
actionList = new Action[InitialSize];
waitingListCount = 0;
waitingList = new Action[InitialSize];
return rest;
}
// delegate entrypoint.
public void Run ()
{
// for debugging, create named stacktrace.
#if DEBUG
switch (timing)
{
case PlayerLoopTiming.Initialization:
Initialization();
break;
case PlayerLoopTiming.LastInitialization:
LastInitialization();
break;
case PlayerLoopTiming.EarlyUpdate:
EarlyUpdate();
break;
case PlayerLoopTiming.LastEarlyUpdate:
LastEarlyUpdate();
break;
case PlayerLoopTiming.FixedUpdate:
FixedUpdate();
break;
case PlayerLoopTiming.LastFixedUpdate:
LastFixedUpdate();
break;
case PlayerLoopTiming.PreUpdate:
PreUpdate();
break;
case PlayerLoopTiming.LastPreUpdate:
LastPreUpdate();
break;
case PlayerLoopTiming.Update:
Update();
break;
case PlayerLoopTiming.LastUpdate:
LastUpdate();
break;
case PlayerLoopTiming.PreLateUpdate:
PreLateUpdate();
break;
case PlayerLoopTiming.LastPreLateUpdate:
LastPreLateUpdate();
break;
case PlayerLoopTiming.PostLateUpdate:
PostLateUpdate();
break;
case PlayerLoopTiming.LastPostLateUpdate:
LastPostLateUpdate();
break;
#if UNITY_2020_2_OR_NEWER
case PlayerLoopTiming.TimeUpdate:
TimeUpdate();
break;
case PlayerLoopTiming.LastTimeUpdate:
LastTimeUpdate();
break;
#endif
default:
break;
}
#else
RunCore();
#endif
}
private void Initialization () => RunCore();
private void LastInitialization () => RunCore();
private void EarlyUpdate () => RunCore();
private void LastEarlyUpdate () => RunCore();
private void FixedUpdate () => RunCore();
private void LastFixedUpdate () => RunCore();
private void PreUpdate () => RunCore();
private void LastPreUpdate () => RunCore();
private void Update () => RunCore();
private void LastUpdate () => RunCore();
private void PreLateUpdate () => RunCore();
private void LastPreLateUpdate () => RunCore();
private void PostLateUpdate () => RunCore();
private void LastPostLateUpdate () => RunCore();
#if UNITY_2020_2_OR_NEWER
void TimeUpdate() => RunCore();
void LastTimeUpdate() => RunCore();
#endif
[System.Diagnostics.DebuggerHidden]
private void RunCore ()
{
{
bool lockTaken = false;
try
{
gate.Enter(ref lockTaken);
if (actionListCount == 0) return;
dequing = true;
}
finally
{
if (lockTaken) gate.Exit(false);
}
}
for (int i = 0; i < actionListCount; i++)
{
var action = actionList[i];
actionList[i] = null;
try
{
action();
}
catch (Exception ex)
{
UnityEngine.Debug.LogException(ex);
}
}
{
bool lockTaken = false;
try
{
gate.Enter(ref lockTaken);
dequing = false;
var swapTempActionList = actionList;
actionListCount = waitingListCount;
actionList = waitingList;
waitingListCount = 0;
waitingList = swapTempActionList;
}
finally
{
if (lockTaken) gate.Exit(false);
}
}
}
}
}
| 412 | 0.907079 | 1 | 0.907079 | game-dev | MEDIA | 0.529066 | game-dev | 0.992969 | 1 | 0.992969 |
ShortTailLab/ph-open | 1,069 | libs/extensions/CCBReader/CCMenuItemLoader.cpp | #include "CCMenuItemLoader.h"
#define PROPERTY_BLOCK "block"
#define PROPERTY_ISENABLED "isEnabled"
NS_CC_EXT_BEGIN
void CCMenuItemLoader::onHandlePropTypeBlock(CCNode * pNode, CCNode * pParent, const char * pPropertyName, BlockData * pBlockData, CCBReader * pCCBReader) {
if(strcmp(pPropertyName, PROPERTY_BLOCK) == 0) {
if (NULL != pBlockData) // Add this condition to allow CCMenuItemImage without target/selector predefined
{
((CCMenuItem *)pNode)->setTarget(pBlockData->mTarget, pBlockData->mSELMenuHandler);
}
} else {
CCNodeLoader::onHandlePropTypeBlock(pNode, pParent, pPropertyName, pBlockData, pCCBReader);
}
}
void CCMenuItemLoader::onHandlePropTypeCheck(CCNode * pNode, CCNode * pParent, const char * pPropertyName, bool pCheck, CCBReader * pCCBReader) {
if(strcmp(pPropertyName, PROPERTY_ISENABLED) == 0) {
((CCMenuItem *)pNode)->setEnabled(pCheck);
} else {
CCNodeLoader::onHandlePropTypeCheck(pNode, pParent, pPropertyName, pCheck, pCCBReader);
}
}
NS_CC_EXT_END | 412 | 0.917045 | 1 | 0.917045 | game-dev | MEDIA | 0.46733 | game-dev | 0.803401 | 1 | 0.803401 |
KIT-ISAS/iviz | 3,429 | iviz/Assets/Core/FAnimator.cs | #nullable enable
using System;
using System.Threading;
using Iviz.Common;
using Iviz.Msgs;
using Iviz.TfHelpers;
using UnityEngine;
namespace Iviz.Core
{
/// <summary>
/// Convenience class that will call back a given function each frame for a given time interval.
/// Used by displays to implement animations.
/// </summary>
public sealed class FAnimator
{
readonly Action<float> update;
readonly Action? dispose;
readonly CancellationToken token;
readonly float startTime;
readonly float duration;
FAnimator(Action<float> update, Action? dispose, CancellationToken token, float duration)
{
this.update = update;
this.dispose = dispose;
this.token = token;
this.duration = duration;
startTime = GameThread.GameTime;
if (token.IsCancellationRequested)
{
TryCallDispose();
return;
}
TryCallUpdate(0);
if (duration <= 0)
{
TryCallUpdate(1);
TryCallDispose();
return;
}
GameThread.AfterFramesUpdated += OnFrameUpdate;
}
void OnFrameUpdate()
{
if (token.IsCancellationRequested)
{
TryCallDispose();
GameThread.AfterFramesUpdated -= OnFrameUpdate;
return;
}
float t = Mathf.Min((GameThread.GameTime - startTime) / duration, 1);
TryCallUpdate(t);
if (t < 1)
{
return;
}
TryCallDispose();
GameThread.AfterFramesUpdated -= OnFrameUpdate;
}
void TryCallUpdate(float t)
{
try
{
update(t);
}
catch (Exception e)
{
RosLogger.Error($"{this}: Error during Animator update", e);
}
}
void TryCallDispose()
{
if (dispose == null)
{
return;
}
try
{
dispose();
}
catch (Exception e)
{
RosLogger.Error($"{this}: Error during Animator dispose", e);
}
}
public static void Spawn(CancellationToken token, float durationInSec, Action<float> update, Action? dispose = null)
{
ThrowHelper.ThrowIfNull(update, nameof(update));
_ = new FAnimator(update, dispose, token, durationInSec); // won't be GC'd as long as it remains in EveryFrame
}
public static void Start(IAnimatable highlighter) =>
Spawn(highlighter.Token, highlighter.Duration, highlighter.Update, highlighter.Dispose);
public override string ToString() => $"[{nameof(FAnimator)} " +
$"{(GameThread.GameTime - startTime).ToString(BuiltIns.Culture)}/" +
$"{duration.ToString(BuiltIns.Culture)}]";
}
public interface IAnimatable
{
CancellationToken Token { get; }
float Duration { get; }
void Update(float t);
void Dispose();
}
} | 412 | 0.929309 | 1 | 0.929309 | game-dev | MEDIA | 0.940694 | game-dev | 0.991803 | 1 | 0.991803 |
fzi-forschungszentrum-informatik/anovox | 7,991 | Scenarios/ScenarioDefinitionGenerator.py | import json
import logging
import random
import shutil
import uuid
import Definitions
from Definitions import (
AnomalyTypes,
WeatherPresets,
selected_anomaly_types,
TOWN_CONFIGS,
)
from FileStructureManager import (
get_scenario_config_output_dir,
)
from Models.World import World
from Scenarios import Util
# ======================================================================================================================
# region -- GENERATE ALL SCENARIO CONFIG FILES -------------------------------------------------------------------------
# ======================================================================================================================
def generate_all_scenario_config_files(nbr_of_scenarios, maps):
# Step 1: Initialize variables
town_nbr_scenarios_allocation = {map: 0 for map in maps}
nbr_scenarios_to_be_allocated = nbr_of_scenarios
average_nbr_scenarios_per_map = nbr_of_scenarios // len(maps)
# Step 2: Allocate scenarios to maps
for index, map in enumerate(maps):
if index == len(maps) - 1:
town_nbr_scenarios_allocation[map] = nbr_scenarios_to_be_allocated
break
town_nbr_scenarios_allocation[map] = average_nbr_scenarios_per_map
nbr_scenarios_to_be_allocated -= average_nbr_scenarios_per_map
# Step 3: Log allocation
logging.info(f"Allocated: {town_nbr_scenarios_allocation} Scenarios")
# Step 4: Clear previous configuration files
shutil.rmtree(get_scenario_config_output_dir())
file_paths = []
# Step 5: Generate scenario definition for each map
for (map_name, allocated_scenarios,) in town_nbr_scenarios_allocation.items():
World.change_world(World.WORLD_STATE, map_name)
logging.info(f"TOWN_NBR_SCENARIOS_ALLOCATION[{map_name}]: {allocated_scenarios}")
file_path = generate_scenario_definition(
allocated_scenarios,
map_name=map_name,
selected_anomaly_types=selected_anomaly_types,
)
# Append the file path to the list
file_paths.append(file_path)
# Return the list of file paths
return file_paths
# endregion
# ======================================================================================================================
# ======================================================================================================================
# region -- GENERATE SCENARIO DEFINITION -------------------------------------------------------------------------------
# ======================================================================================================================
def generate_scenario_definition(amount, map_name, selected_anomaly_types):
# Mapping anomaly types to corresponding generator functions
anomaly_configs = {
AnomalyTypes.NORMALITY: generate_normal_config,
AnomalyTypes.STATIC: generate_static_config,
AnomalyTypes.SUDDEN_BREAKING_OF_VEHICLE_AHEAD: generate_sudden_breaking_config,
}
data = {
"scenario_definition": {
"map": map_name,
"scenarios": [],
},
}
# Get configuration data for the map
town_config = TOWN_CONFIGS[map_name]
for i in range(amount):
# Selecting a random anomaly type
anomaly_type = random.choice(selected_anomaly_types)
generator = anomaly_configs[anomaly_type]
anomaly_config = generator()
logging.info(anomaly_config)
# Generating random spawn points for ego vehicle
list_of_spawnpoints = World.get_world().get_map().get_spawn_points()
ego_start_spawnpoint, ego_end_spawnpoint, ego_vehicle_route = Util.get_valid_route(list_of_spawnpoints)
# Generate scenario template based on anomaly config, spawn points, and route
scenario_template = generate_scenario_template(
anomaly_config,
ego_start_spawnpoint,
ego_end_spawnpoint,
ego_vehicle_route,
town_config
)
# Append the scenario template to the list of scenarios
data["scenario_definition"]["scenarios"].append(scenario_template)
# Save the generated scenarios to a JSON file
file_path = f"{get_scenario_config_output_dir()}/scenario_config_map_{map_name}.json"
with open(file_path, "w") as outfile:
json.dump(data, outfile, indent=4)
return file_path
def load_blueprint_id(blueprint_list):
return f"{random.choice(blueprint_list).id}"
def generate_normal_config():
return {
"anomalytype": "NORMALITY",
"anomaly_bp_name": "---",
"distance_to_waypoint": 0,
"rotation": 0
}
def generate_static_config():
categories = Definitions.categories
static_blueprints = []
for category in categories:
blueprint_list = [bp for bp in World.get_world().get_blueprint_library().filter(f"static.prop.o_*_{category}")]
static_blueprints.extend(blueprint_list)
return {
"anomalytype": AnomalyTypes.STATIC.name,
"anomaly_bp_name": load_blueprint_id(static_blueprints),
"distance_to_waypoint": random.randint(
Definitions.DISTANCE_INTERVAL[0],
Definitions.DISTANCE_INTERVAL[1],
),
"rotation": random.uniform(0, 360),
}
def generate_sudden_breaking_config():
vehicle_blueprints = [bp for bp in World.get_world().get_blueprint_library().filter("vehicle.*")]
non_car_keywords = ['bike', 'ambulance', 'firetruck', 'police', 'carlacola', 'fusorosa', 'vespa', 'harley-davidson',
'kawasaki', 'yamaha', 'bh', 'diamondback', 'gazelle', 'volkswagen']
cars_only = [vehicle for vehicle in vehicle_blueprints if
all(keyword not in vehicle.id for keyword in non_car_keywords)]
return {
"anomalytype": AnomalyTypes.SUDDEN_BREAKING_OF_VEHICLE_AHEAD.name,
"anomaly_bp_name": load_blueprint_id(cars_only),
"approximate_dist_to_spawning_waypoint": random.randint(
Definitions.DISTANCE_INTERVAL_SUDDEN_BREAKING[0],
Definitions.DISTANCE_INTERVAL_SUDDEN_BREAKING[1],
),
}
def generate_scenario_template(
anomaly_config,
ego_spawnpoint,
ego_end_spawnpoint,
ego_vehicle_route,
town_config,
):
return {
"anomaly_config": {**anomaly_config},
"id": f"{uuid.uuid4()}",
"ego_spawnpoint": {
"location": {
"x": ego_spawnpoint.location.x,
"y": ego_spawnpoint.location.y,
"z": ego_spawnpoint.location.z,
},
"rotation": {
"pitch": ego_spawnpoint.rotation.pitch,
"yaw": ego_spawnpoint.rotation.yaw,
"roll": ego_spawnpoint.rotation.roll,
},
},
"ego_end_spawnpoint": {
"location": {
"x": ego_end_spawnpoint.location.x,
"y": ego_end_spawnpoint.location.y,
"z": ego_end_spawnpoint.location.z,
},
"rotation": {
"pitch": ego_end_spawnpoint.rotation.pitch,
"yaw": ego_end_spawnpoint.rotation.yaw,
"roll": ego_end_spawnpoint.rotation.roll,
},
},
"ego_route": {
"locations": [
{
"x": point[0].transform.location.x,
"y": point[0].transform.location.y,
"z": point[0].transform.location.z,
}
for point in ego_vehicle_route
]
},
"weather_preset": f"{random.choice(list(WeatherPresets)).name}",
"npc_vehicle_amount": town_config["npc_vehicle_amount"],
"npc_walker_amount": town_config["npc_walker_amount"],
}
# endregion
# ======================================================================================================================
| 412 | 0.859048 | 1 | 0.859048 | game-dev | MEDIA | 0.847716 | game-dev | 0.765495 | 1 | 0.765495 |
jphp-group/develnext | 1,711 | platforms/develnext-desktop-platform/src/ide/behaviour/spec/CameraSnapBehaviourSpec.php | <?php
namespace ide\behaviour\spec;
use behaviour\custom\BlinkAnimationBehaviour;
use behaviour\custom\CameraSnapBehaviour;
use behaviour\custom\CameraTargetBehaviour;
use behaviour\custom\ChatterAnimationBehaviour;
use behaviour\custom\DraggingBehaviour;
use behaviour\custom\DraggingFormBehaviour;
use behaviour\custom\GameEntityBehaviour;
use behaviour\custom\GameSceneBehaviour;
use behaviour\custom\LimitedMovementBehaviour;
use behaviour\custom\WrapScreenBehaviour;
use ide\behaviour\AbstractBehaviourSpec;
use ide\formats\form\AbstractFormElement;
use ide\formats\form\elements\FormFormElement;
use ide\formats\form\elements\GamePaneFormElement;
use ide\formats\form\elements\PanelFormElement;
use ide\formats\form\elements\ScrollPaneFormElement;
use ide\formats\form\elements\SpriteViewFormElement;
use ide\scripts\AbstractScriptComponent;
use php\gui\UXNode;
class CameraSnapBehaviourSpec extends AbstractBehaviourSpec
{
/**
* @return string
*/
public function getName()
{
return 'Следовать за камерой';
}
public function getGroup()
{
return self::GROUP_GAME;
}
public function getIcon()
{
return "icons/gameMonitor16.png";
}
/**
* @return string
*/
public function getDescription()
{
return 'Привязать объект к позиции камеры.';
}
/**
* @return string
*/
public function getType()
{
return CameraSnapBehaviour::class;
}
/**
* @param $target
* @return bool
*/
public function isAllowedFor($target)
{
return !($target instanceof AbstractScriptComponent)
&& !($target instanceof FormFormElement);
}
} | 412 | 0.736654 | 1 | 0.736654 | game-dev | MEDIA | 0.58182 | game-dev | 0.750781 | 1 | 0.750781 |
warxander/los-santos-v | 2,998 | resources/[los-santos-v]/lsv-main/client/baseevents.lua | AddEventHandler('lsv:init', function()
local scaleform = Scaleform.NewAsync('MP_BIG_MESSAGE_FREEMODE')
local instructionalButtonsScaleform = Scaleform.NewAsync('INSTRUCTIONAL_BUTTONS')
RequestScriptAudioBank('MP_WASTED', 0)
while true do
Citizen.Wait(0)
if NetworkIsPlayerActive(PlayerId()) then
local playerPed = PlayerPedId()
if IsPedFatallyInjured(playerPed) then
local deathSource, weaponHash = NetworkGetEntityKillerOfPlayer(PlayerId())
local killer = nil
if deathSource == -1 or deathSource == playerPed then
killer = PlayerId()
elseif IsEntityAPed(deathSource) and IsPedAPlayer(deathSource) then
killer = NetworkGetPlayerIndexFromPed(deathSource)
end
local deathDetails = ''
local playerPos = Player.Position()
if not killer then
TriggerServerEvent('lsv:onPlayerDied', false, playerPos)
elseif killer == PlayerId() then
TriggerServerEvent('lsv:onPlayerDied', true, playerPos)
else
local killData = { }
killData.killer = GetPlayerServerId(killer)
killData.position = playerPos
killData.killerPosition = GetEntityCoords(deathSource)
if IsPedInAnyVehicle(deathSource, false) then
killData.isKillerInVehicle = true
end
if IsPedInAnyVehicle(playerPed, false) then
killData.isVictimInVehicle = true
end
killData.killDistance = math.floor(World.GetDistance(playerPos, killData.killerPosition, true))
deathDetails = string.format('Distance: %dm', killData.killDistance)
local hasDamagedBone, damagedBone = GetPedLastDamageBone(playerPed)
if hasDamagedBone and damagedBone == 31086 then
killData.headshot = true
end
if IsWeaponValid(weaponHash) then
killData.weaponHash = weaponHash
killData.weaponGroup = GetWeapontypeGroup(weaponHash)
local weaponName = WeaponUtility.GetNameByHash(weaponHash)
if weaponName then
local tint = GetPedWeaponTintIndex(deathSource, weaponHash)
local tintName = Settings.weaponTintNames[tint]
if tintName then
weaponName = weaponName..' ('..tintName..')'
end
deathDetails = 'Killed with '..weaponName..'\n'..deathDetails
end
end
TriggerServerEvent('lsv:onPlayerKilled', killData)
end
StartScreenEffect('DeathFailOut', 0, true)
ShakeGameplayCam('DEATH_FAIL_IN_EFFECT_SHAKE', 1.0)
PlaySoundFrontend(-1, 'MP_Flash', 'WastedSounds', 1)
instructionalButtonsScaleform:call('CLEAR_ALL')
instructionalButtonsScaleform:call('SET_DATA_SLOT', 0, '~INPUT_ATTACK~', 'Respawn Faster')
instructionalButtonsScaleform:call('DRAW_INSTRUCTIONAL_BUTTONS')
scaleform:call('SHOW_SHARD_WASTED_MP_MESSAGE', '~r~WASTED', deathDetails)
repeat
scaleform:renderFullscreen()
instructionalButtonsScaleform:renderFullscreen()
Citizen.Wait(0)
until not IsPedFatallyInjured(PlayerPedId())
StopScreenEffect('DeathFailOut')
StopGameplayCamShaking(true)
end
end
end
end)
| 412 | 0.732869 | 1 | 0.732869 | game-dev | MEDIA | 0.977166 | game-dev | 0.711822 | 1 | 0.711822 |
pvigier/ecs | 5,392 | include/ecs/EntityManager.h | #pragma once
#include "EntitySet.h"
#include "Visitor.h"
namespace ecs
{
template<typename T>
class Component;
class EntityManager
{
public:
static constexpr auto UndefinedEntity = static_cast<Entity>(std::numeric_limits<std::underlying_type_t<Entity>>::max());
EntityManager()
{
auto nbComponents = BaseComponent::getComponentCount();
// Component containers
mComponentContainers.resize(nbComponents);
for (auto type = std::size_t(0); type < mComponentContainers.size(); ++type)
mComponentContainers[type] = BaseComponent::createComponentContainer(type);
// Entity sets
mComponentToEntitySets.resize(nbComponents);
mEntitySets.resize(BaseEntitySet::getEntitySetCount());
for (auto type = std::size_t(0); type < mEntitySets.size(); ++type)
mEntitySets[type] = BaseEntitySet::createEntitySet(type, mEntities, mComponentContainers, mComponentToEntitySets);
}
void reserve(std::size_t size)
{
mEntities.reserve(size);
}
// Entities
bool hasEntity(Entity entity) const
{
return mEntities.has(entity);
}
Entity createEntity()
{
return mEntities.emplace().first;
}
void removeEntity(Entity entity)
{
const auto& entityData = mEntities.get(entity);
// Remove components
for (auto& [componentType, componentId] : entityData.getComponents())
mComponentContainers[componentType]->remove(componentId);
// Send message to entity sets
for (auto entitySetType : entityData.getEntitySets())
mEntitySets[entitySetType]->onEntityRemoved(entity);
// Remove entity
mEntities.erase(entity);
}
void visitEntity(Entity entity, const Visitor& visitor)
{
for (const auto& [componentType, componentId] : mEntities.get(entity).getComponents())
visitor.handle(componentType, mComponentContainers[componentType]->get(componentId));
}
// Components
template<typename T>
bool hasComponent(Entity entity) const
{
checkComponentType<T>();
return mEntities.get(entity).hasComponent<T>();
}
template<typename ...Ts>
bool hasComponents(Entity entity) const
{
checkComponentTypes<Ts...>();
return mEntities.get(entity).hasComponents<Ts...>();
}
template<typename T>
T& getComponent(Entity entity)
{
checkComponentType<T>();
return getComponentSparseSet<T>().get(mEntities.get(entity).getComponent<T>());
}
template<typename T>
const T& getComponent(Entity entity) const
{
checkComponentType<T>();
return getComponentSparseSet<T>().get(mEntities.get(entity).getComponent<T>());
}
template<typename ...Ts>
std::tuple<Ts&...> getComponents(Entity entity)
{
checkComponentTypes<Ts...>();
auto& entityData = mEntities.get(entity);
return std::tie(getComponentSparseSet<Ts>().get(entityData.getComponent<Ts>())...);
}
template<typename ...Ts>
std::tuple<const Ts&...> getComponents(Entity entity) const
{
checkComponentTypes<Ts...>();
auto& entityData = mEntities.get(entity);
return std::tie(std::as_const(getComponentSparseSet<Ts>().get(entityData.getComponent<Ts>()))...);
}
template<typename T, typename ...Args>
T& addComponent(Entity entity, Args&&... args)
{
checkComponentType<T>();
auto [componentId, component] = getComponentSparseSet<T>().emplace(std::forward<Args>(args)...);
mEntities.get(entity).addComponent<T>(componentId);
// Send message to entity sets
for (auto entitySet : mComponentToEntitySets[T::Type])
entitySet->onEntityUpdated(entity);
// Return the created component
return component;
}
template<typename T>
void removeComponent(Entity entity)
{
checkComponentType<T>();
// Remove component from entity and component container
getComponentSparseSet<T>().erase(mEntities.get(entity).removeComponent<T>());
// Send message to entity sets
for (auto entitySet : mComponentToEntitySets[T::Type])
entitySet->onEntityUpdated(entity);
}
// Entity sets
template<typename ...Ts>
EntitySet<Ts...>& getEntitySet()
{
checkComponentTypes<Ts...>();
return *static_cast<EntitySet<Ts...>*>(mEntitySets[EntitySet<Ts...>::Type].get());
}
template<typename ...Ts>
const EntitySet<Ts...>& getEntitySet() const
{
checkComponentTypes<Ts...>();
return *static_cast<EntitySet<Ts...>*>(mEntitySets[EntitySet<Ts...>::Type].get());
}
private:
std::vector<std::unique_ptr<BaseComponentContainer>> mComponentContainers;
EntityContainer mEntities;
std::vector<std::unique_ptr<BaseEntitySet>> mEntitySets;
std::vector<std::vector<BaseEntitySet*>> mComponentToEntitySets;
template<typename T>
ComponentSparseSet<T>& getComponentSparseSet()
{
return static_cast<ComponentContainer<T>*>(mComponentContainers[T::Type].get())->components;
}
template<typename T>
const ComponentSparseSet<T>& getComponentSparseSet() const
{
return static_cast<const ComponentContainer<T>*>(mComponentContainers[T::Type].get())->components;
}
};
} | 412 | 0.883467 | 1 | 0.883467 | game-dev | MEDIA | 0.85139 | game-dev | 0.819625 | 1 | 0.819625 |
TrashboxBobylev/Summoning-Pixel-Dungeon | 2,456 | core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/levels/rooms/standard/FissureRoom.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.levels.rooms.standard;
import com.shatteredpixel.shatteredpixeldungeon.levels.Level;
import com.shatteredpixel.shatteredpixeldungeon.levels.Terrain;
import com.shatteredpixel.shatteredpixeldungeon.levels.painters.Painter;
import com.watabou.utils.Point;
import com.watabou.utils.Random;
public class FissureRoom extends StandardRoom {
@Override
public float[] sizeCatProbs() {
return new float[]{12, 8, 3, 1};
}
@Override
public void paint(Level level) {
Painter.fill( level, this, Terrain.WALL );
for (Door door : connected.values()) {
door.set( Door.Type.REGULAR );
}
Painter.fill( level, this, 1, Terrain.EMPTY );
if (square() <= 25){
//just fill in one tile if the room is tiny
Point p = center();
Painter.set( level, p.x, p.y, Terrain.CHASM);
} else {
int smallestDim = Math.min(width(), height());
int floorW = (int)Math.sqrt(smallestDim);
//chance for a tile at the edge of the floor to remain a floor tile
float edgeFloorChance = (float)Math.sqrt(smallestDim) % 1;
//the wider the floor the more edge chances tend toward 50%
edgeFloorChance = (edgeFloorChance + (floorW-1)*0.5f) / (float)floorW;
for (int i=top + 2; i <= bottom - 2; i++) {
for (int j=left + 2; j <= right - 2; j++) {
int v = Math.min( i - top, bottom - i );
int h = Math.min( j - left, right - j );
if (Math.min( v, h ) > floorW
|| (Math.min( v, h ) == floorW && Random.Float() > edgeFloorChance)) {
Painter.set( level, j, i, Terrain.CHASM );
}
}
}
}
}
}
| 412 | 0.896715 | 1 | 0.896715 | game-dev | MEDIA | 0.958072 | game-dev | 0.989278 | 1 | 0.989278 |
arendjr/PlainText | 2,244 | src/commands/go_command.rs | use super::CommandHelpers;
use crate::{
actions::{self, ActionOutput},
entity::{Entity, EntityRef, Realm},
relative_direction::RelativeDirection,
utils::{describe_entities_from_room, join_sentence, visible_portals_from_position},
};
/// Makes the character travel to another room.
pub fn go(realm: &mut Realm, player_ref: EntityRef, helpers: CommandHelpers) -> ActionOutput {
let processor = helpers.command_line_processor;
let alias = processor.take_word().unwrap();
let relative_direction = if alias == "go" {
let relative_direction = processor
.peek_word()
.and_then(RelativeDirection::from_string);
processor.skip_connecting_word("to");
relative_direction
} else {
None
};
let (_, room) = realm.character_and_room_res(player_ref)?;
let portal_ref = match processor.take_entity(realm, room.portals()) {
Some(portal_ref) => Ok(portal_ref),
None => {
if let Some(direction) = relative_direction {
get_portal_in_direction(realm, player_ref, direction)
} else {
Err("Go where?".into())
}
}
}?;
let room_ref = room.entity_ref();
actions::enter_portal(
realm,
helpers.action_dispatcher,
player_ref,
portal_ref,
room_ref,
)
}
pub fn get_portal_in_direction(
realm: &Realm,
player_ref: EntityRef,
relative_direction: RelativeDirection,
) -> Result<EntityRef, String> {
let (player, room) = realm.character_and_room_res(player_ref)?;
let direction = &relative_direction.from(player.direction());
let portal_refs = visible_portals_from_position(realm, room, direction);
if portal_refs.is_empty() {
Err(format!("There's no way {}.", relative_direction))
} else if let Some(portal_ref) = EntityRef::only(&portal_refs) {
Ok(portal_ref)
} else {
let destination_descriptions =
describe_entities_from_room(realm, &portal_refs, room.entity_ref());
Err(format!(
"There are multiple ways {}, to the {}.",
relative_direction,
join_sentence(&destination_descriptions)
))
}
}
| 412 | 0.861242 | 1 | 0.861242 | game-dev | MEDIA | 0.856486 | game-dev | 0.888049 | 1 | 0.888049 |
Arcthesia/ArcCreate | 4,473 | Assets/Plugins/Graphy/Runtime/Fps/G_FpsMonitor.cs | /* ---------------------------------------
* Author: Martin Pane (martintayx@gmail.com) (@martinTayx)
* Contributors: https://github.com/Tayx94/graphy/graphs/contributors
* Project: Graphy - Ultimate Stats Monitor
* Date: 15-Dec-17
* Studio: Tayx
*
* Git repo: https://github.com/Tayx94/graphy
*
* This project is released under the MIT license.
* Attribution is not required, but it is always welcomed!
* -------------------------------------*/
using System;
using System.Xml.Linq;
using UnityEngine;
using Random = UnityEngine.Random;
namespace Tayx.Graphy.Fps
{
public class G_FpsMonitor : MonoBehaviour
{
#region Variables -> Private
private short[] m_fpsSamples;
private short[] m_fpsSamplesSorted;
private short m_fpsSamplesCapacity = 1024;
private short m_onePercentSamples = 10;
private short m_zero1PercentSamples = 1;
private short m_fpsSamplesCount = 0;
private short m_indexSample = 0;
private float m_unscaledDeltaTime = 0f;
#endregion
#region Properties -> Public
public short CurrentFPS { get; private set; } = 0;
public short AverageFPS { get; private set; } = 0;
public short OnePercentFPS { get; private set; } = 0;
public short Zero1PercentFps { get; private set; } = 0;
#endregion
#region Methods -> Unity Callbacks
private void Awake()
{
Init();
}
private void Update()
{
m_unscaledDeltaTime = Time.unscaledDeltaTime;
// Update fps and ms
CurrentFPS = (short) (Mathf.RoundToInt( 1f / m_unscaledDeltaTime ));
// Update avg fps
uint averageAddedFps = 0;
m_indexSample++;
if( m_indexSample >= m_fpsSamplesCapacity ) m_indexSample = 0;
m_fpsSamples[ m_indexSample ] = CurrentFPS;
if( m_fpsSamplesCount < m_fpsSamplesCapacity )
{
m_fpsSamplesCount++;
}
for( int i = 0; i < m_fpsSamplesCount; i++ )
{
averageAddedFps += (uint) m_fpsSamples[ i ];
}
AverageFPS = (short) ((float) averageAddedFps / (float) m_fpsSamplesCount);
// Update percent lows
m_fpsSamples.CopyTo( m_fpsSamplesSorted, 0 );
/*
* TODO: Find a faster way to do this.
* We can probably avoid copying the full array every time
* and insert the new item already sorted in the list.
*/
Array.Sort( m_fpsSamplesSorted,
( x, y ) => x.CompareTo( y ) ); // The lambda expression avoids garbage generation
bool zero1PercentCalculated = false;
uint totalAddedFps = 0;
short samplesToIterateThroughForOnePercent = m_fpsSamplesCount < m_onePercentSamples
? m_fpsSamplesCount
: m_onePercentSamples;
short samplesToIterateThroughForZero1Percent = m_fpsSamplesCount < m_zero1PercentSamples
? m_fpsSamplesCount
: m_zero1PercentSamples;
short sampleToStartIn = (short) (m_fpsSamplesCapacity - m_fpsSamplesCount);
for( short i = sampleToStartIn; i < sampleToStartIn + samplesToIterateThroughForOnePercent; i++ )
{
totalAddedFps += (ushort) m_fpsSamplesSorted[ i ];
if( !zero1PercentCalculated && i >= samplesToIterateThroughForZero1Percent - 1 )
{
zero1PercentCalculated = true;
Zero1PercentFps = (short) ((float) totalAddedFps / (float) m_zero1PercentSamples);
}
}
OnePercentFPS = (short) ((float) totalAddedFps / (float) m_onePercentSamples);
}
#endregion
#region Methods -> Public
public void UpdateParameters()
{
m_onePercentSamples = (short) (m_fpsSamplesCapacity / 100);
m_zero1PercentSamples = (short) (m_fpsSamplesCapacity / 1000);
}
#endregion
#region Methods -> Private
private void Init()
{
m_fpsSamples = new short[m_fpsSamplesCapacity];
m_fpsSamplesSorted = new short[m_fpsSamplesCapacity];
UpdateParameters();
}
#endregion
}
} | 412 | 0.716925 | 1 | 0.716925 | game-dev | MEDIA | 0.753433 | game-dev | 0.768516 | 1 | 0.768516 |
evanbowman/blind-jump-portable | 13,087 | source/blind_jump/state/lispReplState.cpp | #include "script/lisp.hpp"
#include "state_impl.hpp"
static int paren_balance(const char* ptr)
{
int balance = 0;
while (*ptr not_eq '\0') {
if (*ptr == '(') {
++balance;
} else if (*ptr == ')') {
--balance;
}
++ptr;
}
return balance;
}
// Inspired by the dvorak keyboard layout, redesigned for use with a gameboy
// dpad. Optimized for the smallest horizontal _and_ vertical travel between key
// presses.
static const char* keyboard[7][6] = {{"z", "y", "g", "f", "v", "q"},
{"m", "b", "i", "d", "l", "j"},
{"w", "a", "o", "e", "u", "k"},
{"p", "h", "t", "n", "s", "r"},
{"x", "c", "(", ")", "-", " "},
{"$", "'", "0", "1", "2", "3"},
{"4", "5", "6", "7", "8", "9"}};
void LispReplState::repaint_entry(Platform& pfrm, bool show_cursor)
{
const auto screen_tiles = calc_screen_tiles(pfrm);
const auto darker_clr = Text::OptColors{
{ColorConstant::med_blue_gray, ColorConstant::rich_black}};
entry_->assign(":", darker_clr);
for (int i = 1; i < 32; ++i) {
pfrm.set_tile(Layer::overlay, i, screen_tiles.y - 1, 112);
}
auto colors = [this]() -> Text::OptColors {
switch (display_mode_) {
default:
case DisplayMode::entry:
return std::nullopt;
case DisplayMode::show_result:
return {{ColorConstant::med_blue_gray, ColorConstant::rich_black}};
}
}();
const int scroll =
std::max(0, (int)command_.length() - (screen_tiles.x - 1));
const int balance = paren_balance(command_.c_str());
if (balance < 0 and command_.length() and
command_[command_.length() - 1] == ')') {
// Give a hint to the user, that he/she entered too many closing parens.
command_.pop_back();
entry_->append(command_.c_str() + scroll, colors);
command_.push_back(')');
entry_->append(")",
Text::OptColors{{ColorConstant::aerospace_orange,
ColorConstant::rich_black}});
} else {
entry_->append(command_.c_str() + scroll, colors);
}
keyboard_.clear();
keyboard_top_.emplace(pfrm, OverlayCoord{2, 2});
keyboard_bottom_.emplace(pfrm, OverlayCoord{2, 10});
for (int x = 0; x < 6; ++x) {
keyboard_top_->append(::keyboard[6][x], darker_clr);
keyboard_bottom_->append(::keyboard[0][x], darker_clr);
}
for (int i = 0; i < 7; ++i) {
keyboard_.emplace_back(pfrm, OverlayCoord{1, u8(3 + i)});
keyboard_.back().append(::keyboard[i][5], darker_clr);
for (int j = 0; j < 6; ++j) {
if (show_cursor and j == keyboard_cursor_.x and
keyboard_cursor_.y == i) {
const auto colors =
Text::OptColors{{ColorConstant::rich_black,
ColorConstant::aerospace_orange}};
keyboard_.back().append(::keyboard[i][j], colors);
} else {
keyboard_.back().append(::keyboard[i][j]);
}
}
keyboard_.back().append(::keyboard[i][0], darker_clr);
}
}
void LispReplState::enter(Platform& pfrm, Game& game, State& prev_state)
{
// pfrm.load_overlay_texture("repl");
locale_set_language(1);
keyboard_cursor_ = {2, 4}; // For convenience, place cursor at left paren
const auto screen_tiles = calc_screen_tiles(pfrm);
entry_.emplace(pfrm, OverlayCoord{0, u8(screen_tiles.y - 1)});
const char* version_text = "BlindJump LISP v01";
for (int i = 0; i < 31; ++i) {
pfrm.set_tile(Layer::overlay, i, 0, 112);
}
const auto vrsn_coord =
OverlayCoord{u8((screen_tiles.x - 2) - str_len(version_text)), 0};
version_text_.emplace(pfrm, vrsn_coord);
version_text_->assign(version_text);
repaint_entry(pfrm);
}
void LispReplState::exit(Platform& pfrm, Game& game, State& next_state)
{
locale_set_language(game.persistent_data().settings_.language_.get());
entry_.reset();
keyboard_.clear();
version_text_.reset();
keyboard_top_.reset();
keyboard_bottom_.reset();
}
namespace {
class Printer : public lisp::Printer {
public:
Printer(LispReplState::Command& cmd) : cmd_(cmd)
{
}
void put_str(const char* str) override
{
cmd_ += str;
}
private:
LispReplState::Command& cmd_;
};
} // namespace
void LispReplState::repaint_completions(Platform& pfrm)
{
completions_.clear();
for (u32 i = 0; i < completion_strs_.size(); ++i) {
Text::OptColors opts;
if (i == completion_cursor_) {
opts = Text::OptColors{
{ColorConstant::rich_black, ColorConstant::aerospace_orange}};
}
completions_.emplace_back(pfrm, OverlayCoord{10, u8(2 + i)});
const auto str = completion_strs_[i];
int j;
char tempstr[2] = {'\0', '\0'};
for (j = 0; j < completion_prefix_len_; ++j) {
tempstr[0] = str[j];
completions_.back().append(
tempstr,
i == completion_cursor_
? opts
: Text::OptColors{
{custom_color(0x766df7), ColorConstant::rich_black}});
}
const int len = str_len(str);
for (; j < len; ++j) {
tempstr[0] = str[j];
completions_.back().append(tempstr, opts);
}
tempstr[0] = ' ';
for (; j < 20; ++j) {
completions_.back().append(tempstr, opts);
}
}
}
StatePtr LispReplState::update(Platform& pfrm, Game& game, Microseconds delta)
{
constexpr auto fade_duration = milliseconds(700);
if (timer_ < fade_duration) {
if (timer_ + delta > fade_duration) {
pfrm.screen().fade(0.34f);
}
timer_ += delta;
const auto amount =
(1.f - (1.f - 0.34f) * smoothstep(0.f, fade_duration, timer_));
if (timer_ < fade_duration) {
pfrm.screen().fade(amount);
}
}
switch (display_mode_) {
case DisplayMode::completion_list:
if (pfrm.keyboard().down_transition<Key::down>() and
completion_cursor_ < completion_strs_.size() - 1) {
++completion_cursor_;
repaint_completions(pfrm);
pfrm.speaker().play_sound("scroll", 1);
} else if (pfrm.keyboard().down_transition<Key::up>() and
completion_cursor_ > 0) {
--completion_cursor_;
repaint_completions(pfrm);
pfrm.speaker().play_sound("scroll", 1);
} else if (pfrm.keyboard().down_transition(game.action1_key())) {
repaint_entry(pfrm);
completion_strs_.clear();
completions_.clear();
display_mode_ = DisplayMode::entry;
} else if (pfrm.keyboard().down_transition(game.action2_key())) {
command_ +=
(completion_strs_[completion_cursor_] + completion_prefix_len_);
repaint_entry(pfrm);
completion_strs_.clear();
completions_.clear();
pfrm.speaker().play_sound("typewriter", 2);
display_mode_ = DisplayMode::entry;
}
break;
case DisplayMode::entry:
if (pfrm.keyboard().down_transition(game.action1_key())) {
if (command_.empty()) {
return state_pool().create<PauseScreenState>(false);
}
command_.pop_back();
repaint_entry(pfrm);
} else if (pfrm.keyboard().down_transition(game.action2_key())) {
command_.push_back(
keyboard[keyboard_cursor_.y][keyboard_cursor_.x][0]);
repaint_entry(pfrm);
pfrm.speaker().play_sound("typewriter", 2);
} else if (pfrm.keyboard().down_transition<Key::alt_1>()) {
// Try to isolate an identifier from the command buffer, for autocomplete.
auto is_delimiter = [](char c) {
return c == ' ' or c == ')' or c == '(' or c == '\'';
};
if (not command_.empty() and
not is_delimiter(command_[command_.length() - 1])) {
std::optional<int> ident_start;
error(pfrm, "checking for ident start");
for (int i = command_.length() - 1; i >= 0; --i) {
if (is_delimiter(command_[i])) {
ident_start = i + 1;
break;
} else if (i == 0 and not is_delimiter(command_[i])) {
ident_start = 0;
}
}
if (ident_start) {
StringBuffer<8> ident(command_.c_str() + *ident_start);
// We need to store this value for later, if a user selects
// a completion, we need to know how many characters of the
// substitution to skip, unless we want to parse the
// identifier out of the command buffer again.
completion_prefix_len_ = ident.length();
lisp::get_interns([&ident, this](const char* intern) {
if (completion_strs_.full()) {
return;
}
const auto intern_len = str_len(intern);
if (intern_len <= ident.length()) {
// I mean, there's no reason to autocomplete
// to something shorter or the same length...
return;
}
for (u32 i = 0; i < ident.length() and i < intern_len;
++i) {
if (ident[i] not_eq intern[i]) {
return;
}
}
completion_strs_.push_back(intern);
});
if (not completion_strs_.empty()) {
display_mode_ = DisplayMode::completion_list;
completion_cursor_ = 0;
repaint_completions(pfrm);
repaint_entry(pfrm, false);
}
} else {
error(pfrm, "autocomplete did not find ident start");
}
} else {
error(pfrm, "command empty or recent delimiter");
}
}
if (pfrm.keyboard().down_transition<Key::start>()) {
pfrm.speaker().play_sound("tw_bell", 2);
lisp::read(command_.c_str());
lisp::eval(lisp::get_op(0));
command_.clear();
Printer p(command_);
format(lisp::get_op(0), p);
lisp::pop_op();
lisp::pop_op();
display_mode_ = DisplayMode::show_result;
repaint_entry(pfrm);
}
if (pfrm.keyboard().down_transition<Key::left>()) {
if (keyboard_cursor_.x == 0) {
keyboard_cursor_.x = 5;
} else {
keyboard_cursor_.x -= 1;
}
pfrm.speaker().play_sound("scroll", 1);
repaint_entry(pfrm);
} else if (pfrm.keyboard().down_transition<Key::right>()) {
if (keyboard_cursor_.x == 5) {
keyboard_cursor_.x = 0;
} else {
keyboard_cursor_.x += 1;
}
pfrm.speaker().play_sound("scroll", 1);
repaint_entry(pfrm);
} else if (pfrm.keyboard().down_transition<Key::up>()) {
if (keyboard_cursor_.y == 0) {
keyboard_cursor_.y = 6;
} else {
keyboard_cursor_.y -= 1;
}
pfrm.speaker().play_sound("scroll", 1);
repaint_entry(pfrm);
} else if (pfrm.keyboard().down_transition<Key::down>()) {
if (keyboard_cursor_.y == 6) {
keyboard_cursor_.y = 0;
} else {
keyboard_cursor_.y += 1;
}
pfrm.speaker().play_sound("scroll", 1);
repaint_entry(pfrm);
}
break;
case DisplayMode::show_result:
if (pfrm.keyboard()
.down_transition<Key::action_1,
Key::action_2,
Key::start,
Key::left,
Key::right,
Key::up,
Key::down>()) {
display_mode_ = DisplayMode::entry;
command_.clear();
repaint_entry(pfrm);
return null_state();
}
break;
}
return null_state();
}
| 412 | 0.976185 | 1 | 0.976185 | game-dev | MEDIA | 0.503306 | game-dev,cli-devtools | 0.965811 | 1 | 0.965811 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.